diff --git a/vendor/dario.cat/mergo/.deepsource.toml b/vendor/dario.cat/mergo/.deepsource.toml deleted file mode 100644 index a8bc979e0..000000000 --- a/vendor/dario.cat/mergo/.deepsource.toml +++ /dev/null @@ -1,12 +0,0 @@ -version = 1 - -test_patterns = [ - "*_test.go" -] - -[[analyzers]] -name = "go" -enabled = true - - [analyzers.meta] - import_path = "dario.cat/mergo" \ No newline at end of file diff --git a/vendor/dario.cat/mergo/.gitignore b/vendor/dario.cat/mergo/.gitignore deleted file mode 100644 index 529c3412b..000000000 --- a/vendor/dario.cat/mergo/.gitignore +++ /dev/null @@ -1,33 +0,0 @@ -#### joe made this: http://goel.io/joe - -#### go #### -# Binaries for programs and plugins -*.exe -*.dll -*.so -*.dylib - -# Test binary, build with `go test -c` -*.test - -# Output of the go coverage tool, specifically when used with LiteIDE -*.out - -# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 -.glide/ - -#### vim #### -# Swap -[._]*.s[a-v][a-z] -[._]*.sw[a-p] -[._]s[a-v][a-z] -[._]sw[a-p] - -# Session -Session.vim - -# Temporary -.netrwhist -*~ -# Auto-generated tag files -tags diff --git a/vendor/dario.cat/mergo/.travis.yml b/vendor/dario.cat/mergo/.travis.yml deleted file mode 100644 index d324c43ba..000000000 --- a/vendor/dario.cat/mergo/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -language: go -arch: - - amd64 - - ppc64le -install: - - go get -t - - go get golang.org/x/tools/cmd/cover - - go get github.com/mattn/goveralls -script: - - go test -race -v ./... -after_script: - - $HOME/gopath/bin/goveralls -service=travis-ci -repotoken $COVERALLS_TOKEN diff --git a/vendor/dario.cat/mergo/CODE_OF_CONDUCT.md b/vendor/dario.cat/mergo/CODE_OF_CONDUCT.md deleted file mode 100644 index 469b44907..000000000 --- a/vendor/dario.cat/mergo/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,46 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. - -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, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at i@dario.im. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/dario.cat/mergo/CONTRIBUTING.md b/vendor/dario.cat/mergo/CONTRIBUTING.md deleted file mode 100644 index 0a1ff9f94..000000000 --- a/vendor/dario.cat/mergo/CONTRIBUTING.md +++ /dev/null @@ -1,112 +0,0 @@ - -# Contributing to mergo - -First off, thanks for taking the time to contribute! ❤️ - -All types of contributions are encouraged and valued. See the [Table of Contents](#table-of-contents) for different ways to help and details about how this project handles them. Please make sure to read the relevant section before making your contribution. It will make it a lot easier for us maintainers and smooth out the experience for all involved. The community looks forward to your contributions. 🎉 - -> And if you like the project, but just don't have time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about: -> - Star the project -> - Tweet about it -> - Refer this project in your project's readme -> - Mention the project at local meetups and tell your friends/colleagues - - -## Table of Contents - -- [Code of Conduct](#code-of-conduct) -- [I Have a Question](#i-have-a-question) -- [I Want To Contribute](#i-want-to-contribute) -- [Reporting Bugs](#reporting-bugs) -- [Suggesting Enhancements](#suggesting-enhancements) - -## Code of Conduct - -This project and everyone participating in it is governed by the -[mergo Code of Conduct](https://github.com/imdario/mergoblob/master/CODE_OF_CONDUCT.md). -By participating, you are expected to uphold this code. Please report unacceptable behavior -to <>. - - -## I Have a Question - -> If you want to ask a question, we assume that you have read the available [Documentation](https://pkg.go.dev/github.com/imdario/mergo). - -Before you ask a question, it is best to search for existing [Issues](https://github.com/imdario/mergo/issues) that might help you. In case you have found a suitable issue and still need clarification, you can write your question in this issue. It is also advisable to search the internet for answers first. - -If you then still feel the need to ask a question and need clarification, we recommend the following: - -- Open an [Issue](https://github.com/imdario/mergo/issues/new). -- Provide as much context as you can about what you're running into. -- Provide project and platform versions (nodejs, npm, etc), depending on what seems relevant. - -We will then take care of the issue as soon as possible. - -## I Want To Contribute - -> ### Legal Notice -> When contributing to this project, you must agree that you have authored 100% of the content, that you have the necessary rights to the content and that the content you contribute may be provided under the project license. - -### Reporting Bugs - - -#### Before Submitting a Bug Report - -A good bug report shouldn't leave others needing to chase you up for more information. Therefore, we ask you to investigate carefully, collect information and describe the issue in detail in your report. Please complete the following steps in advance to help us fix any potential bug as fast as possible. - -- Make sure that you are using the latest version. -- Determine if your bug is really a bug and not an error on your side e.g. using incompatible environment components/versions (Make sure that you have read the [documentation](). If you are looking for support, you might want to check [this section](#i-have-a-question)). -- To see if other users have experienced (and potentially already solved) the same issue you are having, check if there is not already a bug report existing for your bug or error in the [bug tracker](https://github.com/imdario/mergoissues?q=label%3Abug). -- Also make sure to search the internet (including Stack Overflow) to see if users outside of the GitHub community have discussed the issue. -- Collect information about the bug: -- Stack trace (Traceback) -- OS, Platform and Version (Windows, Linux, macOS, x86, ARM) -- Version of the interpreter, compiler, SDK, runtime environment, package manager, depending on what seems relevant. -- Possibly your input and the output -- Can you reliably reproduce the issue? And can you also reproduce it with older versions? - - -#### How Do I Submit a Good Bug Report? - -> You must never report security related issues, vulnerabilities or bugs including sensitive information to the issue tracker, or elsewhere in public. Instead sensitive bugs must be sent by email to . - - -We use GitHub issues to track bugs and errors. If you run into an issue with the project: - -- Open an [Issue](https://github.com/imdario/mergo/issues/new). (Since we can't be sure at this point whether it is a bug or not, we ask you not to talk about a bug yet and not to label the issue.) -- Explain the behavior you would expect and the actual behavior. -- Please provide as much context as possible and describe the *reproduction steps* that someone else can follow to recreate the issue on their own. This usually includes your code. For good bug reports you should isolate the problem and create a reduced test case. -- Provide the information you collected in the previous section. - -Once it's filed: - -- The project team will label the issue accordingly. -- A team member will try to reproduce the issue with your provided steps. If there are no reproduction steps or no obvious way to reproduce the issue, the team will ask you for those steps and mark the issue as `needs-repro`. Bugs with the `needs-repro` tag will not be addressed until they are reproduced. -- If the team is able to reproduce the issue, it will be marked `needs-fix`, as well as possibly other tags (such as `critical`), and the issue will be left to be implemented by someone. - -### Suggesting Enhancements - -This section guides you through submitting an enhancement suggestion for mergo, **including completely new features and minor improvements to existing functionality**. Following these guidelines will help maintainers and the community to understand your suggestion and find related suggestions. - - -#### Before Submitting an Enhancement - -- Make sure that you are using the latest version. -- Read the [documentation]() carefully and find out if the functionality is already covered, maybe by an individual configuration. -- Perform a [search](https://github.com/imdario/mergo/issues) to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one. -- Find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Keep in mind that we want features that will be useful to the majority of our users and not just a small subset. If you're just targeting a minority of users, consider writing an add-on/plugin library. - - -#### How Do I Submit a Good Enhancement Suggestion? - -Enhancement suggestions are tracked as [GitHub issues](https://github.com/imdario/mergo/issues). - -- Use a **clear and descriptive title** for the issue to identify the suggestion. -- Provide a **step-by-step description of the suggested enhancement** in as many details as possible. -- **Describe the current behavior** and **explain which behavior you expected to see instead** and why. At this point you can also tell which alternatives do not work for you. -- You may want to **include screenshots and animated GIFs** which help you demonstrate the steps or point out the part which the suggestion is related to. You can use [this tool](https://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux. -- **Explain why this enhancement would be useful** to most mergo users. You may also want to point out the other projects that solved it better and which could serve as inspiration. - - -## Attribution -This guide is based on the **contributing-gen**. [Make your own](https://github.com/bttger/contributing-gen)! diff --git a/vendor/dario.cat/mergo/LICENSE b/vendor/dario.cat/mergo/LICENSE deleted file mode 100644 index 686680298..000000000 --- a/vendor/dario.cat/mergo/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright (c) 2013 Dario Castañé. All rights reserved. -Copyright (c) 2012 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/dario.cat/mergo/README.md b/vendor/dario.cat/mergo/README.md deleted file mode 100644 index 7d0cf9f32..000000000 --- a/vendor/dario.cat/mergo/README.md +++ /dev/null @@ -1,248 +0,0 @@ -# Mergo - -[![GitHub release][5]][6] -[![GoCard][7]][8] -[![Test status][1]][2] -[![OpenSSF Scorecard][21]][22] -[![OpenSSF Best Practices][19]][20] -[![Coverage status][9]][10] -[![Sourcegraph][11]][12] -[![FOSSA status][13]][14] - -[![GoDoc][3]][4] -[![Become my sponsor][15]][16] -[![Tidelift][17]][18] - -[1]: https://github.com/imdario/mergo/workflows/tests/badge.svg?branch=master -[2]: https://github.com/imdario/mergo/actions/workflows/tests.yml -[3]: https://godoc.org/github.com/imdario/mergo?status.svg -[4]: https://godoc.org/github.com/imdario/mergo -[5]: https://img.shields.io/github/release/imdario/mergo.svg -[6]: https://github.com/imdario/mergo/releases -[7]: https://goreportcard.com/badge/imdario/mergo -[8]: https://goreportcard.com/report/github.com/imdario/mergo -[9]: https://coveralls.io/repos/github/imdario/mergo/badge.svg?branch=master -[10]: https://coveralls.io/github/imdario/mergo?branch=master -[11]: https://sourcegraph.com/github.com/imdario/mergo/-/badge.svg -[12]: https://sourcegraph.com/github.com/imdario/mergo?badge -[13]: https://app.fossa.io/api/projects/git%2Bgithub.com%2Fimdario%2Fmergo.svg?type=shield -[14]: https://app.fossa.io/projects/git%2Bgithub.com%2Fimdario%2Fmergo?ref=badge_shield -[15]: https://img.shields.io/github/sponsors/imdario -[16]: https://github.com/sponsors/imdario -[17]: https://tidelift.com/badges/package/go/github.com%2Fimdario%2Fmergo -[18]: https://tidelift.com/subscription/pkg/go-github.com-imdario-mergo -[19]: https://bestpractices.coreinfrastructure.org/projects/7177/badge -[20]: https://bestpractices.coreinfrastructure.org/projects/7177 -[21]: https://api.securityscorecards.dev/projects/github.com/imdario/mergo/badge -[22]: https://api.securityscorecards.dev/projects/github.com/imdario/mergo - -A helper to merge structs and maps in Golang. Useful for configuration default values, avoiding messy if-statements. - -Mergo merges same-type structs and maps by setting default values in zero-value fields. Mergo won't merge unexported (private) fields. It will do recursively any exported one. It also won't merge structs inside maps (because they are not addressable using Go reflection). - -Also a lovely [comune](http://en.wikipedia.org/wiki/Mergo) (municipality) in the Province of Ancona in the Italian region of Marche. - -## Status - -It is ready for production use. [It is used in several projects by Docker, Google, The Linux Foundation, VMWare, Shopify, Microsoft, etc](https://github.com/imdario/mergo#mergo-in-the-wild). - -### Important notes - -#### 1.0.0 - -In [1.0.0](//github.com/imdario/mergo/releases/tag/1.0.0) Mergo moves to a vanity URL `dario.cat/mergo`. - -#### 0.3.9 - -Please keep in mind that a problematic PR broke [0.3.9](//github.com/imdario/mergo/releases/tag/0.3.9). I reverted it in [0.3.10](//github.com/imdario/mergo/releases/tag/0.3.10), and I consider it stable but not bug-free. Also, this version adds support for go modules. - -Keep in mind that in [0.3.2](//github.com/imdario/mergo/releases/tag/0.3.2), Mergo changed `Merge()`and `Map()` signatures to support [transformers](#transformers). I added an optional/variadic argument so that it won't break the existing code. - -If you were using Mergo before April 6th, 2015, please check your project works as intended after updating your local copy with ```go get -u dario.cat/mergo```. I apologize for any issue caused by its previous behavior and any future bug that Mergo could cause in existing projects after the change (release 0.2.0). - -### Donations - -If Mergo is useful to you, consider buying me a coffee, a beer, or making a monthly donation to allow me to keep building great free software. :heart_eyes: - -Buy Me a Coffee at ko-fi.com -Donate using Liberapay -Become my sponsor - -### Mergo in the wild - -- [moby/moby](https://github.com/moby/moby) -- [kubernetes/kubernetes](https://github.com/kubernetes/kubernetes) -- [vmware/dispatch](https://github.com/vmware/dispatch) -- [Shopify/themekit](https://github.com/Shopify/themekit) -- [imdario/zas](https://github.com/imdario/zas) -- [matcornic/hermes](https://github.com/matcornic/hermes) -- [OpenBazaar/openbazaar-go](https://github.com/OpenBazaar/openbazaar-go) -- [kataras/iris](https://github.com/kataras/iris) -- [michaelsauter/crane](https://github.com/michaelsauter/crane) -- [go-task/task](https://github.com/go-task/task) -- [sensu/uchiwa](https://github.com/sensu/uchiwa) -- [ory/hydra](https://github.com/ory/hydra) -- [sisatech/vcli](https://github.com/sisatech/vcli) -- [dairycart/dairycart](https://github.com/dairycart/dairycart) -- [projectcalico/felix](https://github.com/projectcalico/felix) -- [resin-os/balena](https://github.com/resin-os/balena) -- [go-kivik/kivik](https://github.com/go-kivik/kivik) -- [Telefonica/govice](https://github.com/Telefonica/govice) -- [supergiant/supergiant](supergiant/supergiant) -- [SergeyTsalkov/brooce](https://github.com/SergeyTsalkov/brooce) -- [soniah/dnsmadeeasy](https://github.com/soniah/dnsmadeeasy) -- [ohsu-comp-bio/funnel](https://github.com/ohsu-comp-bio/funnel) -- [EagerIO/Stout](https://github.com/EagerIO/Stout) -- [lynndylanhurley/defsynth-api](https://github.com/lynndylanhurley/defsynth-api) -- [russross/canvasassignments](https://github.com/russross/canvasassignments) -- [rdegges/cryptly-api](https://github.com/rdegges/cryptly-api) -- [casualjim/exeggutor](https://github.com/casualjim/exeggutor) -- [divshot/gitling](https://github.com/divshot/gitling) -- [RWJMurphy/gorl](https://github.com/RWJMurphy/gorl) -- [andrerocker/deploy42](https://github.com/andrerocker/deploy42) -- [elwinar/rambler](https://github.com/elwinar/rambler) -- [tmaiaroto/gopartman](https://github.com/tmaiaroto/gopartman) -- [jfbus/impressionist](https://github.com/jfbus/impressionist) -- [Jmeyering/zealot](https://github.com/Jmeyering/zealot) -- [godep-migrator/rigger-host](https://github.com/godep-migrator/rigger-host) -- [Dronevery/MultiwaySwitch-Go](https://github.com/Dronevery/MultiwaySwitch-Go) -- [thoas/picfit](https://github.com/thoas/picfit) -- [mantasmatelis/whooplist-server](https://github.com/mantasmatelis/whooplist-server) -- [jnuthong/item_search](https://github.com/jnuthong/item_search) -- [bukalapak/snowboard](https://github.com/bukalapak/snowboard) -- [containerssh/containerssh](https://github.com/containerssh/containerssh) -- [goreleaser/goreleaser](https://github.com/goreleaser/goreleaser) -- [tjpnz/structbot](https://github.com/tjpnz/structbot) - -## Install - - go get dario.cat/mergo - - // use in your .go code - import ( - "dario.cat/mergo" - ) - -## Usage - -You can only merge same-type structs with exported fields initialized as zero value of their type and same-types maps. Mergo won't merge unexported (private) fields but will do recursively any exported one. It won't merge empty structs value as [they are zero values](https://golang.org/ref/spec#The_zero_value) too. Also, maps will be merged recursively except for structs inside maps (because they are not addressable using Go reflection). - -```go -if err := mergo.Merge(&dst, src); err != nil { - // ... -} -``` - -Also, you can merge overwriting values using the transformer `WithOverride`. - -```go -if err := mergo.Merge(&dst, src, mergo.WithOverride); err != nil { - // ... -} -``` - -Additionally, you can map a `map[string]interface{}` to a struct (and otherwise, from struct to map), following the same restrictions as in `Merge()`. Keys are capitalized to find each corresponding exported field. - -```go -if err := mergo.Map(&dst, srcMap); err != nil { - // ... -} -``` - -Warning: if you map a struct to map, it won't do it recursively. Don't expect Mergo to map struct members of your struct as `map[string]interface{}`. They will be just assigned as values. - -Here is a nice example: - -```go -package main - -import ( - "fmt" - "dario.cat/mergo" -) - -type Foo struct { - A string - B int64 -} - -func main() { - src := Foo{ - A: "one", - B: 2, - } - dest := Foo{ - A: "two", - } - mergo.Merge(&dest, src) - fmt.Println(dest) - // Will print - // {two 2} -} -``` - -Note: if test are failing due missing package, please execute: - - go get gopkg.in/yaml.v3 - -### Transformers - -Transformers allow to merge specific types differently than in the default behavior. In other words, now you can customize how some types are merged. For example, `time.Time` is a struct; it doesn't have zero value but IsZero can return true because it has fields with zero value. How can we merge a non-zero `time.Time`? - -```go -package main - -import ( - "fmt" - "dario.cat/mergo" - "reflect" - "time" -) - -type timeTransformer struct { -} - -func (t timeTransformer) Transformer(typ reflect.Type) func(dst, src reflect.Value) error { - if typ == reflect.TypeOf(time.Time{}) { - return func(dst, src reflect.Value) error { - if dst.CanSet() { - isZero := dst.MethodByName("IsZero") - result := isZero.Call([]reflect.Value{}) - if result[0].Bool() { - dst.Set(src) - } - } - return nil - } - } - return nil -} - -type Snapshot struct { - Time time.Time - // ... -} - -func main() { - src := Snapshot{time.Now()} - dest := Snapshot{} - mergo.Merge(&dest, src, mergo.WithTransformers(timeTransformer{})) - fmt.Println(dest) - // Will print - // { 2018-01-12 01:15:00 +0000 UTC m=+0.000000001 } -} -``` - -## Contact me - -If I can help you, you have an idea or you are using Mergo in your projects, don't hesitate to drop me a line (or a pull request): [@im_dario](https://twitter.com/im_dario) - -## About - -Written by [Dario Castañé](http://dario.im). - -## License - -[BSD 3-Clause](http://opensource.org/licenses/BSD-3-Clause) license, as [Go language](http://golang.org/LICENSE). - -[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fimdario%2Fmergo.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fimdario%2Fmergo?ref=badge_large) diff --git a/vendor/dario.cat/mergo/SECURITY.md b/vendor/dario.cat/mergo/SECURITY.md deleted file mode 100644 index a5de61f77..000000000 --- a/vendor/dario.cat/mergo/SECURITY.md +++ /dev/null @@ -1,14 +0,0 @@ -# Security Policy - -## Supported Versions - -| Version | Supported | -| ------- | ------------------ | -| 0.3.x | :white_check_mark: | -| < 0.3 | :x: | - -## Security contact information - -To report a security vulnerability, please use the -[Tidelift security contact](https://tidelift.com/security). -Tidelift will coordinate the fix and disclosure. diff --git a/vendor/dario.cat/mergo/doc.go b/vendor/dario.cat/mergo/doc.go deleted file mode 100644 index 7d96ec054..000000000 --- a/vendor/dario.cat/mergo/doc.go +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright 2013 Dario Castañé. All rights reserved. -// 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. - -/* -A helper to merge structs and maps in Golang. Useful for configuration default values, avoiding messy if-statements. - -Mergo merges same-type structs and maps by setting default values in zero-value fields. Mergo won't merge unexported (private) fields. It will do recursively any exported one. It also won't merge structs inside maps (because they are not addressable using Go reflection). - -# Status - -It is ready for production use. It is used in several projects by Docker, Google, The Linux Foundation, VMWare, Shopify, etc. - -# Important notes - -1.0.0 - -In 1.0.0 Mergo moves to a vanity URL `dario.cat/mergo`. - -0.3.9 - -Please keep in mind that a problematic PR broke 0.3.9. We reverted it in 0.3.10. We consider 0.3.10 as stable but not bug-free. . Also, this version adds suppot for go modules. - -Keep in mind that in 0.3.2, Mergo changed Merge() and Map() signatures to support transformers. We added an optional/variadic argument so that it won't break the existing code. - -If you were using Mergo before April 6th, 2015, please check your project works as intended after updating your local copy with go get -u dario.cat/mergo. I apologize for any issue caused by its previous behavior and any future bug that Mergo could cause in existing projects after the change (release 0.2.0). - -# Install - -Do your usual installation procedure: - - go get dario.cat/mergo - - // use in your .go code - import ( - "dario.cat/mergo" - ) - -# Usage - -You can only merge same-type structs with exported fields initialized as zero value of their type and same-types maps. Mergo won't merge unexported (private) fields but will do recursively any exported one. It won't merge empty structs value as they are zero values too. Also, maps will be merged recursively except for structs inside maps (because they are not addressable using Go reflection). - - if err := mergo.Merge(&dst, src); err != nil { - // ... - } - -Also, you can merge overwriting values using the transformer WithOverride. - - if err := mergo.Merge(&dst, src, mergo.WithOverride); err != nil { - // ... - } - -Additionally, you can map a map[string]interface{} to a struct (and otherwise, from struct to map), following the same restrictions as in Merge(). Keys are capitalized to find each corresponding exported field. - - if err := mergo.Map(&dst, srcMap); err != nil { - // ... - } - -Warning: if you map a struct to map, it won't do it recursively. Don't expect Mergo to map struct members of your struct as map[string]interface{}. They will be just assigned as values. - -Here is a nice example: - - package main - - import ( - "fmt" - "dario.cat/mergo" - ) - - type Foo struct { - A string - B int64 - } - - func main() { - src := Foo{ - A: "one", - B: 2, - } - dest := Foo{ - A: "two", - } - mergo.Merge(&dest, src) - fmt.Println(dest) - // Will print - // {two 2} - } - -# Transformers - -Transformers allow to merge specific types differently than in the default behavior. In other words, now you can customize how some types are merged. For example, time.Time is a struct; it doesn't have zero value but IsZero can return true because it has fields with zero value. How can we merge a non-zero time.Time? - - package main - - import ( - "fmt" - "dario.cat/mergo" - "reflect" - "time" - ) - - type timeTransformer struct { - } - - func (t timeTransformer) Transformer(typ reflect.Type) func(dst, src reflect.Value) error { - if typ == reflect.TypeOf(time.Time{}) { - return func(dst, src reflect.Value) error { - if dst.CanSet() { - isZero := dst.MethodByName("IsZero") - result := isZero.Call([]reflect.Value{}) - if result[0].Bool() { - dst.Set(src) - } - } - return nil - } - } - return nil - } - - type Snapshot struct { - Time time.Time - // ... - } - - func main() { - src := Snapshot{time.Now()} - dest := Snapshot{} - mergo.Merge(&dest, src, mergo.WithTransformers(timeTransformer{})) - fmt.Println(dest) - // Will print - // { 2018-01-12 01:15:00 +0000 UTC m=+0.000000001 } - } - -# Contact me - -If I can help you, you have an idea or you are using Mergo in your projects, don't hesitate to drop me a line (or a pull request): https://twitter.com/im_dario - -# About - -Written by Dario Castañé: https://da.rio.hn - -# License - -BSD 3-Clause license, as Go language. -*/ -package mergo diff --git a/vendor/dario.cat/mergo/map.go b/vendor/dario.cat/mergo/map.go deleted file mode 100644 index b50d5c2a4..000000000 --- a/vendor/dario.cat/mergo/map.go +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright 2014 Dario Castañé. All rights reserved. -// 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. - -// Based on src/pkg/reflect/deepequal.go from official -// golang's stdlib. - -package mergo - -import ( - "fmt" - "reflect" - "unicode" - "unicode/utf8" -) - -func changeInitialCase(s string, mapper func(rune) rune) string { - if s == "" { - return s - } - r, n := utf8.DecodeRuneInString(s) - return string(mapper(r)) + s[n:] -} - -func isExported(field reflect.StructField) bool { - r, _ := utf8.DecodeRuneInString(field.Name) - return r >= 'A' && r <= 'Z' -} - -// Traverses recursively both values, assigning src's fields values to dst. -// The map argument tracks comparisons that have already been seen, which allows -// short circuiting on recursive types. -func deepMap(dst, src reflect.Value, visited map[uintptr]*visit, depth int, config *Config) (err error) { - overwrite := config.Overwrite - if dst.CanAddr() { - addr := dst.UnsafeAddr() - h := 17 * addr - seen := visited[h] - typ := dst.Type() - for p := seen; p != nil; p = p.next { - if p.ptr == addr && p.typ == typ { - return nil - } - } - // Remember, remember... - visited[h] = &visit{typ, seen, addr} - } - zeroValue := reflect.Value{} - switch dst.Kind() { - case reflect.Map: - dstMap := dst.Interface().(map[string]interface{}) - for i, n := 0, src.NumField(); i < n; i++ { - srcType := src.Type() - field := srcType.Field(i) - if !isExported(field) { - continue - } - fieldName := field.Name - fieldName = changeInitialCase(fieldName, unicode.ToLower) - if v, ok := dstMap[fieldName]; !ok || (isEmptyValue(reflect.ValueOf(v), !config.ShouldNotDereference) || overwrite) { - dstMap[fieldName] = src.Field(i).Interface() - } - } - case reflect.Ptr: - if dst.IsNil() { - v := reflect.New(dst.Type().Elem()) - dst.Set(v) - } - dst = dst.Elem() - fallthrough - case reflect.Struct: - srcMap := src.Interface().(map[string]interface{}) - for key := range srcMap { - config.overwriteWithEmptyValue = true - srcValue := srcMap[key] - fieldName := changeInitialCase(key, unicode.ToUpper) - dstElement := dst.FieldByName(fieldName) - if dstElement == zeroValue { - // We discard it because the field doesn't exist. - continue - } - srcElement := reflect.ValueOf(srcValue) - dstKind := dstElement.Kind() - srcKind := srcElement.Kind() - if srcKind == reflect.Ptr && dstKind != reflect.Ptr { - srcElement = srcElement.Elem() - srcKind = reflect.TypeOf(srcElement.Interface()).Kind() - } else if dstKind == reflect.Ptr { - // Can this work? I guess it can't. - if srcKind != reflect.Ptr && srcElement.CanAddr() { - srcPtr := srcElement.Addr() - srcElement = reflect.ValueOf(srcPtr) - srcKind = reflect.Ptr - } - } - - if !srcElement.IsValid() { - continue - } - if srcKind == dstKind { - if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil { - return - } - } else if dstKind == reflect.Interface && dstElement.Kind() == reflect.Interface { - if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil { - return - } - } else if srcKind == reflect.Map { - if err = deepMap(dstElement, srcElement, visited, depth+1, config); err != nil { - return - } - } else { - return fmt.Errorf("type mismatch on %s field: found %v, expected %v", fieldName, srcKind, dstKind) - } - } - } - return -} - -// Map sets fields' values in dst from src. -// src can be a map with string keys or a struct. dst must be the opposite: -// if src is a map, dst must be a valid pointer to struct. If src is a struct, -// dst must be map[string]interface{}. -// It won't merge unexported (private) fields and will do recursively -// any exported field. -// If dst is a map, keys will be src fields' names in lower camel case. -// Missing key in src that doesn't match a field in dst will be skipped. This -// doesn't apply if dst is a map. -// This is separated method from Merge because it is cleaner and it keeps sane -// semantics: merging equal types, mapping different (restricted) types. -func Map(dst, src interface{}, opts ...func(*Config)) error { - return _map(dst, src, opts...) -} - -// MapWithOverwrite will do the same as Map except that non-empty dst attributes will be overridden by -// non-empty src attribute values. -// Deprecated: Use Map(…) with WithOverride -func MapWithOverwrite(dst, src interface{}, opts ...func(*Config)) error { - return _map(dst, src, append(opts, WithOverride)...) -} - -func _map(dst, src interface{}, opts ...func(*Config)) error { - if dst != nil && reflect.ValueOf(dst).Kind() != reflect.Ptr { - return ErrNonPointerArgument - } - var ( - vDst, vSrc reflect.Value - err error - ) - config := &Config{} - - for _, opt := range opts { - opt(config) - } - - if vDst, vSrc, err = resolveValues(dst, src); err != nil { - return err - } - // To be friction-less, we redirect equal-type arguments - // to deepMerge. Only because arguments can be anything. - if vSrc.Kind() == vDst.Kind() { - return deepMerge(vDst, vSrc, make(map[uintptr]*visit), 0, config) - } - switch vSrc.Kind() { - case reflect.Struct: - if vDst.Kind() != reflect.Map { - return ErrExpectedMapAsDestination - } - case reflect.Map: - if vDst.Kind() != reflect.Struct { - return ErrExpectedStructAsDestination - } - default: - return ErrNotSupported - } - return deepMap(vDst, vSrc, make(map[uintptr]*visit), 0, config) -} diff --git a/vendor/dario.cat/mergo/merge.go b/vendor/dario.cat/mergo/merge.go deleted file mode 100644 index 0ef9b2138..000000000 --- a/vendor/dario.cat/mergo/merge.go +++ /dev/null @@ -1,409 +0,0 @@ -// Copyright 2013 Dario Castañé. All rights reserved. -// 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. - -// Based on src/pkg/reflect/deepequal.go from official -// golang's stdlib. - -package mergo - -import ( - "fmt" - "reflect" -) - -func hasMergeableFields(dst reflect.Value) (exported bool) { - for i, n := 0, dst.NumField(); i < n; i++ { - field := dst.Type().Field(i) - if field.Anonymous && dst.Field(i).Kind() == reflect.Struct { - exported = exported || hasMergeableFields(dst.Field(i)) - } else if isExportedComponent(&field) { - exported = exported || len(field.PkgPath) == 0 - } - } - return -} - -func isExportedComponent(field *reflect.StructField) bool { - pkgPath := field.PkgPath - if len(pkgPath) > 0 { - return false - } - c := field.Name[0] - if 'a' <= c && c <= 'z' || c == '_' { - return false - } - return true -} - -type Config struct { - Transformers Transformers - Overwrite bool - ShouldNotDereference bool - AppendSlice bool - TypeCheck bool - overwriteWithEmptyValue bool - overwriteSliceWithEmptyValue bool - sliceDeepCopy bool - debug bool -} - -type Transformers interface { - Transformer(reflect.Type) func(dst, src reflect.Value) error -} - -// Traverses recursively both values, assigning src's fields values to dst. -// The map argument tracks comparisons that have already been seen, which allows -// short circuiting on recursive types. -func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, config *Config) (err error) { - overwrite := config.Overwrite - typeCheck := config.TypeCheck - overwriteWithEmptySrc := config.overwriteWithEmptyValue - overwriteSliceWithEmptySrc := config.overwriteSliceWithEmptyValue - sliceDeepCopy := config.sliceDeepCopy - - if !src.IsValid() { - return - } - if dst.CanAddr() { - addr := dst.UnsafeAddr() - h := 17 * addr - seen := visited[h] - typ := dst.Type() - for p := seen; p != nil; p = p.next { - if p.ptr == addr && p.typ == typ { - return nil - } - } - // Remember, remember... - visited[h] = &visit{typ, seen, addr} - } - - if config.Transformers != nil && !isReflectNil(dst) && dst.IsValid() { - if fn := config.Transformers.Transformer(dst.Type()); fn != nil { - err = fn(dst, src) - return - } - } - - switch dst.Kind() { - case reflect.Struct: - if hasMergeableFields(dst) { - for i, n := 0, dst.NumField(); i < n; i++ { - if err = deepMerge(dst.Field(i), src.Field(i), visited, depth+1, config); err != nil { - return - } - } - } else { - if dst.CanSet() && (isReflectNil(dst) || overwrite) && (!isEmptyValue(src, !config.ShouldNotDereference) || overwriteWithEmptySrc) { - dst.Set(src) - } - } - case reflect.Map: - if dst.IsNil() && !src.IsNil() { - if dst.CanSet() { - dst.Set(reflect.MakeMap(dst.Type())) - } else { - dst = src - return - } - } - - if src.Kind() != reflect.Map { - if overwrite && dst.CanSet() { - dst.Set(src) - } - return - } - - for _, key := range src.MapKeys() { - srcElement := src.MapIndex(key) - if !srcElement.IsValid() { - continue - } - dstElement := dst.MapIndex(key) - switch srcElement.Kind() { - case reflect.Chan, reflect.Func, reflect.Map, reflect.Interface, reflect.Slice: - if srcElement.IsNil() { - if overwrite { - dst.SetMapIndex(key, srcElement) - } - continue - } - fallthrough - default: - if !srcElement.CanInterface() { - continue - } - switch reflect.TypeOf(srcElement.Interface()).Kind() { - case reflect.Struct: - fallthrough - case reflect.Ptr: - fallthrough - case reflect.Map: - srcMapElm := srcElement - dstMapElm := dstElement - if srcMapElm.CanInterface() { - srcMapElm = reflect.ValueOf(srcMapElm.Interface()) - if dstMapElm.IsValid() { - dstMapElm = reflect.ValueOf(dstMapElm.Interface()) - } - } - if err = deepMerge(dstMapElm, srcMapElm, visited, depth+1, config); err != nil { - return - } - case reflect.Slice: - srcSlice := reflect.ValueOf(srcElement.Interface()) - - var dstSlice reflect.Value - if !dstElement.IsValid() || dstElement.IsNil() { - dstSlice = reflect.MakeSlice(srcSlice.Type(), 0, srcSlice.Len()) - } else { - dstSlice = reflect.ValueOf(dstElement.Interface()) - } - - if (!isEmptyValue(src, !config.ShouldNotDereference) || overwriteWithEmptySrc || overwriteSliceWithEmptySrc) && (overwrite || isEmptyValue(dst, !config.ShouldNotDereference)) && !config.AppendSlice && !sliceDeepCopy { - if typeCheck && srcSlice.Type() != dstSlice.Type() { - return fmt.Errorf("cannot override two slices with different type (%s, %s)", srcSlice.Type(), dstSlice.Type()) - } - dstSlice = srcSlice - } else if config.AppendSlice { - if srcSlice.Type() != dstSlice.Type() { - return fmt.Errorf("cannot append two slices with different type (%s, %s)", srcSlice.Type(), dstSlice.Type()) - } - dstSlice = reflect.AppendSlice(dstSlice, srcSlice) - } else if sliceDeepCopy { - i := 0 - for ; i < srcSlice.Len() && i < dstSlice.Len(); i++ { - srcElement := srcSlice.Index(i) - dstElement := dstSlice.Index(i) - - if srcElement.CanInterface() { - srcElement = reflect.ValueOf(srcElement.Interface()) - } - if dstElement.CanInterface() { - dstElement = reflect.ValueOf(dstElement.Interface()) - } - - if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil { - return - } - } - - } - dst.SetMapIndex(key, dstSlice) - } - } - - if dstElement.IsValid() && !isEmptyValue(dstElement, !config.ShouldNotDereference) { - if reflect.TypeOf(srcElement.Interface()).Kind() == reflect.Slice { - continue - } - if reflect.TypeOf(srcElement.Interface()).Kind() == reflect.Map && reflect.TypeOf(dstElement.Interface()).Kind() == reflect.Map { - continue - } - } - - if srcElement.IsValid() && ((srcElement.Kind() != reflect.Ptr && overwrite) || !dstElement.IsValid() || isEmptyValue(dstElement, !config.ShouldNotDereference)) { - if dst.IsNil() { - dst.Set(reflect.MakeMap(dst.Type())) - } - dst.SetMapIndex(key, srcElement) - } - } - - // Ensure that all keys in dst are deleted if they are not in src. - if overwriteWithEmptySrc { - for _, key := range dst.MapKeys() { - srcElement := src.MapIndex(key) - if !srcElement.IsValid() { - dst.SetMapIndex(key, reflect.Value{}) - } - } - } - case reflect.Slice: - if !dst.CanSet() { - break - } - if (!isEmptyValue(src, !config.ShouldNotDereference) || overwriteWithEmptySrc || overwriteSliceWithEmptySrc) && (overwrite || isEmptyValue(dst, !config.ShouldNotDereference)) && !config.AppendSlice && !sliceDeepCopy { - dst.Set(src) - } else if config.AppendSlice { - if src.Type() != dst.Type() { - return fmt.Errorf("cannot append two slice with different type (%s, %s)", src.Type(), dst.Type()) - } - dst.Set(reflect.AppendSlice(dst, src)) - } else if sliceDeepCopy { - for i := 0; i < src.Len() && i < dst.Len(); i++ { - srcElement := src.Index(i) - dstElement := dst.Index(i) - if srcElement.CanInterface() { - srcElement = reflect.ValueOf(srcElement.Interface()) - } - if dstElement.CanInterface() { - dstElement = reflect.ValueOf(dstElement.Interface()) - } - - if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil { - return - } - } - } - case reflect.Ptr: - fallthrough - case reflect.Interface: - if isReflectNil(src) { - if overwriteWithEmptySrc && dst.CanSet() && src.Type().AssignableTo(dst.Type()) { - dst.Set(src) - } - break - } - - if src.Kind() != reflect.Interface { - if dst.IsNil() || (src.Kind() != reflect.Ptr && overwrite) { - if dst.CanSet() && (overwrite || isEmptyValue(dst, !config.ShouldNotDereference)) { - dst.Set(src) - } - } else if src.Kind() == reflect.Ptr { - if !config.ShouldNotDereference { - if err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1, config); err != nil { - return - } - } else { - if overwriteWithEmptySrc || (overwrite && !src.IsNil()) || dst.IsNil() { - dst.Set(src) - } - } - } else if dst.Elem().Type() == src.Type() { - if err = deepMerge(dst.Elem(), src, visited, depth+1, config); err != nil { - return - } - } else { - return ErrDifferentArgumentsTypes - } - break - } - - if dst.IsNil() || overwrite { - if dst.CanSet() && (overwrite || isEmptyValue(dst, !config.ShouldNotDereference)) { - dst.Set(src) - } - break - } - - if dst.Elem().Kind() == src.Elem().Kind() { - if err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1, config); err != nil { - return - } - break - } - default: - mustSet := (isEmptyValue(dst, !config.ShouldNotDereference) || overwrite) && (!isEmptyValue(src, !config.ShouldNotDereference) || overwriteWithEmptySrc) - if mustSet { - if dst.CanSet() { - dst.Set(src) - } else { - dst = src - } - } - } - - return -} - -// Merge will fill any empty for value type attributes on the dst struct using corresponding -// src attributes if they themselves are not empty. dst and src must be valid same-type structs -// and dst must be a pointer to struct. -// It won't merge unexported (private) fields and will do recursively any exported field. -func Merge(dst, src interface{}, opts ...func(*Config)) error { - return merge(dst, src, opts...) -} - -// MergeWithOverwrite will do the same as Merge except that non-empty dst attributes will be overridden by -// non-empty src attribute values. -// Deprecated: use Merge(…) with WithOverride -func MergeWithOverwrite(dst, src interface{}, opts ...func(*Config)) error { - return merge(dst, src, append(opts, WithOverride)...) -} - -// WithTransformers adds transformers to merge, allowing to customize the merging of some types. -func WithTransformers(transformers Transformers) func(*Config) { - return func(config *Config) { - config.Transformers = transformers - } -} - -// WithOverride will make merge override non-empty dst attributes with non-empty src attributes values. -func WithOverride(config *Config) { - config.Overwrite = true -} - -// WithOverwriteWithEmptyValue will make merge override non empty dst attributes with empty src attributes values. -func WithOverwriteWithEmptyValue(config *Config) { - config.Overwrite = true - config.overwriteWithEmptyValue = true -} - -// WithOverrideEmptySlice will make merge override empty dst slice with empty src slice. -func WithOverrideEmptySlice(config *Config) { - config.overwriteSliceWithEmptyValue = true -} - -// WithoutDereference prevents dereferencing pointers when evaluating whether they are empty -// (i.e. a non-nil pointer is never considered empty). -func WithoutDereference(config *Config) { - config.ShouldNotDereference = true -} - -// WithAppendSlice will make merge append slices instead of overwriting it. -func WithAppendSlice(config *Config) { - config.AppendSlice = true -} - -// WithTypeCheck will make merge check types while overwriting it (must be used with WithOverride). -func WithTypeCheck(config *Config) { - config.TypeCheck = true -} - -// WithSliceDeepCopy will merge slice element one by one with Overwrite flag. -func WithSliceDeepCopy(config *Config) { - config.sliceDeepCopy = true - config.Overwrite = true -} - -func merge(dst, src interface{}, opts ...func(*Config)) error { - if dst != nil && reflect.ValueOf(dst).Kind() != reflect.Ptr { - return ErrNonPointerArgument - } - var ( - vDst, vSrc reflect.Value - err error - ) - - config := &Config{} - - for _, opt := range opts { - opt(config) - } - - if vDst, vSrc, err = resolveValues(dst, src); err != nil { - return err - } - if vDst.Type() != vSrc.Type() { - return ErrDifferentArgumentsTypes - } - return deepMerge(vDst, vSrc, make(map[uintptr]*visit), 0, config) -} - -// IsReflectNil is the reflect value provided nil -func isReflectNil(v reflect.Value) bool { - k := v.Kind() - switch k { - case reflect.Interface, reflect.Slice, reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr: - // Both interface and slice are nil if first word is 0. - // Both are always bigger than a word; assume flagIndir. - return v.IsNil() - default: - return false - } -} diff --git a/vendor/dario.cat/mergo/mergo.go b/vendor/dario.cat/mergo/mergo.go deleted file mode 100644 index 0a721e2d8..000000000 --- a/vendor/dario.cat/mergo/mergo.go +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2013 Dario Castañé. All rights reserved. -// 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. - -// Based on src/pkg/reflect/deepequal.go from official -// golang's stdlib. - -package mergo - -import ( - "errors" - "reflect" -) - -// Errors reported by Mergo when it finds invalid arguments. -var ( - ErrNilArguments = errors.New("src and dst must not be nil") - ErrDifferentArgumentsTypes = errors.New("src and dst must be of same type") - ErrNotSupported = errors.New("only structs, maps, and slices are supported") - ErrExpectedMapAsDestination = errors.New("dst was expected to be a map") - ErrExpectedStructAsDestination = errors.New("dst was expected to be a struct") - ErrNonPointerArgument = errors.New("dst must be a pointer") -) - -// During deepMerge, must keep track of checks that are -// in progress. The comparison algorithm assumes that all -// checks in progress are true when it reencounters them. -// Visited are stored in a map indexed by 17 * a1 + a2; -type visit struct { - typ reflect.Type - next *visit - ptr uintptr -} - -// From src/pkg/encoding/json/encode.go. -func isEmptyValue(v reflect.Value, shouldDereference bool) bool { - switch v.Kind() { - case reflect.Array, reflect.Map, reflect.Slice, reflect.String: - return v.Len() == 0 - case reflect.Bool: - return !v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Interface, reflect.Ptr: - if v.IsNil() { - return true - } - if shouldDereference { - return isEmptyValue(v.Elem(), shouldDereference) - } - return false - case reflect.Func: - return v.IsNil() - case reflect.Invalid: - return true - } - return false -} - -func resolveValues(dst, src interface{}) (vDst, vSrc reflect.Value, err error) { - if dst == nil || src == nil { - err = ErrNilArguments - return - } - vDst = reflect.ValueOf(dst).Elem() - if vDst.Kind() != reflect.Struct && vDst.Kind() != reflect.Map && vDst.Kind() != reflect.Slice { - err = ErrNotSupported - return - } - vSrc = reflect.ValueOf(src) - // We check if vSrc is a pointer to dereference it. - if vSrc.Kind() == reflect.Ptr { - vSrc = vSrc.Elem() - } - return -} diff --git a/vendor/github.com/AdaLogics/go-fuzz-headers/LICENSE b/vendor/github.com/AdaLogics/go-fuzz-headers/LICENSE deleted file mode 100644 index 261eeb9e9..000000000 --- a/vendor/github.com/AdaLogics/go-fuzz-headers/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/AdaLogics/go-fuzz-headers/README.md b/vendor/github.com/AdaLogics/go-fuzz-headers/README.md deleted file mode 100644 index 0a0d60c74..000000000 --- a/vendor/github.com/AdaLogics/go-fuzz-headers/README.md +++ /dev/null @@ -1,93 +0,0 @@ -# go-fuzz-headers -This repository contains various helper functions for go fuzzing. It is mostly used in combination with [go-fuzz](https://github.com/dvyukov/go-fuzz), but compatibility with fuzzing in the standard library will also be supported. Any coverage guided fuzzing engine that provides an array or slice of bytes can be used with go-fuzz-headers. - - -## Usage -Using go-fuzz-headers is easy. First create a new consumer with the bytes provided by the fuzzing engine: - -```go -import ( - fuzz "github.com/AdaLogics/go-fuzz-headers" -) -data := []byte{'R', 'a', 'n', 'd', 'o', 'm'} -f := fuzz.NewConsumer(data) - -``` - -This creates a `Consumer` that consumes the bytes of the input as it uses them to fuzz different types. - -After that, `f` can be used to easily create fuzzed instances of different types. Below are some examples: - -### Structs -One of the most useful features of go-fuzz-headers is its ability to fill structs with the data provided by the fuzzing engine. This is done with a single line: -```go -type Person struct { - Name string - Age int -} -p := Person{} -// Fill p with values based on the data provided by the fuzzing engine: -err := f.GenerateStruct(&p) -``` - -This includes nested structs too. In this example, the fuzz Consumer will also insert values in `p.BestFriend`: -```go -type PersonI struct { - Name string - Age int - BestFriend PersonII -} -type PersonII struct { - Name string - Age int -} -p := PersonI{} -err := f.GenerateStruct(&p) -``` - -If the consumer should insert values for unexported fields as well as exported, this can be enabled with: - -```go -f.AllowUnexportedFields() -``` - -...and disabled with: - -```go -f.DisallowUnexportedFields() -``` - -### Other types: - -Other useful APIs: - -```go -createdString, err := f.GetString() // Gets a string -createdInt, err := f.GetInt() // Gets an integer -createdByte, err := f.GetByte() // Gets a byte -createdBytes, err := f.GetBytes() // Gets a byte slice -createdBool, err := f.GetBool() // Gets a boolean -err := f.FuzzMap(target_map) // Fills a map -createdTarBytes, err := f.TarBytes() // Gets bytes of a valid tar archive -err := f.CreateFiles(inThisDir) // Fills inThisDir with files -createdString, err := f.GetStringFrom("anyCharInThisString", ofThisLength) // Gets a string that consists of chars from "anyCharInThisString" and has the exact length "ofThisLength" -``` - -Most APIs are added as they are needed. - -## Projects that use go-fuzz-headers -- [runC](https://github.com/opencontainers/runc) -- [Istio](https://github.com/istio/istio) -- [Vitess](https://github.com/vitessio/vitess) -- [Containerd](https://github.com/containerd/containerd) - -Feel free to add your own project to the list, if you use go-fuzz-headers to fuzz it. - - - - -## Status -The project is under development and will be updated regularly. - -## References -go-fuzz-headers' approach to fuzzing structs is strongly inspired by [gofuzz](https://github.com/google/gofuzz). \ No newline at end of file diff --git a/vendor/github.com/AdaLogics/go-fuzz-headers/consumer.go b/vendor/github.com/AdaLogics/go-fuzz-headers/consumer.go deleted file mode 100644 index adfeedf5e..000000000 --- a/vendor/github.com/AdaLogics/go-fuzz-headers/consumer.go +++ /dev/null @@ -1,914 +0,0 @@ -// Copyright 2023 The go-fuzz-headers 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 gofuzzheaders - -import ( - "archive/tar" - "bytes" - "encoding/binary" - "errors" - "fmt" - "io" - "math" - "os" - "path/filepath" - "reflect" - "strconv" - "strings" - "time" - "unsafe" -) - -var ( - MaxTotalLen uint32 = 2000000 - maxDepth = 100 -) - -func SetMaxTotalLen(newLen uint32) { - MaxTotalLen = newLen -} - -type ConsumeFuzzer struct { - data []byte - dataTotal uint32 - CommandPart []byte - RestOfArray []byte - NumberOfCalls int - position uint32 - fuzzUnexportedFields bool - curDepth int - Funcs map[reflect.Type]reflect.Value -} - -func IsDivisibleBy(n int, divisibleby int) bool { - return (n % divisibleby) == 0 -} - -func NewConsumer(fuzzData []byte) *ConsumeFuzzer { - return &ConsumeFuzzer{ - data: fuzzData, - dataTotal: uint32(len(fuzzData)), - Funcs: make(map[reflect.Type]reflect.Value), - curDepth: 0, - } -} - -func (f *ConsumeFuzzer) Split(minCalls, maxCalls int) error { - if f.dataTotal == 0 { - return errors.New("could not split") - } - numberOfCalls := int(f.data[0]) - if numberOfCalls < minCalls || numberOfCalls > maxCalls { - return errors.New("bad number of calls") - } - if int(f.dataTotal) < numberOfCalls+numberOfCalls+1 { - return errors.New("length of data does not match required parameters") - } - - // Define part 2 and 3 of the data array - commandPart := f.data[1 : numberOfCalls+1] - restOfArray := f.data[numberOfCalls+1:] - - // Just a small check. It is necessary - if len(commandPart) != numberOfCalls { - return errors.New("length of commandPart does not match number of calls") - } - - // Check if restOfArray is divisible by numberOfCalls - if !IsDivisibleBy(len(restOfArray), numberOfCalls) { - return errors.New("length of commandPart does not match number of calls") - } - f.CommandPart = commandPart - f.RestOfArray = restOfArray - f.NumberOfCalls = numberOfCalls - return nil -} - -func (f *ConsumeFuzzer) AllowUnexportedFields() { - f.fuzzUnexportedFields = true -} - -func (f *ConsumeFuzzer) DisallowUnexportedFields() { - f.fuzzUnexportedFields = false -} - -func (f *ConsumeFuzzer) GenerateStruct(targetStruct interface{}) error { - e := reflect.ValueOf(targetStruct).Elem() - return f.fuzzStruct(e, false) -} - -func (f *ConsumeFuzzer) setCustom(v reflect.Value) error { - // First: see if we have a fuzz function for it. - doCustom, ok := f.Funcs[v.Type()] - if !ok { - return fmt.Errorf("could not find a custom function") - } - - switch v.Kind() { - case reflect.Ptr: - if v.IsNil() { - if !v.CanSet() { - return fmt.Errorf("could not use a custom function") - } - v.Set(reflect.New(v.Type().Elem())) - } - case reflect.Map: - if v.IsNil() { - if !v.CanSet() { - return fmt.Errorf("could not use a custom function") - } - v.Set(reflect.MakeMap(v.Type())) - } - default: - return fmt.Errorf("could not use a custom function") - } - - verr := doCustom.Call([]reflect.Value{v, reflect.ValueOf(Continue{ - F: f, - })}) - - // check if we return an error - if verr[0].IsNil() { - return nil - } - return fmt.Errorf("could not use a custom function") -} - -func (f *ConsumeFuzzer) fuzzStruct(e reflect.Value, customFunctions bool) error { - if f.curDepth >= maxDepth { - // return err or nil here? - return nil - } - f.curDepth++ - defer func() { f.curDepth-- }() - - // We check if we should check for custom functions - if customFunctions && e.IsValid() && e.CanAddr() { - err := f.setCustom(e.Addr()) - if err != nil { - return err - } - } - - switch e.Kind() { - case reflect.Struct: - for i := 0; i < e.NumField(); i++ { - var v reflect.Value - if !e.Field(i).CanSet() { - if f.fuzzUnexportedFields { - v = reflect.NewAt(e.Field(i).Type(), unsafe.Pointer(e.Field(i).UnsafeAddr())).Elem() - } - if err := f.fuzzStruct(v, customFunctions); err != nil { - return err - } - } else { - v = e.Field(i) - if err := f.fuzzStruct(v, customFunctions); err != nil { - return err - } - } - } - case reflect.String: - str, err := f.GetString() - if err != nil { - return err - } - if e.CanSet() { - e.SetString(str) - } - case reflect.Slice: - var maxElements uint32 - // Byte slices should not be restricted - if e.Type().String() == "[]uint8" { - maxElements = 10000000 - } else { - maxElements = 50 - } - - randQty, err := f.GetUint32() - if err != nil { - return err - } - numOfElements := randQty % maxElements - if (f.dataTotal - f.position) < numOfElements { - numOfElements = f.dataTotal - f.position - } - - uu := reflect.MakeSlice(e.Type(), int(numOfElements), int(numOfElements)) - - for i := 0; i < int(numOfElements); i++ { - // If we have more than 10, then we can proceed with that. - if err := f.fuzzStruct(uu.Index(i), customFunctions); err != nil { - if i >= 10 { - if e.CanSet() { - e.Set(uu) - } - return nil - } else { - return err - } - } - } - if e.CanSet() { - e.Set(uu) - } - case reflect.Uint16: - newInt, err := f.GetUint16() - if err != nil { - return err - } - if e.CanSet() { - e.SetUint(uint64(newInt)) - } - case reflect.Uint32: - newInt, err := f.GetUint32() - if err != nil { - return err - } - if e.CanSet() { - e.SetUint(uint64(newInt)) - } - case reflect.Uint64: - newInt, err := f.GetInt() - if err != nil { - return err - } - if e.CanSet() { - e.SetUint(uint64(newInt)) - } - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - newInt, err := f.GetInt() - if err != nil { - return err - } - if e.CanSet() { - e.SetInt(int64(newInt)) - } - case reflect.Float32: - newFloat, err := f.GetFloat32() - if err != nil { - return err - } - if e.CanSet() { - e.SetFloat(float64(newFloat)) - } - case reflect.Float64: - newFloat, err := f.GetFloat64() - if err != nil { - return err - } - if e.CanSet() { - e.SetFloat(float64(newFloat)) - } - case reflect.Map: - if e.CanSet() { - e.Set(reflect.MakeMap(e.Type())) - const maxElements = 50 - randQty, err := f.GetInt() - if err != nil { - return err - } - numOfElements := randQty % maxElements - for i := 0; i < numOfElements; i++ { - key := reflect.New(e.Type().Key()).Elem() - if err := f.fuzzStruct(key, customFunctions); err != nil { - return err - } - val := reflect.New(e.Type().Elem()).Elem() - if err = f.fuzzStruct(val, customFunctions); err != nil { - return err - } - e.SetMapIndex(key, val) - } - } - case reflect.Ptr: - if e.CanSet() { - e.Set(reflect.New(e.Type().Elem())) - if err := f.fuzzStruct(e.Elem(), customFunctions); err != nil { - return err - } - return nil - } - case reflect.Uint8: - b, err := f.GetByte() - if err != nil { - return err - } - if e.CanSet() { - e.SetUint(uint64(b)) - } - } - return nil -} - -func (f *ConsumeFuzzer) GetStringArray() (reflect.Value, error) { - // The max size of the array: - const max uint32 = 20 - - arraySize := f.position - if arraySize > max { - arraySize = max - } - stringArray := reflect.MakeSlice(reflect.SliceOf(reflect.TypeOf("string")), int(arraySize), int(arraySize)) - if f.position+arraySize >= f.dataTotal { - return stringArray, errors.New("could not make string array") - } - - for i := 0; i < int(arraySize); i++ { - stringSize := uint32(f.data[f.position]) - if f.position+stringSize >= f.dataTotal { - return stringArray, nil - } - stringToAppend := string(f.data[f.position : f.position+stringSize]) - strVal := reflect.ValueOf(stringToAppend) - stringArray = reflect.Append(stringArray, strVal) - f.position += stringSize - } - return stringArray, nil -} - -func (f *ConsumeFuzzer) GetInt() (int, error) { - if f.position >= f.dataTotal { - return 0, errors.New("not enough bytes to create int") - } - returnInt := int(f.data[f.position]) - f.position++ - return returnInt, nil -} - -func (f *ConsumeFuzzer) GetByte() (byte, error) { - if f.position >= f.dataTotal { - return 0x00, errors.New("not enough bytes to get byte") - } - returnByte := f.data[f.position] - f.position++ - return returnByte, nil -} - -func (f *ConsumeFuzzer) GetNBytes(numberOfBytes int) ([]byte, error) { - if f.position >= f.dataTotal { - return nil, errors.New("not enough bytes to get byte") - } - returnBytes := make([]byte, 0, numberOfBytes) - for i := 0; i < numberOfBytes; i++ { - newByte, err := f.GetByte() - if err != nil { - return nil, err - } - returnBytes = append(returnBytes, newByte) - } - return returnBytes, nil -} - -func (f *ConsumeFuzzer) GetUint16() (uint16, error) { - u16, err := f.GetNBytes(2) - if err != nil { - return 0, err - } - littleEndian, err := f.GetBool() - if err != nil { - return 0, err - } - if littleEndian { - return binary.LittleEndian.Uint16(u16), nil - } - return binary.BigEndian.Uint16(u16), nil -} - -func (f *ConsumeFuzzer) GetUint32() (uint32, error) { - u32, err := f.GetNBytes(4) - if err != nil { - return 0, err - } - return binary.BigEndian.Uint32(u32), nil -} - -func (f *ConsumeFuzzer) GetUint64() (uint64, error) { - u64, err := f.GetNBytes(8) - if err != nil { - return 0, err - } - littleEndian, err := f.GetBool() - if err != nil { - return 0, err - } - if littleEndian { - return binary.LittleEndian.Uint64(u64), nil - } - return binary.BigEndian.Uint64(u64), nil -} - -func (f *ConsumeFuzzer) GetBytes() ([]byte, error) { - var length uint32 - var err error - length, err = f.GetUint32() - if err != nil { - return nil, errors.New("not enough bytes to create byte array") - } - - if length == 0 { - length = 30 - } - bytesLeft := f.dataTotal - f.position - if bytesLeft <= 0 { - return nil, errors.New("not enough bytes to create byte array") - } - - // If the length is the same as bytes left, we will not overflow - // the remaining bytes. - if length != bytesLeft { - length = length % bytesLeft - } - byteBegin := f.position - if byteBegin+length < byteBegin { - return nil, errors.New("numbers overflow") - } - f.position = byteBegin + length - return f.data[byteBegin:f.position], nil -} - -func (f *ConsumeFuzzer) GetString() (string, error) { - if f.position >= f.dataTotal { - return "nil", errors.New("not enough bytes to create string") - } - length, err := f.GetUint32() - if err != nil { - return "nil", errors.New("not enough bytes to create string") - } - if f.position > MaxTotalLen { - return "nil", errors.New("created too large a string") - } - byteBegin := f.position - if byteBegin >= f.dataTotal { - return "nil", errors.New("not enough bytes to create string") - } - if byteBegin+length > f.dataTotal { - return "nil", errors.New("not enough bytes to create string") - } - if byteBegin > byteBegin+length { - return "nil", errors.New("numbers overflow") - } - f.position = byteBegin + length - return string(f.data[byteBegin:f.position]), nil -} - -func (f *ConsumeFuzzer) GetBool() (bool, error) { - if f.position >= f.dataTotal { - return false, errors.New("not enough bytes to create bool") - } - if IsDivisibleBy(int(f.data[f.position]), 2) { - f.position++ - return true, nil - } else { - f.position++ - return false, nil - } -} - -func (f *ConsumeFuzzer) FuzzMap(m interface{}) error { - return f.GenerateStruct(m) -} - -func returnTarBytes(buf []byte) ([]byte, error) { - return buf, nil - // Count files - var fileCounter int - tr := tar.NewReader(bytes.NewReader(buf)) - for { - _, err := tr.Next() - if err == io.EOF { - break - } - if err != nil { - return nil, err - } - fileCounter++ - } - if fileCounter >= 1 { - return buf, nil - } - return nil, fmt.Errorf("not enough files were created\n") -} - -func setTarHeaderFormat(hdr *tar.Header, f *ConsumeFuzzer) error { - ind, err := f.GetInt() - if err != nil { - hdr.Format = tar.FormatGNU - //return nil - } - switch ind % 4 { - case 0: - hdr.Format = tar.FormatUnknown - case 1: - hdr.Format = tar.FormatUSTAR - case 2: - hdr.Format = tar.FormatPAX - case 3: - hdr.Format = tar.FormatGNU - } - return nil -} - -func setTarHeaderTypeflag(hdr *tar.Header, f *ConsumeFuzzer) error { - ind, err := f.GetInt() - if err != nil { - return err - } - switch ind % 13 { - case 0: - hdr.Typeflag = tar.TypeReg - case 1: - hdr.Typeflag = tar.TypeLink - linkname, err := f.GetString() - if err != nil { - return err - } - hdr.Linkname = linkname - case 2: - hdr.Typeflag = tar.TypeSymlink - linkname, err := f.GetString() - if err != nil { - return err - } - hdr.Linkname = linkname - case 3: - hdr.Typeflag = tar.TypeChar - case 4: - hdr.Typeflag = tar.TypeBlock - case 5: - hdr.Typeflag = tar.TypeDir - case 6: - hdr.Typeflag = tar.TypeFifo - case 7: - hdr.Typeflag = tar.TypeCont - case 8: - hdr.Typeflag = tar.TypeXHeader - case 9: - hdr.Typeflag = tar.TypeXGlobalHeader - case 10: - hdr.Typeflag = tar.TypeGNUSparse - case 11: - hdr.Typeflag = tar.TypeGNULongName - case 12: - hdr.Typeflag = tar.TypeGNULongLink - } - return nil -} - -func (f *ConsumeFuzzer) createTarFileBody() ([]byte, error) { - return f.GetBytes() - /*length, err := f.GetUint32() - if err != nil { - return nil, errors.New("not enough bytes to create byte array") - } - - // A bit of optimization to attempt to create a file body - // when we don't have as many bytes left as "length" - remainingBytes := f.dataTotal - f.position - if remainingBytes <= 0 { - return nil, errors.New("created too large a string") - } - if f.position+length > MaxTotalLen { - return nil, errors.New("created too large a string") - } - byteBegin := f.position - if byteBegin >= f.dataTotal { - return nil, errors.New("not enough bytes to create byte array") - } - if length == 0 { - return nil, errors.New("zero-length is not supported") - } - if byteBegin+length >= f.dataTotal { - return nil, errors.New("not enough bytes to create byte array") - } - if byteBegin+length < byteBegin { - return nil, errors.New("numbers overflow") - } - f.position = byteBegin + length - return f.data[byteBegin:f.position], nil*/ -} - -// getTarFileName is similar to GetString(), but creates string based -// on the length of f.data to reduce the likelihood of overflowing -// f.data. -func (f *ConsumeFuzzer) getTarFilename() (string, error) { - return f.GetString() - /*length, err := f.GetUint32() - if err != nil { - return "nil", errors.New("not enough bytes to create string") - } - - // A bit of optimization to attempt to create a file name - // when we don't have as many bytes left as "length" - remainingBytes := f.dataTotal - f.position - if remainingBytes <= 0 { - return "nil", errors.New("created too large a string") - } - if f.position > MaxTotalLen { - return "nil", errors.New("created too large a string") - } - byteBegin := f.position - if byteBegin >= f.dataTotal { - return "nil", errors.New("not enough bytes to create string") - } - if byteBegin+length > f.dataTotal { - return "nil", errors.New("not enough bytes to create string") - } - if byteBegin > byteBegin+length { - return "nil", errors.New("numbers overflow") - } - f.position = byteBegin + length - return string(f.data[byteBegin:f.position]), nil*/ -} - -type TarFile struct { - Hdr *tar.Header - Body []byte -} - -// TarBytes returns valid bytes for a tar archive -func (f *ConsumeFuzzer) TarBytes() ([]byte, error) { - numberOfFiles, err := f.GetInt() - if err != nil { - return nil, err - } - var tarFiles []*TarFile - tarFiles = make([]*TarFile, 0) - - const maxNoOfFiles = 100 - for i := 0; i < numberOfFiles%maxNoOfFiles; i++ { - var filename string - var filebody []byte - var sec, nsec int - var err error - - filename, err = f.getTarFilename() - if err != nil { - var sb strings.Builder - sb.WriteString("file-") - sb.WriteString(strconv.Itoa(i)) - filename = sb.String() - } - filebody, err = f.createTarFileBody() - if err != nil { - var sb strings.Builder - sb.WriteString("filebody-") - sb.WriteString(strconv.Itoa(i)) - filebody = []byte(sb.String()) - } - - sec, err = f.GetInt() - if err != nil { - sec = 1672531200 // beginning of 2023 - } - nsec, err = f.GetInt() - if err != nil { - nsec = 1703980800 // end of 2023 - } - - hdr := &tar.Header{ - Name: filename, - Size: int64(len(filebody)), - Mode: 0o600, - ModTime: time.Unix(int64(sec), int64(nsec)), - } - if err := setTarHeaderTypeflag(hdr, f); err != nil { - return []byte(""), err - } - if err := setTarHeaderFormat(hdr, f); err != nil { - return []byte(""), err - } - tf := &TarFile{ - Hdr: hdr, - Body: filebody, - } - tarFiles = append(tarFiles, tf) - } - - var buf bytes.Buffer - tw := tar.NewWriter(&buf) - defer tw.Close() - - for _, tf := range tarFiles { - tw.WriteHeader(tf.Hdr) - tw.Write(tf.Body) - } - return buf.Bytes(), nil -} - -// This is similar to TarBytes, but it returns a series of -// files instead of raw tar bytes. The advantage of this -// api is that it is cheaper in terms of cpu power to -// modify or check the files in the fuzzer with TarFiles() -// because it avoids creating a tar reader. -func (f *ConsumeFuzzer) TarFiles() ([]*TarFile, error) { - numberOfFiles, err := f.GetInt() - if err != nil { - return nil, err - } - var tarFiles []*TarFile - tarFiles = make([]*TarFile, 0) - - const maxNoOfFiles = 100 - for i := 0; i < numberOfFiles%maxNoOfFiles; i++ { - filename, err := f.getTarFilename() - if err != nil { - return tarFiles, err - } - filebody, err := f.createTarFileBody() - if err != nil { - return tarFiles, err - } - - sec, err := f.GetInt() - if err != nil { - return tarFiles, err - } - nsec, err := f.GetInt() - if err != nil { - return tarFiles, err - } - - hdr := &tar.Header{ - Name: filename, - Size: int64(len(filebody)), - Mode: 0o600, - ModTime: time.Unix(int64(sec), int64(nsec)), - } - if err := setTarHeaderTypeflag(hdr, f); err != nil { - hdr.Typeflag = tar.TypeReg - } - if err := setTarHeaderFormat(hdr, f); err != nil { - return tarFiles, err // should not happend - } - tf := &TarFile{ - Hdr: hdr, - Body: filebody, - } - tarFiles = append(tarFiles, tf) - } - return tarFiles, nil -} - -// CreateFiles creates pseudo-random files in rootDir. -// It creates subdirs and places the files there. -// It is the callers responsibility to ensure that -// rootDir exists. -func (f *ConsumeFuzzer) CreateFiles(rootDir string) error { - numberOfFiles, err := f.GetInt() - if err != nil { - return err - } - maxNumberOfFiles := numberOfFiles % 4000 // This is completely arbitrary - if maxNumberOfFiles == 0 { - return errors.New("maxNumberOfFiles is nil") - } - - var noOfCreatedFiles int - for i := 0; i < maxNumberOfFiles; i++ { - // The file to create: - fileName, err := f.GetString() - if err != nil { - if noOfCreatedFiles > 0 { - // If files have been created, we don't return an error. - break - } else { - return errors.New("could not get fileName") - } - } - if strings.Contains(fileName, "..") || (len(fileName) > 0 && fileName[0] == 47) || strings.Contains(fileName, "\\") { - continue - } - fullFilePath := filepath.Join(rootDir, fileName) - - // Find the subdirectory of the file - if subDir := filepath.Dir(fileName); subDir != "" && subDir != "." { - // create the dir first; avoid going outside the root dir - if strings.Contains(subDir, "../") || (len(subDir) > 0 && subDir[0] == 47) || strings.Contains(subDir, "\\") { - continue - } - dirPath := filepath.Join(rootDir, subDir) - if _, err := os.Stat(dirPath); os.IsNotExist(err) { - err2 := os.MkdirAll(dirPath, 0o777) - if err2 != nil { - continue - } - } - fullFilePath = filepath.Join(dirPath, fileName) - } else { - // Create symlink - createSymlink, err := f.GetBool() - if err != nil { - if noOfCreatedFiles > 0 { - break - } else { - return errors.New("could not create the symlink") - } - } - if createSymlink { - symlinkTarget, err := f.GetString() - if err != nil { - return err - } - err = os.Symlink(symlinkTarget, fullFilePath) - if err != nil { - return err - } - // stop loop here, since a symlink needs no further action - noOfCreatedFiles++ - continue - } - // We create a normal file - fileContents, err := f.GetBytes() - if err != nil { - if noOfCreatedFiles > 0 { - break - } else { - return errors.New("could not create the file") - } - } - err = os.WriteFile(fullFilePath, fileContents, 0o666) - if err != nil { - continue - } - noOfCreatedFiles++ - } - } - return nil -} - -// GetStringFrom returns a string that can only consist of characters -// included in possibleChars. It returns an error if the created string -// does not have the specified length. -func (f *ConsumeFuzzer) GetStringFrom(possibleChars string, length int) (string, error) { - if (f.dataTotal - f.position) < uint32(length) { - return "", errors.New("not enough bytes to create a string") - } - output := make([]byte, 0, length) - for i := 0; i < length; i++ { - charIndex, err := f.GetInt() - if err != nil { - return string(output), err - } - output = append(output, possibleChars[charIndex%len(possibleChars)]) - } - return string(output), nil -} - -func (f *ConsumeFuzzer) GetRune() ([]rune, error) { - stringToConvert, err := f.GetString() - if err != nil { - return []rune("nil"), err - } - return []rune(stringToConvert), nil -} - -func (f *ConsumeFuzzer) GetFloat32() (float32, error) { - u32, err := f.GetNBytes(4) - if err != nil { - return 0, err - } - littleEndian, err := f.GetBool() - if err != nil { - return 0, err - } - if littleEndian { - u32LE := binary.LittleEndian.Uint32(u32) - return math.Float32frombits(u32LE), nil - } - u32BE := binary.BigEndian.Uint32(u32) - return math.Float32frombits(u32BE), nil -} - -func (f *ConsumeFuzzer) GetFloat64() (float64, error) { - u64, err := f.GetNBytes(8) - if err != nil { - return 0, err - } - littleEndian, err := f.GetBool() - if err != nil { - return 0, err - } - if littleEndian { - u64LE := binary.LittleEndian.Uint64(u64) - return math.Float64frombits(u64LE), nil - } - u64BE := binary.BigEndian.Uint64(u64) - return math.Float64frombits(u64BE), nil -} - -func (f *ConsumeFuzzer) CreateSlice(targetSlice interface{}) error { - return f.GenerateStruct(targetSlice) -} diff --git a/vendor/github.com/AdaLogics/go-fuzz-headers/funcs.go b/vendor/github.com/AdaLogics/go-fuzz-headers/funcs.go deleted file mode 100644 index 8ca3a61b8..000000000 --- a/vendor/github.com/AdaLogics/go-fuzz-headers/funcs.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2023 The go-fuzz-headers 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 gofuzzheaders - -import ( - "fmt" - "reflect" -) - -type Continue struct { - F *ConsumeFuzzer -} - -func (f *ConsumeFuzzer) AddFuncs(fuzzFuncs []interface{}) { - for i := range fuzzFuncs { - v := reflect.ValueOf(fuzzFuncs[i]) - if v.Kind() != reflect.Func { - panic("Need only funcs!") - } - t := v.Type() - if t.NumIn() != 2 || t.NumOut() != 1 { - fmt.Println(t.NumIn(), t.NumOut()) - - panic("Need 2 in and 1 out params. In must be the type. Out must be an error") - } - argT := t.In(0) - switch argT.Kind() { - case reflect.Ptr, reflect.Map: - default: - panic("fuzzFunc must take pointer or map type") - } - if t.In(1) != reflect.TypeOf(Continue{}) { - panic("fuzzFunc's second parameter must be type Continue") - } - f.Funcs[argT] = v - } -} - -func (f *ConsumeFuzzer) GenerateWithCustom(targetStruct interface{}) error { - e := reflect.ValueOf(targetStruct).Elem() - return f.fuzzStruct(e, true) -} - -func (c Continue) GenerateStruct(targetStruct interface{}) error { - return c.F.GenerateStruct(targetStruct) -} - -func (c Continue) GenerateStructWithCustom(targetStruct interface{}) error { - return c.F.GenerateWithCustom(targetStruct) -} diff --git a/vendor/github.com/AdaLogics/go-fuzz-headers/sql.go b/vendor/github.com/AdaLogics/go-fuzz-headers/sql.go deleted file mode 100644 index 2afd49f84..000000000 --- a/vendor/github.com/AdaLogics/go-fuzz-headers/sql.go +++ /dev/null @@ -1,556 +0,0 @@ -// Copyright 2023 The go-fuzz-headers 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 gofuzzheaders - -import ( - "fmt" - "strings" -) - -// returns a keyword by index -func getKeyword(f *ConsumeFuzzer) (string, error) { - index, err := f.GetInt() - if err != nil { - return keywords[0], err - } - for i, k := range keywords { - if i == index { - return k, nil - } - } - return keywords[0], fmt.Errorf("could not get a kw") -} - -// Simple utility function to check if a string -// slice contains a string. -func containsString(s []string, e string) bool { - for _, a := range s { - if a == e { - return true - } - } - return false -} - -// These keywords are used specifically for fuzzing Vitess -var keywords = []string{ - "accessible", "action", "add", "after", "against", "algorithm", - "all", "alter", "always", "analyze", "and", "as", "asc", "asensitive", - "auto_increment", "avg_row_length", "before", "begin", "between", - "bigint", "binary", "_binary", "_utf8mb4", "_utf8", "_latin1", "bit", - "blob", "bool", "boolean", "both", "by", "call", "cancel", "cascade", - "cascaded", "case", "cast", "channel", "change", "char", "character", - "charset", "check", "checksum", "coalesce", "code", "collate", "collation", - "column", "columns", "comment", "committed", "commit", "compact", "complete", - "compressed", "compression", "condition", "connection", "constraint", "continue", - "convert", "copy", "cume_dist", "substr", "substring", "create", "cross", - "csv", "current_date", "current_time", "current_timestamp", "current_user", - "cursor", "data", "database", "databases", "day", "day_hour", "day_microsecond", - "day_minute", "day_second", "date", "datetime", "dec", "decimal", "declare", - "default", "definer", "delay_key_write", "delayed", "delete", "dense_rank", - "desc", "describe", "deterministic", "directory", "disable", "discard", - "disk", "distinct", "distinctrow", "div", "double", "do", "drop", "dumpfile", - "duplicate", "dynamic", "each", "else", "elseif", "empty", "enable", - "enclosed", "encryption", "end", "enforced", "engine", "engines", "enum", - "error", "escape", "escaped", "event", "exchange", "exclusive", "exists", - "exit", "explain", "expansion", "export", "extended", "extract", "false", - "fetch", "fields", "first", "first_value", "fixed", "float", "float4", - "float8", "flush", "for", "force", "foreign", "format", "from", "full", - "fulltext", "function", "general", "generated", "geometry", "geometrycollection", - "get", "global", "gtid_executed", "grant", "group", "grouping", "groups", - "group_concat", "having", "header", "high_priority", "hosts", "hour", "hour_microsecond", - "hour_minute", "hour_second", "if", "ignore", "import", "in", "index", "indexes", - "infile", "inout", "inner", "inplace", "insensitive", "insert", "insert_method", - "int", "int1", "int2", "int3", "int4", "int8", "integer", "interval", - "into", "io_after_gtids", "is", "isolation", "iterate", "invoker", "join", - "json", "json_table", "key", "keys", "keyspaces", "key_block_size", "kill", "lag", - "language", "last", "last_value", "last_insert_id", "lateral", "lead", "leading", - "leave", "left", "less", "level", "like", "limit", "linear", "lines", - "linestring", "load", "local", "localtime", "localtimestamp", "lock", "logs", - "long", "longblob", "longtext", "loop", "low_priority", "manifest", - "master_bind", "match", "max_rows", "maxvalue", "mediumblob", "mediumint", - "mediumtext", "memory", "merge", "microsecond", "middleint", "min_rows", "minute", - "minute_microsecond", "minute_second", "mod", "mode", "modify", "modifies", - "multilinestring", "multipoint", "multipolygon", "month", "name", - "names", "natural", "nchar", "next", "no", "none", "not", "no_write_to_binlog", - "nth_value", "ntile", "null", "numeric", "of", "off", "offset", "on", - "only", "open", "optimize", "optimizer_costs", "option", "optionally", - "or", "order", "out", "outer", "outfile", "over", "overwrite", "pack_keys", - "parser", "partition", "partitioning", "password", "percent_rank", "plugins", - "point", "polygon", "precision", "primary", "privileges", "processlist", - "procedure", "query", "quarter", "range", "rank", "read", "reads", "read_write", - "real", "rebuild", "recursive", "redundant", "references", "regexp", "relay", - "release", "remove", "rename", "reorganize", "repair", "repeat", "repeatable", - "replace", "require", "resignal", "restrict", "return", "retry", "revert", - "revoke", "right", "rlike", "rollback", "row", "row_format", "row_number", - "rows", "s3", "savepoint", "schema", "schemas", "second", "second_microsecond", - "security", "select", "sensitive", "separator", "sequence", "serializable", - "session", "set", "share", "shared", "show", "signal", "signed", "slow", - "smallint", "spatial", "specific", "sql", "sqlexception", "sqlstate", - "sqlwarning", "sql_big_result", "sql_cache", "sql_calc_found_rows", - "sql_no_cache", "sql_small_result", "ssl", "start", "starting", - "stats_auto_recalc", "stats_persistent", "stats_sample_pages", "status", - "storage", "stored", "straight_join", "stream", "system", "vstream", - "table", "tables", "tablespace", "temporary", "temptable", "terminated", - "text", "than", "then", "time", "timestamp", "timestampadd", "timestampdiff", - "tinyblob", "tinyint", "tinytext", "to", "trailing", "transaction", "tree", - "traditional", "trigger", "triggers", "true", "truncate", "uncommitted", - "undefined", "undo", "union", "unique", "unlock", "unsigned", "update", - "upgrade", "usage", "use", "user", "user_resources", "using", "utc_date", - "utc_time", "utc_timestamp", "validation", "values", "variables", "varbinary", - "varchar", "varcharacter", "varying", "vgtid_executed", "virtual", "vindex", - "vindexes", "view", "vitess", "vitess_keyspaces", "vitess_metadata", - "vitess_migration", "vitess_migrations", "vitess_replication_status", - "vitess_shards", "vitess_tablets", "vschema", "warnings", "when", - "where", "while", "window", "with", "without", "work", "write", "xor", - "year", "year_month", "zerofill", -} - -// Keywords that could get an additional keyword -var needCustomString = []string{ - "DISTINCTROW", "FROM", // Select keywords: - "GROUP BY", "HAVING", "WINDOW", - "FOR", - "ORDER BY", "LIMIT", - "INTO", "PARTITION", "AS", // Insert Keywords: - "ON DUPLICATE KEY UPDATE", - "WHERE", "LIMIT", // Delete keywords - "INFILE", "INTO TABLE", "CHARACTER SET", // Load keywords - "TERMINATED BY", "ENCLOSED BY", - "ESCAPED BY", "STARTING BY", - "TERMINATED BY", "STARTING BY", - "IGNORE", - "VALUE", "VALUES", // Replace tokens - "SET", // Update tokens - "ENGINE =", // Drop tokens - "DEFINER =", "ON SCHEDULE", "RENAME TO", // Alter tokens - "COMMENT", "DO", "INITIAL_SIZE = ", "OPTIONS", -} - -var alterTableTokens = [][]string{ - {"CUSTOM_FUZZ_STRING"}, - {"CUSTOM_ALTTER_TABLE_OPTIONS"}, - {"PARTITION_OPTIONS_FOR_ALTER_TABLE"}, -} - -var alterTokens = [][]string{ - { - "DATABASE", "SCHEMA", "DEFINER = ", "EVENT", "FUNCTION", "INSTANCE", - "LOGFILE GROUP", "PROCEDURE", "SERVER", - }, - {"CUSTOM_FUZZ_STRING"}, - { - "ON SCHEDULE", "ON COMPLETION PRESERVE", "ON COMPLETION NOT PRESERVE", - "ADD UNDOFILE", "OPTIONS", - }, - {"RENAME TO", "INITIAL_SIZE = "}, - {"ENABLE", "DISABLE", "DISABLE ON SLAVE", "ENGINE"}, - {"COMMENT"}, - {"DO"}, -} - -var setTokens = [][]string{ - {"CHARACTER SET", "CHARSET", "CUSTOM_FUZZ_STRING", "NAMES"}, - {"CUSTOM_FUZZ_STRING", "DEFAULT", "="}, - {"CUSTOM_FUZZ_STRING"}, -} - -var dropTokens = [][]string{ - {"TEMPORARY", "UNDO"}, - { - "DATABASE", "SCHEMA", "EVENT", "INDEX", "LOGFILE GROUP", - "PROCEDURE", "FUNCTION", "SERVER", "SPATIAL REFERENCE SYSTEM", - "TABLE", "TABLESPACE", "TRIGGER", "VIEW", - }, - {"IF EXISTS"}, - {"CUSTOM_FUZZ_STRING"}, - {"ON", "ENGINE = ", "RESTRICT", "CASCADE"}, -} - -var renameTokens = [][]string{ - {"TABLE"}, - {"CUSTOM_FUZZ_STRING"}, - {"TO"}, - {"CUSTOM_FUZZ_STRING"}, -} - -var truncateTokens = [][]string{ - {"TABLE"}, - {"CUSTOM_FUZZ_STRING"}, -} - -var createTokens = [][]string{ - {"OR REPLACE", "TEMPORARY", "UNDO"}, // For create spatial reference system - { - "UNIQUE", "FULLTEXT", "SPATIAL", "ALGORITHM = UNDEFINED", "ALGORITHM = MERGE", - "ALGORITHM = TEMPTABLE", - }, - { - "DATABASE", "SCHEMA", "EVENT", "FUNCTION", "INDEX", "LOGFILE GROUP", - "PROCEDURE", "SERVER", "SPATIAL REFERENCE SYSTEM", "TABLE", "TABLESPACE", - "TRIGGER", "VIEW", - }, - {"IF NOT EXISTS"}, - {"CUSTOM_FUZZ_STRING"}, -} - -/* -// For future use. -var updateTokens = [][]string{ - {"LOW_PRIORITY"}, - {"IGNORE"}, - {"SET"}, - {"WHERE"}, - {"ORDER BY"}, - {"LIMIT"}, -} -*/ - -var replaceTokens = [][]string{ - {"LOW_PRIORITY", "DELAYED"}, - {"INTO"}, - {"PARTITION"}, - {"CUSTOM_FUZZ_STRING"}, - {"VALUES", "VALUE"}, -} - -var loadTokens = [][]string{ - {"DATA"}, - {"LOW_PRIORITY", "CONCURRENT", "LOCAL"}, - {"INFILE"}, - {"REPLACE", "IGNORE"}, - {"INTO TABLE"}, - {"PARTITION"}, - {"CHARACTER SET"}, - {"FIELDS", "COLUMNS"}, - {"TERMINATED BY"}, - {"OPTIONALLY"}, - {"ENCLOSED BY"}, - {"ESCAPED BY"}, - {"LINES"}, - {"STARTING BY"}, - {"TERMINATED BY"}, - {"IGNORE"}, - {"LINES", "ROWS"}, - {"CUSTOM_FUZZ_STRING"}, -} - -// These Are everything that comes after "INSERT" -var insertTokens = [][]string{ - {"LOW_PRIORITY", "DELAYED", "HIGH_PRIORITY", "IGNORE"}, - {"INTO"}, - {"PARTITION"}, - {"CUSTOM_FUZZ_STRING"}, - {"AS"}, - {"ON DUPLICATE KEY UPDATE"}, -} - -// These are everything that comes after "SELECT" -var selectTokens = [][]string{ - {"*", "CUSTOM_FUZZ_STRING", "DISTINCTROW"}, - {"HIGH_PRIORITY"}, - {"STRAIGHT_JOIN"}, - {"SQL_SMALL_RESULT", "SQL_BIG_RESULT", "SQL_BUFFER_RESULT"}, - {"SQL_NO_CACHE", "SQL_CALC_FOUND_ROWS"}, - {"CUSTOM_FUZZ_STRING"}, - {"FROM"}, - {"WHERE"}, - {"GROUP BY"}, - {"HAVING"}, - {"WINDOW"}, - {"ORDER BY"}, - {"LIMIT"}, - {"CUSTOM_FUZZ_STRING"}, - {"FOR"}, -} - -// These are everything that comes after "DELETE" -var deleteTokens = [][]string{ - {"LOW_PRIORITY", "QUICK", "IGNORE", "FROM", "AS"}, - {"PARTITION"}, - {"WHERE"}, - {"ORDER BY"}, - {"LIMIT"}, -} - -var alter_table_options = []string{ - "ADD", "COLUMN", "FIRST", "AFTER", "INDEX", "KEY", "FULLTEXT", "SPATIAL", - "CONSTRAINT", "UNIQUE", "FOREIGN KEY", "CHECK", "ENFORCED", "DROP", "ALTER", - "NOT", "INPLACE", "COPY", "SET", "VISIBLE", "INVISIBLE", "DEFAULT", "CHANGE", - "CHARACTER SET", "COLLATE", "DISABLE", "ENABLE", "KEYS", "TABLESPACE", "LOCK", - "FORCE", "MODIFY", "SHARED", "EXCLUSIVE", "NONE", "ORDER BY", "RENAME COLUMN", - "AS", "=", "ASC", "DESC", "WITH", "WITHOUT", "VALIDATION", "ADD PARTITION", - "DROP PARTITION", "DISCARD PARTITION", "IMPORT PARTITION", "TRUNCATE PARTITION", - "COALESCE PARTITION", "REORGANIZE PARTITION", "EXCHANGE PARTITION", - "ANALYZE PARTITION", "CHECK PARTITION", "OPTIMIZE PARTITION", "REBUILD PARTITION", - "REPAIR PARTITION", "REMOVE PARTITIONING", "USING", "BTREE", "HASH", "COMMENT", - "KEY_BLOCK_SIZE", "WITH PARSER", "AUTOEXTEND_SIZE", "AUTO_INCREMENT", "AVG_ROW_LENGTH", - "CHECKSUM", "INSERT_METHOD", "ROW_FORMAT", "DYNAMIC", "FIXED", "COMPRESSED", "REDUNDANT", - "COMPACT", "SECONDARY_ENGINE_ATTRIBUTE", "STATS_AUTO_RECALC", "STATS_PERSISTENT", - "STATS_SAMPLE_PAGES", "ZLIB", "LZ4", "ENGINE_ATTRIBUTE", "KEY_BLOCK_SIZE", "MAX_ROWS", - "MIN_ROWS", "PACK_KEYS", "PASSWORD", "COMPRESSION", "CONNECTION", "DIRECTORY", - "DELAY_KEY_WRITE", "ENCRYPTION", "STORAGE", "DISK", "MEMORY", "UNION", -} - -// Creates an 'alter table' statement. 'alter table' is an exception -// in that it has its own function. The majority of statements -// are created by 'createStmt()'. -func createAlterTableStmt(f *ConsumeFuzzer) (string, error) { - maxArgs, err := f.GetInt() - if err != nil { - return "", err - } - maxArgs = maxArgs % 30 - if maxArgs == 0 { - return "", fmt.Errorf("could not create alter table stmt") - } - - var stmt strings.Builder - stmt.WriteString("ALTER TABLE ") - for i := 0; i < maxArgs; i++ { - // Calculate if we get existing token or custom string - tokenType, err := f.GetInt() - if err != nil { - return "", err - } - if tokenType%4 == 1 { - customString, err := f.GetString() - if err != nil { - return "", err - } - stmt.WriteString(" " + customString) - } else { - tokenIndex, err := f.GetInt() - if err != nil { - return "", err - } - stmt.WriteString(" " + alter_table_options[tokenIndex%len(alter_table_options)]) - } - } - return stmt.String(), nil -} - -func chooseToken(tokens []string, f *ConsumeFuzzer) (string, error) { - index, err := f.GetInt() - if err != nil { - return "", err - } - var token strings.Builder - token.WriteString(tokens[index%len(tokens)]) - if token.String() == "CUSTOM_FUZZ_STRING" { - customFuzzString, err := f.GetString() - if err != nil { - return "", err - } - return customFuzzString, nil - } - - // Check if token requires an argument - if containsString(needCustomString, token.String()) { - customFuzzString, err := f.GetString() - if err != nil { - return "", err - } - token.WriteString(" " + customFuzzString) - } - return token.String(), nil -} - -var stmtTypes = map[string][][]string{ - "DELETE": deleteTokens, - "INSERT": insertTokens, - "SELECT": selectTokens, - "LOAD": loadTokens, - "REPLACE": replaceTokens, - "CREATE": createTokens, - "DROP": dropTokens, - "RENAME": renameTokens, - "TRUNCATE": truncateTokens, - "SET": setTokens, - "ALTER": alterTokens, - "ALTER TABLE": alterTableTokens, // ALTER TABLE has its own set of tokens -} - -var stmtTypeEnum = map[int]string{ - 0: "DELETE", - 1: "INSERT", - 2: "SELECT", - 3: "LOAD", - 4: "REPLACE", - 5: "CREATE", - 6: "DROP", - 7: "RENAME", - 8: "TRUNCATE", - 9: "SET", - 10: "ALTER", - 11: "ALTER TABLE", -} - -func createStmt(f *ConsumeFuzzer) (string, error) { - stmtIndex, err := f.GetInt() - if err != nil { - return "", err - } - stmtIndex = stmtIndex % len(stmtTypes) - - queryType := stmtTypeEnum[stmtIndex] - tokens := stmtTypes[queryType] - - // We have custom creator for ALTER TABLE - if queryType == "ALTER TABLE" { - query, err := createAlterTableStmt(f) - if err != nil { - return "", err - } - return query, nil - } - - // Here we are creating a query that is not - // an 'alter table' query. For available - // queries, see "stmtTypes" - - // First specify the first query keyword: - var query strings.Builder - query.WriteString(queryType) - - // Next create the args for the - queryArgs, err := createStmtArgs(tokens, f) - if err != nil { - return "", err - } - query.WriteString(" " + queryArgs) - return query.String(), nil -} - -// Creates the arguments of a statements. In a select statement -// that would be everything after "select". -func createStmtArgs(tokenslice [][]string, f *ConsumeFuzzer) (string, error) { - var query, token strings.Builder - - // We go through the tokens in the tokenslice, - // create the respective token and add it to - // "query" - for _, tokens := range tokenslice { - // For extra randomization, the fuzzer can - // choose to not include this token. - includeThisToken, err := f.GetBool() - if err != nil { - return "", err - } - if !includeThisToken { - continue - } - - // There may be several tokens to choose from: - if len(tokens) > 1 { - chosenToken, err := chooseToken(tokens, f) - if err != nil { - return "", err - } - query.WriteString(" " + chosenToken) - } else { - token.WriteString(tokens[0]) - - // In case the token is "CUSTOM_FUZZ_STRING" - // we will then create a non-structured string - if token.String() == "CUSTOM_FUZZ_STRING" { - customFuzzString, err := f.GetString() - if err != nil { - return "", err - } - query.WriteString(" " + customFuzzString) - continue - } - - // Check if token requires an argument. - // Tokens that take an argument can be found - // in 'needCustomString'. If so, we add a - // non-structured string to the token. - if containsString(needCustomString, token.String()) { - customFuzzString, err := f.GetString() - if err != nil { - return "", err - } - token.WriteString(fmt.Sprintf(" %s", customFuzzString)) - } - query.WriteString(fmt.Sprintf(" %s", token.String())) - } - } - return query.String(), nil -} - -// Creates a semi-structured query. It creates a string -// that is a combination of the keywords and random strings. -func createQuery(f *ConsumeFuzzer) (string, error) { - queryLen, err := f.GetInt() - if err != nil { - return "", err - } - maxLen := queryLen % 60 - if maxLen == 0 { - return "", fmt.Errorf("could not create a query") - } - var query strings.Builder - for i := 0; i < maxLen; i++ { - // Get a new token: - useKeyword, err := f.GetBool() - if err != nil { - return "", err - } - if useKeyword { - keyword, err := getKeyword(f) - if err != nil { - return "", err - } - query.WriteString(" " + keyword) - } else { - customString, err := f.GetString() - if err != nil { - return "", err - } - query.WriteString(" " + customString) - } - } - if query.String() == "" { - return "", fmt.Errorf("could not create a query") - } - return query.String(), nil -} - -// GetSQLString is the API that users interact with. -// -// Usage: -// -// f := NewConsumer(data) -// sqlString, err := f.GetSQLString() -func (f *ConsumeFuzzer) GetSQLString() (string, error) { - var query string - veryStructured, err := f.GetBool() - if err != nil { - return "", err - } - if veryStructured { - query, err = createStmt(f) - if err != nil { - return "", err - } - } else { - query, err = createQuery(f) - if err != nil { - return "", err - } - } - return query, nil -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/CONTRIBUTING.md b/vendor/github.com/AlecAivazis/survey/v2/CONTRIBUTING.md deleted file mode 100644 index 31f5be906..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/CONTRIBUTING.md +++ /dev/null @@ -1,55 +0,0 @@ -# Contributing to Survey - -🎉🎉 First off, thanks for the interest in contributing to `survey`! 🎉🎉 - -The following is a set of guidelines to follow when contributing to this package. These are not hard rules, please use common sense and feel free to propose changes to this document in a pull request. - -## Code of Conduct - -This project and its contibutors are expected to uphold the [Go Community Code of Conduct](https://golang.org/conduct). By participating, you are expected to follow these guidelines. - -## Getting help - -* [Open an issue](https://github.com/AlecAivazis/survey/issues/new/choose) -* Reach out to `@AlecAivazis` or `@mislav` in the Gophers slack (please use only when urgent) - -## Submitting a contribution - -When submitting a contribution, - -- Try to make a series of smaller changes instead of one large change -- Provide a description of each change that you are proposing -- Reference the issue addressed by your pull request (if there is one) -- Document all new exported Go APIs -- Update the project's README when applicable -- Include unit tests if possible -- Contributions with visual ramifications or interaction changes should be accompanied with an integration test—see below for details. - -## Writing and running tests - -When submitting features, please add as many units tests as necessary to test both positive and negative cases. - -Integration tests for survey uses [go-expect](https://github.com/Netflix/go-expect) to expect a match on stdout and respond on stdin. Since `os.Stdout` in a `go test` process is not a TTY, you need a way to interpret terminal / ANSI escape sequences for things like `CursorLocation`. The stdin/stdout handled by `go-expect` is also multiplexed to a [virtual terminal](https://github.com/hinshun/vt10x). - -For example, you can extend the tests for Input by specifying the following test case: - -```go -{ - "Test Input prompt interaction", // Name of the test. - &Input{ // An implementation of the survey.Prompt interface. - Message: "What is your name?", - }, - func(c *expect.Console) { // An expect procedure. You can expect strings / regexps and - c.ExpectString("What is your name?") // write back strings / bytes to its psuedoterminal for survey. - c.SendLine("Johnny Appleseed") - c.ExpectEOF() // Nothing is read from the tty without an expect, and once an - // expectation is met, no further bytes are read. End your - // procedure with `c.ExpectEOF()` to read until survey finishes. - }, - "Johnny Appleseed", // The expected result. -} -``` - -If you want to write your own `go-expect` test from scratch, you'll need to instantiate a virtual terminal, -multiplex it into an `*expect.Console`, and hook up its tty with survey's optional stdio. Please see `go-expect` -[documentation](https://godoc.org/github.com/Netflix/go-expect) for more detail. diff --git a/vendor/github.com/AlecAivazis/survey/v2/LICENSE b/vendor/github.com/AlecAivazis/survey/v2/LICENSE deleted file mode 100644 index 07a709ae2..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2018 Alec Aivazis - -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/AlecAivazis/survey/v2/README.md b/vendor/github.com/AlecAivazis/survey/v2/README.md deleted file mode 100644 index ba75b329f..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/README.md +++ /dev/null @@ -1,510 +0,0 @@ -# Survey - -[![GoDoc](http://img.shields.io/badge/godoc-reference-5272B4.svg)](https://pkg.go.dev/github.com/AlecAivazis/survey/v2) - -A library for building interactive and accessible prompts on terminals supporting ANSI escape sequences. - - - -```go -package main - -import ( - "fmt" - "github.com/AlecAivazis/survey/v2" -) - -// the questions to ask -var qs = []*survey.Question{ - { - Name: "name", - Prompt: &survey.Input{Message: "What is your name?"}, - Validate: survey.Required, - Transform: survey.Title, - }, - { - Name: "color", - Prompt: &survey.Select{ - Message: "Choose a color:", - Options: []string{"red", "blue", "green"}, - Default: "red", - }, - }, - { - Name: "age", - Prompt: &survey.Input{Message: "How old are you?"}, - }, -} - -func main() { - // the answers will be written to this struct - answers := struct { - Name string // survey will match the question and field names - FavoriteColor string `survey:"color"` // or you can tag fields to match a specific name - Age int // if the types don't match, survey will convert it - }{} - - // perform the questions - err := survey.Ask(qs, &answers) - if err != nil { - fmt.Println(err.Error()) - return - } - - fmt.Printf("%s chose %s.", answers.Name, answers.FavoriteColor) -} -``` - -## Examples - -Examples can be found in the `examples/` directory. Run them -to see basic behavior: - -```bash -go run examples/simple.go -go run examples/validation.go -``` - -## Running the Prompts - -There are two primary ways to execute prompts and start collecting information from your users: `Ask` and -`AskOne`. The primary difference is whether you are interested in collecting a single piece of information -or if you have a list of questions to ask whose answers should be collected in a single struct. -For most basic usecases, `Ask` should be enough. However, for surveys with complicated branching logic, -we recommend that you break out your questions into multiple calls to both of these functions to fit your needs. - -### Configuring the Prompts - -Most prompts take fine-grained configuration through fields on the structs you instantiate. It is also -possible to change survey's default behaviors by passing `AskOpts` to either `Ask` or `AskOne`. Examples -in this document will do both interchangeably: - -```golang -prompt := &Select{ - Message: "Choose a color:", - Options: []string{"red", "blue", "green"}, - // can pass a validator directly - Validate: survey.Required, -} - -// or define a default for the single call to `AskOne` -// the answer will get written to the color variable -survey.AskOne(prompt, &color, survey.WithValidator(survey.Required)) - -// or define a default for every entry in a list of questions -// the answer will get copied into the matching field of the struct as shown above -survey.Ask(questions, &answers, survey.WithValidator(survey.Required)) -``` - -## Prompts - -### Input - - - -```golang -name := "" -prompt := &survey.Input{ - Message: "ping", -} -survey.AskOne(prompt, &name) -``` - -#### Suggestion Options - - - -```golang -file := "" -prompt := &survey.Input{ - Message: "inform a file to save:", - Suggest: func (toComplete string) []string { - files, _ := filepath.Glob(toComplete + "*") - return files - }, -} -} -survey.AskOne(prompt, &file) -``` - -### Multiline - - - -```golang -text := "" -prompt := &survey.Multiline{ - Message: "ping", -} -survey.AskOne(prompt, &text) -``` - -### Password - - - -```golang -password := "" -prompt := &survey.Password{ - Message: "Please type your password", -} -survey.AskOne(prompt, &password) -``` - -### Confirm - - - -```golang -name := false -prompt := &survey.Confirm{ - Message: "Do you like pie?", -} -survey.AskOne(prompt, &name) -``` - -### Select - - - -```golang -color := "" -prompt := &survey.Select{ - Message: "Choose a color:", - Options: []string{"red", "blue", "green"}, -} -survey.AskOne(prompt, &color) -``` - -Fields and values that come from a `Select` prompt can be one of two different things. If you pass an `int` -the field will have the value of the selected index. If you instead pass a string, the string value selected -will be written to the field. - -The user can also press `esc` to toggle the ability cycle through the options with the j and k keys to do down and up respectively. - -By default, the select prompt is limited to showing 7 options at a time -and will paginate lists of options longer than that. This can be changed a number of ways: - -```golang -// as a field on a single select -prompt := &survey.MultiSelect{..., PageSize: 10} - -// or as an option to Ask or AskOne -survey.AskOne(prompt, &days, survey.WithPageSize(10)) -``` - -#### Select options description - -The optional description text can be used to add extra information to each option listed in the select prompt: - -```golang -color := "" -prompt := &survey.Select{ - Message: "Choose a color:", - Options: []string{"red", "blue", "green"}, - Description: func(value string, index int) string { - if value == "red" { - return "My favorite color" - } - return "" - }, -} -survey.AskOne(prompt, &color) - -// Assuming that the user chose "red - My favorite color": -fmt.Println(color) //=> "red" -``` - -### MultiSelect - -![Example](img/multi-select-all-none.gif) - -```golang -days := []string{} -prompt := &survey.MultiSelect{ - Message: "What days do you prefer:", - Options: []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}, -} -survey.AskOne(prompt, &days) -``` - -Fields and values that come from a `MultiSelect` prompt can be one of two different things. If you pass an `int` -the field will have a slice of the selected indices. If you instead pass a string, a slice of the string values -selected will be written to the field. - -The user can also press `esc` to toggle the ability cycle through the options with the j and k keys to do down and up respectively. - -By default, the MultiSelect prompt is limited to showing 7 options at a time -and will paginate lists of options longer than that. This can be changed a number of ways: - -```golang -// as a field on a single select -prompt := &survey.MultiSelect{..., PageSize: 10} - -// or as an option to Ask or AskOne -survey.AskOne(prompt, &days, survey.WithPageSize(10)) -``` - -### Editor - -Launches the user's preferred editor (defined by the \$VISUAL or \$EDITOR environment variables) on a -temporary file. Once the user exits their editor, the contents of the temporary file are read in as -the result. If neither of those are present, notepad (on Windows) or vim (Linux or Mac) is used. - -You can also specify a [pattern](https://golang.org/pkg/io/ioutil/#TempFile) for the name of the temporary file. This -can be useful for ensuring syntax highlighting matches your usecase. - -```golang -prompt := &survey.Editor{ - Message: "Shell code snippet", - FileName: "*.sh", -} - -survey.AskOne(prompt, &content) -``` - -## Filtering Options - -By default, the user can filter for options in Select and MultiSelects by typing while the prompt -is active. This will filter out all options that don't contain the typed string anywhere in their name, ignoring case. - -A custom filter function can also be provided to change this behavior: - -```golang -func myFilter(filterValue string, optValue string, optIndex int) bool { - // only include the option if it includes the filter and has length greater than 5 - return strings.Contains(optValue, filterValue) && len(optValue) >= 5 -} - -// configure it for a specific prompt -&Select{ - Message: "Choose a color:", - Options: []string{"red", "blue", "green"}, - Filter: myFilter, -} - -// or define a default for all of the questions -survey.AskOne(prompt, &color, survey.WithFilter(myFilter)) -``` - -## Keeping the filter active - -By default the filter will disappear if the user selects one of the filtered elements. Once the user selects one element the filter setting is gone. - -However the user can prevent this from happening and keep the filter active for multiple selections in a e.g. MultiSelect: - -```golang -// configure it for a specific prompt -&Select{ - Message: "Choose a color:", - Options: []string{"light-green", "green", "dark-green", "red"}, - KeepFilter: true, -} - -// or define a default for all of the questions -survey.AskOne(prompt, &color, survey.WithKeepFilter(true)) -``` - -## Validation - -Validating individual responses for a particular question can be done by defining a -`Validate` field on the `survey.Question` to be validated. This function takes an -`interface{}` type and returns an error to show to the user, prompting them for another -response. Like usual, validators can be provided directly to the prompt or with `survey.WithValidator`: - -```golang -q := &survey.Question{ - Prompt: &survey.Input{Message: "Hello world validation"}, - Validate: func (val interface{}) error { - // since we are validating an Input, the assertion will always succeed - if str, ok := val.(string) ; !ok || len(str) > 10 { - return errors.New("This response cannot be longer than 10 characters.") - } - return nil - }, -} - -color := "" -prompt := &survey.Input{ Message: "Whats your name?" } - -// you can pass multiple validators here and survey will make sure each one passes -survey.AskOne(prompt, &color, survey.WithValidator(survey.Required)) -``` - -### Built-in Validators - -`survey` comes prepackaged with a few validators to fit common situations. Currently these -validators include: - -| name | valid types | description | notes | -| ------------ | -------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------- | -| Required | any | Rejects zero values of the response type | Boolean values pass straight through since the zero value (false) is a valid response | -| MinLength(n) | string | Enforces that a response is at least the given length | | -| MaxLength(n) | string | Enforces that a response is no longer than the given length | | -| MaxItems(n) | []OptionAnswer | Enforces that a response has no more selections of the indicated | | -| MinItems(n) | []OptionAnswer | Enforces that a response has no less selections of the indicated | | - -## Help Text - -All of the prompts have a `Help` field which can be defined to provide more information to your users: - - - -```golang -&survey.Input{ - Message: "What is your phone number:", - Help: "Phone number should include the area code", -} -``` - -## Removing the "Select All" and "Select None" options - -By default, users can select all of the multi-select options using the right arrow key. To prevent users from being able to do this (and remove the ` to all` message from the prompt), use the option `WithRemoveSelectAll`: - -```golang -import ( - "github.com/AlecAivazis/survey/v2" -) - -number := "" -prompt := &survey.Input{ - Message: "This question has the select all option removed", -} - -survey.AskOne(prompt, &number, survey.WithRemoveSelectAll()) -``` - -Also by default, users can use the left arrow key to unselect all of the options. To prevent users from being able to do this (and remove the ` to none` message from the prompt), use the option `WithRemoveSelectNone`: - -```golang -import ( - "github.com/AlecAivazis/survey/v2" -) - -number := "" -prompt := &survey.Input{ - Message: "This question has the select all option removed", -} - -survey.AskOne(prompt, &number, survey.WithRemoveSelectNone()) -``` - - -### Changing the input rune - -In some situations, `?` is a perfectly valid response. To handle this, you can change the rune that survey -looks for with `WithHelpInput`: - -```golang -import ( - "github.com/AlecAivazis/survey/v2" -) - -number := "" -prompt := &survey.Input{ - Message: "If you have this need, please give me a reasonable message.", - Help: "I couldn't come up with one.", -} - -survey.AskOne(prompt, &number, survey.WithHelpInput('^')) -``` - -## Changing the Icons - -Changing the icons and their color/format can be done by passing the `WithIcons` option. The format -follows the patterns outlined [here](https://github.com/mgutz/ansi#style-format). For example: - -```golang -import ( - "github.com/AlecAivazis/survey/v2" -) - -number := "" -prompt := &survey.Input{ - Message: "If you have this need, please give me a reasonable message.", - Help: "I couldn't come up with one.", -} - -survey.AskOne(prompt, &number, survey.WithIcons(func(icons *survey.IconSet) { - // you can set any icons - icons.Question.Text = "⁇" - // for more information on formatting the icons, see here: https://github.com/mgutz/ansi#style-format - icons.Question.Format = "yellow+hb" -})) -``` - -The icons and their default text and format are summarized below: - -| name | text | format | description | -| -------------- | ---- | ---------- | ------------------------------------------------------------- | -| Error | X | red | Before an error | -| Help | i | cyan | Before help text | -| Question | ? | green+hb | Before the message of a prompt | -| SelectFocus | > | green | Marks the current focus in `Select` and `MultiSelect` prompts | -| UnmarkedOption | [ ] | default+hb | Marks an unselected option in a `MultiSelect` prompt | -| MarkedOption | [x] | cyan+b | Marks a chosen selection in a `MultiSelect` prompt | - -## Custom Types - -survey will assign prompt answers to your custom types if they implement this interface: - -```golang -type Settable interface { - WriteAnswer(field string, value interface{}) error -} -``` - -Here is an example how to use them: - -```golang -type MyValue struct { - value string -} -func (my *MyValue) WriteAnswer(name string, value interface{}) error { - my.value = value.(string) -} - -myval := MyValue{} -survey.AskOne( - &survey.Input{ - Message: "Enter something:", - }, - &myval -) -``` - -## Testing - -You can test your program's interactive prompts using [go-expect](https://github.com/Netflix/go-expect). The library -can be used to expect a match on stdout and respond on stdin. Since `os.Stdout` in a `go test` process is not a TTY, -if you are manipulating the cursor or using `survey`, you will need a way to interpret terminal / ANSI escape sequences -for things like `CursorLocation`. `vt10x.NewVT10XConsole` will create a `go-expect` console that also multiplexes -stdio to an in-memory [virtual terminal](https://github.com/hinshun/vt10x). - -For some examples, you can see any of the tests in this repo. - -## FAQ - -### What kinds of IO are supported by `survey`? - -survey aims to support most terminal emulators; it expects support for ANSI escape sequences. -This means that reading from piped stdin or writing to piped stdout is **not supported**, -and likely to break your application in these situations. See [#337](https://github.com/AlecAivazis/survey/pull/337#issue-581351617) - -### Why isn't Ctrl-C working? - -Ordinarily, when you type Ctrl-C, the terminal recognizes this as the QUIT button and delivers a SIGINT signal to the process, which terminates it. -However, Survey temporarily configures the terminal to deliver control codes as ordinary input bytes. -When Survey reads a ^C byte (ASCII \x03, "end of text"), it interrupts the current survey and returns a -`github.com/AlecAivazis/survey/v2/terminal.InterruptErr` from `Ask` or `AskOne`. -If you want to stop the process, handle the returned error in your code: - -```go -err := survey.AskOne(prompt, &myVar) -if err != nil { - if err == terminal.InterruptErr { - log.Fatal("interrupted") - } - ... -} -``` diff --git a/vendor/github.com/AlecAivazis/survey/v2/confirm.go b/vendor/github.com/AlecAivazis/survey/v2/confirm.go deleted file mode 100644 index 1c23fb4d1..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/confirm.go +++ /dev/null @@ -1,154 +0,0 @@ -package survey - -import ( - "fmt" - "regexp" -) - -// Confirm is a regular text input that accept yes/no answers. Response type is a bool. -type Confirm struct { - Renderer - Message string - Default bool - Help string -} - -// data available to the templates when processing -type ConfirmTemplateData struct { - Confirm - Answer string - ShowHelp bool - Config *PromptConfig -} - -// Templates with Color formatting. See Documentation: https://github.com/mgutz/ansi#style-format -var ConfirmQuestionTemplate = ` -{{- if .ShowHelp }}{{- color .Config.Icons.Help.Format }}{{ .Config.Icons.Help.Text }} {{ .Help }}{{color "reset"}}{{"\n"}}{{end}} -{{- color .Config.Icons.Question.Format }}{{ .Config.Icons.Question.Text }} {{color "reset"}} -{{- color "default+hb"}}{{ .Message }} {{color "reset"}} -{{- if .Answer}} - {{- color "cyan"}}{{.Answer}}{{color "reset"}}{{"\n"}} -{{- else }} - {{- if and .Help (not .ShowHelp)}}{{color "cyan"}}[{{ .Config.HelpInput }} for help]{{color "reset"}} {{end}} - {{- color "white"}}{{if .Default}}(Y/n) {{else}}(y/N) {{end}}{{color "reset"}} -{{- end}}` - -// the regex for answers -var ( - yesRx = regexp.MustCompile("^(?i:y(?:es)?)$") - noRx = regexp.MustCompile("^(?i:n(?:o)?)$") -) - -func yesNo(t bool) string { - if t { - return "Yes" - } - return "No" -} - -func (c *Confirm) getBool(showHelp bool, config *PromptConfig) (bool, error) { - cursor := c.NewCursor() - rr := c.NewRuneReader() - _ = rr.SetTermMode() - defer func() { - _ = rr.RestoreTermMode() - }() - - // start waiting for input - for { - line, err := rr.ReadLine(0) - if err != nil { - return false, err - } - // move back up a line to compensate for the \n echoed from terminal - cursor.PreviousLine(1) - val := string(line) - - // get the answer that matches the - var answer bool - switch { - case yesRx.Match([]byte(val)): - answer = true - case noRx.Match([]byte(val)): - answer = false - case val == "": - answer = c.Default - case val == config.HelpInput && c.Help != "": - err := c.Render( - ConfirmQuestionTemplate, - ConfirmTemplateData{ - Confirm: *c, - ShowHelp: true, - Config: config, - }, - ) - if err != nil { - // use the default value and bubble up - return c.Default, err - } - showHelp = true - continue - default: - // we didnt get a valid answer, so print error and prompt again - //lint:ignore ST1005 it should be fine for this error message to have punctuation - if err := c.Error(config, fmt.Errorf("%q is not a valid answer, please try again.", val)); err != nil { - return c.Default, err - } - err := c.Render( - ConfirmQuestionTemplate, - ConfirmTemplateData{ - Confirm: *c, - ShowHelp: showHelp, - Config: config, - }, - ) - if err != nil { - // use the default value and bubble up - return c.Default, err - } - continue - } - return answer, nil - } -} - -/* -Prompt prompts the user with a simple text field and expects a reply followed -by a carriage return. - - likesPie := false - prompt := &survey.Confirm{ Message: "What is your name?" } - survey.AskOne(prompt, &likesPie) -*/ -func (c *Confirm) Prompt(config *PromptConfig) (interface{}, error) { - // render the question template - err := c.Render( - ConfirmQuestionTemplate, - ConfirmTemplateData{ - Confirm: *c, - Config: config, - }, - ) - if err != nil { - return "", err - } - - // get input and return - return c.getBool(false, config) -} - -// Cleanup overwrite the line with the finalized formatted version -func (c *Confirm) Cleanup(config *PromptConfig, val interface{}) error { - // if the value was previously true - ans := yesNo(val.(bool)) - - // render the template - return c.Render( - ConfirmQuestionTemplate, - ConfirmTemplateData{ - Confirm: *c, - Answer: ans, - Config: config, - }, - ) -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/core/template.go b/vendor/github.com/AlecAivazis/survey/v2/core/template.go deleted file mode 100644 index 02da879dc..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/core/template.go +++ /dev/null @@ -1,104 +0,0 @@ -package core - -import ( - "bytes" - "os" - "sync" - "text/template" - - "github.com/mgutz/ansi" -) - -// DisableColor can be used to make testing reliable -var DisableColor = false - -var TemplateFuncsWithColor = map[string]interface{}{ - // Templates with Color formatting. See Documentation: https://github.com/mgutz/ansi#style-format - "color": ansi.ColorCode, -} - -var TemplateFuncsNoColor = map[string]interface{}{ - // Templates without Color formatting. For layout/ testing. - "color": func(color string) string { - return "" - }, -} - -// envColorDisabled returns if output colors are forbid by environment variables -func envColorDisabled() bool { - return os.Getenv("NO_COLOR") != "" || os.Getenv("CLICOLOR") == "0" -} - -// envColorForced returns if output colors are forced from environment variables -func envColorForced() bool { - val, ok := os.LookupEnv("CLICOLOR_FORCE") - return ok && val != "0" -} - -// RunTemplate returns two formatted strings given a template and -// the data it requires. The first string returned is generated for -// user-facing output and may or may not contain ANSI escape codes -// for colored output. The second string does not contain escape codes -// and can be used by the renderer for layout purposes. -func RunTemplate(tmpl string, data interface{}) (string, string, error) { - tPair, err := GetTemplatePair(tmpl) - if err != nil { - return "", "", err - } - userBuf := bytes.NewBufferString("") - err = tPair[0].Execute(userBuf, data) - if err != nil { - return "", "", err - } - layoutBuf := bytes.NewBufferString("") - err = tPair[1].Execute(layoutBuf, data) - if err != nil { - return userBuf.String(), "", err - } - return userBuf.String(), layoutBuf.String(), err -} - -var ( - memoizedGetTemplate = map[string][2]*template.Template{} - - memoMutex = &sync.RWMutex{} -) - -// GetTemplatePair returns a pair of compiled templates where the -// first template is generated for user-facing output and the -// second is generated for use by the renderer. The second -// template does not contain any color escape codes, whereas -// the first template may or may not depending on DisableColor. -func GetTemplatePair(tmpl string) ([2]*template.Template, error) { - memoMutex.RLock() - if t, ok := memoizedGetTemplate[tmpl]; ok { - memoMutex.RUnlock() - return t, nil - } - memoMutex.RUnlock() - - templatePair := [2]*template.Template{nil, nil} - - templateNoColor, err := template.New("prompt").Funcs(TemplateFuncsNoColor).Parse(tmpl) - if err != nil { - return [2]*template.Template{}, err - } - - templatePair[1] = templateNoColor - - envColorHide := envColorDisabled() && !envColorForced() - if DisableColor || envColorHide { - templatePair[0] = templatePair[1] - } else { - templateWithColor, err := template.New("prompt").Funcs(TemplateFuncsWithColor).Parse(tmpl) - templatePair[0] = templateWithColor - if err != nil { - return [2]*template.Template{}, err - } - } - - memoMutex.Lock() - memoizedGetTemplate[tmpl] = templatePair - memoMutex.Unlock() - return templatePair, nil -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/core/write.go b/vendor/github.com/AlecAivazis/survey/v2/core/write.go deleted file mode 100644 index 2225e3b22..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/core/write.go +++ /dev/null @@ -1,376 +0,0 @@ -package core - -import ( - "errors" - "fmt" - "reflect" - "strconv" - "strings" - "time" -) - -// the tag used to denote the name of the question -const tagName = "survey" - -// Settable allow for configuration when assigning answers -type Settable interface { - WriteAnswer(field string, value interface{}) error -} - -// OptionAnswer is the return type of Selects/MultiSelects that lets the appropriate information -// get copied to the user's struct -type OptionAnswer struct { - Value string - Index int -} - -type reflectField struct { - value reflect.Value - fieldType reflect.StructField -} - -func OptionAnswerList(incoming []string) []OptionAnswer { - list := []OptionAnswer{} - for i, opt := range incoming { - list = append(list, OptionAnswer{Value: opt, Index: i}) - } - return list -} - -func WriteAnswer(t interface{}, name string, v interface{}) (err error) { - // if the field is a custom type - if s, ok := t.(Settable); ok { - // use the interface method - return s.WriteAnswer(name, v) - } - - // the target to write to - target := reflect.ValueOf(t) - // the value to write from - value := reflect.ValueOf(v) - - // make sure we are writing to a pointer - if target.Kind() != reflect.Ptr { - return errors.New("you must pass a pointer as the target of a Write operation") - } - // the object "inside" of the target pointer - elem := target.Elem() - - // handle the special types - switch elem.Kind() { - // if we are writing to a struct - case reflect.Struct: - // if we are writing to an option answer than we want to treat - // it like a single thing and not a place to deposit answers - if elem.Type().Name() == "OptionAnswer" { - // copy the value over to the normal struct - return copy(elem, value) - } - - // get the name of the field that matches the string we were given - field, _, err := findField(elem, name) - // if something went wrong - if err != nil { - // bubble up - return err - } - // handle references to the Settable interface aswell - if s, ok := field.Interface().(Settable); ok { - // use the interface method - return s.WriteAnswer(name, v) - } - if field.CanAddr() { - if s, ok := field.Addr().Interface().(Settable); ok { - // use the interface method - return s.WriteAnswer(name, v) - } - } - - // copy the value over to the normal struct - return copy(field, value) - case reflect.Map: - mapType := reflect.TypeOf(t).Elem() - if mapType.Key().Kind() != reflect.String { - return errors.New("answer maps key must be of type string") - } - - // copy only string value/index value to map if, - // map is not of type interface and is 'OptionAnswer' - if value.Type().Name() == "OptionAnswer" { - if kval := mapType.Elem().Kind(); kval == reflect.String { - mt := *t.(*map[string]string) - mt[name] = value.FieldByName("Value").String() - return nil - } else if kval == reflect.Int { - mt := *t.(*map[string]int) - mt[name] = int(value.FieldByName("Index").Int()) - return nil - } - } - - if mapType.Elem().Kind() != reflect.Interface { - return errors.New("answer maps must be of type map[string]interface") - } - mt := *t.(*map[string]interface{}) - mt[name] = value.Interface() - return nil - } - // otherwise just copy the value to the target - return copy(elem, value) -} - -type errFieldNotMatch struct { - questionName string -} - -func (err errFieldNotMatch) Error() string { - return fmt.Sprintf("could not find field matching %v", err.questionName) -} - -func (err errFieldNotMatch) Is(target error) bool { // implements the dynamic errors.Is interface. - if target != nil { - if name, ok := IsFieldNotMatch(target); ok { - // if have a filled questionName then perform "deeper" comparison. - return name == "" || err.questionName == "" || name == err.questionName - } - } - - return false -} - -// IsFieldNotMatch reports whether an "err" is caused by a non matching field. -// It returns the Question.Name that couldn't be matched with a destination field. -// -// Usage: -// -// if err := survey.Ask(qs, &v); err != nil { -// if name, ok := core.IsFieldNotMatch(err); ok { -// // name is the question name that did not match a field -// } -// } -func IsFieldNotMatch(err error) (string, bool) { - if err != nil { - if v, ok := err.(errFieldNotMatch); ok { - return v.questionName, true - } - } - - return "", false -} - -// BUG(AlecAivazis): the current implementation might cause weird conflicts if there are -// two fields with same name that only differ by casing. -func findField(s reflect.Value, name string) (reflect.Value, reflect.StructField, error) { - - fields := flattenFields(s) - - // first look for matching tags so we can overwrite matching field names - for _, f := range fields { - // the value of the survey tag - tag := f.fieldType.Tag.Get(tagName) - // if the tag matches the name we are looking for - if tag != "" && tag == name { - // then we found our index - return f.value, f.fieldType, nil - } - } - - // then look for matching names - for _, f := range fields { - // if the name of the field matches what we're looking for - if strings.EqualFold(f.fieldType.Name, name) { - return f.value, f.fieldType, nil - } - } - - // we didn't find the field - return reflect.Value{}, reflect.StructField{}, errFieldNotMatch{name} -} - -func flattenFields(s reflect.Value) []reflectField { - sType := s.Type() - numField := sType.NumField() - fields := make([]reflectField, 0, numField) - for i := 0; i < numField; i++ { - fieldType := sType.Field(i) - field := s.Field(i) - - if field.Kind() == reflect.Struct && fieldType.Anonymous { - // field is a promoted structure - fields = append(fields, flattenFields(field)...) - continue - } - fields = append(fields, reflectField{field, fieldType}) - } - return fields -} - -// isList returns true if the element is something we can Len() -func isList(v reflect.Value) bool { - switch v.Type().Kind() { - case reflect.Array, reflect.Slice: - return true - default: - return false - } -} - -// Write takes a value and copies it to the target -func copy(t reflect.Value, v reflect.Value) (err error) { - // if something ends up panicing we need to catch it in a deferred func - defer func() { - if r := recover(); r != nil { - // if we paniced with an error - if _, ok := r.(error); ok { - // cast the result to an error object - err = r.(error) - } else if _, ok := r.(string); ok { - // otherwise we could have paniced with a string so wrap it in an error - err = errors.New(r.(string)) - } - } - }() - - // if we are copying from a string result to something else - if v.Kind() == reflect.String && v.Type() != t.Type() { - var castVal interface{} - var casterr error - vString := v.Interface().(string) - - switch t.Kind() { - case reflect.Bool: - castVal, casterr = strconv.ParseBool(vString) - case reflect.Int: - castVal, casterr = strconv.Atoi(vString) - case reflect.Int8: - var val64 int64 - val64, casterr = strconv.ParseInt(vString, 10, 8) - if casterr == nil { - castVal = int8(val64) - } - case reflect.Int16: - var val64 int64 - val64, casterr = strconv.ParseInt(vString, 10, 16) - if casterr == nil { - castVal = int16(val64) - } - case reflect.Int32: - var val64 int64 - val64, casterr = strconv.ParseInt(vString, 10, 32) - if casterr == nil { - castVal = int32(val64) - } - case reflect.Int64: - if t.Type() == reflect.TypeOf(time.Duration(0)) { - castVal, casterr = time.ParseDuration(vString) - } else { - castVal, casterr = strconv.ParseInt(vString, 10, 64) - } - case reflect.Uint: - var val64 uint64 - val64, casterr = strconv.ParseUint(vString, 10, 8) - if casterr == nil { - castVal = uint(val64) - } - case reflect.Uint8: - var val64 uint64 - val64, casterr = strconv.ParseUint(vString, 10, 8) - if casterr == nil { - castVal = uint8(val64) - } - case reflect.Uint16: - var val64 uint64 - val64, casterr = strconv.ParseUint(vString, 10, 16) - if casterr == nil { - castVal = uint16(val64) - } - case reflect.Uint32: - var val64 uint64 - val64, casterr = strconv.ParseUint(vString, 10, 32) - if casterr == nil { - castVal = uint32(val64) - } - case reflect.Uint64: - castVal, casterr = strconv.ParseUint(vString, 10, 64) - case reflect.Float32: - var val64 float64 - val64, casterr = strconv.ParseFloat(vString, 32) - if casterr == nil { - castVal = float32(val64) - } - case reflect.Float64: - castVal, casterr = strconv.ParseFloat(vString, 64) - default: - //lint:ignore ST1005 allow this error message to be capitalized - return fmt.Errorf("Unable to convert from string to type %s", t.Kind()) - } - - if casterr != nil { - return casterr - } - - t.Set(reflect.ValueOf(castVal)) - return - } - - // if we are copying from an OptionAnswer to something - if v.Type().Name() == "OptionAnswer" { - // copying an option answer to a string - if t.Kind() == reflect.String { - // copies the Value field of the struct - t.Set(reflect.ValueOf(v.FieldByName("Value").Interface())) - return - } - - // copying an option answer to an int - if t.Kind() == reflect.Int { - // copies the Index field of the struct - t.Set(reflect.ValueOf(v.FieldByName("Index").Interface())) - return - } - - // copying an OptionAnswer to an OptionAnswer - if t.Type().Name() == "OptionAnswer" { - t.Set(v) - return - } - - // we're copying an option answer to an incorrect type - //lint:ignore ST1005 allow this error message to be capitalized - return fmt.Errorf("Unable to convert from OptionAnswer to type %s", t.Kind()) - } - - // if we are copying from one slice or array to another - if isList(v) && isList(t) { - // loop over every item in the desired value - for i := 0; i < v.Len(); i++ { - // write to the target given its kind - switch t.Kind() { - // if its a slice - case reflect.Slice: - // an object of the correct type - obj := reflect.Indirect(reflect.New(t.Type().Elem())) - - // write the appropriate value to the obj and catch any errors - if err := copy(obj, v.Index(i)); err != nil { - return err - } - - // just append the value to the end - t.Set(reflect.Append(t, obj)) - // otherwise it could be an array - case reflect.Array: - // set the index to the appropriate value - if err := copy(t.Slice(i, i+1).Index(0), v.Index(i)); err != nil { - return err - } - } - } - } else { - // set the value to the target - t.Set(v) - } - - // we're done - return -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/editor.go b/vendor/github.com/AlecAivazis/survey/v2/editor.go deleted file mode 100644 index 20470f119..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/editor.go +++ /dev/null @@ -1,226 +0,0 @@ -package survey - -import ( - "bytes" - "io/ioutil" - "os" - "os/exec" - "runtime" - - "github.com/AlecAivazis/survey/v2/terminal" - shellquote "github.com/kballard/go-shellquote" -) - -/* -Editor launches an instance of the users preferred editor on a temporary file. -The editor to use is determined by reading the $VISUAL or $EDITOR environment -variables. If neither of those are present, notepad (on Windows) or vim -(others) is used. -The launch of the editor is triggered by the enter key. Since the response may -be long, it will not be echoed as Input does, instead, it print . -Response type is a string. - - message := "" - prompt := &survey.Editor{ Message: "What is your commit message?" } - survey.AskOne(prompt, &message) -*/ -type Editor struct { - Renderer - Message string - Default string - Help string - Editor string - HideDefault bool - AppendDefault bool - FileName string -} - -// data available to the templates when processing -type EditorTemplateData struct { - Editor - Answer string - ShowAnswer bool - ShowHelp bool - Config *PromptConfig -} - -// Templates with Color formatting. See Documentation: https://github.com/mgutz/ansi#style-format -var EditorQuestionTemplate = ` -{{- if .ShowHelp }}{{- color .Config.Icons.Help.Format }}{{ .Config.Icons.Help.Text }} {{ .Help }}{{color "reset"}}{{"\n"}}{{end}} -{{- color .Config.Icons.Question.Format }}{{ .Config.Icons.Question.Text }} {{color "reset"}} -{{- color "default+hb"}}{{ .Message }} {{color "reset"}} -{{- if .ShowAnswer}} - {{- color "cyan"}}{{.Answer}}{{color "reset"}}{{"\n"}} -{{- else }} - {{- if and .Help (not .ShowHelp)}}{{color "cyan"}}[{{ .Config.HelpInput }} for help]{{color "reset"}} {{end}} - {{- if and .Default (not .HideDefault)}}{{color "white"}}({{.Default}}) {{color "reset"}}{{end}} - {{- color "cyan"}}[Enter to launch editor] {{color "reset"}} -{{- end}}` - -var ( - bom = []byte{0xef, 0xbb, 0xbf} - editor = "vim" -) - -func init() { - if runtime.GOOS == "windows" { - editor = "notepad" - } - if v := os.Getenv("VISUAL"); v != "" { - editor = v - } else if e := os.Getenv("EDITOR"); e != "" { - editor = e - } -} - -func (e *Editor) PromptAgain(config *PromptConfig, invalid interface{}, err error) (interface{}, error) { - initialValue := invalid.(string) - return e.prompt(initialValue, config) -} - -func (e *Editor) Prompt(config *PromptConfig) (interface{}, error) { - initialValue := "" - if e.Default != "" && e.AppendDefault { - initialValue = e.Default - } - return e.prompt(initialValue, config) -} - -func (e *Editor) prompt(initialValue string, config *PromptConfig) (interface{}, error) { - // render the template - err := e.Render( - EditorQuestionTemplate, - EditorTemplateData{ - Editor: *e, - Config: config, - }, - ) - if err != nil { - return "", err - } - - // start reading runes from the standard in - rr := e.NewRuneReader() - _ = rr.SetTermMode() - defer func() { - _ = rr.RestoreTermMode() - }() - - cursor := e.NewCursor() - cursor.Hide() - defer cursor.Show() - - for { - r, _, err := rr.ReadRune() - if err != nil { - return "", err - } - if r == '\r' || r == '\n' { - break - } - if r == terminal.KeyInterrupt { - return "", terminal.InterruptErr - } - if r == terminal.KeyEndTransmission { - break - } - if string(r) == config.HelpInput && e.Help != "" { - err = e.Render( - EditorQuestionTemplate, - EditorTemplateData{ - Editor: *e, - ShowHelp: true, - Config: config, - }, - ) - if err != nil { - return "", err - } - } - continue - } - - // prepare the temp file - pattern := e.FileName - if pattern == "" { - pattern = "survey*.txt" - } - f, err := ioutil.TempFile("", pattern) - if err != nil { - return "", err - } - defer func() { - _ = os.Remove(f.Name()) - }() - - // write utf8 BOM header - // The reason why we do this is because notepad.exe on Windows determines the - // encoding of an "empty" text file by the locale, for example, GBK in China, - // while golang string only handles utf8 well. However, a text file with utf8 - // BOM header is not considered "empty" on Windows, and the encoding will then - // be determined utf8 by notepad.exe, instead of GBK or other encodings. - if _, err := f.Write(bom); err != nil { - return "", err - } - - // write initial value - if _, err := f.WriteString(initialValue); err != nil { - return "", err - } - - // close the fd to prevent the editor unable to save file - if err := f.Close(); err != nil { - return "", err - } - - // check is input editor exist - if e.Editor != "" { - editor = e.Editor - } - - stdio := e.Stdio() - - args, err := shellquote.Split(editor) - if err != nil { - return "", err - } - args = append(args, f.Name()) - - // open the editor - cmd := exec.Command(args[0], args[1:]...) - cmd.Stdin = stdio.In - cmd.Stdout = stdio.Out - cmd.Stderr = stdio.Err - cursor.Show() - if err := cmd.Run(); err != nil { - return "", err - } - - // raw is a BOM-unstripped UTF8 byte slice - raw, err := ioutil.ReadFile(f.Name()) - if err != nil { - return "", err - } - - // strip BOM header - text := string(bytes.TrimPrefix(raw, bom)) - - // check length, return default value on empty - if len(text) == 0 && !e.AppendDefault { - return e.Default, nil - } - - return text, nil -} - -func (e *Editor) Cleanup(config *PromptConfig, val interface{}) error { - return e.Render( - EditorQuestionTemplate, - EditorTemplateData{ - Editor: *e, - Answer: "", - ShowAnswer: true, - Config: config, - }, - ) -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/filter.go b/vendor/github.com/AlecAivazis/survey/v2/filter.go deleted file mode 100644 index 56f702678..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/filter.go +++ /dev/null @@ -1 +0,0 @@ -package survey diff --git a/vendor/github.com/AlecAivazis/survey/v2/input.go b/vendor/github.com/AlecAivazis/survey/v2/input.go deleted file mode 100644 index 047476386..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/input.go +++ /dev/null @@ -1,219 +0,0 @@ -package survey - -import ( - "errors" - - "github.com/AlecAivazis/survey/v2/core" - "github.com/AlecAivazis/survey/v2/terminal" -) - -/* -Input is a regular text input that prints each character the user types on the screen -and accepts the input with the enter key. Response type is a string. - - name := "" - prompt := &survey.Input{ Message: "What is your name?" } - survey.AskOne(prompt, &name) -*/ -type Input struct { - Renderer - Message string - Default string - Help string - Suggest func(toComplete string) []string - answer string - typedAnswer string - options []core.OptionAnswer - selectedIndex int - showingHelp bool -} - -// data available to the templates when processing -type InputTemplateData struct { - Input - ShowAnswer bool - ShowHelp bool - Answer string - PageEntries []core.OptionAnswer - SelectedIndex int - Config *PromptConfig -} - -// Templates with Color formatting. See Documentation: https://github.com/mgutz/ansi#style-format -var InputQuestionTemplate = ` -{{- if .ShowHelp }}{{- color .Config.Icons.Help.Format }}{{ .Config.Icons.Help.Text }} {{ .Help }}{{color "reset"}}{{"\n"}}{{end}} -{{- color .Config.Icons.Question.Format }}{{ .Config.Icons.Question.Text }} {{color "reset"}} -{{- color "default+hb"}}{{ .Message }} {{color "reset"}} -{{- if .ShowAnswer}} - {{- color "cyan"}}{{.Answer}}{{color "reset"}}{{"\n"}} -{{- else if .PageEntries -}} - {{- .Answer}} [Use arrows to move, enter to select, type to continue] - {{- "\n"}} - {{- range $ix, $choice := .PageEntries}} - {{- if eq $ix $.SelectedIndex }}{{color $.Config.Icons.SelectFocus.Format }}{{ $.Config.Icons.SelectFocus.Text }} {{else}}{{color "default"}} {{end}} - {{- $choice.Value}} - {{- color "reset"}}{{"\n"}} - {{- end}} -{{- else }} - {{- if or (and .Help (not .ShowHelp)) .Suggest }}{{color "cyan"}}[ - {{- if and .Help (not .ShowHelp)}}{{ print .Config.HelpInput }} for help {{- if and .Suggest}}, {{end}}{{end -}} - {{- if and .Suggest }}{{color "cyan"}}{{ print .Config.SuggestInput }} for suggestions{{end -}} - ]{{color "reset"}} {{end}} - {{- if .Default}}{{color "white"}}({{.Default}}) {{color "reset"}}{{end}} -{{- end}}` - -func (i *Input) onRune(config *PromptConfig) terminal.OnRuneFn { - return terminal.OnRuneFn(func(key rune, line []rune) ([]rune, bool, error) { - if i.options != nil && (key == terminal.KeyEnter || key == '\n') { - return []rune(i.answer), true, nil - } else if i.options != nil && key == terminal.KeyEscape { - i.answer = i.typedAnswer - i.options = nil - } else if key == terminal.KeyArrowUp && len(i.options) > 0 { - if i.selectedIndex == 0 { - i.selectedIndex = len(i.options) - 1 - } else { - i.selectedIndex-- - } - i.answer = i.options[i.selectedIndex].Value - } else if (key == terminal.KeyArrowDown || key == terminal.KeyTab) && len(i.options) > 0 { - if i.selectedIndex == len(i.options)-1 { - i.selectedIndex = 0 - } else { - i.selectedIndex++ - } - i.answer = i.options[i.selectedIndex].Value - } else if key == terminal.KeyTab && i.Suggest != nil { - i.answer = string(line) - i.typedAnswer = i.answer - options := i.Suggest(i.answer) - i.selectedIndex = 0 - if len(options) == 0 { - return line, false, nil - } - - i.answer = options[0] - if len(options) == 1 { - i.typedAnswer = i.answer - i.options = nil - } else { - i.options = core.OptionAnswerList(options) - } - } else { - if i.options == nil { - return line, false, nil - } - - if key >= terminal.KeySpace { - i.answer += string(key) - } - i.typedAnswer = i.answer - - i.options = nil - } - - pageSize := config.PageSize - opts, idx := paginate(pageSize, i.options, i.selectedIndex) - err := i.Render( - InputQuestionTemplate, - InputTemplateData{ - Input: *i, - Answer: i.answer, - ShowHelp: i.showingHelp, - SelectedIndex: idx, - PageEntries: opts, - Config: config, - }, - ) - - if err == nil { - err = errReadLineAgain - } - - return []rune(i.typedAnswer), true, err - }) -} - -var errReadLineAgain = errors.New("read line again") - -func (i *Input) Prompt(config *PromptConfig) (interface{}, error) { - // render the template - err := i.Render( - InputQuestionTemplate, - InputTemplateData{ - Input: *i, - Config: config, - ShowHelp: i.showingHelp, - }, - ) - if err != nil { - return "", err - } - - // start reading runes from the standard in - rr := i.NewRuneReader() - _ = rr.SetTermMode() - defer func() { - _ = rr.RestoreTermMode() - }() - cursor := i.NewCursor() - if !config.ShowCursor { - cursor.Hide() // hide the cursor - defer cursor.Show() // show the cursor when we're done - } - - var line []rune - - for { - if i.options != nil { - line = []rune{} - } - - line, err = rr.ReadLineWithDefault(0, line, i.onRune(config)) - if err == errReadLineAgain { - continue - } - - if err != nil { - return "", err - } - - break - } - - i.answer = string(line) - // readline print an empty line, go up before we render the follow up - cursor.Up(1) - - // if we ran into the help string - if i.answer == config.HelpInput && i.Help != "" { - // show the help and prompt again - i.showingHelp = true - return i.Prompt(config) - } - - // if the line is empty - if len(i.answer) == 0 { - // use the default value - return i.Default, err - } - - lineStr := i.answer - - i.AppendRenderedText(lineStr) - - // we're done - return lineStr, err -} - -func (i *Input) Cleanup(config *PromptConfig, val interface{}) error { - return i.Render( - InputQuestionTemplate, - InputTemplateData{ - Input: *i, - ShowAnswer: true, - Config: config, - Answer: val.(string), - }, - ) -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/multiline.go b/vendor/github.com/AlecAivazis/survey/v2/multiline.go deleted file mode 100644 index bff9622f6..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/multiline.go +++ /dev/null @@ -1,112 +0,0 @@ -package survey - -import ( - "strings" - - "github.com/AlecAivazis/survey/v2/terminal" -) - -type Multiline struct { - Renderer - Message string - Default string - Help string -} - -// data available to the templates when processing -type MultilineTemplateData struct { - Multiline - Answer string - ShowAnswer bool - ShowHelp bool - Config *PromptConfig -} - -// Templates with Color formatting. See Documentation: https://github.com/mgutz/ansi#style-format -var MultilineQuestionTemplate = ` -{{- if .ShowHelp }}{{- color .Config.Icons.Help.Format }}{{ .Config.Icons.Help.Text }} {{ .Help }}{{color "reset"}}{{"\n"}}{{end}} -{{- color .Config.Icons.Question.Format }}{{ .Config.Icons.Question.Text }} {{color "reset"}} -{{- color "default+hb"}}{{ .Message }} {{color "reset"}} -{{- if .ShowAnswer}} - {{- "\n"}}{{color "cyan"}}{{.Answer}}{{color "reset"}} - {{- if .Answer }}{{ "\n" }}{{ end }} -{{- else }} - {{- if .Default}}{{color "white"}}({{.Default}}) {{color "reset"}}{{end}} - {{- color "cyan"}}[Enter 2 empty lines to finish]{{color "reset"}} -{{- end}}` - -func (i *Multiline) Prompt(config *PromptConfig) (interface{}, error) { - // render the template - err := i.Render( - MultilineQuestionTemplate, - MultilineTemplateData{ - Multiline: *i, - Config: config, - }, - ) - if err != nil { - return "", err - } - - // start reading runes from the standard in - rr := i.NewRuneReader() - _ = rr.SetTermMode() - defer func() { - _ = rr.RestoreTermMode() - }() - - cursor := i.NewCursor() - - multiline := make([]string, 0) - - emptyOnce := false - // get the next line - for { - var line []rune - line, err = rr.ReadLine(0) - if err != nil { - return string(line), err - } - - if string(line) == "" { - if emptyOnce { - numLines := len(multiline) + 2 - cursor.PreviousLine(numLines) - for j := 0; j < numLines; j++ { - terminal.EraseLine(i.Stdio().Out, terminal.ERASE_LINE_ALL) - cursor.NextLine(1) - } - cursor.PreviousLine(numLines) - break - } - emptyOnce = true - } else { - emptyOnce = false - } - multiline = append(multiline, string(line)) - } - - val := strings.Join(multiline, "\n") - val = strings.TrimSpace(val) - - // if the line is empty - if len(val) == 0 { - // use the default value - return i.Default, err - } - - i.AppendRenderedText(val) - return val, err -} - -func (i *Multiline) Cleanup(config *PromptConfig, val interface{}) error { - return i.Render( - MultilineQuestionTemplate, - MultilineTemplateData{ - Multiline: *i, - Answer: val.(string), - ShowAnswer: true, - Config: config, - }, - ) -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/multiselect.go b/vendor/github.com/AlecAivazis/survey/v2/multiselect.go deleted file mode 100644 index 396169f3e..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/multiselect.go +++ /dev/null @@ -1,360 +0,0 @@ -package survey - -import ( - "errors" - "fmt" - - "github.com/AlecAivazis/survey/v2/core" - "github.com/AlecAivazis/survey/v2/terminal" -) - -/* -MultiSelect is a prompt that presents a list of various options to the user -for them to select using the arrow keys and enter. Response type is a slice of strings. - - days := []string{} - prompt := &survey.MultiSelect{ - Message: "What days do you prefer:", - Options: []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}, - } - survey.AskOne(prompt, &days) -*/ -type MultiSelect struct { - Renderer - Message string - Options []string - Default interface{} - Help string - PageSize int - VimMode bool - FilterMessage string - Filter func(filter string, value string, index int) bool - Description func(value string, index int) string - filter string - selectedIndex int - checked map[int]bool - showingHelp bool -} - -// data available to the templates when processing -type MultiSelectTemplateData struct { - MultiSelect - Answer string - ShowAnswer bool - Checked map[int]bool - SelectedIndex int - ShowHelp bool - Description func(value string, index int) string - PageEntries []core.OptionAnswer - Config *PromptConfig - - // These fields are used when rendering an individual option - CurrentOpt core.OptionAnswer - CurrentIndex int -} - -// IterateOption sets CurrentOpt and CurrentIndex appropriately so a multiselect option can be rendered individually -func (m MultiSelectTemplateData) IterateOption(ix int, opt core.OptionAnswer) interface{} { - copy := m - copy.CurrentIndex = ix - copy.CurrentOpt = opt - return copy -} - -func (m MultiSelectTemplateData) GetDescription(opt core.OptionAnswer) string { - if m.Description == nil { - return "" - } - return m.Description(opt.Value, opt.Index) -} - -var MultiSelectQuestionTemplate = ` -{{- define "option"}} - {{- if eq .SelectedIndex .CurrentIndex }}{{color .Config.Icons.SelectFocus.Format }}{{ .Config.Icons.SelectFocus.Text }}{{color "reset"}}{{else}} {{end}} - {{- if index .Checked .CurrentOpt.Index }}{{color .Config.Icons.MarkedOption.Format }} {{ .Config.Icons.MarkedOption.Text }} {{else}}{{color .Config.Icons.UnmarkedOption.Format }} {{ .Config.Icons.UnmarkedOption.Text }} {{end}} - {{- color "reset"}} - {{- " "}}{{- .CurrentOpt.Value}}{{ if ne ($.GetDescription .CurrentOpt) "" }} - {{color "cyan"}}{{ $.GetDescription .CurrentOpt }}{{color "reset"}}{{end}} -{{end}} -{{- if .ShowHelp }}{{- color .Config.Icons.Help.Format }}{{ .Config.Icons.Help.Text }} {{ .Help }}{{color "reset"}}{{"\n"}}{{end}} -{{- color .Config.Icons.Question.Format }}{{ .Config.Icons.Question.Text }} {{color "reset"}} -{{- color "default+hb"}}{{ .Message }}{{ .FilterMessage }}{{color "reset"}} -{{- if .ShowAnswer}}{{color "cyan"}} {{.Answer}}{{color "reset"}}{{"\n"}} -{{- else }} - {{- " "}}{{- color "cyan"}}[Use arrows to move, space to select,{{- if not .Config.RemoveSelectAll }} to all,{{end}}{{- if not .Config.RemoveSelectNone }} to none,{{end}} type to filter{{- if and .Help (not .ShowHelp)}}, {{ .Config.HelpInput }} for more help{{end}}]{{color "reset"}} - {{- "\n"}} - {{- range $ix, $option := .PageEntries}} - {{- template "option" $.IterateOption $ix $option}} - {{- end}} -{{- end}}` - -// OnChange is called on every keypress. -func (m *MultiSelect) OnChange(key rune, config *PromptConfig) { - options := m.filterOptions(config) - oldFilter := m.filter - - if key == terminal.KeyArrowUp || (m.VimMode && key == 'k') { - // if we are at the top of the list - if m.selectedIndex == 0 { - // go to the bottom - m.selectedIndex = len(options) - 1 - } else { - // decrement the selected index - m.selectedIndex-- - } - } else if key == terminal.KeyTab || key == terminal.KeyArrowDown || (m.VimMode && key == 'j') { - // if we are at the bottom of the list - if m.selectedIndex == len(options)-1 { - // start at the top - m.selectedIndex = 0 - } else { - // increment the selected index - m.selectedIndex++ - } - // if the user pressed down and there is room to move - } else if key == terminal.KeySpace { - // the option they have selected - if m.selectedIndex < len(options) { - selectedOpt := options[m.selectedIndex] - - // if we haven't seen this index before - if old, ok := m.checked[selectedOpt.Index]; !ok { - // set the value to true - m.checked[selectedOpt.Index] = true - } else { - // otherwise just invert the current value - m.checked[selectedOpt.Index] = !old - } - if !config.KeepFilter { - m.filter = "" - } - } - // only show the help message if we have one to show - } else if string(key) == config.HelpInput && m.Help != "" { - m.showingHelp = true - } else if key == terminal.KeyEscape { - m.VimMode = !m.VimMode - } else if key == terminal.KeyDeleteWord || key == terminal.KeyDeleteLine { - m.filter = "" - } else if key == terminal.KeyDelete || key == terminal.KeyBackspace { - if m.filter != "" { - runeFilter := []rune(m.filter) - m.filter = string(runeFilter[0 : len(runeFilter)-1]) - } - } else if key >= terminal.KeySpace { - m.filter += string(key) - m.VimMode = false - } else if !config.RemoveSelectAll && key == terminal.KeyArrowRight { - for _, v := range options { - m.checked[v.Index] = true - } - if !config.KeepFilter { - m.filter = "" - } - } else if !config.RemoveSelectNone && key == terminal.KeyArrowLeft { - for _, v := range options { - m.checked[v.Index] = false - } - if !config.KeepFilter { - m.filter = "" - } - } - - m.FilterMessage = "" - if m.filter != "" { - m.FilterMessage = " " + m.filter - } - if oldFilter != m.filter { - // filter changed - options = m.filterOptions(config) - if len(options) > 0 && len(options) <= m.selectedIndex { - m.selectedIndex = len(options) - 1 - } - } - // paginate the options - // figure out the page size - pageSize := m.PageSize - // if we dont have a specific one - if pageSize == 0 { - // grab the global value - pageSize = config.PageSize - } - - // TODO if we have started filtering and were looking at the end of a list - // and we have modified the filter then we should move the page back! - opts, idx := paginate(pageSize, options, m.selectedIndex) - - tmplData := MultiSelectTemplateData{ - MultiSelect: *m, - SelectedIndex: idx, - Checked: m.checked, - ShowHelp: m.showingHelp, - Description: m.Description, - PageEntries: opts, - Config: config, - } - - // render the options - _ = m.RenderWithCursorOffset(MultiSelectQuestionTemplate, tmplData, opts, idx) -} - -func (m *MultiSelect) filterOptions(config *PromptConfig) []core.OptionAnswer { - // the filtered list - answers := []core.OptionAnswer{} - - // if there is no filter applied - if m.filter == "" { - // return all of the options - return core.OptionAnswerList(m.Options) - } - - // the filter to apply - filter := m.Filter - if filter == nil { - filter = config.Filter - } - - // apply the filter to each option - for i, opt := range m.Options { - // i the filter says to include the option - if filter(m.filter, opt, i) { - answers = append(answers, core.OptionAnswer{ - Index: i, - Value: opt, - }) - } - } - - // we're done here - return answers -} - -func (m *MultiSelect) Prompt(config *PromptConfig) (interface{}, error) { - // compute the default state - m.checked = make(map[int]bool) - // if there is a default - if m.Default != nil { - // if the default is string values - if defaultValues, ok := m.Default.([]string); ok { - for _, dflt := range defaultValues { - for i, opt := range m.Options { - // if the option corresponds to the default - if opt == dflt { - // we found our initial value - m.checked[i] = true - // stop looking - break - } - } - } - // if the default value is index values - } else if defaultIndices, ok := m.Default.([]int); ok { - // go over every index we need to enable by default - for _, idx := range defaultIndices { - // and enable it - m.checked[idx] = true - } - } - } - - // if there are no options to render - if len(m.Options) == 0 { - // we failed - return "", errors.New("please provide options to select from") - } - - // figure out the page size - pageSize := m.PageSize - // if we dont have a specific one - if pageSize == 0 { - // grab the global value - pageSize = config.PageSize - } - // paginate the options - // build up a list of option answers - opts, idx := paginate(pageSize, core.OptionAnswerList(m.Options), m.selectedIndex) - - cursor := m.NewCursor() - cursor.Save() // for proper cursor placement during selection - cursor.Hide() // hide the cursor - defer cursor.Show() // show the cursor when we're done - defer cursor.Restore() // clear any accessibility offsetting on exit - - tmplData := MultiSelectTemplateData{ - MultiSelect: *m, - SelectedIndex: idx, - Description: m.Description, - Checked: m.checked, - PageEntries: opts, - Config: config, - } - - // ask the question - err := m.RenderWithCursorOffset(MultiSelectQuestionTemplate, tmplData, opts, idx) - if err != nil { - return "", err - } - - rr := m.NewRuneReader() - _ = rr.SetTermMode() - defer func() { - _ = rr.RestoreTermMode() - }() - - // start waiting for input - for { - r, _, err := rr.ReadRune() - if err != nil { - return "", err - } - if r == '\r' || r == '\n' { - break - } - if r == terminal.KeyInterrupt { - return "", terminal.InterruptErr - } - if r == terminal.KeyEndTransmission { - break - } - m.OnChange(r, config) - } - m.filter = "" - m.FilterMessage = "" - - answers := []core.OptionAnswer{} - for i, option := range m.Options { - if val, ok := m.checked[i]; ok && val { - answers = append(answers, core.OptionAnswer{Value: option, Index: i}) - } - } - - return answers, nil -} - -// Cleanup removes the options section, and renders the ask like a normal question. -func (m *MultiSelect) Cleanup(config *PromptConfig, val interface{}) error { - // the answer to show - answer := "" - for _, ans := range val.([]core.OptionAnswer) { - answer = fmt.Sprintf("%s, %s", answer, ans.Value) - } - - // if we answered anything - if len(answer) > 2 { - // remove the precending commas - answer = answer[2:] - } - - // execute the output summary template with the answer - return m.Render( - MultiSelectQuestionTemplate, - MultiSelectTemplateData{ - MultiSelect: *m, - SelectedIndex: m.selectedIndex, - Checked: m.checked, - Answer: answer, - ShowAnswer: true, - Description: m.Description, - Config: config, - }, - ) -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/password.go b/vendor/github.com/AlecAivazis/survey/v2/password.go deleted file mode 100644 index 96a2ae89f..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/password.go +++ /dev/null @@ -1,106 +0,0 @@ -package survey - -import ( - "fmt" - "strings" - - "github.com/AlecAivazis/survey/v2/core" - "github.com/AlecAivazis/survey/v2/terminal" -) - -/* -Password is like a normal Input but the text shows up as *'s and there is no default. Response -type is a string. - - password := "" - prompt := &survey.Password{ Message: "Please type your password" } - survey.AskOne(prompt, &password) -*/ -type Password struct { - Renderer - Message string - Help string -} - -type PasswordTemplateData struct { - Password - ShowHelp bool - Config *PromptConfig -} - -// PasswordQuestionTemplate is a template with color formatting. See Documentation: https://github.com/mgutz/ansi#style-format -var PasswordQuestionTemplate = ` -{{- if .ShowHelp }}{{- color .Config.Icons.Help.Format }}{{ .Config.Icons.Help.Text }} {{ .Help }}{{color "reset"}}{{"\n"}}{{end}} -{{- color .Config.Icons.Question.Format }}{{ .Config.Icons.Question.Text }} {{color "reset"}} -{{- color "default+hb"}}{{ .Message }} {{color "reset"}} -{{- if and .Help (not .ShowHelp)}}{{color "cyan"}}[{{ .Config.HelpInput }} for help]{{color "reset"}} {{end}}` - -func (p *Password) Prompt(config *PromptConfig) (interface{}, error) { - // render the question template - userOut, _, err := core.RunTemplate( - PasswordQuestionTemplate, - PasswordTemplateData{ - Password: *p, - Config: config, - }, - ) - if err != nil { - return "", err - } - - if _, err := fmt.Fprint(terminal.NewAnsiStdout(p.Stdio().Out), userOut); err != nil { - return "", err - } - - rr := p.NewRuneReader() - _ = rr.SetTermMode() - defer func() { - _ = rr.RestoreTermMode() - }() - - // no help msg? Just return any response - if p.Help == "" { - line, err := rr.ReadLine(config.HideCharacter) - return string(line), err - } - - cursor := p.NewCursor() - - var line []rune - // process answers looking for help prompt answer - for { - line, err = rr.ReadLine(config.HideCharacter) - if err != nil { - return string(line), err - } - - if string(line) == config.HelpInput { - // terminal will echo the \n so we need to jump back up one row - cursor.PreviousLine(1) - - err = p.Render( - PasswordQuestionTemplate, - PasswordTemplateData{ - Password: *p, - ShowHelp: true, - Config: config, - }, - ) - if err != nil { - return "", err - } - continue - } - - break - } - - lineStr := string(line) - p.AppendRenderedText(strings.Repeat(string(config.HideCharacter), len(lineStr))) - return lineStr, err -} - -// Cleanup hides the string with a fixed number of characters. -func (prompt *Password) Cleanup(config *PromptConfig, val interface{}) error { - return nil -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/renderer.go b/vendor/github.com/AlecAivazis/survey/v2/renderer.go deleted file mode 100644 index a16207de0..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/renderer.go +++ /dev/null @@ -1,195 +0,0 @@ -package survey - -import ( - "bytes" - "fmt" - "github.com/AlecAivazis/survey/v2/core" - "github.com/AlecAivazis/survey/v2/terminal" - "golang.org/x/term" -) - -type Renderer struct { - stdio terminal.Stdio - renderedErrors bytes.Buffer - renderedText bytes.Buffer -} - -type ErrorTemplateData struct { - Error error - Icon Icon -} - -var ErrorTemplate = `{{color .Icon.Format }}{{ .Icon.Text }} Sorry, your reply was invalid: {{ .Error.Error }}{{color "reset"}} -` - -func (r *Renderer) WithStdio(stdio terminal.Stdio) { - r.stdio = stdio -} - -func (r *Renderer) Stdio() terminal.Stdio { - return r.stdio -} - -func (r *Renderer) NewRuneReader() *terminal.RuneReader { - return terminal.NewRuneReader(r.stdio) -} - -func (r *Renderer) NewCursor() *terminal.Cursor { - return &terminal.Cursor{ - In: r.stdio.In, - Out: r.stdio.Out, - } -} - -func (r *Renderer) Error(config *PromptConfig, invalid error) error { - // cleanup the currently rendered errors - r.resetPrompt(r.countLines(r.renderedErrors)) - r.renderedErrors.Reset() - - // cleanup the rest of the prompt - r.resetPrompt(r.countLines(r.renderedText)) - r.renderedText.Reset() - - userOut, layoutOut, err := core.RunTemplate(ErrorTemplate, &ErrorTemplateData{ - Error: invalid, - Icon: config.Icons.Error, - }) - if err != nil { - return err - } - - // send the message to the user - if _, err := fmt.Fprint(terminal.NewAnsiStdout(r.stdio.Out), userOut); err != nil { - return err - } - - // add the printed text to the rendered error buffer so we can cleanup later - r.appendRenderedError(layoutOut) - - return nil -} - -func (r *Renderer) OffsetCursor(offset int) { - cursor := r.NewCursor() - for offset > 0 { - cursor.PreviousLine(1) - offset-- - } -} - -func (r *Renderer) Render(tmpl string, data interface{}) error { - // cleanup the currently rendered text - lineCount := r.countLines(r.renderedText) - r.resetPrompt(lineCount) - r.renderedText.Reset() - - // render the template summarizing the current state - userOut, layoutOut, err := core.RunTemplate(tmpl, data) - if err != nil { - return err - } - - // print the summary - if _, err := fmt.Fprint(terminal.NewAnsiStdout(r.stdio.Out), userOut); err != nil { - return err - } - - // add the printed text to the rendered text buffer so we can cleanup later - r.AppendRenderedText(layoutOut) - - // nothing went wrong - return nil -} - -func (r *Renderer) RenderWithCursorOffset(tmpl string, data IterableOpts, opts []core.OptionAnswer, idx int) error { - cursor := r.NewCursor() - cursor.Restore() // clear any accessibility offsetting - - if err := r.Render(tmpl, data); err != nil { - return err - } - cursor.Save() - - offset := computeCursorOffset(MultiSelectQuestionTemplate, data, opts, idx, r.termWidthSafe()) - r.OffsetCursor(offset) - - return nil -} - -// appendRenderedError appends text to the renderer's error buffer -// which is used to track what has been printed. It is not exported -// as errors should only be displayed via Error(config, error). -func (r *Renderer) appendRenderedError(text string) { - r.renderedErrors.WriteString(text) -} - -// AppendRenderedText appends text to the renderer's text buffer -// which is used to track of what has been printed. The buffer is used -// to calculate how many lines to erase before updating the prompt. -func (r *Renderer) AppendRenderedText(text string) { - r.renderedText.WriteString(text) -} - -func (r *Renderer) resetPrompt(lines int) { - // clean out current line in case tmpl didnt end in newline - cursor := r.NewCursor() - cursor.HorizontalAbsolute(0) - terminal.EraseLine(r.stdio.Out, terminal.ERASE_LINE_ALL) - // clean up what we left behind last time - for i := 0; i < lines; i++ { - cursor.PreviousLine(1) - terminal.EraseLine(r.stdio.Out, terminal.ERASE_LINE_ALL) - } -} - -func (r *Renderer) termWidth() (int, error) { - fd := int(r.stdio.Out.Fd()) - termWidth, _, err := term.GetSize(fd) - return termWidth, err -} - -func (r *Renderer) termWidthSafe() int { - w, err := r.termWidth() - if err != nil || w == 0 { - // if we got an error due to terminal.GetSize not being supported - // on current platform then just assume a very wide terminal - w = 10000 - } - return w -} - -// countLines will return the count of `\n` with the addition of any -// lines that have wrapped due to narrow terminal width -func (r *Renderer) countLines(buf bytes.Buffer) int { - w := r.termWidthSafe() - - bufBytes := buf.Bytes() - - count := 0 - curr := 0 - for curr < len(bufBytes) { - var delim int - // read until the next newline or the end of the string - relDelim := bytes.IndexRune(bufBytes[curr:], '\n') - if relDelim != -1 { - count += 1 // new line found, add it to the count - delim = curr + relDelim - } else { - delim = len(bufBytes) // no new line found, read rest of text - } - - str := string(bufBytes[curr:delim]) - if lineWidth := terminal.StringWidth(str); lineWidth > w { - // account for word wrapping - count += lineWidth / w - if (lineWidth % w) == 0 { - // content whose width is exactly a multiplier of available width should not - // count as having wrapped on the last line - count -= 1 - } - } - curr = delim + 1 - } - - return count -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/select.go b/vendor/github.com/AlecAivazis/survey/v2/select.go deleted file mode 100644 index 1210122f4..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/select.go +++ /dev/null @@ -1,329 +0,0 @@ -package survey - -import ( - "errors" - "fmt" - - "github.com/AlecAivazis/survey/v2/core" - "github.com/AlecAivazis/survey/v2/terminal" -) - -/* -Select is a prompt that presents a list of various options to the user -for them to select using the arrow keys and enter. Response type is a string. - - color := "" - prompt := &survey.Select{ - Message: "Choose a color:", - Options: []string{"red", "blue", "green"}, - } - survey.AskOne(prompt, &color) -*/ -type Select struct { - Renderer - Message string - Options []string - Default interface{} - Help string - PageSize int - VimMode bool - FilterMessage string - Filter func(filter string, value string, index int) bool - Description func(value string, index int) string - filter string - selectedIndex int - showingHelp bool -} - -// SelectTemplateData is the data available to the templates when processing -type SelectTemplateData struct { - Select - PageEntries []core.OptionAnswer - SelectedIndex int - Answer string - ShowAnswer bool - ShowHelp bool - Description func(value string, index int) string - Config *PromptConfig - - // These fields are used when rendering an individual option - CurrentOpt core.OptionAnswer - CurrentIndex int -} - -// IterateOption sets CurrentOpt and CurrentIndex appropriately so a select option can be rendered individually -func (s SelectTemplateData) IterateOption(ix int, opt core.OptionAnswer) interface{} { - copy := s - copy.CurrentIndex = ix - copy.CurrentOpt = opt - return copy -} - -func (s SelectTemplateData) GetDescription(opt core.OptionAnswer) string { - if s.Description == nil { - return "" - } - return s.Description(opt.Value, opt.Index) -} - -var SelectQuestionTemplate = ` -{{- define "option"}} - {{- if eq .SelectedIndex .CurrentIndex }}{{color .Config.Icons.SelectFocus.Format }}{{ .Config.Icons.SelectFocus.Text }} {{else}}{{color "default"}} {{end}} - {{- .CurrentOpt.Value}}{{ if ne ($.GetDescription .CurrentOpt) "" }} - {{color "cyan"}}{{ $.GetDescription .CurrentOpt }}{{end}} - {{- color "reset"}} -{{end}} -{{- if .ShowHelp }}{{- color .Config.Icons.Help.Format }}{{ .Config.Icons.Help.Text }} {{ .Help }}{{color "reset"}}{{"\n"}}{{end}} -{{- color .Config.Icons.Question.Format }}{{ .Config.Icons.Question.Text }} {{color "reset"}} -{{- color "default+hb"}}{{ .Message }}{{ .FilterMessage }}{{color "reset"}} -{{- if .ShowAnswer}}{{color "cyan"}} {{.Answer}}{{color "reset"}}{{"\n"}} -{{- else}} - {{- " "}}{{- color "cyan"}}[Use arrows to move, type to filter{{- if and .Help (not .ShowHelp)}}, {{ .Config.HelpInput }} for more help{{end}}]{{color "reset"}} - {{- "\n"}} - {{- range $ix, $option := .PageEntries}} - {{- template "option" $.IterateOption $ix $option}} - {{- end}} -{{- end}}` - -// OnChange is called on every keypress. -func (s *Select) OnChange(key rune, config *PromptConfig) bool { - options := s.filterOptions(config) - oldFilter := s.filter - - // if the user pressed the enter key and the index is a valid option - if key == terminal.KeyEnter || key == '\n' { - // if the selected index is a valid option - if len(options) > 0 && s.selectedIndex < len(options) { - - // we're done (stop prompting the user) - return true - } - - // we're not done (keep prompting) - return false - - // if the user pressed the up arrow or 'k' to emulate vim - } else if (key == terminal.KeyArrowUp || (s.VimMode && key == 'k')) && len(options) > 0 { - // if we are at the top of the list - if s.selectedIndex == 0 { - // start from the button - s.selectedIndex = len(options) - 1 - } else { - // otherwise we are not at the top of the list so decrement the selected index - s.selectedIndex-- - } - - // if the user pressed down or 'j' to emulate vim - } else if (key == terminal.KeyTab || key == terminal.KeyArrowDown || (s.VimMode && key == 'j')) && len(options) > 0 { - // if we are at the bottom of the list - if s.selectedIndex == len(options)-1 { - // start from the top - s.selectedIndex = 0 - } else { - // increment the selected index - s.selectedIndex++ - } - // only show the help message if we have one - } else if string(key) == config.HelpInput && s.Help != "" { - s.showingHelp = true - // if the user wants to toggle vim mode on/off - } else if key == terminal.KeyEscape { - s.VimMode = !s.VimMode - // if the user hits any of the keys that clear the filter - } else if key == terminal.KeyDeleteWord || key == terminal.KeyDeleteLine { - s.filter = "" - // if the user is deleting a character in the filter - } else if key == terminal.KeyDelete || key == terminal.KeyBackspace { - // if there is content in the filter to delete - if s.filter != "" { - runeFilter := []rune(s.filter) - // subtract a line from the current filter - s.filter = string(runeFilter[0 : len(runeFilter)-1]) - // we removed the last value in the filter - } - } else if key >= terminal.KeySpace { - s.filter += string(key) - // make sure vim mode is disabled - s.VimMode = false - } - - s.FilterMessage = "" - if s.filter != "" { - s.FilterMessage = " " + s.filter - } - if oldFilter != s.filter { - // filter changed - options = s.filterOptions(config) - if len(options) > 0 && len(options) <= s.selectedIndex { - s.selectedIndex = len(options) - 1 - } - } - - // figure out the options and index to render - // figure out the page size - pageSize := s.PageSize - // if we dont have a specific one - if pageSize == 0 { - // grab the global value - pageSize = config.PageSize - } - - // TODO if we have started filtering and were looking at the end of a list - // and we have modified the filter then we should move the page back! - opts, idx := paginate(pageSize, options, s.selectedIndex) - - tmplData := SelectTemplateData{ - Select: *s, - SelectedIndex: idx, - ShowHelp: s.showingHelp, - Description: s.Description, - PageEntries: opts, - Config: config, - } - - // render the options - _ = s.RenderWithCursorOffset(SelectQuestionTemplate, tmplData, opts, idx) - - // keep prompting - return false -} - -func (s *Select) filterOptions(config *PromptConfig) []core.OptionAnswer { - // the filtered list - answers := []core.OptionAnswer{} - - // if there is no filter applied - if s.filter == "" { - return core.OptionAnswerList(s.Options) - } - - // the filter to apply - filter := s.Filter - if filter == nil { - filter = config.Filter - } - - for i, opt := range s.Options { - // i the filter says to include the option - if filter(s.filter, opt, i) { - answers = append(answers, core.OptionAnswer{ - Index: i, - Value: opt, - }) - } - } - - // return the list of answers - return answers -} - -func (s *Select) Prompt(config *PromptConfig) (interface{}, error) { - // if there are no options to render - if len(s.Options) == 0 { - // we failed - return "", errors.New("please provide options to select from") - } - - s.selectedIndex = 0 - if s.Default != nil { - switch defaultValue := s.Default.(type) { - case string: - var found bool - for i, opt := range s.Options { - if opt == defaultValue { - s.selectedIndex = i - found = true - } - } - if !found { - return "", fmt.Errorf("default value %q not found in options", defaultValue) - } - case int: - if defaultValue >= len(s.Options) { - return "", fmt.Errorf("default index %d exceeds the number of options", defaultValue) - } - s.selectedIndex = defaultValue - default: - return "", errors.New("default value of select must be an int or string") - } - } - - // figure out the page size - pageSize := s.PageSize - // if we dont have a specific one - if pageSize == 0 { - // grab the global value - pageSize = config.PageSize - } - - // figure out the options and index to render - opts, idx := paginate(pageSize, core.OptionAnswerList(s.Options), s.selectedIndex) - - cursor := s.NewCursor() - cursor.Save() // for proper cursor placement during selection - cursor.Hide() // hide the cursor - defer cursor.Show() // show the cursor when we're done - defer cursor.Restore() // clear any accessibility offsetting on exit - - tmplData := SelectTemplateData{ - Select: *s, - SelectedIndex: idx, - Description: s.Description, - ShowHelp: s.showingHelp, - PageEntries: opts, - Config: config, - } - - // ask the question - err := s.RenderWithCursorOffset(SelectQuestionTemplate, tmplData, opts, idx) - if err != nil { - return "", err - } - - rr := s.NewRuneReader() - _ = rr.SetTermMode() - defer func() { - _ = rr.RestoreTermMode() - }() - - // start waiting for input - for { - r, _, err := rr.ReadRune() - if err != nil { - return "", err - } - if r == terminal.KeyInterrupt { - return "", terminal.InterruptErr - } - if r == terminal.KeyEndTransmission { - break - } - if s.OnChange(r, config) { - break - } - } - - options := s.filterOptions(config) - s.filter = "" - s.FilterMessage = "" - - if s.selectedIndex < len(options) { - return options[s.selectedIndex], err - } - - return options[0], err -} - -func (s *Select) Cleanup(config *PromptConfig, val interface{}) error { - cursor := s.NewCursor() - cursor.Restore() - return s.Render( - SelectQuestionTemplate, - SelectTemplateData{ - Select: *s, - Answer: val.(core.OptionAnswer).Value, - ShowAnswer: true, - Description: s.Description, - Config: config, - }, - ) -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/survey.go b/vendor/github.com/AlecAivazis/survey/v2/survey.go deleted file mode 100644 index aad73bbe7..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/survey.go +++ /dev/null @@ -1,474 +0,0 @@ -package survey - -import ( - "bytes" - "errors" - "io" - "os" - "strings" - "unicode/utf8" - - "github.com/AlecAivazis/survey/v2/core" - "github.com/AlecAivazis/survey/v2/terminal" -) - -// DefaultAskOptions is the default options on ask, using the OS stdio. -func defaultAskOptions() *AskOptions { - return &AskOptions{ - Stdio: terminal.Stdio{ - In: os.Stdin, - Out: os.Stdout, - Err: os.Stderr, - }, - PromptConfig: PromptConfig{ - PageSize: 7, - HelpInput: "?", - SuggestInput: "tab", - Icons: IconSet{ - Error: Icon{ - Text: "X", - Format: "red", - }, - Help: Icon{ - Text: "?", - Format: "cyan", - }, - Question: Icon{ - Text: "?", - Format: "green+hb", - }, - MarkedOption: Icon{ - Text: "[x]", - Format: "green", - }, - UnmarkedOption: Icon{ - Text: "[ ]", - Format: "default+hb", - }, - SelectFocus: Icon{ - Text: ">", - Format: "cyan+b", - }, - }, - Filter: func(filter string, value string, index int) (include bool) { - filter = strings.ToLower(filter) - - // include this option if it matches - return strings.Contains(strings.ToLower(value), filter) - }, - KeepFilter: false, - ShowCursor: false, - RemoveSelectAll: false, - RemoveSelectNone: false, - HideCharacter: '*', - }, - } -} -func defaultPromptConfig() *PromptConfig { - return &defaultAskOptions().PromptConfig -} - -func defaultIcons() *IconSet { - return &defaultPromptConfig().Icons -} - -// OptionAnswer is an ergonomic alias for core.OptionAnswer -type OptionAnswer = core.OptionAnswer - -// Icon holds the text and format to show for a particular icon -type Icon struct { - Text string - Format string -} - -// IconSet holds the icons to use for various prompts -type IconSet struct { - HelpInput Icon - Error Icon - Help Icon - Question Icon - MarkedOption Icon - UnmarkedOption Icon - SelectFocus Icon -} - -// Validator is a function passed to a Question after a user has provided a response. -// If the function returns an error, then the user will be prompted again for another -// response. -type Validator func(ans interface{}) error - -// Transformer is a function passed to a Question after a user has provided a response. -// The function can be used to implement a custom logic that will result to return -// a different representation of the given answer. -// -// Look `TransformString`, `ToLower` `Title` and `ComposeTransformers` for more. -type Transformer func(ans interface{}) (newAns interface{}) - -// Question is the core data structure for a survey questionnaire. -type Question struct { - Name string - Prompt Prompt - Validate Validator - Transform Transformer -} - -// PromptConfig holds the global configuration for a prompt -type PromptConfig struct { - PageSize int - Icons IconSet - HelpInput string - SuggestInput string - Filter func(filter string, option string, index int) bool - KeepFilter bool - ShowCursor bool - RemoveSelectAll bool - RemoveSelectNone bool - HideCharacter rune -} - -// Prompt is the primary interface for the objects that can take user input -// and return a response. -type Prompt interface { - Prompt(config *PromptConfig) (interface{}, error) - Cleanup(*PromptConfig, interface{}) error - Error(*PromptConfig, error) error -} - -// PromptAgainer Interface for Prompts that support prompting again after invalid input -type PromptAgainer interface { - PromptAgain(config *PromptConfig, invalid interface{}, err error) (interface{}, error) -} - -// AskOpt allows setting optional ask options. -type AskOpt func(options *AskOptions) error - -// AskOptions provides additional options on ask. -type AskOptions struct { - Stdio terminal.Stdio - Validators []Validator - PromptConfig PromptConfig -} - -// WithStdio specifies the standard input, output and error files survey -// interacts with. By default, these are os.Stdin, os.Stdout, and os.Stderr. -func WithStdio(in terminal.FileReader, out terminal.FileWriter, err io.Writer) AskOpt { - return func(options *AskOptions) error { - options.Stdio.In = in - options.Stdio.Out = out - options.Stdio.Err = err - return nil - } -} - -// WithFilter specifies the default filter to use when asking questions. -func WithFilter(filter func(filter string, value string, index int) (include bool)) AskOpt { - return func(options *AskOptions) error { - // save the filter internally - options.PromptConfig.Filter = filter - - return nil - } -} - -// WithKeepFilter sets the if the filter is kept after selections -func WithKeepFilter(KeepFilter bool) AskOpt { - return func(options *AskOptions) error { - // set the page size - options.PromptConfig.KeepFilter = KeepFilter - - // nothing went wrong - return nil - } -} - -// WithRemoveSelectAll remove the select all option in Multiselect -func WithRemoveSelectAll() AskOpt { - return func(options *AskOptions) error { - options.PromptConfig.RemoveSelectAll = true - return nil - } -} - -// WithRemoveSelectNone remove the select none/unselect all in Multiselect -func WithRemoveSelectNone() AskOpt { - return func(options *AskOptions) error { - options.PromptConfig.RemoveSelectNone = true - return nil - } -} - -// WithValidator specifies a validator to use while prompting the user -func WithValidator(v Validator) AskOpt { - return func(options *AskOptions) error { - // add the provided validator to the list - options.Validators = append(options.Validators, v) - - // nothing went wrong - return nil - } -} - -type wantsStdio interface { - WithStdio(terminal.Stdio) -} - -// WithPageSize sets the default page size used by prompts -func WithPageSize(pageSize int) AskOpt { - return func(options *AskOptions) error { - // set the page size - options.PromptConfig.PageSize = pageSize - - // nothing went wrong - return nil - } -} - -// WithHelpInput changes the character that prompts look for to give the user helpful information. -func WithHelpInput(r rune) AskOpt { - return func(options *AskOptions) error { - // set the input character - options.PromptConfig.HelpInput = string(r) - - // nothing went wrong - return nil - } -} - -// WithIcons sets the icons that will be used when prompting the user -func WithIcons(setIcons func(*IconSet)) AskOpt { - return func(options *AskOptions) error { - // update the default icons with whatever the user says - setIcons(&options.PromptConfig.Icons) - - // nothing went wrong - return nil - } -} - -// WithShowCursor sets the show cursor behavior when prompting the user -func WithShowCursor(ShowCursor bool) AskOpt { - return func(options *AskOptions) error { - // set the page size - options.PromptConfig.ShowCursor = ShowCursor - - // nothing went wrong - return nil - } -} - -// WithHideCharacter sets the default character shown instead of the password for password inputs -func WithHideCharacter(char rune) AskOpt { - return func(options *AskOptions) error { - // set the hide character - options.PromptConfig.HideCharacter = char - - // nothing went wrong - return nil - } -} - -/* -AskOne performs the prompt for a single prompt and asks for validation if required. -Response types should be something that can be casted from the response type designated -in the documentation. For example: - - name := "" - prompt := &survey.Input{ - Message: "name", - } - - survey.AskOne(prompt, &name) -*/ -func AskOne(p Prompt, response interface{}, opts ...AskOpt) error { - err := Ask([]*Question{{Prompt: p}}, response, opts...) - if err != nil { - return err - } - - return nil -} - -/* -Ask performs the prompt loop, asking for validation when appropriate. The response -type can be one of two options. If a struct is passed, the answer will be written to -the field whose name matches the Name field on the corresponding question. Field types -should be something that can be casted from the response type designated in the -documentation. Note, a survey tag can also be used to identify a Otherwise, a -map[string]interface{} can be passed, responses will be written to the key with the -matching name. For example: - - qs := []*survey.Question{ - { - Name: "name", - Prompt: &survey.Input{Message: "What is your name?"}, - Validate: survey.Required, - Transform: survey.Title, - }, - } - - answers := struct{ Name string }{} - - - err := survey.Ask(qs, &answers) -*/ -func Ask(qs []*Question, response interface{}, opts ...AskOpt) error { - // build up the configuration options - options := defaultAskOptions() - for _, opt := range opts { - if opt == nil { - continue - } - if err := opt(options); err != nil { - return err - } - } - - // if we weren't passed a place to record the answers - if response == nil { - // we can't go any further - return errors.New("cannot call Ask() with a nil reference to record the answers") - } - - validate := func(q *Question, val interface{}) error { - if q.Validate != nil { - if err := q.Validate(val); err != nil { - return err - } - } - for _, v := range options.Validators { - if err := v(val); err != nil { - return err - } - } - return nil - } - - // go over every question - for _, q := range qs { - // If Prompt implements controllable stdio, pass in specified stdio. - if p, ok := q.Prompt.(wantsStdio); ok { - p.WithStdio(options.Stdio) - } - - var ans interface{} - var validationErr error - // prompt and validation loop - for { - if validationErr != nil { - if err := q.Prompt.Error(&options.PromptConfig, validationErr); err != nil { - return err - } - } - var err error - if promptAgainer, ok := q.Prompt.(PromptAgainer); ok && validationErr != nil { - ans, err = promptAgainer.PromptAgain(&options.PromptConfig, ans, validationErr) - } else { - ans, err = q.Prompt.Prompt(&options.PromptConfig) - } - if err != nil { - return err - } - validationErr = validate(q, ans) - if validationErr == nil { - break - } - } - - if q.Transform != nil { - // check if we have a transformer available, if so - // then try to acquire the new representation of the - // answer, if the resulting answer is not nil. - if newAns := q.Transform(ans); newAns != nil { - ans = newAns - } - } - - // tell the prompt to cleanup with the validated value - if err := q.Prompt.Cleanup(&options.PromptConfig, ans); err != nil { - return err - } - - // add it to the map - if err := core.WriteAnswer(response, q.Name, ans); err != nil { - return err - } - } - - // return the response - return nil -} - -// paginate returns a single page of choices given the page size, the total list of -// possible choices, and the current selected index in the total list. -func paginate(pageSize int, choices []core.OptionAnswer, sel int) ([]core.OptionAnswer, int) { - var start, end, cursor int - - if len(choices) < pageSize { - // if we dont have enough options to fill a page - start = 0 - end = len(choices) - cursor = sel - - } else if sel < pageSize/2 { - // if we are in the first half page - start = 0 - end = pageSize - cursor = sel - - } else if len(choices)-sel-1 < pageSize/2 { - // if we are in the last half page - start = len(choices) - pageSize - end = len(choices) - cursor = sel - start - - } else { - // somewhere in the middle - above := pageSize / 2 - below := pageSize - above - - cursor = pageSize / 2 - start = sel - above - end = sel + below - } - - // return the subset we care about and the index - return choices[start:end], cursor -} - -type IterableOpts interface { - IterateOption(int, core.OptionAnswer) interface{} -} - -func computeCursorOffset(tmpl string, data IterableOpts, opts []core.OptionAnswer, idx, tWidth int) int { - tmpls, err := core.GetTemplatePair(tmpl) - if err != nil { - return 0 - } - - t := tmpls[0] - - renderOpt := func(ix int, opt core.OptionAnswer) string { - var buf bytes.Buffer - _ = t.ExecuteTemplate(&buf, "option", data.IterateOption(ix, opt)) - return buf.String() - } - - offset := len(opts) - idx - - for i, o := range opts { - if i < idx { - continue - } - renderedOpt := renderOpt(i, o) - valWidth := utf8.RuneCount([]byte(renderedOpt)) - if valWidth > tWidth { - splitCount := valWidth / tWidth - if valWidth%tWidth == 0 { - splitCount -= 1 - } - offset += splitCount - } - } - - return offset -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/LICENSE.txt b/vendor/github.com/AlecAivazis/survey/v2/terminal/LICENSE.txt deleted file mode 100644 index ade5fef6d..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/LICENSE.txt +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2014 Takashi Kokubun - -MIT License - -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/AlecAivazis/survey/v2/terminal/README.md b/vendor/github.com/AlecAivazis/survey/v2/terminal/README.md deleted file mode 100644 index d0b9db0fd..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# survey/terminal - -This package started as a copy of [kokuban/go-ansi](http://github.com/k0kubun/go-ansi) but has since been modified to fit survey's specific needs. diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/buffered_reader.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/buffered_reader.go deleted file mode 100644 index 55eac1522..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/buffered_reader.go +++ /dev/null @@ -1,22 +0,0 @@ -package terminal - -import ( - "bytes" - "io" -) - -type BufferedReader struct { - In io.Reader - Buffer *bytes.Buffer -} - -func (br *BufferedReader) Read(p []byte) (int, error) { - n, err := br.Buffer.Read(p) - if err != nil && err != io.EOF { - return n, err - } else if err == nil { - return n, nil - } - - return br.In.Read(p[n:]) -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/cursor.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/cursor.go deleted file mode 100644 index 75117e080..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/cursor.go +++ /dev/null @@ -1,209 +0,0 @@ -//go:build !windows -// +build !windows - -package terminal - -import ( - "bufio" - "bytes" - "fmt" - "io" - "regexp" - "strconv" -) - -var COORDINATE_SYSTEM_BEGIN Short = 1 - -var dsrPattern = regexp.MustCompile(`\x1b\[(\d+);(\d+)R$`) - -type Cursor struct { - In FileReader - Out FileWriter -} - -// Up moves the cursor n cells to up. -func (c *Cursor) Up(n int) error { - _, err := fmt.Fprintf(c.Out, "\x1b[%dA", n) - return err -} - -// Down moves the cursor n cells to down. -func (c *Cursor) Down(n int) error { - _, err := fmt.Fprintf(c.Out, "\x1b[%dB", n) - return err -} - -// Forward moves the cursor n cells to right. -func (c *Cursor) Forward(n int) error { - _, err := fmt.Fprintf(c.Out, "\x1b[%dC", n) - return err -} - -// Back moves the cursor n cells to left. -func (c *Cursor) Back(n int) error { - _, err := fmt.Fprintf(c.Out, "\x1b[%dD", n) - return err -} - -// NextLine moves cursor to beginning of the line n lines down. -func (c *Cursor) NextLine(n int) error { - if err := c.Down(1); err != nil { - return err - } - return c.HorizontalAbsolute(0) -} - -// PreviousLine moves cursor to beginning of the line n lines up. -func (c *Cursor) PreviousLine(n int) error { - if err := c.Up(1); err != nil { - return err - } - return c.HorizontalAbsolute(0) -} - -// HorizontalAbsolute moves cursor horizontally to x. -func (c *Cursor) HorizontalAbsolute(x int) error { - _, err := fmt.Fprintf(c.Out, "\x1b[%dG", x) - return err -} - -// Show shows the cursor. -func (c *Cursor) Show() error { - _, err := fmt.Fprint(c.Out, "\x1b[?25h") - return err -} - -// Hide hide the cursor. -func (c *Cursor) Hide() error { - _, err := fmt.Fprint(c.Out, "\x1b[?25l") - return err -} - -// move moves the cursor to a specific x,y location. -func (c *Cursor) move(x int, y int) error { - _, err := fmt.Fprintf(c.Out, "\x1b[%d;%df", x, y) - return err -} - -// Save saves the current position -func (c *Cursor) Save() error { - _, err := fmt.Fprint(c.Out, "\x1b7") - return err -} - -// Restore restores the saved position of the cursor -func (c *Cursor) Restore() error { - _, err := fmt.Fprint(c.Out, "\x1b8") - return err -} - -// for comparability purposes between windows -// in unix we need to print out a new line on some terminals -func (c *Cursor) MoveNextLine(cur *Coord, terminalSize *Coord) error { - if cur.Y == terminalSize.Y { - if _, err := fmt.Fprintln(c.Out); err != nil { - return err - } - } - return c.NextLine(1) -} - -// Location returns the current location of the cursor in the terminal -func (c *Cursor) Location(buf *bytes.Buffer) (*Coord, error) { - // ANSI escape sequence for DSR - Device Status Report - // https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences - if _, err := fmt.Fprint(c.Out, "\x1b[6n"); err != nil { - return nil, err - } - - // There may be input in Stdin prior to CursorLocation so make sure we don't - // drop those bytes. - var loc []int - var match string - for loc == nil { - // Reports the cursor position (CPR) to the application as (as though typed at - // the keyboard) ESC[n;mR, where n is the row and m is the column. - reader := bufio.NewReader(c.In) - text, err := reader.ReadSlice(byte('R')) - if err != nil { - return nil, err - } - - loc = dsrPattern.FindStringIndex(string(text)) - if loc == nil { - // After reading slice to byte 'R', the bufio Reader may have read more - // bytes into its internal buffer which will be discarded on next ReadSlice. - // We create a temporary buffer to read the remaining buffered slice and - // write them to output buffer. - buffered := make([]byte, reader.Buffered()) - _, err = io.ReadFull(reader, buffered) - if err != nil { - return nil, err - } - - // Stdin contains R that doesn't match DSR, so pass the bytes along to - // output buffer. - buf.Write(text) - buf.Write(buffered) - } else { - // Write the non-matching leading bytes to output buffer. - buf.Write(text[:loc[0]]) - - // Save the matching bytes to extract the row and column of the cursor. - match = string(text[loc[0]:loc[1]]) - } - } - - matches := dsrPattern.FindStringSubmatch(string(match)) - if len(matches) != 3 { - return nil, fmt.Errorf("incorrect number of matches: %d", len(matches)) - } - - col, err := strconv.Atoi(matches[2]) - if err != nil { - return nil, err - } - - row, err := strconv.Atoi(matches[1]) - if err != nil { - return nil, err - } - - return &Coord{Short(col), Short(row)}, nil -} - -func (cur Coord) CursorIsAtLineEnd(size *Coord) bool { - return cur.X == size.X -} - -func (cur Coord) CursorIsAtLineBegin() bool { - return cur.X == COORDINATE_SYSTEM_BEGIN -} - -// Size returns the height and width of the terminal. -func (c *Cursor) Size(buf *bytes.Buffer) (*Coord, error) { - // the general approach here is to move the cursor to the very bottom - // of the terminal, ask for the current location and then move the - // cursor back where we started - - // hide the cursor (so it doesn't blink when getting the size of the terminal) - c.Hide() - defer c.Show() - - // save the current location of the cursor - c.Save() - defer c.Restore() - - // move the cursor to the very bottom of the terminal - c.move(999, 999) - - // ask for the current location - bottom, err := c.Location(buf) - if err != nil { - return nil, err - } - - // since the bottom was calculated in the lower right corner, it - // is the dimensions we are looking for - return bottom, nil -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/cursor_windows.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/cursor_windows.go deleted file mode 100644 index c26459199..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/cursor_windows.go +++ /dev/null @@ -1,164 +0,0 @@ -package terminal - -import ( - "bytes" - "syscall" - "unsafe" -) - -var COORDINATE_SYSTEM_BEGIN Short = 0 - -// shared variable to save the cursor location from CursorSave() -var cursorLoc Coord - -type Cursor struct { - In FileReader - Out FileWriter -} - -func (c *Cursor) Up(n int) error { - return c.cursorMove(0, n) -} - -func (c *Cursor) Down(n int) error { - return c.cursorMove(0, -1*n) -} - -func (c *Cursor) Forward(n int) error { - return c.cursorMove(n, 0) -} - -func (c *Cursor) Back(n int) error { - return c.cursorMove(-1*n, 0) -} - -// save the cursor location -func (c *Cursor) Save() error { - loc, err := c.Location(nil) - if err != nil { - return err - } - cursorLoc = *loc - return nil -} - -func (c *Cursor) Restore() error { - handle := syscall.Handle(c.Out.Fd()) - // restore it to the original position - _, _, err := procSetConsoleCursorPosition.Call(uintptr(handle), uintptr(*(*int32)(unsafe.Pointer(&cursorLoc)))) - return normalizeError(err) -} - -func (cur Coord) CursorIsAtLineEnd(size *Coord) bool { - return cur.X == size.X -} - -func (cur Coord) CursorIsAtLineBegin() bool { - return cur.X == 0 -} - -func (c *Cursor) cursorMove(x int, y int) error { - handle := syscall.Handle(c.Out.Fd()) - - var csbi consoleScreenBufferInfo - if _, _, err := procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))); normalizeError(err) != nil { - return err - } - - var cursor Coord - cursor.X = csbi.cursorPosition.X + Short(x) - cursor.Y = csbi.cursorPosition.Y + Short(y) - - _, _, err := procSetConsoleCursorPosition.Call(uintptr(handle), uintptr(*(*int32)(unsafe.Pointer(&cursor)))) - return normalizeError(err) -} - -func (c *Cursor) NextLine(n int) error { - if err := c.Up(n); err != nil { - return err - } - return c.HorizontalAbsolute(0) -} - -func (c *Cursor) PreviousLine(n int) error { - if err := c.Down(n); err != nil { - return err - } - return c.HorizontalAbsolute(0) -} - -// for comparability purposes between windows -// in windows we don't have to print out a new line -func (c *Cursor) MoveNextLine(cur *Coord, terminalSize *Coord) error { - return c.NextLine(1) -} - -func (c *Cursor) HorizontalAbsolute(x int) error { - handle := syscall.Handle(c.Out.Fd()) - - var csbi consoleScreenBufferInfo - if _, _, err := procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))); normalizeError(err) != nil { - return err - } - - var cursor Coord - cursor.X = Short(x) - cursor.Y = csbi.cursorPosition.Y - - if csbi.size.X < cursor.X { - cursor.X = csbi.size.X - } - - _, _, err := procSetConsoleCursorPosition.Call(uintptr(handle), uintptr(*(*int32)(unsafe.Pointer(&cursor)))) - return normalizeError(err) -} - -func (c *Cursor) Show() error { - handle := syscall.Handle(c.Out.Fd()) - - var cci consoleCursorInfo - if _, _, err := procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&cci))); normalizeError(err) != nil { - return err - } - cci.visible = 1 - - _, _, err := procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&cci))) - return normalizeError(err) -} - -func (c *Cursor) Hide() error { - handle := syscall.Handle(c.Out.Fd()) - - var cci consoleCursorInfo - if _, _, err := procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&cci))); normalizeError(err) != nil { - return err - } - cci.visible = 0 - - _, _, err := procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&cci))) - return normalizeError(err) -} - -func (c *Cursor) Location(buf *bytes.Buffer) (*Coord, error) { - handle := syscall.Handle(c.Out.Fd()) - - var csbi consoleScreenBufferInfo - if _, _, err := procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))); normalizeError(err) != nil { - return nil, err - } - - return &csbi.cursorPosition, nil -} - -func (c *Cursor) Size(buf *bytes.Buffer) (*Coord, error) { - handle := syscall.Handle(c.Out.Fd()) - - var csbi consoleScreenBufferInfo - if _, _, err := procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))); normalizeError(err) != nil { - return nil, err - } - // windows' coordinate system begins at (0, 0) - csbi.size.X-- - csbi.size.Y-- - return &csbi.size, nil -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/display.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/display.go deleted file mode 100644 index 0f014b135..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/display.go +++ /dev/null @@ -1,9 +0,0 @@ -package terminal - -type EraseLineMode int - -const ( - ERASE_LINE_END EraseLineMode = iota - ERASE_LINE_START - ERASE_LINE_ALL -) diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/display_posix.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/display_posix.go deleted file mode 100644 index fbd1b7947..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/display_posix.go +++ /dev/null @@ -1,13 +0,0 @@ -//go:build !windows -// +build !windows - -package terminal - -import ( - "fmt" -) - -func EraseLine(out FileWriter, mode EraseLineMode) error { - _, err := fmt.Fprintf(out, "\x1b[%dK", mode) - return err -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/display_windows.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/display_windows.go deleted file mode 100644 index fc9db9f74..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/display_windows.go +++ /dev/null @@ -1,31 +0,0 @@ -package terminal - -import ( - "syscall" - "unsafe" -) - -func EraseLine(out FileWriter, mode EraseLineMode) error { - handle := syscall.Handle(out.Fd()) - - var csbi consoleScreenBufferInfo - if _, _, err := procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))); normalizeError(err) != nil { - return err - } - - var w uint32 - var x Short - cursor := csbi.cursorPosition - switch mode { - case ERASE_LINE_END: - x = csbi.size.X - case ERASE_LINE_START: - x = 0 - case ERASE_LINE_ALL: - cursor.X = 0 - x = csbi.size.X - } - - _, _, err := procFillConsoleOutputCharacter.Call(uintptr(handle), uintptr(' '), uintptr(x), uintptr(*(*int32)(unsafe.Pointer(&cursor))), uintptr(unsafe.Pointer(&w))) - return normalizeError(err) -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/error.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/error.go deleted file mode 100644 index 55eb66540..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/error.go +++ /dev/null @@ -1,10 +0,0 @@ -package terminal - -import ( - "errors" -) - -var ( - //lint:ignore ST1012 keeping old name for backwards compatibility - InterruptErr = errors.New("interrupt") -) diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/output.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/output.go deleted file mode 100644 index 29102420c..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/output.go +++ /dev/null @@ -1,20 +0,0 @@ -//go:build !windows -// +build !windows - -package terminal - -import ( - "io" -) - -// NewAnsiStdout returns special stdout, which converts escape sequences to Windows API calls -// on Windows environment. -func NewAnsiStdout(out FileWriter) io.Writer { - return out -} - -// NewAnsiStderr returns special stderr, which converts escape sequences to Windows API calls -// on Windows environment. -func NewAnsiStderr(out FileWriter) io.Writer { - return out -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/output_windows.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/output_windows.go deleted file mode 100644 index eaf5c4341..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/output_windows.go +++ /dev/null @@ -1,253 +0,0 @@ -package terminal - -import ( - "bytes" - "fmt" - "io" - "strconv" - "strings" - "syscall" - "unsafe" - - "github.com/mattn/go-isatty" -) - -const ( - foregroundBlue = 0x1 - foregroundGreen = 0x2 - foregroundRed = 0x4 - foregroundIntensity = 0x8 - foregroundMask = (foregroundRed | foregroundBlue | foregroundGreen | foregroundIntensity) - backgroundBlue = 0x10 - backgroundGreen = 0x20 - backgroundRed = 0x40 - backgroundIntensity = 0x80 - backgroundMask = (backgroundRed | backgroundBlue | backgroundGreen | backgroundIntensity) -) - -type Writer struct { - out FileWriter - handle syscall.Handle - orgAttr word -} - -func NewAnsiStdout(out FileWriter) io.Writer { - var csbi consoleScreenBufferInfo - if !isatty.IsTerminal(out.Fd()) { - return out - } - handle := syscall.Handle(out.Fd()) - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - return &Writer{out: out, handle: handle, orgAttr: csbi.attributes} -} - -func NewAnsiStderr(out FileWriter) io.Writer { - var csbi consoleScreenBufferInfo - if !isatty.IsTerminal(out.Fd()) { - return out - } - handle := syscall.Handle(out.Fd()) - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - return &Writer{out: out, handle: handle, orgAttr: csbi.attributes} -} - -func (w *Writer) Write(data []byte) (n int, err error) { - r := bytes.NewReader(data) - - for { - var ch rune - var size int - ch, size, err = r.ReadRune() - if err != nil { - if err == io.EOF { - err = nil - } - return - } - n += size - - switch ch { - case '\x1b': - size, err = w.handleEscape(r) - n += size - if err != nil { - return - } - default: - _, err = fmt.Fprint(w.out, string(ch)) - if err != nil { - return - } - } - } -} - -func (w *Writer) handleEscape(r *bytes.Reader) (n int, err error) { - buf := make([]byte, 0, 10) - buf = append(buf, "\x1b"...) - - var ch rune - var size int - // Check '[' continues after \x1b - ch, size, err = r.ReadRune() - if err != nil { - if err == io.EOF { - err = nil - } - fmt.Fprint(w.out, string(buf)) - return - } - n += size - if ch != '[' { - fmt.Fprint(w.out, string(buf)) - return - } - - // Parse escape code - var code rune - argBuf := make([]byte, 0, 10) - for { - ch, size, err = r.ReadRune() - if err != nil { - if err == io.EOF { - err = nil - } - fmt.Fprint(w.out, string(buf)) - return - } - n += size - if ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') { - code = ch - break - } - argBuf = append(argBuf, string(ch)...) - } - - err = w.applyEscapeCode(buf, string(argBuf), code) - return -} - -func (w *Writer) applyEscapeCode(buf []byte, arg string, code rune) error { - c := &Cursor{Out: w.out} - - switch arg + string(code) { - case "?25h": - return c.Show() - case "?25l": - return c.Hide() - } - - if code >= 'A' && code <= 'G' { - if n, err := strconv.Atoi(arg); err == nil { - switch code { - case 'A': - return c.Up(n) - case 'B': - return c.Down(n) - case 'C': - return c.Forward(n) - case 'D': - return c.Back(n) - case 'E': - return c.NextLine(n) - case 'F': - return c.PreviousLine(n) - case 'G': - return c.HorizontalAbsolute(n) - } - } - } - - switch code { - case 'm': - return w.applySelectGraphicRendition(arg) - default: - buf = append(buf, string(code)...) - _, err := fmt.Fprint(w.out, string(buf)) - return err - } -} - -// Original implementation: https://github.com/mattn/go-colorable -func (w *Writer) applySelectGraphicRendition(arg string) error { - if arg == "" { - _, _, err := procSetConsoleTextAttribute.Call(uintptr(w.handle), uintptr(w.orgAttr)) - return normalizeError(err) - } - - var csbi consoleScreenBufferInfo - if _, _, err := procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))); normalizeError(err) != nil { - return err - } - attr := csbi.attributes - - for _, param := range strings.Split(arg, ";") { - n, err := strconv.Atoi(param) - if err != nil { - continue - } - - switch { - case n == 0 || n == 100: - attr = w.orgAttr - case 1 <= n && n <= 5: - attr |= foregroundIntensity - case 30 <= n && n <= 37: - attr = (attr & backgroundMask) - if (n-30)&1 != 0 { - attr |= foregroundRed - } - if (n-30)&2 != 0 { - attr |= foregroundGreen - } - if (n-30)&4 != 0 { - attr |= foregroundBlue - } - case 40 <= n && n <= 47: - attr = (attr & foregroundMask) - if (n-40)&1 != 0 { - attr |= backgroundRed - } - if (n-40)&2 != 0 { - attr |= backgroundGreen - } - if (n-40)&4 != 0 { - attr |= backgroundBlue - } - case 90 <= n && n <= 97: - attr = (attr & backgroundMask) - attr |= foregroundIntensity - if (n-90)&1 != 0 { - attr |= foregroundRed - } - if (n-90)&2 != 0 { - attr |= foregroundGreen - } - if (n-90)&4 != 0 { - attr |= foregroundBlue - } - case 100 <= n && n <= 107: - attr = (attr & foregroundMask) - attr |= backgroundIntensity - if (n-100)&1 != 0 { - attr |= backgroundRed - } - if (n-100)&2 != 0 { - attr |= backgroundGreen - } - if (n-100)&4 != 0 { - attr |= backgroundBlue - } - } - } - - _, _, err := procSetConsoleTextAttribute.Call(uintptr(w.handle), uintptr(attr)) - return normalizeError(err) -} - -func normalizeError(err error) error { - if syserr, ok := err.(syscall.Errno); ok && syserr == 0 { - return nil - } - return err -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader.go deleted file mode 100644 index 998e415e5..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader.go +++ /dev/null @@ -1,417 +0,0 @@ -package terminal - -import ( - "fmt" - "unicode" - - "golang.org/x/text/width" -) - -type RuneReader struct { - stdio Stdio - state runeReaderState -} - -func NewRuneReader(stdio Stdio) *RuneReader { - return &RuneReader{ - stdio: stdio, - state: newRuneReaderState(stdio.In), - } -} - -func (rr *RuneReader) printChar(char rune, mask rune) error { - // if we don't need to mask the input - if mask == 0 { - // just print the character the user pressed - _, err := fmt.Fprintf(rr.stdio.Out, "%c", char) - return err - } - // otherwise print the mask we were given - _, err := fmt.Fprintf(rr.stdio.Out, "%c", mask) - return err -} - -type OnRuneFn func(rune, []rune) ([]rune, bool, error) - -func (rr *RuneReader) ReadLine(mask rune, onRunes ...OnRuneFn) ([]rune, error) { - return rr.ReadLineWithDefault(mask, []rune{}, onRunes...) -} - -func (rr *RuneReader) ReadLineWithDefault(mask rune, d []rune, onRunes ...OnRuneFn) ([]rune, error) { - line := []rune{} - // we only care about horizontal displacements from the origin so start counting at 0 - index := 0 - - cursor := &Cursor{ - In: rr.stdio.In, - Out: rr.stdio.Out, - } - - onRune := func(r rune, line []rune) ([]rune, bool, error) { - return line, false, nil - } - - // if the user pressed a key the caller was interested in capturing - if len(onRunes) > 0 { - onRune = onRunes[0] - } - - // we get the terminal width and height (if resized after this point the property might become invalid) - terminalSize, _ := cursor.Size(rr.Buffer()) - // we set the current location of the cursor once - cursorCurrent, _ := cursor.Location(rr.Buffer()) - - increment := func() { - if cursorCurrent.CursorIsAtLineEnd(terminalSize) { - cursorCurrent.X = COORDINATE_SYSTEM_BEGIN - cursorCurrent.Y++ - } else { - cursorCurrent.X++ - } - } - decrement := func() { - if cursorCurrent.CursorIsAtLineBegin() { - cursorCurrent.X = terminalSize.X - cursorCurrent.Y-- - } else { - cursorCurrent.X-- - } - } - - if len(d) > 0 { - index = len(d) - if _, err := fmt.Fprint(rr.stdio.Out, string(d)); err != nil { - return d, err - } - line = d - for range d { - increment() - } - } - - for { - // wait for some input - r, _, err := rr.ReadRune() - if err != nil { - return line, err - } - - if l, stop, err := onRune(r, line); stop || err != nil { - return l, err - } - - // if the user pressed enter or some other newline/termination like ctrl+d - if r == '\r' || r == '\n' || r == KeyEndTransmission { - // delete what's printed out on the console screen (cleanup) - for index > 0 { - if cursorCurrent.CursorIsAtLineBegin() { - EraseLine(rr.stdio.Out, ERASE_LINE_END) - cursor.PreviousLine(1) - cursor.Forward(int(terminalSize.X)) - } else { - cursor.Back(1) - } - decrement() - index-- - } - // move the cursor the a new line - cursor.MoveNextLine(cursorCurrent, terminalSize) - - // we're done processing the input - return line, nil - } - // if the user interrupts (ie with ctrl+c) - if r == KeyInterrupt { - // go to the beginning of the next line - if _, err := fmt.Fprint(rr.stdio.Out, "\r\n"); err != nil { - return line, err - } - - // we're done processing the input, and treat interrupt like an error - return line, InterruptErr - } - - // allow for backspace/delete editing of inputs - if r == KeyBackspace || r == KeyDelete { - // and we're not at the beginning of the line - if index > 0 && len(line) > 0 { - // if we are at the end of the word - if index == len(line) { - // just remove the last letter from the internal representation - // also count the number of cells the rune before the cursor occupied - cells := runeWidth(line[len(line)-1]) - line = line[:len(line)-1] - // go back one - if cursorCurrent.X == 1 { - cursor.PreviousLine(1) - cursor.Forward(int(terminalSize.X)) - } else { - cursor.Back(cells) - } - - // clear the rest of the line - EraseLine(rr.stdio.Out, ERASE_LINE_END) - } else { - // we need to remove a character from the middle of the word - - cells := runeWidth(line[index-1]) - - // remove the current index from the list - line = append(line[:index-1], line[index:]...) - - // save the current position of the cursor, as we have to move the cursor one back to erase the current symbol - // and then move the cursor for each symbol in line[index-1:] to print it out, afterwards we want to restore - // the cursor to its previous location. - cursor.Save() - - // clear the rest of the line - cursor.Back(cells) - - // print what comes after - for _, char := range line[index-1:] { - //Erase symbols which are left over from older print - EraseLine(rr.stdio.Out, ERASE_LINE_END) - // print characters to the new line appropriately - if err := rr.printChar(char, mask); err != nil { - return line, err - } - } - // erase what's left over from last print - if cursorCurrent.Y < terminalSize.Y { - cursor.NextLine(1) - EraseLine(rr.stdio.Out, ERASE_LINE_END) - } - // restore cursor - cursor.Restore() - if cursorCurrent.CursorIsAtLineBegin() { - cursor.PreviousLine(1) - cursor.Forward(int(terminalSize.X)) - } else { - cursor.Back(cells) - } - } - - // decrement the index - index-- - decrement() - } else { - // otherwise the user pressed backspace while at the beginning of the line - _ = soundBell(rr.stdio.Out) - } - - // we're done processing this key - continue - } - - // if the left arrow is pressed - if r == KeyArrowLeft { - // if we have space to the left - if index > 0 { - //move the cursor to the prev line if necessary - if cursorCurrent.CursorIsAtLineBegin() { - cursor.PreviousLine(1) - cursor.Forward(int(terminalSize.X)) - } else { - cursor.Back(runeWidth(line[index-1])) - } - //decrement the index - index-- - decrement() - - } else { - // otherwise we are at the beginning of where we started reading lines - // sound the bell - _ = soundBell(rr.stdio.Out) - } - - // we're done processing this key press - continue - } - - // if the right arrow is pressed - if r == KeyArrowRight { - // if we have space to the right - if index < len(line) { - // move the cursor to the next line if necessary - if cursorCurrent.CursorIsAtLineEnd(terminalSize) { - cursor.NextLine(1) - } else { - cursor.Forward(runeWidth(line[index])) - } - index++ - increment() - - } else { - // otherwise we are at the end of the word and can't go past - // sound the bell - _ = soundBell(rr.stdio.Out) - } - - // we're done processing this key press - continue - } - // the user pressed one of the special keys - if r == SpecialKeyHome { - for index > 0 { - if cursorCurrent.CursorIsAtLineBegin() { - cursor.PreviousLine(1) - cursor.Forward(int(terminalSize.X)) - cursorCurrent.Y-- - cursorCurrent.X = terminalSize.X - } else { - cursor.Back(runeWidth(line[index-1])) - cursorCurrent.X -= Short(runeWidth(line[index-1])) - } - index-- - } - continue - // user pressed end - } else if r == SpecialKeyEnd { - for index != len(line) { - if cursorCurrent.CursorIsAtLineEnd(terminalSize) { - cursor.NextLine(1) - cursorCurrent.Y++ - cursorCurrent.X = COORDINATE_SYSTEM_BEGIN - } else { - cursor.Forward(runeWidth(line[index])) - cursorCurrent.X += Short(runeWidth(line[index])) - } - index++ - } - continue - // user pressed forward delete key - } else if r == SpecialKeyDelete { - // if index at the end of the line nothing to delete - if index != len(line) { - // save the current position of the cursor, as we have to erase the current symbol - // and then move the cursor for each symbol in line[index:] to print it out, afterwards we want to restore - // the cursor to its previous location. - cursor.Save() - // remove the symbol after the cursor - line = append(line[:index], line[index+1:]...) - // print the updated line - for _, char := range line[index:] { - EraseLine(rr.stdio.Out, ERASE_LINE_END) - // print out the character - if err := rr.printChar(char, mask); err != nil { - return line, err - } - } - // erase what's left on last line - if cursorCurrent.Y < terminalSize.Y { - cursor.NextLine(1) - EraseLine(rr.stdio.Out, ERASE_LINE_END) - } - // restore cursor - cursor.Restore() - if len(line) == 0 || index == len(line) { - EraseLine(rr.stdio.Out, ERASE_LINE_END) - } - } - continue - } - - // if the letter is another escape sequence - if unicode.IsControl(r) || r == IgnoreKey { - // ignore it - continue - } - - // the user pressed a regular key - - // if we are at the end of the line - if index == len(line) { - // just append the character at the end of the line - line = append(line, r) - // save the location of the cursor - index++ - increment() - // print out the character - if err := rr.printChar(r, mask); err != nil { - return line, err - } - } else { - // we are in the middle of the word so we need to insert the character the user pressed - line = append(line[:index], append([]rune{r}, line[index:]...)...) - // save the current position of the cursor, as we have to move the cursor back to erase the current symbol - // and then move for each symbol in line[index:] to print it out, afterwards we want to restore - // cursor's location to its previous one. - cursor.Save() - EraseLine(rr.stdio.Out, ERASE_LINE_END) - // remove the symbol after the cursor - // print the updated line - for _, char := range line[index:] { - EraseLine(rr.stdio.Out, ERASE_LINE_END) - // print out the character - if err := rr.printChar(char, mask); err != nil { - return line, err - } - increment() - } - // if we are at the last line, we want to visually insert a new line and append to it. - if cursorCurrent.CursorIsAtLineEnd(terminalSize) && cursorCurrent.Y == terminalSize.Y { - // add a new line to the terminal - if _, err := fmt.Fprintln(rr.stdio.Out); err != nil { - return line, err - } - // restore the position of the cursor horizontally - cursor.Restore() - // restore the position of the cursor vertically - cursor.PreviousLine(1) - } else { - // restore cursor - cursor.Restore() - } - // check if cursor needs to move to next line - cursorCurrent, _ = cursor.Location(rr.Buffer()) - if cursorCurrent.CursorIsAtLineEnd(terminalSize) { - cursor.NextLine(1) - } else { - cursor.Forward(runeWidth(r)) - } - // increment the index - index++ - increment() - - } - } -} - -// runeWidth returns the number of columns spanned by a rune when printed to the terminal -func runeWidth(r rune) int { - switch width.LookupRune(r).Kind() { - case width.EastAsianWide, width.EastAsianFullwidth: - return 2 - } - - if !unicode.IsPrint(r) { - return 0 - } - return 1 -} - -// isAnsiMarker returns if a rune denotes the start of an ANSI sequence -func isAnsiMarker(r rune) bool { - return r == '\x1B' -} - -// isAnsiTerminator returns if a rune denotes the end of an ANSI sequence -func isAnsiTerminator(r rune) bool { - return (r >= 0x40 && r <= 0x5a) || (r == 0x5e) || (r >= 0x60 && r <= 0x7e) -} - -// StringWidth returns the visible width of a string when printed to the terminal -func StringWidth(str string) int { - w := 0 - ansi := false - - for _, r := range str { - // increase width only when outside of ANSI escape sequences - if ansi || isAnsiMarker(r) { - ansi = !isAnsiTerminator(r) - } else { - w += runeWidth(r) - } - } - return w -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_bsd.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_bsd.go deleted file mode 100644 index 57f101425..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_bsd.go +++ /dev/null @@ -1,14 +0,0 @@ -// copied from: https://github.com/golang/crypto/blob/master/ssh/terminal/util_bsd.go -// 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. - -//go:build darwin || dragonfly || freebsd || netbsd || openbsd -// +build darwin dragonfly freebsd netbsd openbsd - -package terminal - -import "syscall" - -const ioctlReadTermios = syscall.TIOCGETA -const ioctlWriteTermios = syscall.TIOCSETA diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_linux.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_linux.go deleted file mode 100644 index dc7ec670c..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_linux.go +++ /dev/null @@ -1,14 +0,0 @@ -// copied from https://github.com/golang/crypto/blob/master/ssh/terminal/util_linux.go -// 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. -//go:build linux && !ppc64le -// +build linux,!ppc64le - -package terminal - -// These constants are declared here, rather than importing -// them from the syscall package as some syscall packages, even -// on linux, for example gccgo, do not declare them. -const ioctlReadTermios = 0x5401 // syscall.TCGETS -const ioctlWriteTermios = 0x5402 // syscall.TCSETS diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_posix.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_posix.go deleted file mode 100644 index 563a08115..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_posix.go +++ /dev/null @@ -1,132 +0,0 @@ -//go:build !windows -// +build !windows - -// The terminal mode manipulation code is derived heavily from: -// https://github.com/golang/crypto/blob/master/ssh/terminal/util.go: -// 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 terminal - -import ( - "bufio" - "bytes" - "fmt" - "syscall" - "unsafe" -) - -const ( - normalKeypad = '[' - applicationKeypad = 'O' -) - -type runeReaderState struct { - term syscall.Termios - reader *bufio.Reader - buf *bytes.Buffer -} - -func newRuneReaderState(input FileReader) runeReaderState { - buf := new(bytes.Buffer) - return runeReaderState{ - reader: bufio.NewReader(&BufferedReader{ - In: input, - Buffer: buf, - }), - buf: buf, - } -} - -func (rr *RuneReader) Buffer() *bytes.Buffer { - return rr.state.buf -} - -// For reading runes we just want to disable echo. -func (rr *RuneReader) SetTermMode() error { - if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(rr.stdio.In.Fd()), ioctlReadTermios, uintptr(unsafe.Pointer(&rr.state.term)), 0, 0, 0); err != 0 { - return err - } - - newState := rr.state.term - newState.Lflag &^= syscall.ECHO | syscall.ECHONL | syscall.ICANON | syscall.ISIG - // Because we are clearing canonical mode, we need to ensure VMIN & VTIME are - // set to the values we expect. This combination puts things in standard - // "blocking read" mode (see termios(3)). - newState.Cc[syscall.VMIN] = 1 - newState.Cc[syscall.VTIME] = 0 - - if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(rr.stdio.In.Fd()), ioctlWriteTermios, uintptr(unsafe.Pointer(&newState)), 0, 0, 0); err != 0 { - return err - } - - return nil -} - -func (rr *RuneReader) RestoreTermMode() error { - if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(rr.stdio.In.Fd()), ioctlWriteTermios, uintptr(unsafe.Pointer(&rr.state.term)), 0, 0, 0); err != 0 { - return err - } - return nil -} - -// ReadRune Parse escape sequences such as ESC [ A for arrow keys. -// See https://vt100.net/docs/vt102-ug/appendixc.html -func (rr *RuneReader) ReadRune() (rune, int, error) { - r, size, err := rr.state.reader.ReadRune() - if err != nil { - return r, size, err - } - - if r != KeyEscape { - return r, size, err - } - - if rr.state.reader.Buffered() == 0 { - // no more characters so must be `Esc` key - return KeyEscape, 1, nil - } - - r, size, err = rr.state.reader.ReadRune() - if err != nil { - return r, size, err - } - - // ESC O ... or ESC [ ...? - if r != normalKeypad && r != applicationKeypad { - return r, size, fmt.Errorf("unexpected escape sequence from terminal: %q", []rune{KeyEscape, r}) - } - - keypad := r - - r, size, err = rr.state.reader.ReadRune() - if err != nil { - return r, size, err - } - - switch r { - case 'A': // ESC [ A or ESC O A - return KeyArrowUp, 1, nil - case 'B': // ESC [ B or ESC O B - return KeyArrowDown, 1, nil - case 'C': // ESC [ C or ESC O C - return KeyArrowRight, 1, nil - case 'D': // ESC [ D or ESC O D - return KeyArrowLeft, 1, nil - case 'F': // ESC [ F or ESC O F - return SpecialKeyEnd, 1, nil - case 'H': // ESC [ H or ESC O H - return SpecialKeyHome, 1, nil - case '3': // ESC [ 3 - if keypad == normalKeypad { - // discard the following '~' key from buffer - _, _ = rr.state.reader.Discard(1) - return SpecialKeyDelete, 1, nil - } - } - - // discard the following '~' key from buffer - _, _ = rr.state.reader.Discard(1) - return IgnoreKey, 1, nil -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_ppc64le.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_ppc64le.go deleted file mode 100644 index 450f796c6..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_ppc64le.go +++ /dev/null @@ -1,8 +0,0 @@ -//go:build ppc64le && linux -// +build ppc64le,linux - -package terminal - -// Used syscall numbers from https://github.com/golang/go/blob/master/src/syscall/ztypes_linux_ppc64le.go -const ioctlReadTermios = 0x402c7413 // syscall.TCGETS -const ioctlWriteTermios = 0x802c7414 // syscall.TCSETS diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_windows.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_windows.go deleted file mode 100644 index 791092f53..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_windows.go +++ /dev/null @@ -1,142 +0,0 @@ -package terminal - -import ( - "bytes" - "syscall" - "unsafe" -) - -var ( - dll = syscall.NewLazyDLL("kernel32.dll") - setConsoleMode = dll.NewProc("SetConsoleMode") - getConsoleMode = dll.NewProc("GetConsoleMode") - readConsoleInput = dll.NewProc("ReadConsoleInputW") -) - -const ( - EVENT_KEY = 0x0001 - - // key codes for arrow keys - // https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx - VK_DELETE = 0x2E - VK_END = 0x23 - VK_HOME = 0x24 - VK_LEFT = 0x25 - VK_UP = 0x26 - VK_RIGHT = 0x27 - VK_DOWN = 0x28 - - RIGHT_CTRL_PRESSED = 0x0004 - LEFT_CTRL_PRESSED = 0x0008 - - ENABLE_ECHO_INPUT uint32 = 0x0004 - ENABLE_LINE_INPUT uint32 = 0x0002 - ENABLE_PROCESSED_INPUT uint32 = 0x0001 -) - -type inputRecord struct { - eventType uint16 - padding uint16 - event [16]byte -} - -type keyEventRecord struct { - bKeyDown int32 - wRepeatCount uint16 - wVirtualKeyCode uint16 - wVirtualScanCode uint16 - unicodeChar uint16 - wdControlKeyState uint32 -} - -type runeReaderState struct { - term uint32 -} - -func newRuneReaderState(input FileReader) runeReaderState { - return runeReaderState{} -} - -func (rr *RuneReader) Buffer() *bytes.Buffer { - return nil -} - -func (rr *RuneReader) SetTermMode() error { - r, _, err := getConsoleMode.Call(uintptr(rr.stdio.In.Fd()), uintptr(unsafe.Pointer(&rr.state.term))) - // windows return 0 on error - if r == 0 { - return err - } - - newState := rr.state.term - newState &^= ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT - r, _, err = setConsoleMode.Call(uintptr(rr.stdio.In.Fd()), uintptr(newState)) - // windows return 0 on error - if r == 0 { - return err - } - return nil -} - -func (rr *RuneReader) RestoreTermMode() error { - r, _, err := setConsoleMode.Call(uintptr(rr.stdio.In.Fd()), uintptr(rr.state.term)) - // windows return 0 on error - if r == 0 { - return err - } - return nil -} - -func (rr *RuneReader) ReadRune() (rune, int, error) { - ir := &inputRecord{} - bytesRead := 0 - for { - rv, _, e := readConsoleInput.Call(rr.stdio.In.Fd(), uintptr(unsafe.Pointer(ir)), 1, uintptr(unsafe.Pointer(&bytesRead))) - // windows returns non-zero to indicate success - if rv == 0 && e != nil { - return 0, 0, e - } - - if ir.eventType != EVENT_KEY { - continue - } - - // the event data is really a c struct union, so here we have to do an usafe - // cast to put the data into the keyEventRecord (since we have already verified - // above that this event does correspond to a key event - key := (*keyEventRecord)(unsafe.Pointer(&ir.event[0])) - // we only care about key down events - if key.bKeyDown == 0 { - continue - } - if key.wdControlKeyState&(LEFT_CTRL_PRESSED|RIGHT_CTRL_PRESSED) != 0 && key.unicodeChar == 'C' { - return KeyInterrupt, bytesRead, nil - } - // not a normal character so look up the input sequence from the - // virtual key code mappings (VK_*) - if key.unicodeChar == 0 { - switch key.wVirtualKeyCode { - case VK_DOWN: - return KeyArrowDown, bytesRead, nil - case VK_LEFT: - return KeyArrowLeft, bytesRead, nil - case VK_RIGHT: - return KeyArrowRight, bytesRead, nil - case VK_UP: - return KeyArrowUp, bytesRead, nil - case VK_DELETE: - return SpecialKeyDelete, bytesRead, nil - case VK_HOME: - return SpecialKeyHome, bytesRead, nil - case VK_END: - return SpecialKeyEnd, bytesRead, nil - default: - // not a virtual key that we care about so just continue on to - // the next input key - continue - } - } - r := rune(key.unicodeChar) - return r, bytesRead, nil - } -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/sequences.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/sequences.go deleted file mode 100644 index 5f61e2b65..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/sequences.go +++ /dev/null @@ -1,32 +0,0 @@ -package terminal - -import ( - "fmt" - "io" -) - -const ( - KeyArrowLeft = '\x02' - KeyArrowRight = '\x06' - KeyArrowUp = '\x10' - KeyArrowDown = '\x0e' - KeySpace = ' ' - KeyEnter = '\r' - KeyBackspace = '\b' - KeyDelete = '\x7f' - KeyInterrupt = '\x03' - KeyEndTransmission = '\x04' - KeyEscape = '\x1b' - KeyDeleteWord = '\x17' // Ctrl+W - KeyDeleteLine = '\x18' // Ctrl+X - SpecialKeyHome = '\x01' - SpecialKeyEnd = '\x11' - SpecialKeyDelete = '\x12' - IgnoreKey = '\000' - KeyTab = '\t' -) - -func soundBell(out io.Writer) error { - _, err := fmt.Fprint(out, "\a") - return err -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/stdio.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/stdio.go deleted file mode 100644 index 88bf7c4ea..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/stdio.go +++ /dev/null @@ -1,24 +0,0 @@ -package terminal - -import ( - "io" -) - -// Stdio is the standard input/output the terminal reads/writes with. -type Stdio struct { - In FileReader - Out FileWriter - Err io.Writer -} - -// FileWriter provides a minimal interface for Stdin. -type FileWriter interface { - io.Writer - Fd() uintptr -} - -// FileReader provides a minimal interface for Stdout. -type FileReader interface { - io.Reader - Fd() uintptr -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/syscall_windows.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/syscall_windows.go deleted file mode 100644 index 63b85d4c3..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/syscall_windows.go +++ /dev/null @@ -1,39 +0,0 @@ -package terminal - -import ( - "syscall" -) - -var ( - kernel32 = syscall.NewLazyDLL("kernel32.dll") - procGetConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo") - procSetConsoleTextAttribute = kernel32.NewProc("SetConsoleTextAttribute") - procSetConsoleCursorPosition = kernel32.NewProc("SetConsoleCursorPosition") - procFillConsoleOutputCharacter = kernel32.NewProc("FillConsoleOutputCharacterW") - procGetConsoleCursorInfo = kernel32.NewProc("GetConsoleCursorInfo") - procSetConsoleCursorInfo = kernel32.NewProc("SetConsoleCursorInfo") -) - -type wchar uint16 -type dword uint32 -type word uint16 - -type smallRect struct { - left Short - top Short - right Short - bottom Short -} - -type consoleScreenBufferInfo struct { - size Coord - cursorPosition Coord - attributes word - window smallRect - maximumWindowSize Coord -} - -type consoleCursorInfo struct { - size dword - visible int32 -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/terminal.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/terminal.go deleted file mode 100644 index 4b59062c7..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/terminal.go +++ /dev/null @@ -1,8 +0,0 @@ -package terminal - -type Short int16 - -type Coord struct { - X Short - Y Short -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/transform.go b/vendor/github.com/AlecAivazis/survey/v2/transform.go deleted file mode 100644 index a78ada392..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/transform.go +++ /dev/null @@ -1,82 +0,0 @@ -package survey - -import ( - "reflect" - "strings" - - "golang.org/x/text/cases" - "golang.org/x/text/language" -) - -// TransformString returns a `Transformer` based on the "f" -// function which accepts a string representation of the answer -// and returns a new one, transformed, answer. -// Take for example the functions inside the std `strings` package, -// they can be converted to a compatible `Transformer` by using this function, -// i.e: `TransformString(strings.Title)`, `TransformString(strings.ToUpper)`. -// -// Note that `TransformString` is just a helper, `Transformer` can be used -// to transform any type of answer. -func TransformString(f func(s string) string) Transformer { - return func(ans interface{}) interface{} { - // if the answer value passed in is the zero value of the appropriate type - if isZero(reflect.ValueOf(ans)) { - // skip this `Transformer` by returning a zero value of string. - // The original answer will be not affected, - // see survey.go#L125. - // A zero value of string should be returned to be handled by - // next Transformer in a composed Tranformer, - // see tranform.go#L75 - return "" - } - - // "ans" is never nil here, so we don't have to check that - // see survey.go#L338 for more. - // Make sure that the the answer's value was a typeof string. - s, ok := ans.(string) - if !ok { - return "" - } - - return f(s) - } -} - -// ToLower is a `Transformer`. -// It receives an answer value -// and returns a copy of the "ans" -// with all Unicode letters mapped to their lower case. -// -// Note that if "ans" is not a string then it will -// return a nil value, meaning that the above answer -// will not be affected by this call at all. -func ToLower(ans interface{}) interface{} { - transformer := TransformString(strings.ToLower) - return transformer(ans) -} - -// Title is a `Transformer`. -// It receives an answer value -// and returns a copy of the "ans" -// with all Unicode letters that begin words -// mapped to their title case. -// -// Note that if "ans" is not a string then it will -// return a nil value, meaning that the above answer -// will not be affected by this call at all. -func Title(ans interface{}) interface{} { - transformer := TransformString(cases.Title(language.English).String) - return transformer(ans) -} - -// ComposeTransformers is a variadic function used to create one transformer from many. -func ComposeTransformers(transformers ...Transformer) Transformer { - // return a transformer that calls each one sequentially - return func(ans interface{}) interface{} { - // execute each transformer - for _, t := range transformers { - ans = t(ans) - } - return ans - } -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/validate.go b/vendor/github.com/AlecAivazis/survey/v2/validate.go deleted file mode 100644 index 7f03b23ac..000000000 --- a/vendor/github.com/AlecAivazis/survey/v2/validate.go +++ /dev/null @@ -1,128 +0,0 @@ -package survey - -import ( - "errors" - "fmt" - "reflect" - - "github.com/AlecAivazis/survey/v2/core" -) - -// Required does not allow an empty value -func Required(val interface{}) error { - // the reflect value of the result - value := reflect.ValueOf(val) - - // if the value passed in is the zero value of the appropriate type - if isZero(value) && value.Kind() != reflect.Bool { - //lint:ignore ST1005 this error message should render as capitalized - return errors.New("Value is required") - } - return nil -} - -// MaxLength requires that the string is no longer than the specified value -func MaxLength(length int) Validator { - // return a validator that checks the length of the string - return func(val interface{}) error { - if str, ok := val.(string); ok { - // if the string is longer than the given value - if len([]rune(str)) > length { - // yell loudly - return fmt.Errorf("value is too long. Max length is %v", length) - } - } else { - // otherwise we cannot convert the value into a string and cannot enforce length - return fmt.Errorf("cannot enforce length on response of type %v", reflect.TypeOf(val).Name()) - } - - // the input is fine - return nil - } -} - -// MinLength requires that the string is longer or equal in length to the specified value -func MinLength(length int) Validator { - // return a validator that checks the length of the string - return func(val interface{}) error { - if str, ok := val.(string); ok { - // if the string is shorter than the given value - if len([]rune(str)) < length { - // yell loudly - return fmt.Errorf("value is too short. Min length is %v", length) - } - } else { - // otherwise we cannot convert the value into a string and cannot enforce length - return fmt.Errorf("cannot enforce length on response of type %v", reflect.TypeOf(val).Name()) - } - - // the input is fine - return nil - } -} - -// MaxItems requires that the list is no longer than the specified value -func MaxItems(numberItems int) Validator { - // return a validator that checks the length of the list - return func(val interface{}) error { - if list, ok := val.([]core.OptionAnswer); ok { - // if the list is longer than the given value - if len(list) > numberItems { - // yell loudly - return fmt.Errorf("value is too long. Max items is %v", numberItems) - } - } else { - // otherwise we cannot convert the value into a list of answer and cannot enforce length - return fmt.Errorf("cannot impose the length on something other than a list of answers") - } - // the input is fine - return nil - } -} - -// MinItems requires that the list is longer or equal in length to the specified value -func MinItems(numberItems int) Validator { - // return a validator that checks the length of the list - return func(val interface{}) error { - if list, ok := val.([]core.OptionAnswer); ok { - // if the list is shorter than the given value - if len(list) < numberItems { - // yell loudly - return fmt.Errorf("value is too short. Min items is %v", numberItems) - } - } else { - // otherwise we cannot convert the value into a list of answer and cannot enforce length - return fmt.Errorf("cannot impose the length on something other than a list of answers") - } - // the input is fine - return nil - } -} - -// ComposeValidators is a variadic function used to create one validator from many. -func ComposeValidators(validators ...Validator) Validator { - // return a validator that calls each one sequentially - return func(val interface{}) error { - // execute each validator - for _, validator := range validators { - // if the answer's value is not valid - if err := validator(val); err != nil { - // return the error - return err - } - } - // we passed all validators, the answer is valid - return nil - } -} - -// isZero returns true if the passed value is the zero object -func isZero(v reflect.Value) bool { - switch v.Kind() { - case reflect.Slice, reflect.Map: - return v.Len() == 0 - } - - // compare the types directly with more general coverage - return reflect.DeepEqual(v.Interface(), reflect.Zero(v.Type()).Interface()) -} diff --git a/vendor/github.com/Azure/go-ansiterm/LICENSE b/vendor/github.com/Azure/go-ansiterm/LICENSE deleted file mode 100644 index e3d9a64d1..000000000 --- a/vendor/github.com/Azure/go-ansiterm/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Microsoft Corporation - -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/Azure/go-ansiterm/README.md b/vendor/github.com/Azure/go-ansiterm/README.md deleted file mode 100644 index 261c041e7..000000000 --- a/vendor/github.com/Azure/go-ansiterm/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# go-ansiterm - -This is a cross platform Ansi Terminal Emulation library. It reads a stream of Ansi characters and produces the appropriate function calls. The results of the function calls are platform dependent. - -For example the parser might receive "ESC, [, A" as a stream of three characters. This is the code for Cursor Up (http://www.vt100.net/docs/vt510-rm/CUU). The parser then calls the cursor up function (CUU()) on an event handler. The event handler determines what platform specific work must be done to cause the cursor to move up one position. - -The parser (parser.go) is a partial implementation of this state machine (http://vt100.net/emu/vt500_parser.png). There are also two event handler implementations, one for tests (test_event_handler.go) to validate that the expected events are being produced and called, the other is a Windows implementation (winterm/win_event_handler.go). - -See parser_test.go for examples exercising the state machine and generating appropriate function calls. - ------ -This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. diff --git a/vendor/github.com/Azure/go-ansiterm/SECURITY.md b/vendor/github.com/Azure/go-ansiterm/SECURITY.md deleted file mode 100644 index e138ec5d6..000000000 --- a/vendor/github.com/Azure/go-ansiterm/SECURITY.md +++ /dev/null @@ -1,41 +0,0 @@ - - -## Security - -Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/). - -If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/opensource/security/definition), please report it to us as described below. - -## Reporting Security Issues - -**Please do not report security vulnerabilities through public GitHub issues.** - -Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/opensource/security/create-report). - -If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/opensource/security/pgpkey). - -You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://aka.ms/opensource/security/msrc). - -Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: - - * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) - * Full paths of source file(s) related to the manifestation of the issue - * The location of the affected source code (tag/branch/commit or direct URL) - * Any special configuration required to reproduce the issue - * Step-by-step instructions to reproduce the issue - * Proof-of-concept or exploit code (if possible) - * Impact of the issue, including how an attacker might exploit the issue - -This information will help us triage your report more quickly. - -If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/opensource/security/bounty) page for more details about our active programs. - -## Preferred Languages - -We prefer all communications to be in English. - -## Policy - -Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/opensource/security/cvd). - - diff --git a/vendor/github.com/Azure/go-ansiterm/constants.go b/vendor/github.com/Azure/go-ansiterm/constants.go deleted file mode 100644 index 96504a33b..000000000 --- a/vendor/github.com/Azure/go-ansiterm/constants.go +++ /dev/null @@ -1,188 +0,0 @@ -package ansiterm - -const LogEnv = "DEBUG_TERMINAL" - -// ANSI constants -// References: -// -- http://www.ecma-international.org/publications/standards/Ecma-048.htm -// -- http://man7.org/linux/man-pages/man4/console_codes.4.html -// -- http://manpages.ubuntu.com/manpages/intrepid/man4/console_codes.4.html -// -- http://en.wikipedia.org/wiki/ANSI_escape_code -// -- http://vt100.net/emu/dec_ansi_parser -// -- http://vt100.net/emu/vt500_parser.svg -// -- http://invisible-island.net/xterm/ctlseqs/ctlseqs.html -// -- http://www.inwap.com/pdp10/ansicode.txt -const ( - // ECMA-48 Set Graphics Rendition - // Note: - // -- Constants leading with an underscore (e.g., _ANSI_xxx) are unsupported or reserved - // -- Fonts could possibly be supported via SetCurrentConsoleFontEx - // -- Windows does not expose the per-window cursor (i.e., caret) blink times - ANSI_SGR_RESET = 0 - ANSI_SGR_BOLD = 1 - ANSI_SGR_DIM = 2 - _ANSI_SGR_ITALIC = 3 - ANSI_SGR_UNDERLINE = 4 - _ANSI_SGR_BLINKSLOW = 5 - _ANSI_SGR_BLINKFAST = 6 - ANSI_SGR_REVERSE = 7 - _ANSI_SGR_INVISIBLE = 8 - _ANSI_SGR_LINETHROUGH = 9 - _ANSI_SGR_FONT_00 = 10 - _ANSI_SGR_FONT_01 = 11 - _ANSI_SGR_FONT_02 = 12 - _ANSI_SGR_FONT_03 = 13 - _ANSI_SGR_FONT_04 = 14 - _ANSI_SGR_FONT_05 = 15 - _ANSI_SGR_FONT_06 = 16 - _ANSI_SGR_FONT_07 = 17 - _ANSI_SGR_FONT_08 = 18 - _ANSI_SGR_FONT_09 = 19 - _ANSI_SGR_FONT_10 = 20 - _ANSI_SGR_DOUBLEUNDERLINE = 21 - ANSI_SGR_BOLD_DIM_OFF = 22 - _ANSI_SGR_ITALIC_OFF = 23 - ANSI_SGR_UNDERLINE_OFF = 24 - _ANSI_SGR_BLINK_OFF = 25 - _ANSI_SGR_RESERVED_00 = 26 - ANSI_SGR_REVERSE_OFF = 27 - _ANSI_SGR_INVISIBLE_OFF = 28 - _ANSI_SGR_LINETHROUGH_OFF = 29 - ANSI_SGR_FOREGROUND_BLACK = 30 - ANSI_SGR_FOREGROUND_RED = 31 - ANSI_SGR_FOREGROUND_GREEN = 32 - ANSI_SGR_FOREGROUND_YELLOW = 33 - ANSI_SGR_FOREGROUND_BLUE = 34 - ANSI_SGR_FOREGROUND_MAGENTA = 35 - ANSI_SGR_FOREGROUND_CYAN = 36 - ANSI_SGR_FOREGROUND_WHITE = 37 - _ANSI_SGR_RESERVED_01 = 38 - ANSI_SGR_FOREGROUND_DEFAULT = 39 - ANSI_SGR_BACKGROUND_BLACK = 40 - ANSI_SGR_BACKGROUND_RED = 41 - ANSI_SGR_BACKGROUND_GREEN = 42 - ANSI_SGR_BACKGROUND_YELLOW = 43 - ANSI_SGR_BACKGROUND_BLUE = 44 - ANSI_SGR_BACKGROUND_MAGENTA = 45 - ANSI_SGR_BACKGROUND_CYAN = 46 - ANSI_SGR_BACKGROUND_WHITE = 47 - _ANSI_SGR_RESERVED_02 = 48 - ANSI_SGR_BACKGROUND_DEFAULT = 49 - // 50 - 65: Unsupported - - ANSI_MAX_CMD_LENGTH = 4096 - - MAX_INPUT_EVENTS = 128 - DEFAULT_WIDTH = 80 - DEFAULT_HEIGHT = 24 - - ANSI_BEL = 0x07 - ANSI_BACKSPACE = 0x08 - ANSI_TAB = 0x09 - ANSI_LINE_FEED = 0x0A - ANSI_VERTICAL_TAB = 0x0B - ANSI_FORM_FEED = 0x0C - ANSI_CARRIAGE_RETURN = 0x0D - ANSI_ESCAPE_PRIMARY = 0x1B - ANSI_ESCAPE_SECONDARY = 0x5B - ANSI_OSC_STRING_ENTRY = 0x5D - ANSI_COMMAND_FIRST = 0x40 - ANSI_COMMAND_LAST = 0x7E - DCS_ENTRY = 0x90 - CSI_ENTRY = 0x9B - OSC_STRING = 0x9D - ANSI_PARAMETER_SEP = ";" - ANSI_CMD_G0 = '(' - ANSI_CMD_G1 = ')' - ANSI_CMD_G2 = '*' - ANSI_CMD_G3 = '+' - ANSI_CMD_DECPNM = '>' - ANSI_CMD_DECPAM = '=' - ANSI_CMD_OSC = ']' - ANSI_CMD_STR_TERM = '\\' - - KEY_CONTROL_PARAM_2 = ";2" - KEY_CONTROL_PARAM_3 = ";3" - KEY_CONTROL_PARAM_4 = ";4" - KEY_CONTROL_PARAM_5 = ";5" - KEY_CONTROL_PARAM_6 = ";6" - KEY_CONTROL_PARAM_7 = ";7" - KEY_CONTROL_PARAM_8 = ";8" - KEY_ESC_CSI = "\x1B[" - KEY_ESC_N = "\x1BN" - KEY_ESC_O = "\x1BO" - - FILL_CHARACTER = ' ' -) - -func getByteRange(start byte, end byte) []byte { - bytes := make([]byte, 0, 32) - for i := start; i <= end; i++ { - bytes = append(bytes, byte(i)) - } - - return bytes -} - -var toGroundBytes = getToGroundBytes() -var executors = getExecuteBytes() - -// SPACE 20+A0 hex Always and everywhere a blank space -// Intermediate 20-2F hex !"#$%&'()*+,-./ -var intermeds = getByteRange(0x20, 0x2F) - -// Parameters 30-3F hex 0123456789:;<=>? -// CSI Parameters 30-39, 3B hex 0123456789; -var csiParams = getByteRange(0x30, 0x3F) - -var csiCollectables = append(getByteRange(0x30, 0x39), getByteRange(0x3B, 0x3F)...) - -// Uppercase 40-5F hex @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_ -var upperCase = getByteRange(0x40, 0x5F) - -// Lowercase 60-7E hex `abcdefghijlkmnopqrstuvwxyz{|}~ -var lowerCase = getByteRange(0x60, 0x7E) - -// Alphabetics 40-7E hex (all of upper and lower case) -var alphabetics = append(upperCase, lowerCase...) - -var printables = getByteRange(0x20, 0x7F) - -var escapeIntermediateToGroundBytes = getByteRange(0x30, 0x7E) -var escapeToGroundBytes = getEscapeToGroundBytes() - -// See http://www.vt100.net/emu/vt500_parser.png for description of the complex -// byte ranges below - -func getEscapeToGroundBytes() []byte { - escapeToGroundBytes := getByteRange(0x30, 0x4F) - escapeToGroundBytes = append(escapeToGroundBytes, getByteRange(0x51, 0x57)...) - escapeToGroundBytes = append(escapeToGroundBytes, 0x59) - escapeToGroundBytes = append(escapeToGroundBytes, 0x5A) - escapeToGroundBytes = append(escapeToGroundBytes, 0x5C) - escapeToGroundBytes = append(escapeToGroundBytes, getByteRange(0x60, 0x7E)...) - return escapeToGroundBytes -} - -func getExecuteBytes() []byte { - executeBytes := getByteRange(0x00, 0x17) - executeBytes = append(executeBytes, 0x19) - executeBytes = append(executeBytes, getByteRange(0x1C, 0x1F)...) - return executeBytes -} - -func getToGroundBytes() []byte { - groundBytes := []byte{0x18} - groundBytes = append(groundBytes, 0x1A) - groundBytes = append(groundBytes, getByteRange(0x80, 0x8F)...) - groundBytes = append(groundBytes, getByteRange(0x91, 0x97)...) - groundBytes = append(groundBytes, 0x99) - groundBytes = append(groundBytes, 0x9A) - groundBytes = append(groundBytes, 0x9C) - return groundBytes -} - -// Delete 7F hex Always and everywhere ignored -// C1 Control 80-9F hex 32 additional control characters -// G1 Displayable A1-FE hex 94 additional displayable characters -// Special A0+FF hex Same as SPACE and DELETE diff --git a/vendor/github.com/Azure/go-ansiterm/context.go b/vendor/github.com/Azure/go-ansiterm/context.go deleted file mode 100644 index 8d66e777c..000000000 --- a/vendor/github.com/Azure/go-ansiterm/context.go +++ /dev/null @@ -1,7 +0,0 @@ -package ansiterm - -type ansiContext struct { - currentChar byte - paramBuffer []byte - interBuffer []byte -} diff --git a/vendor/github.com/Azure/go-ansiterm/csi_entry_state.go b/vendor/github.com/Azure/go-ansiterm/csi_entry_state.go deleted file mode 100644 index bcbe00d0c..000000000 --- a/vendor/github.com/Azure/go-ansiterm/csi_entry_state.go +++ /dev/null @@ -1,49 +0,0 @@ -package ansiterm - -type csiEntryState struct { - baseState -} - -func (csiState csiEntryState) Handle(b byte) (s state, e error) { - csiState.parser.logf("CsiEntry::Handle %#x", b) - - nextState, err := csiState.baseState.Handle(b) - if nextState != nil || err != nil { - return nextState, err - } - - switch { - case sliceContains(alphabetics, b): - return csiState.parser.ground, nil - case sliceContains(csiCollectables, b): - return csiState.parser.csiParam, nil - case sliceContains(executors, b): - return csiState, csiState.parser.execute() - } - - return csiState, nil -} - -func (csiState csiEntryState) Transition(s state) error { - csiState.parser.logf("CsiEntry::Transition %s --> %s", csiState.Name(), s.Name()) - csiState.baseState.Transition(s) - - switch s { - case csiState.parser.ground: - return csiState.parser.csiDispatch() - case csiState.parser.csiParam: - switch { - case sliceContains(csiParams, csiState.parser.context.currentChar): - csiState.parser.collectParam() - case sliceContains(intermeds, csiState.parser.context.currentChar): - csiState.parser.collectInter() - } - } - - return nil -} - -func (csiState csiEntryState) Enter() error { - csiState.parser.clear() - return nil -} diff --git a/vendor/github.com/Azure/go-ansiterm/csi_param_state.go b/vendor/github.com/Azure/go-ansiterm/csi_param_state.go deleted file mode 100644 index 7ed5e01c3..000000000 --- a/vendor/github.com/Azure/go-ansiterm/csi_param_state.go +++ /dev/null @@ -1,38 +0,0 @@ -package ansiterm - -type csiParamState struct { - baseState -} - -func (csiState csiParamState) Handle(b byte) (s state, e error) { - csiState.parser.logf("CsiParam::Handle %#x", b) - - nextState, err := csiState.baseState.Handle(b) - if nextState != nil || err != nil { - return nextState, err - } - - switch { - case sliceContains(alphabetics, b): - return csiState.parser.ground, nil - case sliceContains(csiCollectables, b): - csiState.parser.collectParam() - return csiState, nil - case sliceContains(executors, b): - return csiState, csiState.parser.execute() - } - - return csiState, nil -} - -func (csiState csiParamState) Transition(s state) error { - csiState.parser.logf("CsiParam::Transition %s --> %s", csiState.Name(), s.Name()) - csiState.baseState.Transition(s) - - switch s { - case csiState.parser.ground: - return csiState.parser.csiDispatch() - } - - return nil -} diff --git a/vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go b/vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go deleted file mode 100644 index 1c719db9e..000000000 --- a/vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go +++ /dev/null @@ -1,36 +0,0 @@ -package ansiterm - -type escapeIntermediateState struct { - baseState -} - -func (escState escapeIntermediateState) Handle(b byte) (s state, e error) { - escState.parser.logf("escapeIntermediateState::Handle %#x", b) - nextState, err := escState.baseState.Handle(b) - if nextState != nil || err != nil { - return nextState, err - } - - switch { - case sliceContains(intermeds, b): - return escState, escState.parser.collectInter() - case sliceContains(executors, b): - return escState, escState.parser.execute() - case sliceContains(escapeIntermediateToGroundBytes, b): - return escState.parser.ground, nil - } - - return escState, nil -} - -func (escState escapeIntermediateState) Transition(s state) error { - escState.parser.logf("escapeIntermediateState::Transition %s --> %s", escState.Name(), s.Name()) - escState.baseState.Transition(s) - - switch s { - case escState.parser.ground: - return escState.parser.escDispatch() - } - - return nil -} diff --git a/vendor/github.com/Azure/go-ansiterm/escape_state.go b/vendor/github.com/Azure/go-ansiterm/escape_state.go deleted file mode 100644 index 6390abd23..000000000 --- a/vendor/github.com/Azure/go-ansiterm/escape_state.go +++ /dev/null @@ -1,47 +0,0 @@ -package ansiterm - -type escapeState struct { - baseState -} - -func (escState escapeState) Handle(b byte) (s state, e error) { - escState.parser.logf("escapeState::Handle %#x", b) - nextState, err := escState.baseState.Handle(b) - if nextState != nil || err != nil { - return nextState, err - } - - switch { - case b == ANSI_ESCAPE_SECONDARY: - return escState.parser.csiEntry, nil - case b == ANSI_OSC_STRING_ENTRY: - return escState.parser.oscString, nil - case sliceContains(executors, b): - return escState, escState.parser.execute() - case sliceContains(escapeToGroundBytes, b): - return escState.parser.ground, nil - case sliceContains(intermeds, b): - return escState.parser.escapeIntermediate, nil - } - - return escState, nil -} - -func (escState escapeState) Transition(s state) error { - escState.parser.logf("Escape::Transition %s --> %s", escState.Name(), s.Name()) - escState.baseState.Transition(s) - - switch s { - case escState.parser.ground: - return escState.parser.escDispatch() - case escState.parser.escapeIntermediate: - return escState.parser.collectInter() - } - - return nil -} - -func (escState escapeState) Enter() error { - escState.parser.clear() - return nil -} diff --git a/vendor/github.com/Azure/go-ansiterm/event_handler.go b/vendor/github.com/Azure/go-ansiterm/event_handler.go deleted file mode 100644 index 98087b38c..000000000 --- a/vendor/github.com/Azure/go-ansiterm/event_handler.go +++ /dev/null @@ -1,90 +0,0 @@ -package ansiterm - -type AnsiEventHandler interface { - // Print - Print(b byte) error - - // Execute C0 commands - Execute(b byte) error - - // CUrsor Up - CUU(int) error - - // CUrsor Down - CUD(int) error - - // CUrsor Forward - CUF(int) error - - // CUrsor Backward - CUB(int) error - - // Cursor to Next Line - CNL(int) error - - // Cursor to Previous Line - CPL(int) error - - // Cursor Horizontal position Absolute - CHA(int) error - - // Vertical line Position Absolute - VPA(int) error - - // CUrsor Position - CUP(int, int) error - - // Horizontal and Vertical Position (depends on PUM) - HVP(int, int) error - - // Text Cursor Enable Mode - DECTCEM(bool) error - - // Origin Mode - DECOM(bool) error - - // 132 Column Mode - DECCOLM(bool) error - - // Erase in Display - ED(int) error - - // Erase in Line - EL(int) error - - // Insert Line - IL(int) error - - // Delete Line - DL(int) error - - // Insert Character - ICH(int) error - - // Delete Character - DCH(int) error - - // Set Graphics Rendition - SGR([]int) error - - // Pan Down - SU(int) error - - // Pan Up - SD(int) error - - // Device Attributes - DA([]string) error - - // Set Top and Bottom Margins - DECSTBM(int, int) error - - // Index - IND() error - - // Reverse Index - RI() error - - // Flush updates from previous commands - Flush() error -} diff --git a/vendor/github.com/Azure/go-ansiterm/ground_state.go b/vendor/github.com/Azure/go-ansiterm/ground_state.go deleted file mode 100644 index 52451e946..000000000 --- a/vendor/github.com/Azure/go-ansiterm/ground_state.go +++ /dev/null @@ -1,24 +0,0 @@ -package ansiterm - -type groundState struct { - baseState -} - -func (gs groundState) Handle(b byte) (s state, e error) { - gs.parser.context.currentChar = b - - nextState, err := gs.baseState.Handle(b) - if nextState != nil || err != nil { - return nextState, err - } - - switch { - case sliceContains(printables, b): - return gs, gs.parser.print() - - case sliceContains(executors, b): - return gs, gs.parser.execute() - } - - return gs, nil -} diff --git a/vendor/github.com/Azure/go-ansiterm/osc_string_state.go b/vendor/github.com/Azure/go-ansiterm/osc_string_state.go deleted file mode 100644 index 593b10ab6..000000000 --- a/vendor/github.com/Azure/go-ansiterm/osc_string_state.go +++ /dev/null @@ -1,31 +0,0 @@ -package ansiterm - -type oscStringState struct { - baseState -} - -func (oscState oscStringState) Handle(b byte) (s state, e error) { - oscState.parser.logf("OscString::Handle %#x", b) - nextState, err := oscState.baseState.Handle(b) - if nextState != nil || err != nil { - return nextState, err - } - - switch { - case isOscStringTerminator(b): - return oscState.parser.ground, nil - } - - return oscState, nil -} - -// See below for OSC string terminators for linux -// http://man7.org/linux/man-pages/man4/console_codes.4.html -func isOscStringTerminator(b byte) bool { - - if b == ANSI_BEL || b == 0x5C { - return true - } - - return false -} diff --git a/vendor/github.com/Azure/go-ansiterm/parser.go b/vendor/github.com/Azure/go-ansiterm/parser.go deleted file mode 100644 index 03cec7ada..000000000 --- a/vendor/github.com/Azure/go-ansiterm/parser.go +++ /dev/null @@ -1,151 +0,0 @@ -package ansiterm - -import ( - "errors" - "log" - "os" -) - -type AnsiParser struct { - currState state - eventHandler AnsiEventHandler - context *ansiContext - csiEntry state - csiParam state - dcsEntry state - escape state - escapeIntermediate state - error state - ground state - oscString state - stateMap []state - - logf func(string, ...interface{}) -} - -type Option func(*AnsiParser) - -func WithLogf(f func(string, ...interface{})) Option { - return func(ap *AnsiParser) { - ap.logf = f - } -} - -func CreateParser(initialState string, evtHandler AnsiEventHandler, opts ...Option) *AnsiParser { - ap := &AnsiParser{ - eventHandler: evtHandler, - context: &ansiContext{}, - } - for _, o := range opts { - o(ap) - } - - if isDebugEnv := os.Getenv(LogEnv); isDebugEnv == "1" { - logFile, _ := os.Create("ansiParser.log") - logger := log.New(logFile, "", log.LstdFlags) - if ap.logf != nil { - l := ap.logf - ap.logf = func(s string, v ...interface{}) { - l(s, v...) - logger.Printf(s, v...) - } - } else { - ap.logf = logger.Printf - } - } - - if ap.logf == nil { - ap.logf = func(string, ...interface{}) {} - } - - ap.csiEntry = csiEntryState{baseState{name: "CsiEntry", parser: ap}} - ap.csiParam = csiParamState{baseState{name: "CsiParam", parser: ap}} - ap.dcsEntry = dcsEntryState{baseState{name: "DcsEntry", parser: ap}} - ap.escape = escapeState{baseState{name: "Escape", parser: ap}} - ap.escapeIntermediate = escapeIntermediateState{baseState{name: "EscapeIntermediate", parser: ap}} - ap.error = errorState{baseState{name: "Error", parser: ap}} - ap.ground = groundState{baseState{name: "Ground", parser: ap}} - ap.oscString = oscStringState{baseState{name: "OscString", parser: ap}} - - ap.stateMap = []state{ - ap.csiEntry, - ap.csiParam, - ap.dcsEntry, - ap.escape, - ap.escapeIntermediate, - ap.error, - ap.ground, - ap.oscString, - } - - ap.currState = getState(initialState, ap.stateMap) - - ap.logf("CreateParser: parser %p", ap) - return ap -} - -func getState(name string, states []state) state { - for _, el := range states { - if el.Name() == name { - return el - } - } - - return nil -} - -func (ap *AnsiParser) Parse(bytes []byte) (int, error) { - for i, b := range bytes { - if err := ap.handle(b); err != nil { - return i, err - } - } - - return len(bytes), ap.eventHandler.Flush() -} - -func (ap *AnsiParser) handle(b byte) error { - ap.context.currentChar = b - newState, err := ap.currState.Handle(b) - if err != nil { - return err - } - - if newState == nil { - ap.logf("WARNING: newState is nil") - return errors.New("New state of 'nil' is invalid.") - } - - if newState != ap.currState { - if err := ap.changeState(newState); err != nil { - return err - } - } - - return nil -} - -func (ap *AnsiParser) changeState(newState state) error { - ap.logf("ChangeState %s --> %s", ap.currState.Name(), newState.Name()) - - // Exit old state - if err := ap.currState.Exit(); err != nil { - ap.logf("Exit state '%s' failed with : '%v'", ap.currState.Name(), err) - return err - } - - // Perform transition action - if err := ap.currState.Transition(newState); err != nil { - ap.logf("Transition from '%s' to '%s' failed with: '%v'", ap.currState.Name(), newState.Name, err) - return err - } - - // Enter new state - if err := newState.Enter(); err != nil { - ap.logf("Enter state '%s' failed with: '%v'", newState.Name(), err) - return err - } - - ap.currState = newState - return nil -} diff --git a/vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go b/vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go deleted file mode 100644 index de0a1f9cd..000000000 --- a/vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go +++ /dev/null @@ -1,99 +0,0 @@ -package ansiterm - -import ( - "strconv" -) - -func parseParams(bytes []byte) ([]string, error) { - paramBuff := make([]byte, 0, 0) - params := []string{} - - for _, v := range bytes { - if v == ';' { - if len(paramBuff) > 0 { - // Completed parameter, append it to the list - s := string(paramBuff) - params = append(params, s) - paramBuff = make([]byte, 0, 0) - } - } else { - paramBuff = append(paramBuff, v) - } - } - - // Last parameter may not be terminated with ';' - if len(paramBuff) > 0 { - s := string(paramBuff) - params = append(params, s) - } - - return params, nil -} - -func parseCmd(context ansiContext) (string, error) { - return string(context.currentChar), nil -} - -func getInt(params []string, dflt int) int { - i := getInts(params, 1, dflt)[0] - return i -} - -func getInts(params []string, minCount int, dflt int) []int { - ints := []int{} - - for _, v := range params { - i, _ := strconv.Atoi(v) - // Zero is mapped to the default value in VT100. - if i == 0 { - i = dflt - } - ints = append(ints, i) - } - - if len(ints) < minCount { - remaining := minCount - len(ints) - for i := 0; i < remaining; i++ { - ints = append(ints, dflt) - } - } - - return ints -} - -func (ap *AnsiParser) modeDispatch(param string, set bool) error { - switch param { - case "?3": - return ap.eventHandler.DECCOLM(set) - case "?6": - return ap.eventHandler.DECOM(set) - case "?25": - return ap.eventHandler.DECTCEM(set) - } - return nil -} - -func (ap *AnsiParser) hDispatch(params []string) error { - if len(params) == 1 { - return ap.modeDispatch(params[0], true) - } - - return nil -} - -func (ap *AnsiParser) lDispatch(params []string) error { - if len(params) == 1 { - return ap.modeDispatch(params[0], false) - } - - return nil -} - -func getEraseParam(params []string) int { - param := getInt(params, 0) - if param < 0 || 3 < param { - param = 0 - } - - return param -} diff --git a/vendor/github.com/Azure/go-ansiterm/parser_actions.go b/vendor/github.com/Azure/go-ansiterm/parser_actions.go deleted file mode 100644 index 0bb5e51e9..000000000 --- a/vendor/github.com/Azure/go-ansiterm/parser_actions.go +++ /dev/null @@ -1,119 +0,0 @@ -package ansiterm - -func (ap *AnsiParser) collectParam() error { - currChar := ap.context.currentChar - ap.logf("collectParam %#x", currChar) - ap.context.paramBuffer = append(ap.context.paramBuffer, currChar) - return nil -} - -func (ap *AnsiParser) collectInter() error { - currChar := ap.context.currentChar - ap.logf("collectInter %#x", currChar) - ap.context.paramBuffer = append(ap.context.interBuffer, currChar) - return nil -} - -func (ap *AnsiParser) escDispatch() error { - cmd, _ := parseCmd(*ap.context) - intermeds := ap.context.interBuffer - ap.logf("escDispatch currentChar: %#x", ap.context.currentChar) - ap.logf("escDispatch: %v(%v)", cmd, intermeds) - - switch cmd { - case "D": // IND - return ap.eventHandler.IND() - case "E": // NEL, equivalent to CRLF - err := ap.eventHandler.Execute(ANSI_CARRIAGE_RETURN) - if err == nil { - err = ap.eventHandler.Execute(ANSI_LINE_FEED) - } - return err - case "M": // RI - return ap.eventHandler.RI() - } - - return nil -} - -func (ap *AnsiParser) csiDispatch() error { - cmd, _ := parseCmd(*ap.context) - params, _ := parseParams(ap.context.paramBuffer) - ap.logf("Parsed params: %v with length: %d", params, len(params)) - - ap.logf("csiDispatch: %v(%v)", cmd, params) - - switch cmd { - case "@": - return ap.eventHandler.ICH(getInt(params, 1)) - case "A": - return ap.eventHandler.CUU(getInt(params, 1)) - case "B": - return ap.eventHandler.CUD(getInt(params, 1)) - case "C": - return ap.eventHandler.CUF(getInt(params, 1)) - case "D": - return ap.eventHandler.CUB(getInt(params, 1)) - case "E": - return ap.eventHandler.CNL(getInt(params, 1)) - case "F": - return ap.eventHandler.CPL(getInt(params, 1)) - case "G": - return ap.eventHandler.CHA(getInt(params, 1)) - case "H": - ints := getInts(params, 2, 1) - x, y := ints[0], ints[1] - return ap.eventHandler.CUP(x, y) - case "J": - param := getEraseParam(params) - return ap.eventHandler.ED(param) - case "K": - param := getEraseParam(params) - return ap.eventHandler.EL(param) - case "L": - return ap.eventHandler.IL(getInt(params, 1)) - case "M": - return ap.eventHandler.DL(getInt(params, 1)) - case "P": - return ap.eventHandler.DCH(getInt(params, 1)) - case "S": - return ap.eventHandler.SU(getInt(params, 1)) - case "T": - return ap.eventHandler.SD(getInt(params, 1)) - case "c": - return ap.eventHandler.DA(params) - case "d": - return ap.eventHandler.VPA(getInt(params, 1)) - case "f": - ints := getInts(params, 2, 1) - x, y := ints[0], ints[1] - return ap.eventHandler.HVP(x, y) - case "h": - return ap.hDispatch(params) - case "l": - return ap.lDispatch(params) - case "m": - return ap.eventHandler.SGR(getInts(params, 1, 0)) - case "r": - ints := getInts(params, 2, 1) - top, bottom := ints[0], ints[1] - return ap.eventHandler.DECSTBM(top, bottom) - default: - ap.logf("ERROR: Unsupported CSI command: '%s', with full context: %v", cmd, ap.context) - return nil - } - -} - -func (ap *AnsiParser) print() error { - return ap.eventHandler.Print(ap.context.currentChar) -} - -func (ap *AnsiParser) clear() error { - ap.context = &ansiContext{} - return nil -} - -func (ap *AnsiParser) execute() error { - return ap.eventHandler.Execute(ap.context.currentChar) -} diff --git a/vendor/github.com/Azure/go-ansiterm/states.go b/vendor/github.com/Azure/go-ansiterm/states.go deleted file mode 100644 index f2ea1fcd1..000000000 --- a/vendor/github.com/Azure/go-ansiterm/states.go +++ /dev/null @@ -1,71 +0,0 @@ -package ansiterm - -type stateID int - -type state interface { - Enter() error - Exit() error - Handle(byte) (state, error) - Name() string - Transition(state) error -} - -type baseState struct { - name string - parser *AnsiParser -} - -func (base baseState) Enter() error { - return nil -} - -func (base baseState) Exit() error { - return nil -} - -func (base baseState) Handle(b byte) (s state, e error) { - - switch { - case b == CSI_ENTRY: - return base.parser.csiEntry, nil - case b == DCS_ENTRY: - return base.parser.dcsEntry, nil - case b == ANSI_ESCAPE_PRIMARY: - return base.parser.escape, nil - case b == OSC_STRING: - return base.parser.oscString, nil - case sliceContains(toGroundBytes, b): - return base.parser.ground, nil - } - - return nil, nil -} - -func (base baseState) Name() string { - return base.name -} - -func (base baseState) Transition(s state) error { - if s == base.parser.ground { - execBytes := []byte{0x18} - execBytes = append(execBytes, 0x1A) - execBytes = append(execBytes, getByteRange(0x80, 0x8F)...) - execBytes = append(execBytes, getByteRange(0x91, 0x97)...) - execBytes = append(execBytes, 0x99) - execBytes = append(execBytes, 0x9A) - - if sliceContains(execBytes, base.parser.context.currentChar) { - return base.parser.execute() - } - } - - return nil -} - -type dcsEntryState struct { - baseState -} - -type errorState struct { - baseState -} diff --git a/vendor/github.com/Azure/go-ansiterm/utilities.go b/vendor/github.com/Azure/go-ansiterm/utilities.go deleted file mode 100644 index 392114493..000000000 --- a/vendor/github.com/Azure/go-ansiterm/utilities.go +++ /dev/null @@ -1,21 +0,0 @@ -package ansiterm - -import ( - "strconv" -) - -func sliceContains(bytes []byte, b byte) bool { - for _, v := range bytes { - if v == b { - return true - } - } - - return false -} - -func convertBytesToInteger(bytes []byte) int { - s := string(bytes) - i, _ := strconv.Atoi(s) - return i -} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go b/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go deleted file mode 100644 index 5599082ae..000000000 --- a/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go +++ /dev/null @@ -1,196 +0,0 @@ -// +build windows - -package winterm - -import ( - "fmt" - "os" - "strconv" - "strings" - "syscall" - - "github.com/Azure/go-ansiterm" - windows "golang.org/x/sys/windows" -) - -// Windows keyboard constants -// See https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx. -const ( - VK_PRIOR = 0x21 // PAGE UP key - VK_NEXT = 0x22 // PAGE DOWN key - VK_END = 0x23 // END key - VK_HOME = 0x24 // HOME key - VK_LEFT = 0x25 // LEFT ARROW key - VK_UP = 0x26 // UP ARROW key - VK_RIGHT = 0x27 // RIGHT ARROW key - VK_DOWN = 0x28 // DOWN ARROW key - VK_SELECT = 0x29 // SELECT key - VK_PRINT = 0x2A // PRINT key - VK_EXECUTE = 0x2B // EXECUTE key - VK_SNAPSHOT = 0x2C // PRINT SCREEN key - VK_INSERT = 0x2D // INS key - VK_DELETE = 0x2E // DEL key - VK_HELP = 0x2F // HELP key - VK_F1 = 0x70 // F1 key - VK_F2 = 0x71 // F2 key - VK_F3 = 0x72 // F3 key - VK_F4 = 0x73 // F4 key - VK_F5 = 0x74 // F5 key - VK_F6 = 0x75 // F6 key - VK_F7 = 0x76 // F7 key - VK_F8 = 0x77 // F8 key - VK_F9 = 0x78 // F9 key - VK_F10 = 0x79 // F10 key - VK_F11 = 0x7A // F11 key - VK_F12 = 0x7B // F12 key - - RIGHT_ALT_PRESSED = 0x0001 - LEFT_ALT_PRESSED = 0x0002 - RIGHT_CTRL_PRESSED = 0x0004 - LEFT_CTRL_PRESSED = 0x0008 - SHIFT_PRESSED = 0x0010 - NUMLOCK_ON = 0x0020 - SCROLLLOCK_ON = 0x0040 - CAPSLOCK_ON = 0x0080 - ENHANCED_KEY = 0x0100 -) - -type ansiCommand struct { - CommandBytes []byte - Command string - Parameters []string - IsSpecial bool -} - -func newAnsiCommand(command []byte) *ansiCommand { - - if isCharacterSelectionCmdChar(command[1]) { - // Is Character Set Selection commands - return &ansiCommand{ - CommandBytes: command, - Command: string(command), - IsSpecial: true, - } - } - - // last char is command character - lastCharIndex := len(command) - 1 - - ac := &ansiCommand{ - CommandBytes: command, - Command: string(command[lastCharIndex]), - IsSpecial: false, - } - - // more than a single escape - if lastCharIndex != 0 { - start := 1 - // skip if double char escape sequence - if command[0] == ansiterm.ANSI_ESCAPE_PRIMARY && command[1] == ansiterm.ANSI_ESCAPE_SECONDARY { - start++ - } - // convert this to GetNextParam method - ac.Parameters = strings.Split(string(command[start:lastCharIndex]), ansiterm.ANSI_PARAMETER_SEP) - } - - return ac -} - -func (ac *ansiCommand) paramAsSHORT(index int, defaultValue int16) int16 { - if index < 0 || index >= len(ac.Parameters) { - return defaultValue - } - - param, err := strconv.ParseInt(ac.Parameters[index], 10, 16) - if err != nil { - return defaultValue - } - - return int16(param) -} - -func (ac *ansiCommand) String() string { - return fmt.Sprintf("0x%v \"%v\" (\"%v\")", - bytesToHex(ac.CommandBytes), - ac.Command, - strings.Join(ac.Parameters, "\",\"")) -} - -// isAnsiCommandChar returns true if the passed byte falls within the range of ANSI commands. -// See http://manpages.ubuntu.com/manpages/intrepid/man4/console_codes.4.html. -func isAnsiCommandChar(b byte) bool { - switch { - case ansiterm.ANSI_COMMAND_FIRST <= b && b <= ansiterm.ANSI_COMMAND_LAST && b != ansiterm.ANSI_ESCAPE_SECONDARY: - return true - case b == ansiterm.ANSI_CMD_G1 || b == ansiterm.ANSI_CMD_OSC || b == ansiterm.ANSI_CMD_DECPAM || b == ansiterm.ANSI_CMD_DECPNM: - // non-CSI escape sequence terminator - return true - case b == ansiterm.ANSI_CMD_STR_TERM || b == ansiterm.ANSI_BEL: - // String escape sequence terminator - return true - } - return false -} - -func isXtermOscSequence(command []byte, current byte) bool { - return (len(command) >= 2 && command[0] == ansiterm.ANSI_ESCAPE_PRIMARY && command[1] == ansiterm.ANSI_CMD_OSC && current != ansiterm.ANSI_BEL) -} - -func isCharacterSelectionCmdChar(b byte) bool { - return (b == ansiterm.ANSI_CMD_G0 || b == ansiterm.ANSI_CMD_G1 || b == ansiterm.ANSI_CMD_G2 || b == ansiterm.ANSI_CMD_G3) -} - -// bytesToHex converts a slice of bytes to a human-readable string. -func bytesToHex(b []byte) string { - hex := make([]string, len(b)) - for i, ch := range b { - hex[i] = fmt.Sprintf("%X", ch) - } - return strings.Join(hex, "") -} - -// ensureInRange adjusts the passed value, if necessary, to ensure it is within -// the passed min / max range. -func ensureInRange(n int16, min int16, max int16) int16 { - if n < min { - return min - } else if n > max { - return max - } else { - return n - } -} - -func GetStdFile(nFile int) (*os.File, uintptr) { - var file *os.File - - // syscall uses negative numbers - // windows package uses very big uint32 - // Keep these switches split so we don't have to convert ints too much. - switch uint32(nFile) { - case windows.STD_INPUT_HANDLE: - file = os.Stdin - case windows.STD_OUTPUT_HANDLE: - file = os.Stdout - case windows.STD_ERROR_HANDLE: - file = os.Stderr - default: - switch nFile { - case syscall.STD_INPUT_HANDLE: - file = os.Stdin - case syscall.STD_OUTPUT_HANDLE: - file = os.Stdout - case syscall.STD_ERROR_HANDLE: - file = os.Stderr - default: - panic(fmt.Errorf("Invalid standard handle identifier: %v", nFile)) - } - } - - fd, err := syscall.GetStdHandle(nFile) - if err != nil { - panic(fmt.Errorf("Invalid standard handle identifier: %v -- %v", nFile, err)) - } - - return file, uintptr(fd) -} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/api.go b/vendor/github.com/Azure/go-ansiterm/winterm/api.go deleted file mode 100644 index 6055e33b9..000000000 --- a/vendor/github.com/Azure/go-ansiterm/winterm/api.go +++ /dev/null @@ -1,327 +0,0 @@ -// +build windows - -package winterm - -import ( - "fmt" - "syscall" - "unsafe" -) - -//=========================================================================================================== -// IMPORTANT NOTE: -// -// The methods below make extensive use of the "unsafe" package to obtain the required pointers. -// Beginning in Go 1.3, the garbage collector may release local variables (e.g., incoming arguments, stack -// variables) the pointers reference *before* the API completes. -// -// As a result, in those cases, the code must hint that the variables remain in active by invoking the -// dummy method "use" (see below). Newer versions of Go are planned to change the mechanism to no longer -// require unsafe pointers. -// -// If you add or modify methods, ENSURE protection of local variables through the "use" builtin to inform -// the garbage collector the variables remain in use if: -// -// -- The value is not a pointer (e.g., int32, struct) -// -- The value is not referenced by the method after passing the pointer to Windows -// -// See http://golang.org/doc/go1.3. -//=========================================================================================================== - -var ( - kernel32DLL = syscall.NewLazyDLL("kernel32.dll") - - getConsoleCursorInfoProc = kernel32DLL.NewProc("GetConsoleCursorInfo") - setConsoleCursorInfoProc = kernel32DLL.NewProc("SetConsoleCursorInfo") - setConsoleCursorPositionProc = kernel32DLL.NewProc("SetConsoleCursorPosition") - setConsoleModeProc = kernel32DLL.NewProc("SetConsoleMode") - getConsoleScreenBufferInfoProc = kernel32DLL.NewProc("GetConsoleScreenBufferInfo") - setConsoleScreenBufferSizeProc = kernel32DLL.NewProc("SetConsoleScreenBufferSize") - scrollConsoleScreenBufferProc = kernel32DLL.NewProc("ScrollConsoleScreenBufferA") - setConsoleTextAttributeProc = kernel32DLL.NewProc("SetConsoleTextAttribute") - setConsoleWindowInfoProc = kernel32DLL.NewProc("SetConsoleWindowInfo") - writeConsoleOutputProc = kernel32DLL.NewProc("WriteConsoleOutputW") - readConsoleInputProc = kernel32DLL.NewProc("ReadConsoleInputW") - waitForSingleObjectProc = kernel32DLL.NewProc("WaitForSingleObject") -) - -// Windows Console constants -const ( - // Console modes - // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx. - ENABLE_PROCESSED_INPUT = 0x0001 - ENABLE_LINE_INPUT = 0x0002 - ENABLE_ECHO_INPUT = 0x0004 - ENABLE_WINDOW_INPUT = 0x0008 - ENABLE_MOUSE_INPUT = 0x0010 - ENABLE_INSERT_MODE = 0x0020 - ENABLE_QUICK_EDIT_MODE = 0x0040 - ENABLE_EXTENDED_FLAGS = 0x0080 - ENABLE_AUTO_POSITION = 0x0100 - ENABLE_VIRTUAL_TERMINAL_INPUT = 0x0200 - - ENABLE_PROCESSED_OUTPUT = 0x0001 - ENABLE_WRAP_AT_EOL_OUTPUT = 0x0002 - ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004 - DISABLE_NEWLINE_AUTO_RETURN = 0x0008 - ENABLE_LVB_GRID_WORLDWIDE = 0x0010 - - // Character attributes - // Note: - // -- The attributes are combined to produce various colors (e.g., Blue + Green will create Cyan). - // Clearing all foreground or background colors results in black; setting all creates white. - // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms682088(v=vs.85).aspx#_win32_character_attributes. - FOREGROUND_BLUE uint16 = 0x0001 - FOREGROUND_GREEN uint16 = 0x0002 - FOREGROUND_RED uint16 = 0x0004 - FOREGROUND_INTENSITY uint16 = 0x0008 - FOREGROUND_MASK uint16 = 0x000F - - BACKGROUND_BLUE uint16 = 0x0010 - BACKGROUND_GREEN uint16 = 0x0020 - BACKGROUND_RED uint16 = 0x0040 - BACKGROUND_INTENSITY uint16 = 0x0080 - BACKGROUND_MASK uint16 = 0x00F0 - - COMMON_LVB_MASK uint16 = 0xFF00 - COMMON_LVB_REVERSE_VIDEO uint16 = 0x4000 - COMMON_LVB_UNDERSCORE uint16 = 0x8000 - - // Input event types - // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683499(v=vs.85).aspx. - KEY_EVENT = 0x0001 - MOUSE_EVENT = 0x0002 - WINDOW_BUFFER_SIZE_EVENT = 0x0004 - MENU_EVENT = 0x0008 - FOCUS_EVENT = 0x0010 - - // WaitForSingleObject return codes - WAIT_ABANDONED = 0x00000080 - WAIT_FAILED = 0xFFFFFFFF - WAIT_SIGNALED = 0x0000000 - WAIT_TIMEOUT = 0x00000102 - - // WaitForSingleObject wait duration - WAIT_INFINITE = 0xFFFFFFFF - WAIT_ONE_SECOND = 1000 - WAIT_HALF_SECOND = 500 - WAIT_QUARTER_SECOND = 250 -) - -// Windows API Console types -// -- See https://msdn.microsoft.com/en-us/library/windows/desktop/ms682101(v=vs.85).aspx for Console specific types (e.g., COORD) -// -- See https://msdn.microsoft.com/en-us/library/aa296569(v=vs.60).aspx for comments on alignment -type ( - CHAR_INFO struct { - UnicodeChar uint16 - Attributes uint16 - } - - CONSOLE_CURSOR_INFO struct { - Size uint32 - Visible int32 - } - - CONSOLE_SCREEN_BUFFER_INFO struct { - Size COORD - CursorPosition COORD - Attributes uint16 - Window SMALL_RECT - MaximumWindowSize COORD - } - - COORD struct { - X int16 - Y int16 - } - - SMALL_RECT struct { - Left int16 - Top int16 - Right int16 - Bottom int16 - } - - // INPUT_RECORD is a C/C++ union of which KEY_EVENT_RECORD is one case, it is also the largest - // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683499(v=vs.85).aspx. - INPUT_RECORD struct { - EventType uint16 - KeyEvent KEY_EVENT_RECORD - } - - KEY_EVENT_RECORD struct { - KeyDown int32 - RepeatCount uint16 - VirtualKeyCode uint16 - VirtualScanCode uint16 - UnicodeChar uint16 - ControlKeyState uint32 - } - - WINDOW_BUFFER_SIZE struct { - Size COORD - } -) - -// boolToBOOL converts a Go bool into a Windows int32. -func boolToBOOL(f bool) int32 { - if f { - return int32(1) - } else { - return int32(0) - } -} - -// GetConsoleCursorInfo retrieves information about the size and visiblity of the console cursor. -// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683163(v=vs.85).aspx. -func GetConsoleCursorInfo(handle uintptr, cursorInfo *CONSOLE_CURSOR_INFO) error { - r1, r2, err := getConsoleCursorInfoProc.Call(handle, uintptr(unsafe.Pointer(cursorInfo)), 0) - return checkError(r1, r2, err) -} - -// SetConsoleCursorInfo sets the size and visiblity of the console cursor. -// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686019(v=vs.85).aspx. -func SetConsoleCursorInfo(handle uintptr, cursorInfo *CONSOLE_CURSOR_INFO) error { - r1, r2, err := setConsoleCursorInfoProc.Call(handle, uintptr(unsafe.Pointer(cursorInfo)), 0) - return checkError(r1, r2, err) -} - -// SetConsoleCursorPosition location of the console cursor. -// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686025(v=vs.85).aspx. -func SetConsoleCursorPosition(handle uintptr, coord COORD) error { - r1, r2, err := setConsoleCursorPositionProc.Call(handle, coordToPointer(coord)) - use(coord) - return checkError(r1, r2, err) -} - -// GetConsoleMode gets the console mode for given file descriptor -// See http://msdn.microsoft.com/en-us/library/windows/desktop/ms683167(v=vs.85).aspx. -func GetConsoleMode(handle uintptr) (mode uint32, err error) { - err = syscall.GetConsoleMode(syscall.Handle(handle), &mode) - return mode, err -} - -// SetConsoleMode sets the console mode for given file descriptor -// See http://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx. -func SetConsoleMode(handle uintptr, mode uint32) error { - r1, r2, err := setConsoleModeProc.Call(handle, uintptr(mode), 0) - use(mode) - return checkError(r1, r2, err) -} - -// GetConsoleScreenBufferInfo retrieves information about the specified console screen buffer. -// See http://msdn.microsoft.com/en-us/library/windows/desktop/ms683171(v=vs.85).aspx. -func GetConsoleScreenBufferInfo(handle uintptr) (*CONSOLE_SCREEN_BUFFER_INFO, error) { - info := CONSOLE_SCREEN_BUFFER_INFO{} - err := checkError(getConsoleScreenBufferInfoProc.Call(handle, uintptr(unsafe.Pointer(&info)), 0)) - if err != nil { - return nil, err - } - return &info, nil -} - -func ScrollConsoleScreenBuffer(handle uintptr, scrollRect SMALL_RECT, clipRect SMALL_RECT, destOrigin COORD, char CHAR_INFO) error { - r1, r2, err := scrollConsoleScreenBufferProc.Call(handle, uintptr(unsafe.Pointer(&scrollRect)), uintptr(unsafe.Pointer(&clipRect)), coordToPointer(destOrigin), uintptr(unsafe.Pointer(&char))) - use(scrollRect) - use(clipRect) - use(destOrigin) - use(char) - return checkError(r1, r2, err) -} - -// SetConsoleScreenBufferSize sets the size of the console screen buffer. -// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686044(v=vs.85).aspx. -func SetConsoleScreenBufferSize(handle uintptr, coord COORD) error { - r1, r2, err := setConsoleScreenBufferSizeProc.Call(handle, coordToPointer(coord)) - use(coord) - return checkError(r1, r2, err) -} - -// SetConsoleTextAttribute sets the attributes of characters written to the -// console screen buffer by the WriteFile or WriteConsole function. -// See http://msdn.microsoft.com/en-us/library/windows/desktop/ms686047(v=vs.85).aspx. -func SetConsoleTextAttribute(handle uintptr, attribute uint16) error { - r1, r2, err := setConsoleTextAttributeProc.Call(handle, uintptr(attribute), 0) - use(attribute) - return checkError(r1, r2, err) -} - -// SetConsoleWindowInfo sets the size and position of the console screen buffer's window. -// Note that the size and location must be within and no larger than the backing console screen buffer. -// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686125(v=vs.85).aspx. -func SetConsoleWindowInfo(handle uintptr, isAbsolute bool, rect SMALL_RECT) error { - r1, r2, err := setConsoleWindowInfoProc.Call(handle, uintptr(boolToBOOL(isAbsolute)), uintptr(unsafe.Pointer(&rect))) - use(isAbsolute) - use(rect) - return checkError(r1, r2, err) -} - -// WriteConsoleOutput writes the CHAR_INFOs from the provided buffer to the active console buffer. -// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms687404(v=vs.85).aspx. -func WriteConsoleOutput(handle uintptr, buffer []CHAR_INFO, bufferSize COORD, bufferCoord COORD, writeRegion *SMALL_RECT) error { - r1, r2, err := writeConsoleOutputProc.Call(handle, uintptr(unsafe.Pointer(&buffer[0])), coordToPointer(bufferSize), coordToPointer(bufferCoord), uintptr(unsafe.Pointer(writeRegion))) - use(buffer) - use(bufferSize) - use(bufferCoord) - return checkError(r1, r2, err) -} - -// ReadConsoleInput reads (and removes) data from the console input buffer. -// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms684961(v=vs.85).aspx. -func ReadConsoleInput(handle uintptr, buffer []INPUT_RECORD, count *uint32) error { - r1, r2, err := readConsoleInputProc.Call(handle, uintptr(unsafe.Pointer(&buffer[0])), uintptr(len(buffer)), uintptr(unsafe.Pointer(count))) - use(buffer) - return checkError(r1, r2, err) -} - -// WaitForSingleObject waits for the passed handle to be signaled. -// It returns true if the handle was signaled; false otherwise. -// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms687032(v=vs.85).aspx. -func WaitForSingleObject(handle uintptr, msWait uint32) (bool, error) { - r1, _, err := waitForSingleObjectProc.Call(handle, uintptr(uint32(msWait))) - switch r1 { - case WAIT_ABANDONED, WAIT_TIMEOUT: - return false, nil - case WAIT_SIGNALED: - return true, nil - } - use(msWait) - return false, err -} - -// String helpers -func (info CONSOLE_SCREEN_BUFFER_INFO) String() string { - return fmt.Sprintf("Size(%v) Cursor(%v) Window(%v) Max(%v)", info.Size, info.CursorPosition, info.Window, info.MaximumWindowSize) -} - -func (coord COORD) String() string { - return fmt.Sprintf("%v,%v", coord.X, coord.Y) -} - -func (rect SMALL_RECT) String() string { - return fmt.Sprintf("(%v,%v),(%v,%v)", rect.Left, rect.Top, rect.Right, rect.Bottom) -} - -// checkError evaluates the results of a Windows API call and returns the error if it failed. -func checkError(r1, r2 uintptr, err error) error { - // Windows APIs return non-zero to indicate success - if r1 != 0 { - return nil - } - - // Return the error if provided, otherwise default to EINVAL - if err != nil { - return err - } - return syscall.EINVAL -} - -// coordToPointer converts a COORD into a uintptr (by fooling the type system). -func coordToPointer(c COORD) uintptr { - // Note: This code assumes the two SHORTs are correctly laid out; the "cast" to uint32 is just to get a pointer to pass. - return uintptr(*((*uint32)(unsafe.Pointer(&c)))) -} - -// use is a no-op, but the compiler cannot see that it is. -// Calling use(p) ensures that p is kept live until that point. -func use(p interface{}) {} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go b/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go deleted file mode 100644 index cbec8f728..000000000 --- a/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go +++ /dev/null @@ -1,100 +0,0 @@ -// +build windows - -package winterm - -import "github.com/Azure/go-ansiterm" - -const ( - FOREGROUND_COLOR_MASK = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE - BACKGROUND_COLOR_MASK = BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE -) - -// collectAnsiIntoWindowsAttributes modifies the passed Windows text mode flags to reflect the -// request represented by the passed ANSI mode. -func collectAnsiIntoWindowsAttributes(windowsMode uint16, inverted bool, baseMode uint16, ansiMode int16) (uint16, bool) { - switch ansiMode { - - // Mode styles - case ansiterm.ANSI_SGR_BOLD: - windowsMode = windowsMode | FOREGROUND_INTENSITY - - case ansiterm.ANSI_SGR_DIM, ansiterm.ANSI_SGR_BOLD_DIM_OFF: - windowsMode &^= FOREGROUND_INTENSITY - - case ansiterm.ANSI_SGR_UNDERLINE: - windowsMode = windowsMode | COMMON_LVB_UNDERSCORE - - case ansiterm.ANSI_SGR_REVERSE: - inverted = true - - case ansiterm.ANSI_SGR_REVERSE_OFF: - inverted = false - - case ansiterm.ANSI_SGR_UNDERLINE_OFF: - windowsMode &^= COMMON_LVB_UNDERSCORE - - // Foreground colors - case ansiterm.ANSI_SGR_FOREGROUND_DEFAULT: - windowsMode = (windowsMode &^ FOREGROUND_MASK) | (baseMode & FOREGROUND_MASK) - - case ansiterm.ANSI_SGR_FOREGROUND_BLACK: - windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) - - case ansiterm.ANSI_SGR_FOREGROUND_RED: - windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED - - case ansiterm.ANSI_SGR_FOREGROUND_GREEN: - windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_GREEN - - case ansiterm.ANSI_SGR_FOREGROUND_YELLOW: - windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_GREEN - - case ansiterm.ANSI_SGR_FOREGROUND_BLUE: - windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_BLUE - - case ansiterm.ANSI_SGR_FOREGROUND_MAGENTA: - windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_BLUE - - case ansiterm.ANSI_SGR_FOREGROUND_CYAN: - windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_GREEN | FOREGROUND_BLUE - - case ansiterm.ANSI_SGR_FOREGROUND_WHITE: - windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE - - // Background colors - case ansiterm.ANSI_SGR_BACKGROUND_DEFAULT: - // Black with no intensity - windowsMode = (windowsMode &^ BACKGROUND_MASK) | (baseMode & BACKGROUND_MASK) - - case ansiterm.ANSI_SGR_BACKGROUND_BLACK: - windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) - - case ansiterm.ANSI_SGR_BACKGROUND_RED: - windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED - - case ansiterm.ANSI_SGR_BACKGROUND_GREEN: - windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_GREEN - - case ansiterm.ANSI_SGR_BACKGROUND_YELLOW: - windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_GREEN - - case ansiterm.ANSI_SGR_BACKGROUND_BLUE: - windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_BLUE - - case ansiterm.ANSI_SGR_BACKGROUND_MAGENTA: - windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_BLUE - - case ansiterm.ANSI_SGR_BACKGROUND_CYAN: - windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_GREEN | BACKGROUND_BLUE - - case ansiterm.ANSI_SGR_BACKGROUND_WHITE: - windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE - } - - return windowsMode, inverted -} - -// invertAttributes inverts the foreground and background colors of a Windows attributes value -func invertAttributes(windowsMode uint16) uint16 { - return (COMMON_LVB_MASK & windowsMode) | ((FOREGROUND_MASK & windowsMode) << 4) | ((BACKGROUND_MASK & windowsMode) >> 4) -} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go b/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go deleted file mode 100644 index 3ee06ea72..000000000 --- a/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go +++ /dev/null @@ -1,101 +0,0 @@ -// +build windows - -package winterm - -const ( - horizontal = iota - vertical -) - -func (h *windowsAnsiEventHandler) getCursorWindow(info *CONSOLE_SCREEN_BUFFER_INFO) SMALL_RECT { - if h.originMode { - sr := h.effectiveSr(info.Window) - return SMALL_RECT{ - Top: sr.top, - Bottom: sr.bottom, - Left: 0, - Right: info.Size.X - 1, - } - } else { - return SMALL_RECT{ - Top: info.Window.Top, - Bottom: info.Window.Bottom, - Left: 0, - Right: info.Size.X - 1, - } - } -} - -// setCursorPosition sets the cursor to the specified position, bounded to the screen size -func (h *windowsAnsiEventHandler) setCursorPosition(position COORD, window SMALL_RECT) error { - position.X = ensureInRange(position.X, window.Left, window.Right) - position.Y = ensureInRange(position.Y, window.Top, window.Bottom) - err := SetConsoleCursorPosition(h.fd, position) - if err != nil { - return err - } - h.logf("Cursor position set: (%d, %d)", position.X, position.Y) - return err -} - -func (h *windowsAnsiEventHandler) moveCursorVertical(param int) error { - return h.moveCursor(vertical, param) -} - -func (h *windowsAnsiEventHandler) moveCursorHorizontal(param int) error { - return h.moveCursor(horizontal, param) -} - -func (h *windowsAnsiEventHandler) moveCursor(moveMode int, param int) error { - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return err - } - - position := info.CursorPosition - switch moveMode { - case horizontal: - position.X += int16(param) - case vertical: - position.Y += int16(param) - } - - if err = h.setCursorPosition(position, h.getCursorWindow(info)); err != nil { - return err - } - - return nil -} - -func (h *windowsAnsiEventHandler) moveCursorLine(param int) error { - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return err - } - - position := info.CursorPosition - position.X = 0 - position.Y += int16(param) - - if err = h.setCursorPosition(position, h.getCursorWindow(info)); err != nil { - return err - } - - return nil -} - -func (h *windowsAnsiEventHandler) moveCursorColumn(param int) error { - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return err - } - - position := info.CursorPosition - position.X = int16(param) - 1 - - if err = h.setCursorPosition(position, h.getCursorWindow(info)); err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go b/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go deleted file mode 100644 index 244b5fa25..000000000 --- a/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go +++ /dev/null @@ -1,84 +0,0 @@ -// +build windows - -package winterm - -import "github.com/Azure/go-ansiterm" - -func (h *windowsAnsiEventHandler) clearRange(attributes uint16, fromCoord COORD, toCoord COORD) error { - // Ignore an invalid (negative area) request - if toCoord.Y < fromCoord.Y { - return nil - } - - var err error - - var coordStart = COORD{} - var coordEnd = COORD{} - - xCurrent, yCurrent := fromCoord.X, fromCoord.Y - xEnd, yEnd := toCoord.X, toCoord.Y - - // Clear any partial initial line - if xCurrent > 0 { - coordStart.X, coordStart.Y = xCurrent, yCurrent - coordEnd.X, coordEnd.Y = xEnd, yCurrent - - err = h.clearRect(attributes, coordStart, coordEnd) - if err != nil { - return err - } - - xCurrent = 0 - yCurrent += 1 - } - - // Clear intervening rectangular section - if yCurrent < yEnd { - coordStart.X, coordStart.Y = xCurrent, yCurrent - coordEnd.X, coordEnd.Y = xEnd, yEnd-1 - - err = h.clearRect(attributes, coordStart, coordEnd) - if err != nil { - return err - } - - xCurrent = 0 - yCurrent = yEnd - } - - // Clear remaining partial ending line - coordStart.X, coordStart.Y = xCurrent, yCurrent - coordEnd.X, coordEnd.Y = xEnd, yEnd - - err = h.clearRect(attributes, coordStart, coordEnd) - if err != nil { - return err - } - - return nil -} - -func (h *windowsAnsiEventHandler) clearRect(attributes uint16, fromCoord COORD, toCoord COORD) error { - region := SMALL_RECT{Top: fromCoord.Y, Left: fromCoord.X, Bottom: toCoord.Y, Right: toCoord.X} - width := toCoord.X - fromCoord.X + 1 - height := toCoord.Y - fromCoord.Y + 1 - size := uint32(width) * uint32(height) - - if size <= 0 { - return nil - } - - buffer := make([]CHAR_INFO, size) - - char := CHAR_INFO{ansiterm.FILL_CHARACTER, attributes} - for i := 0; i < int(size); i++ { - buffer[i] = char - } - - err := WriteConsoleOutput(h.fd, buffer, COORD{X: width, Y: height}, COORD{X: 0, Y: 0}, ®ion) - if err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go b/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go deleted file mode 100644 index 2d27fa1d0..000000000 --- a/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go +++ /dev/null @@ -1,118 +0,0 @@ -// +build windows - -package winterm - -// effectiveSr gets the current effective scroll region in buffer coordinates -func (h *windowsAnsiEventHandler) effectiveSr(window SMALL_RECT) scrollRegion { - top := addInRange(window.Top, h.sr.top, window.Top, window.Bottom) - bottom := addInRange(window.Top, h.sr.bottom, window.Top, window.Bottom) - if top >= bottom { - top = window.Top - bottom = window.Bottom - } - return scrollRegion{top: top, bottom: bottom} -} - -func (h *windowsAnsiEventHandler) scrollUp(param int) error { - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return err - } - - sr := h.effectiveSr(info.Window) - return h.scroll(param, sr, info) -} - -func (h *windowsAnsiEventHandler) scrollDown(param int) error { - return h.scrollUp(-param) -} - -func (h *windowsAnsiEventHandler) deleteLines(param int) error { - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return err - } - - start := info.CursorPosition.Y - sr := h.effectiveSr(info.Window) - // Lines cannot be inserted or deleted outside the scrolling region. - if start >= sr.top && start <= sr.bottom { - sr.top = start - return h.scroll(param, sr, info) - } else { - return nil - } -} - -func (h *windowsAnsiEventHandler) insertLines(param int) error { - return h.deleteLines(-param) -} - -// scroll scrolls the provided scroll region by param lines. The scroll region is in buffer coordinates. -func (h *windowsAnsiEventHandler) scroll(param int, sr scrollRegion, info *CONSOLE_SCREEN_BUFFER_INFO) error { - h.logf("scroll: scrollTop: %d, scrollBottom: %d", sr.top, sr.bottom) - h.logf("scroll: windowTop: %d, windowBottom: %d", info.Window.Top, info.Window.Bottom) - - // Copy from and clip to the scroll region (full buffer width) - scrollRect := SMALL_RECT{ - Top: sr.top, - Bottom: sr.bottom, - Left: 0, - Right: info.Size.X - 1, - } - - // Origin to which area should be copied - destOrigin := COORD{ - X: 0, - Y: sr.top - int16(param), - } - - char := CHAR_INFO{ - UnicodeChar: ' ', - Attributes: h.attributes, - } - - if err := ScrollConsoleScreenBuffer(h.fd, scrollRect, scrollRect, destOrigin, char); err != nil { - return err - } - return nil -} - -func (h *windowsAnsiEventHandler) deleteCharacters(param int) error { - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return err - } - return h.scrollLine(param, info.CursorPosition, info) -} - -func (h *windowsAnsiEventHandler) insertCharacters(param int) error { - return h.deleteCharacters(-param) -} - -// scrollLine scrolls a line horizontally starting at the provided position by a number of columns. -func (h *windowsAnsiEventHandler) scrollLine(columns int, position COORD, info *CONSOLE_SCREEN_BUFFER_INFO) error { - // Copy from and clip to the scroll region (full buffer width) - scrollRect := SMALL_RECT{ - Top: position.Y, - Bottom: position.Y, - Left: position.X, - Right: info.Size.X - 1, - } - - // Origin to which area should be copied - destOrigin := COORD{ - X: position.X - int16(columns), - Y: position.Y, - } - - char := CHAR_INFO{ - UnicodeChar: ' ', - Attributes: h.attributes, - } - - if err := ScrollConsoleScreenBuffer(h.fd, scrollRect, scrollRect, destOrigin, char); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go b/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go deleted file mode 100644 index afa7635d7..000000000 --- a/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build windows - -package winterm - -// AddInRange increments a value by the passed quantity while ensuring the values -// always remain within the supplied min / max range. -func addInRange(n int16, increment int16, min int16, max int16) int16 { - return ensureInRange(n+increment, min, max) -} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go b/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go deleted file mode 100644 index 2d40fb75a..000000000 --- a/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go +++ /dev/null @@ -1,743 +0,0 @@ -// +build windows - -package winterm - -import ( - "bytes" - "log" - "os" - "strconv" - - "github.com/Azure/go-ansiterm" -) - -type windowsAnsiEventHandler struct { - fd uintptr - file *os.File - infoReset *CONSOLE_SCREEN_BUFFER_INFO - sr scrollRegion - buffer bytes.Buffer - attributes uint16 - inverted bool - wrapNext bool - drewMarginByte bool - originMode bool - marginByte byte - curInfo *CONSOLE_SCREEN_BUFFER_INFO - curPos COORD - logf func(string, ...interface{}) -} - -type Option func(*windowsAnsiEventHandler) - -func WithLogf(f func(string, ...interface{})) Option { - return func(w *windowsAnsiEventHandler) { - w.logf = f - } -} - -func CreateWinEventHandler(fd uintptr, file *os.File, opts ...Option) ansiterm.AnsiEventHandler { - infoReset, err := GetConsoleScreenBufferInfo(fd) - if err != nil { - return nil - } - - h := &windowsAnsiEventHandler{ - fd: fd, - file: file, - infoReset: infoReset, - attributes: infoReset.Attributes, - } - for _, o := range opts { - o(h) - } - - if isDebugEnv := os.Getenv(ansiterm.LogEnv); isDebugEnv == "1" { - logFile, _ := os.Create("winEventHandler.log") - logger := log.New(logFile, "", log.LstdFlags) - if h.logf != nil { - l := h.logf - h.logf = func(s string, v ...interface{}) { - l(s, v...) - logger.Printf(s, v...) - } - } else { - h.logf = logger.Printf - } - } - - if h.logf == nil { - h.logf = func(string, ...interface{}) {} - } - - return h -} - -type scrollRegion struct { - top int16 - bottom int16 -} - -// simulateLF simulates a LF or CR+LF by scrolling if necessary to handle the -// current cursor position and scroll region settings, in which case it returns -// true. If no special handling is necessary, then it does nothing and returns -// false. -// -// In the false case, the caller should ensure that a carriage return -// and line feed are inserted or that the text is otherwise wrapped. -func (h *windowsAnsiEventHandler) simulateLF(includeCR bool) (bool, error) { - if h.wrapNext { - if err := h.Flush(); err != nil { - return false, err - } - h.clearWrap() - } - pos, info, err := h.getCurrentInfo() - if err != nil { - return false, err - } - sr := h.effectiveSr(info.Window) - if pos.Y == sr.bottom { - // Scrolling is necessary. Let Windows automatically scroll if the scrolling region - // is the full window. - if sr.top == info.Window.Top && sr.bottom == info.Window.Bottom { - if includeCR { - pos.X = 0 - h.updatePos(pos) - } - return false, nil - } - - // A custom scroll region is active. Scroll the window manually to simulate - // the LF. - if err := h.Flush(); err != nil { - return false, err - } - h.logf("Simulating LF inside scroll region") - if err := h.scrollUp(1); err != nil { - return false, err - } - if includeCR { - pos.X = 0 - if err := SetConsoleCursorPosition(h.fd, pos); err != nil { - return false, err - } - } - return true, nil - - } else if pos.Y < info.Window.Bottom { - // Let Windows handle the LF. - pos.Y++ - if includeCR { - pos.X = 0 - } - h.updatePos(pos) - return false, nil - } else { - // The cursor is at the bottom of the screen but outside the scroll - // region. Skip the LF. - h.logf("Simulating LF outside scroll region") - if includeCR { - if err := h.Flush(); err != nil { - return false, err - } - pos.X = 0 - if err := SetConsoleCursorPosition(h.fd, pos); err != nil { - return false, err - } - } - return true, nil - } -} - -// executeLF executes a LF without a CR. -func (h *windowsAnsiEventHandler) executeLF() error { - handled, err := h.simulateLF(false) - if err != nil { - return err - } - if !handled { - // Windows LF will reset the cursor column position. Write the LF - // and restore the cursor position. - pos, _, err := h.getCurrentInfo() - if err != nil { - return err - } - h.buffer.WriteByte(ansiterm.ANSI_LINE_FEED) - if pos.X != 0 { - if err := h.Flush(); err != nil { - return err - } - h.logf("Resetting cursor position for LF without CR") - if err := SetConsoleCursorPosition(h.fd, pos); err != nil { - return err - } - } - } - return nil -} - -func (h *windowsAnsiEventHandler) Print(b byte) error { - if h.wrapNext { - h.buffer.WriteByte(h.marginByte) - h.clearWrap() - if _, err := h.simulateLF(true); err != nil { - return err - } - } - pos, info, err := h.getCurrentInfo() - if err != nil { - return err - } - if pos.X == info.Size.X-1 { - h.wrapNext = true - h.marginByte = b - } else { - pos.X++ - h.updatePos(pos) - h.buffer.WriteByte(b) - } - return nil -} - -func (h *windowsAnsiEventHandler) Execute(b byte) error { - switch b { - case ansiterm.ANSI_TAB: - h.logf("Execute(TAB)") - // Move to the next tab stop, but preserve auto-wrap if already set. - if !h.wrapNext { - pos, info, err := h.getCurrentInfo() - if err != nil { - return err - } - pos.X = (pos.X + 8) - pos.X%8 - if pos.X >= info.Size.X { - pos.X = info.Size.X - 1 - } - if err := h.Flush(); err != nil { - return err - } - if err := SetConsoleCursorPosition(h.fd, pos); err != nil { - return err - } - } - return nil - - case ansiterm.ANSI_BEL: - h.buffer.WriteByte(ansiterm.ANSI_BEL) - return nil - - case ansiterm.ANSI_BACKSPACE: - if h.wrapNext { - if err := h.Flush(); err != nil { - return err - } - h.clearWrap() - } - pos, _, err := h.getCurrentInfo() - if err != nil { - return err - } - if pos.X > 0 { - pos.X-- - h.updatePos(pos) - h.buffer.WriteByte(ansiterm.ANSI_BACKSPACE) - } - return nil - - case ansiterm.ANSI_VERTICAL_TAB, ansiterm.ANSI_FORM_FEED: - // Treat as true LF. - return h.executeLF() - - case ansiterm.ANSI_LINE_FEED: - // Simulate a CR and LF for now since there is no way in go-ansiterm - // to tell if the LF should include CR (and more things break when it's - // missing than when it's incorrectly added). - handled, err := h.simulateLF(true) - if handled || err != nil { - return err - } - return h.buffer.WriteByte(ansiterm.ANSI_LINE_FEED) - - case ansiterm.ANSI_CARRIAGE_RETURN: - if h.wrapNext { - if err := h.Flush(); err != nil { - return err - } - h.clearWrap() - } - pos, _, err := h.getCurrentInfo() - if err != nil { - return err - } - if pos.X != 0 { - pos.X = 0 - h.updatePos(pos) - h.buffer.WriteByte(ansiterm.ANSI_CARRIAGE_RETURN) - } - return nil - - default: - return nil - } -} - -func (h *windowsAnsiEventHandler) CUU(param int) error { - if err := h.Flush(); err != nil { - return err - } - h.logf("CUU: [%v]", []string{strconv.Itoa(param)}) - h.clearWrap() - return h.moveCursorVertical(-param) -} - -func (h *windowsAnsiEventHandler) CUD(param int) error { - if err := h.Flush(); err != nil { - return err - } - h.logf("CUD: [%v]", []string{strconv.Itoa(param)}) - h.clearWrap() - return h.moveCursorVertical(param) -} - -func (h *windowsAnsiEventHandler) CUF(param int) error { - if err := h.Flush(); err != nil { - return err - } - h.logf("CUF: [%v]", []string{strconv.Itoa(param)}) - h.clearWrap() - return h.moveCursorHorizontal(param) -} - -func (h *windowsAnsiEventHandler) CUB(param int) error { - if err := h.Flush(); err != nil { - return err - } - h.logf("CUB: [%v]", []string{strconv.Itoa(param)}) - h.clearWrap() - return h.moveCursorHorizontal(-param) -} - -func (h *windowsAnsiEventHandler) CNL(param int) error { - if err := h.Flush(); err != nil { - return err - } - h.logf("CNL: [%v]", []string{strconv.Itoa(param)}) - h.clearWrap() - return h.moveCursorLine(param) -} - -func (h *windowsAnsiEventHandler) CPL(param int) error { - if err := h.Flush(); err != nil { - return err - } - h.logf("CPL: [%v]", []string{strconv.Itoa(param)}) - h.clearWrap() - return h.moveCursorLine(-param) -} - -func (h *windowsAnsiEventHandler) CHA(param int) error { - if err := h.Flush(); err != nil { - return err - } - h.logf("CHA: [%v]", []string{strconv.Itoa(param)}) - h.clearWrap() - return h.moveCursorColumn(param) -} - -func (h *windowsAnsiEventHandler) VPA(param int) error { - if err := h.Flush(); err != nil { - return err - } - h.logf("VPA: [[%d]]", param) - h.clearWrap() - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return err - } - window := h.getCursorWindow(info) - position := info.CursorPosition - position.Y = window.Top + int16(param) - 1 - return h.setCursorPosition(position, window) -} - -func (h *windowsAnsiEventHandler) CUP(row int, col int) error { - if err := h.Flush(); err != nil { - return err - } - h.logf("CUP: [[%d %d]]", row, col) - h.clearWrap() - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return err - } - - window := h.getCursorWindow(info) - position := COORD{window.Left + int16(col) - 1, window.Top + int16(row) - 1} - return h.setCursorPosition(position, window) -} - -func (h *windowsAnsiEventHandler) HVP(row int, col int) error { - if err := h.Flush(); err != nil { - return err - } - h.logf("HVP: [[%d %d]]", row, col) - h.clearWrap() - return h.CUP(row, col) -} - -func (h *windowsAnsiEventHandler) DECTCEM(visible bool) error { - if err := h.Flush(); err != nil { - return err - } - h.logf("DECTCEM: [%v]", []string{strconv.FormatBool(visible)}) - h.clearWrap() - return nil -} - -func (h *windowsAnsiEventHandler) DECOM(enable bool) error { - if err := h.Flush(); err != nil { - return err - } - h.logf("DECOM: [%v]", []string{strconv.FormatBool(enable)}) - h.clearWrap() - h.originMode = enable - return h.CUP(1, 1) -} - -func (h *windowsAnsiEventHandler) DECCOLM(use132 bool) error { - if err := h.Flush(); err != nil { - return err - } - h.logf("DECCOLM: [%v]", []string{strconv.FormatBool(use132)}) - h.clearWrap() - if err := h.ED(2); err != nil { - return err - } - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return err - } - targetWidth := int16(80) - if use132 { - targetWidth = 132 - } - if info.Size.X < targetWidth { - if err := SetConsoleScreenBufferSize(h.fd, COORD{targetWidth, info.Size.Y}); err != nil { - h.logf("set buffer failed: %v", err) - return err - } - } - window := info.Window - window.Left = 0 - window.Right = targetWidth - 1 - if err := SetConsoleWindowInfo(h.fd, true, window); err != nil { - h.logf("set window failed: %v", err) - return err - } - if info.Size.X > targetWidth { - if err := SetConsoleScreenBufferSize(h.fd, COORD{targetWidth, info.Size.Y}); err != nil { - h.logf("set buffer failed: %v", err) - return err - } - } - return SetConsoleCursorPosition(h.fd, COORD{0, 0}) -} - -func (h *windowsAnsiEventHandler) ED(param int) error { - if err := h.Flush(); err != nil { - return err - } - h.logf("ED: [%v]", []string{strconv.Itoa(param)}) - h.clearWrap() - - // [J -- Erases from the cursor to the end of the screen, including the cursor position. - // [1J -- Erases from the beginning of the screen to the cursor, including the cursor position. - // [2J -- Erases the complete display. The cursor does not move. - // Notes: - // -- Clearing the entire buffer, versus just the Window, works best for Windows Consoles - - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return err - } - - var start COORD - var end COORD - - switch param { - case 0: - start = info.CursorPosition - end = COORD{info.Size.X - 1, info.Size.Y - 1} - - case 1: - start = COORD{0, 0} - end = info.CursorPosition - - case 2: - start = COORD{0, 0} - end = COORD{info.Size.X - 1, info.Size.Y - 1} - } - - err = h.clearRange(h.attributes, start, end) - if err != nil { - return err - } - - // If the whole buffer was cleared, move the window to the top while preserving - // the window-relative cursor position. - if param == 2 { - pos := info.CursorPosition - window := info.Window - pos.Y -= window.Top - window.Bottom -= window.Top - window.Top = 0 - if err := SetConsoleCursorPosition(h.fd, pos); err != nil { - return err - } - if err := SetConsoleWindowInfo(h.fd, true, window); err != nil { - return err - } - } - - return nil -} - -func (h *windowsAnsiEventHandler) EL(param int) error { - if err := h.Flush(); err != nil { - return err - } - h.logf("EL: [%v]", strconv.Itoa(param)) - h.clearWrap() - - // [K -- Erases from the cursor to the end of the line, including the cursor position. - // [1K -- Erases from the beginning of the line to the cursor, including the cursor position. - // [2K -- Erases the complete line. - - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return err - } - - var start COORD - var end COORD - - switch param { - case 0: - start = info.CursorPosition - end = COORD{info.Size.X, info.CursorPosition.Y} - - case 1: - start = COORD{0, info.CursorPosition.Y} - end = info.CursorPosition - - case 2: - start = COORD{0, info.CursorPosition.Y} - end = COORD{info.Size.X, info.CursorPosition.Y} - } - - err = h.clearRange(h.attributes, start, end) - if err != nil { - return err - } - - return nil -} - -func (h *windowsAnsiEventHandler) IL(param int) error { - if err := h.Flush(); err != nil { - return err - } - h.logf("IL: [%v]", strconv.Itoa(param)) - h.clearWrap() - return h.insertLines(param) -} - -func (h *windowsAnsiEventHandler) DL(param int) error { - if err := h.Flush(); err != nil { - return err - } - h.logf("DL: [%v]", strconv.Itoa(param)) - h.clearWrap() - return h.deleteLines(param) -} - -func (h *windowsAnsiEventHandler) ICH(param int) error { - if err := h.Flush(); err != nil { - return err - } - h.logf("ICH: [%v]", strconv.Itoa(param)) - h.clearWrap() - return h.insertCharacters(param) -} - -func (h *windowsAnsiEventHandler) DCH(param int) error { - if err := h.Flush(); err != nil { - return err - } - h.logf("DCH: [%v]", strconv.Itoa(param)) - h.clearWrap() - return h.deleteCharacters(param) -} - -func (h *windowsAnsiEventHandler) SGR(params []int) error { - if err := h.Flush(); err != nil { - return err - } - strings := []string{} - for _, v := range params { - strings = append(strings, strconv.Itoa(v)) - } - - h.logf("SGR: [%v]", strings) - - if len(params) <= 0 { - h.attributes = h.infoReset.Attributes - h.inverted = false - } else { - for _, attr := range params { - - if attr == ansiterm.ANSI_SGR_RESET { - h.attributes = h.infoReset.Attributes - h.inverted = false - continue - } - - h.attributes, h.inverted = collectAnsiIntoWindowsAttributes(h.attributes, h.inverted, h.infoReset.Attributes, int16(attr)) - } - } - - attributes := h.attributes - if h.inverted { - attributes = invertAttributes(attributes) - } - err := SetConsoleTextAttribute(h.fd, attributes) - if err != nil { - return err - } - - return nil -} - -func (h *windowsAnsiEventHandler) SU(param int) error { - if err := h.Flush(); err != nil { - return err - } - h.logf("SU: [%v]", []string{strconv.Itoa(param)}) - h.clearWrap() - return h.scrollUp(param) -} - -func (h *windowsAnsiEventHandler) SD(param int) error { - if err := h.Flush(); err != nil { - return err - } - h.logf("SD: [%v]", []string{strconv.Itoa(param)}) - h.clearWrap() - return h.scrollDown(param) -} - -func (h *windowsAnsiEventHandler) DA(params []string) error { - h.logf("DA: [%v]", params) - // DA cannot be implemented because it must send data on the VT100 input stream, - // which is not available to go-ansiterm. - return nil -} - -func (h *windowsAnsiEventHandler) DECSTBM(top int, bottom int) error { - if err := h.Flush(); err != nil { - return err - } - h.logf("DECSTBM: [%d, %d]", top, bottom) - - // Windows is 0 indexed, Linux is 1 indexed - h.sr.top = int16(top - 1) - h.sr.bottom = int16(bottom - 1) - - // This command also moves the cursor to the origin. - h.clearWrap() - return h.CUP(1, 1) -} - -func (h *windowsAnsiEventHandler) RI() error { - if err := h.Flush(); err != nil { - return err - } - h.logf("RI: []") - h.clearWrap() - - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return err - } - - sr := h.effectiveSr(info.Window) - if info.CursorPosition.Y == sr.top { - return h.scrollDown(1) - } - - return h.moveCursorVertical(-1) -} - -func (h *windowsAnsiEventHandler) IND() error { - h.logf("IND: []") - return h.executeLF() -} - -func (h *windowsAnsiEventHandler) Flush() error { - h.curInfo = nil - if h.buffer.Len() > 0 { - h.logf("Flush: [%s]", h.buffer.Bytes()) - if _, err := h.buffer.WriteTo(h.file); err != nil { - return err - } - } - - if h.wrapNext && !h.drewMarginByte { - h.logf("Flush: drawing margin byte '%c'", h.marginByte) - - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return err - } - - charInfo := []CHAR_INFO{{UnicodeChar: uint16(h.marginByte), Attributes: info.Attributes}} - size := COORD{1, 1} - position := COORD{0, 0} - region := SMALL_RECT{Left: info.CursorPosition.X, Top: info.CursorPosition.Y, Right: info.CursorPosition.X, Bottom: info.CursorPosition.Y} - if err := WriteConsoleOutput(h.fd, charInfo, size, position, ®ion); err != nil { - return err - } - h.drewMarginByte = true - } - return nil -} - -// cacheConsoleInfo ensures that the current console screen information has been queried -// since the last call to Flush(). It must be called before accessing h.curInfo or h.curPos. -func (h *windowsAnsiEventHandler) getCurrentInfo() (COORD, *CONSOLE_SCREEN_BUFFER_INFO, error) { - if h.curInfo == nil { - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return COORD{}, nil, err - } - h.curInfo = info - h.curPos = info.CursorPosition - } - return h.curPos, h.curInfo, nil -} - -func (h *windowsAnsiEventHandler) updatePos(pos COORD) { - if h.curInfo == nil { - panic("failed to call getCurrentInfo before calling updatePos") - } - h.curPos = pos -} - -// clearWrap clears the state where the cursor is in the margin -// waiting for the next character before wrapping the line. This must -// be done before most operations that act on the cursor. -func (h *windowsAnsiEventHandler) clearWrap() { - h.wrapNext = false - h.drewMarginByte = false -} diff --git a/vendor/github.com/Masterminds/semver/v3/.gitignore b/vendor/github.com/Masterminds/semver/v3/.gitignore deleted file mode 100644 index 6b061e617..000000000 --- a/vendor/github.com/Masterminds/semver/v3/.gitignore +++ /dev/null @@ -1 +0,0 @@ -_fuzz/ \ No newline at end of file diff --git a/vendor/github.com/Masterminds/semver/v3/.golangci.yml b/vendor/github.com/Masterminds/semver/v3/.golangci.yml deleted file mode 100644 index fbc633259..000000000 --- a/vendor/github.com/Masterminds/semver/v3/.golangci.yml +++ /dev/null @@ -1,27 +0,0 @@ -run: - deadline: 2m - -linters: - disable-all: true - enable: - - misspell - - govet - - staticcheck - - errcheck - - unparam - - ineffassign - - nakedret - - gocyclo - - dupl - - goimports - - revive - - gosec - - gosimple - - typecheck - - unused - -linters-settings: - gofmt: - simplify: true - dupl: - threshold: 600 diff --git a/vendor/github.com/Masterminds/semver/v3/CHANGELOG.md b/vendor/github.com/Masterminds/semver/v3/CHANGELOG.md deleted file mode 100644 index f12626423..000000000 --- a/vendor/github.com/Masterminds/semver/v3/CHANGELOG.md +++ /dev/null @@ -1,214 +0,0 @@ -# Changelog - -## 3.2.0 (2022-11-28) - -### Added - -- #190: Added text marshaling and unmarshaling -- #167: Added JSON marshalling for constraints (thanks @SimonTheLeg) -- #173: Implement encoding.TextMarshaler and encoding.TextUnmarshaler on Version (thanks @MarkRosemaker) -- #179: Added New() version constructor (thanks @kazhuravlev) - -### Changed - -- #182/#183: Updated CI testing setup - -### Fixed - -- #186: Fixing issue where validation of constraint section gave false positives -- #176: Fix constraints check with *-0 (thanks @mtt0) -- #181: Fixed Caret operator (^) gives unexpected results when the minor version in constraint is 0 (thanks @arshchimni) -- #161: Fixed godoc (thanks @afirth) - -## 3.1.1 (2020-11-23) - -### Fixed - -- #158: Fixed issue with generated regex operation order that could cause problem - -## 3.1.0 (2020-04-15) - -### Added - -- #131: Add support for serializing/deserializing SQL (thanks @ryancurrah) - -### Changed - -- #148: More accurate validation messages on constraints - -## 3.0.3 (2019-12-13) - -### Fixed - -- #141: Fixed issue with <= comparison - -## 3.0.2 (2019-11-14) - -### Fixed - -- #134: Fixed broken constraint checking with ^0.0 (thanks @krmichelos) - -## 3.0.1 (2019-09-13) - -### Fixed - -- #125: Fixes issue with module path for v3 - -## 3.0.0 (2019-09-12) - -This is a major release of the semver package which includes API changes. The Go -API is compatible with ^1. The Go API was not changed because many people are using -`go get` without Go modules for their applications and API breaking changes cause -errors which we have or would need to support. - -The changes in this release are the handling based on the data passed into the -functions. These are described in the added and changed sections below. - -### Added - -- StrictNewVersion function. This is similar to NewVersion but will return an - error if the version passed in is not a strict semantic version. For example, - 1.2.3 would pass but v1.2.3 or 1.2 would fail because they are not strictly - speaking semantic versions. This function is faster, performs fewer operations, - and uses fewer allocations than NewVersion. -- Fuzzing has been performed on NewVersion, StrictNewVersion, and NewConstraint. - The Makefile contains the operations used. For more information on you can start - on Wikipedia at https://en.wikipedia.org/wiki/Fuzzing -- Now using Go modules - -### Changed - -- NewVersion has proper prerelease and metadata validation with error messages - to signal an issue with either of them -- ^ now operates using a similar set of rules to npm/js and Rust/Cargo. If the - version is >=1 the ^ ranges works the same as v1. For major versions of 0 the - rules have changed. The minor version is treated as the stable version unless - a patch is specified and then it is equivalent to =. One difference from npm/js - is that prereleases there are only to a specific version (e.g. 1.2.3). - Prereleases here look over multiple versions and follow semantic version - ordering rules. This pattern now follows along with the expected and requested - handling of this packaged by numerous users. - -## 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/v3/LICENSE.txt b/vendor/github.com/Masterminds/semver/v3/LICENSE.txt deleted file mode 100644 index 9ff7da9c4..000000000 --- a/vendor/github.com/Masterminds/semver/v3/LICENSE.txt +++ /dev/null @@ -1,19 +0,0 @@ -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/v3/Makefile b/vendor/github.com/Masterminds/semver/v3/Makefile deleted file mode 100644 index 0e7b5c713..000000000 --- a/vendor/github.com/Masterminds/semver/v3/Makefile +++ /dev/null @@ -1,30 +0,0 @@ -GOPATH=$(shell go env GOPATH) -GOLANGCI_LINT=$(GOPATH)/bin/golangci-lint - -.PHONY: lint -lint: $(GOLANGCI_LINT) - @echo "==> Linting codebase" - @$(GOLANGCI_LINT) run - -.PHONY: test -test: - @echo "==> Running tests" - GO111MODULE=on go test -v - -.PHONY: test-cover -test-cover: - @echo "==> Running Tests with coverage" - GO111MODULE=on go test -cover . - -.PHONY: fuzz -fuzz: - @echo "==> Running Fuzz Tests" - go test -fuzz=FuzzNewVersion -fuzztime=15s . - go test -fuzz=FuzzStrictNewVersion -fuzztime=15s . - go test -fuzz=FuzzNewConstraint -fuzztime=15s . - -$(GOLANGCI_LINT): - # Install golangci-lint. The configuration for it is in the .golangci.yml - # file in the root of the repository - echo ${GOPATH} - curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $(GOPATH)/bin v1.17.1 diff --git a/vendor/github.com/Masterminds/semver/v3/README.md b/vendor/github.com/Masterminds/semver/v3/README.md deleted file mode 100644 index eab8cac3b..000000000 --- a/vendor/github.com/Masterminds/semver/v3/README.md +++ /dev/null @@ -1,258 +0,0 @@ -# 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) -[![](https://github.com/Masterminds/semver/workflows/Tests/badge.svg)](https://github.com/Masterminds/semver/actions) -[![GoDoc](https://img.shields.io/static/v1?label=godoc&message=reference&color=blue)](https://pkg.go.dev/github.com/Masterminds/semver/v3) -[![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. - -## Package Versions - -Note, import `github.com/github.com/Masterminds/semver/v3` to use the latest version. - -There are three major versions fo the `semver` package. - -* 3.x.x is the stable and active version. This version is focused on constraint - compatibility for range handling in other tools from other languages. It has - a similar API to the v1 releases. The development of this version is on the master - branch. The documentation for this version is below. -* 2.x was developed primarily for [dep](https://github.com/golang/dep). There are - no tagged releases and the development was performed by [@sdboyer](https://github.com/sdboyer). - There are API breaking changes from v1. This version lives on the [2.x branch](https://github.com/Masterminds/semver/tree/2.x). -* 1.x.x is the original release. It is no longer maintained. You should use the - v3 release instead. You can read the documentation for the 1.x.x release - [here](https://github.com/Masterminds/semver/blob/release-1/README.md). - -## Parsing Semantic Versions - -There are two functions that can parse semantic versions. The `StrictNewVersion` -function only parses valid version 2 semantic versions as outlined in the -specification. The `NewVersion` function attempts to coerce a version into a -semantic version and parse it. For example, if there is a leading v or a version -listed without all 3 parts (e.g. `v1.2`) it will attempt to coerce it into a valid -semantic version (e.g., 1.2.0). In both cases a `Version` object is returned -that can be sorted, compared, and used in constraints. - -When parsing a version an error is returned if there is an issue parsing the -version. For example, - - v, err := semver.NewVersion("1.2.3-beta.1+build345") - -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. Getting the original string is useful if the semantic version was coerced -into a valid form. - -## Sorting Semantic Versions - -A set of versions can be sorted using the `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 - -There are two methods for comparing versions. One uses comparison methods on -`Version` instances and the other uses `Constraints`. There are some important -differences to notes between these two methods of comparison. - -1. When two versions are compared using functions such as `Compare`, `LessThan`, - and others it will follow the specification and always include prereleases - within the comparison. It will provide an answer that is valid with the - comparison section of the spec at https://semver.org/#spec-item-11 -2. When constraint checking is used for checks or validation it will follow a - different set of rules that are common for ranges with tools like npm/js - and Rust/Cargo. This includes considering prereleases to be invalid if the - ranges does not include one. If you want to have it include pre-releases a - simple solution is to include `-0` in your range. -3. Constraint ranges can have some complex rules including the shorthand use of - ~ and ^. For more details on those see the options below. - -There are differences between the two methods or checking versions because the -comparison methods on `Version` follow the specification while comparison ranges -are not part of the specification. Different packages and tools have taken it -upon themselves to come up with range rules. This has resulted in differences. -For example, npm/js and Cargo/Rust follow similar patterns while PHP has a -different pattern for ^. The comparison features in this package follow the -npm/js and Cargo/Rust lead because applications using it have followed similar -patters with their versions. - -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 parsable. -} - -v, err := semver.NewVersion("1.3") -if err != nil { - // Handle version not being parsable. -} -// 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 space or comma separated AND comparisons. These are then separated by || (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 Prerelease Versions - -Pre-releases, for those not familiar with them, are used for software releases -prior to stable or generally available releases. Examples of prereleases include -development, alpha, beta, and release candidate releases. A prerelease may be -a version such as `1.2.3-beta.1` while the stable release would be `1.2.3`. In the -order of precedence, prereleases come before their associated releases. In this -example `1.2.3-beta.1 < 1.2.3`. - -According to the Semantic Version specification prereleases 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 using constraints without a prerelease comparator will skip -prerelease versions. For example, `>=1.2.3` will skip prereleases when looking -at a list of releases while `>=1.2.3-0` will evaluate and find prereleases. - -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 patch 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 once a stable -(1.0.0) release has occurred. Prior to a 1.0.0 release the minor versions acts -as the API stability level. 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` -* `^0.2.3` is equivalent to `>=0.2.3 <0.3.0` -* `^0.2` is equivalent to `>=0.2.0 <0.3.0` -* `^0.0.3` is equivalent to `>=0.0.3 <0.0.4` -* `^0.0` is equivalent to `>=0.0.0 <0.1.0` -* `^0` is equivalent to `>=0.0.0 <1.0.0` - -## 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, err := 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" -} -``` - -## 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). - -## Security - -Security is an important consideration for this project. The project currently -uses the following tools to help discover security issues: - -* [CodeQL](https://github.com/Masterminds/semver) -* [gosec](https://github.com/securego/gosec) -* Daily Fuzz testing - -If you believe you have found a security vulnerability you can privately disclose -it through the [GitHub security page](https://github.com/Masterminds/semver/security). diff --git a/vendor/github.com/Masterminds/semver/v3/SECURITY.md b/vendor/github.com/Masterminds/semver/v3/SECURITY.md deleted file mode 100644 index a30a66b1f..000000000 --- a/vendor/github.com/Masterminds/semver/v3/SECURITY.md +++ /dev/null @@ -1,19 +0,0 @@ -# Security Policy - -## Supported Versions - -The following versions of semver are currently supported: - -| Version | Supported | -| ------- | ------------------ | -| 3.x | :white_check_mark: | -| 2.x | :x: | -| 1.x | :x: | - -Fixes are only released for the latest minor version in the form of a patch release. - -## Reporting a Vulnerability - -You can privately disclose a vulnerability through GitHubs -[private vulnerability reporting](https://github.com/Masterminds/semver/security/advisories) -mechanism. diff --git a/vendor/github.com/Masterminds/semver/v3/collection.go b/vendor/github.com/Masterminds/semver/v3/collection.go deleted file mode 100644 index a78235895..000000000 --- a/vendor/github.com/Masterminds/semver/v3/collection.go +++ /dev/null @@ -1,24 +0,0 @@ -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/v3/constraints.go b/vendor/github.com/Masterminds/semver/v3/constraints.go deleted file mode 100644 index 8461c7ed9..000000000 --- a/vendor/github.com/Masterminds/semver/v3/constraints.go +++ /dev/null @@ -1,594 +0,0 @@ -package semver - -import ( - "bytes" - "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 { - - // TODO: Find a way to validate and fetch all the constraints in a simpler form - - // Validate the segment - if !validConstraintRegex.MatchString(v) { - return nil, fmt.Errorf("improper constraint: %s", v) - } - - cs := findConstraintRegex.FindAllString(v, -1) - if cs == nil { - cs = append(cs, 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 { - // TODO(mattfarina): For v4 of this library consolidate the Check and Validate - // functions as the underlying functions make that possible now. - // loop over the ORs and check the inner ANDs - for _, o := range cs.constraints { - joy := true - for _, c := range o { - if check, _ := c.check(v); !check { - 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 _, err := c.check(v); err != nil { - e = append(e, err) - joy = false - } - } - } - - if joy { - return true, []error{} - } - } - - return false, e -} - -func (cs Constraints) String() string { - buf := make([]string, len(cs.constraints)) - var tmp bytes.Buffer - - for k, v := range cs.constraints { - tmp.Reset() - vlen := len(v) - for kk, c := range v { - tmp.WriteString(c.string()) - - // Space separate the AND conditions - if vlen > 1 && kk < vlen-1 { - tmp.WriteString(" ") - } - } - buf[k] = tmp.String() - } - - return strings.Join(buf, " || ") -} - -// UnmarshalText implements the encoding.TextUnmarshaler interface. -func (cs *Constraints) UnmarshalText(text []byte) error { - temp, err := NewConstraint(string(text)) - if err != nil { - return err - } - - *cs = *temp - - return nil -} - -// MarshalText implements the encoding.TextMarshaler interface. -func (cs Constraints) MarshalText() ([]byte, error) { - return []byte(cs.String()), nil -} - -var constraintOps map[string]cfunc -var constraintRegex *regexp.Regexp -var constraintRangeRegex *regexp.Regexp - -// Used to find individual constraints within a multi-constraint string -var findConstraintRegex *regexp.Regexp - -// Used to validate an segment of ANDs is valid -var validConstraintRegex *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 init() { - constraintOps = map[string]cfunc{ - "": constraintTildeOrEqual, - "=": constraintTildeOrEqual, - "!=": constraintNotEqual, - ">": constraintGreaterThan, - "<": constraintLessThan, - ">=": constraintGreaterThanEqual, - "=>": constraintGreaterThanEqual, - "<=": constraintLessThanEqual, - "=<": constraintLessThanEqual, - "~": constraintTilde, - "~>": constraintTilde, - "^": constraintCaret, - } - - ops := `=||!=|>|<|>=|=>|<=|=<|~|~>|\^` - - constraintRegex = regexp.MustCompile(fmt.Sprintf( - `^\s*(%s)\s*(%s)\s*$`, - ops, - cvRegex)) - - constraintRangeRegex = regexp.MustCompile(fmt.Sprintf( - `\s*(%s)\s+-\s+(%s)\s*`, - cvRegex, cvRegex)) - - findConstraintRegex = regexp.MustCompile(fmt.Sprintf( - `(%s)\s*(%s)`, - ops, - cvRegex)) - - // The first time a constraint shows up will look slightly different from - // future times it shows up due to a leading space or comma in a given - // string. - validConstraintRegex = regexp.MustCompile(fmt.Sprintf( - `^(\s*(%s)\s*(%s)\s*)((?:\s+|,\s*)(%s)\s*(%s)\s*)*$`, - ops, - cvRegex, - ops, - cvRegex)) -} - -// An individual constraint -type constraint struct { - // 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 - - // The original operator for the constraint - origfunc 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, error) { - return constraintOps[c.origfunc](v, c) -} - -// String prints an individual constraint into a string -func (c *constraint) string() string { - return c.origfunc + c.orig -} - -type cfunc func(v *Version, c *constraint) (bool, error) - -func parseConstraint(c string) (*constraint, error) { - if len(c) > 0 { - m := constraintRegex.FindStringSubmatch(c) - if m == nil { - return nil, fmt.Errorf("improper constraint: %s", c) - } - - cs := &constraint{ - orig: m[2], - origfunc: m[1], - } - - ver := m[2] - minorDirty := false - patchDirty := false - dirty := false - if isX(m[3]) || m[3] == "" { - ver = fmt.Sprintf("0.0.0%s", m[6]) - 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], ".")) || 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.con = con - cs.minorDirty = minorDirty - cs.patchDirty = patchDirty - cs.dirty = dirty - - return cs, nil - } - - // The rest is the special case where an empty string was passed in which - // is equivalent to * or >=0.0.0 - con, err := StrictNewVersion("0.0.0") - 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{ - con: con, - orig: c, - origfunc: "", - minorDirty: false, - patchDirty: false, - dirty: true, - } - return cs, nil -} - -// Constraint functions -func constraintNotEqual(v *Version, c *constraint) (bool, error) { - 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, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) - } - - if c.con.Major() != v.Major() { - return true, nil - } - if c.con.Minor() != v.Minor() && !c.minorDirty { - return true, nil - } else if c.minorDirty { - return false, fmt.Errorf("%s is equal to %s", v, c.orig) - } else if c.con.Patch() != v.Patch() && !c.patchDirty { - return true, nil - } else if c.patchDirty { - // Need to handle prereleases if present - if v.Prerelease() != "" || c.con.Prerelease() != "" { - eq := comparePrerelease(v.Prerelease(), c.con.Prerelease()) != 0 - if eq { - return true, nil - } - return false, fmt.Errorf("%s is equal to %s", v, c.orig) - } - return false, fmt.Errorf("%s is equal to %s", v, c.orig) - } - } - - eq := v.Equal(c.con) - if eq { - return false, fmt.Errorf("%s is equal to %s", v, c.orig) - } - - return true, nil -} - -func constraintGreaterThan(v *Version, c *constraint) (bool, error) { - - // 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, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) - } - - var eq bool - - if !c.dirty { - eq = v.Compare(c.con) == 1 - if eq { - return true, nil - } - return false, fmt.Errorf("%s is less than or equal to %s", v, c.orig) - } - - if v.Major() > c.con.Major() { - return true, nil - } else if v.Major() < c.con.Major() { - return false, fmt.Errorf("%s is less than or equal to %s", v, c.orig) - } else if c.minorDirty { - // This is a range case such as >11. When the version is something like - // 11.1.0 is it not > 11. For that we would need 12 or higher - return false, fmt.Errorf("%s is less than or equal to %s", v, c.orig) - } else if c.patchDirty { - // This is for ranges such as >11.1. A version of 11.1.1 is not greater - // which one of 11.2.1 is greater - eq = v.Minor() > c.con.Minor() - if eq { - return true, nil - } - return false, fmt.Errorf("%s is less than or equal to %s", v, c.orig) - } - - // If we have gotten here we are not comparing pre-preleases and can use the - // Compare function to accomplish that. - eq = v.Compare(c.con) == 1 - if eq { - return true, nil - } - return false, fmt.Errorf("%s is less than or equal to %s", v, c.orig) -} - -func constraintLessThan(v *Version, c *constraint) (bool, error) { - // 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, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) - } - - eq := v.Compare(c.con) < 0 - if eq { - return true, nil - } - return false, fmt.Errorf("%s is greater than or equal to %s", v, c.orig) -} - -func constraintGreaterThanEqual(v *Version, c *constraint) (bool, error) { - - // 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, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) - } - - eq := v.Compare(c.con) >= 0 - if eq { - return true, nil - } - return false, fmt.Errorf("%s is less than %s", v, c.orig) -} - -func constraintLessThanEqual(v *Version, c *constraint) (bool, error) { - // 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, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) - } - - var eq bool - - if !c.dirty { - eq = v.Compare(c.con) <= 0 - if eq { - return true, nil - } - return false, fmt.Errorf("%s is greater than %s", v, c.orig) - } - - if v.Major() > c.con.Major() { - return false, fmt.Errorf("%s is greater than %s", v, c.orig) - } else if v.Major() == c.con.Major() && v.Minor() > c.con.Minor() && !c.minorDirty { - return false, fmt.Errorf("%s is greater than %s", v, c.orig) - } - - return true, nil -} - -// ~*, ~>* --> >= 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, error) { - // 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, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) - } - - if v.LessThan(c.con) { - return false, fmt.Errorf("%s is less than %s", v, c.orig) - } - - // ~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, nil - } - - if v.Major() != c.con.Major() { - return false, fmt.Errorf("%s does not have same major version as %s", v, c.orig) - } - - if v.Minor() != c.con.Minor() && !c.minorDirty { - return false, fmt.Errorf("%s does not have same major and minor version as %s", v, c.orig) - } - - return true, nil -} - -// When there is a .x (dirty) status it automatically opts in to ~. Otherwise -// it's a straight = -func constraintTildeOrEqual(v *Version, c *constraint) (bool, error) { - // 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, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) - } - - if c.dirty { - return constraintTilde(v, c) - } - - eq := v.Equal(c.con) - if eq { - return true, nil - } - - return false, fmt.Errorf("%s is not equal to %s", v, c.orig) -} - -// ^* --> (any) -// ^1.2.3 --> >=1.2.3 <2.0.0 -// ^1.2 --> >=1.2.0 <2.0.0 -// ^1 --> >=1.0.0 <2.0.0 -// ^0.2.3 --> >=0.2.3 <0.3.0 -// ^0.2 --> >=0.2.0 <0.3.0 -// ^0.0.3 --> >=0.0.3 <0.0.4 -// ^0.0 --> >=0.0.0 <0.1.0 -// ^0 --> >=0.0.0 <1.0.0 -func constraintCaret(v *Version, c *constraint) (bool, error) { - // 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, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) - } - - // This less than handles prereleases - if v.LessThan(c.con) { - return false, fmt.Errorf("%s is less than %s", v, c.orig) - } - - var eq bool - - // ^ when the major > 0 is >=x.y.z < x+1 - if c.con.Major() > 0 || c.minorDirty { - - // ^ has to be within a major range for > 0. Everything less than was - // filtered out with the LessThan call above. This filters out those - // that greater but not within the same major range. - eq = v.Major() == c.con.Major() - if eq { - return true, nil - } - return false, fmt.Errorf("%s does not have same major version as %s", v, c.orig) - } - - // ^ when the major is 0 and minor > 0 is >=0.y.z < 0.y+1 - if c.con.Major() == 0 && v.Major() > 0 { - return false, fmt.Errorf("%s does not have same major version as %s", v, c.orig) - } - // If the con Minor is > 0 it is not dirty - if c.con.Minor() > 0 || c.patchDirty { - eq = v.Minor() == c.con.Minor() - if eq { - return true, nil - } - return false, fmt.Errorf("%s does not have same minor version as %s. Expected minor versions to match when constraint major version is 0", v, c.orig) - } - // ^ when the minor is 0 and minor > 0 is =0.0.z - if c.con.Minor() == 0 && v.Minor() > 0 { - return false, fmt.Errorf("%s does not have same minor version as %s", v, c.orig) - } - - // At this point the major is 0 and the minor is 0 and not dirty. The patch - // is not dirty so we need to check if they are equal. If they are not equal - eq = c.con.Patch() == v.Patch() - if eq { - return true, nil - } - return false, fmt.Errorf("%s does not equal %s. Expect version and constraint to equal when major and minor versions are 0", v, c.orig) -} - -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/v3/doc.go b/vendor/github.com/Masterminds/semver/v3/doc.go deleted file mode 100644 index 74f97caa5..000000000 --- a/vendor/github.com/Masterminds/semver/v3/doc.go +++ /dev/null @@ -1,184 +0,0 @@ -/* -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 - -There are two functions that can parse semantic versions. The `StrictNewVersion` -function only parses valid version 2 semantic versions as outlined in the -specification. The `NewVersion` function attempts to coerce a version into a -semantic version and parse it. For example, if there is a leading v or a version -listed without all 3 parts (e.g. 1.2) it will attempt to coerce it into a valid -semantic version (e.g., 1.2.0). In both cases a `Version` object is returned -that can be sorted, compared, and used in constraints. - -When parsing a version an optional error can be returned if there is an issue -parsing the version. For example, - - v, err := semver.NewVersion("1.2.3-beta.1+b345") - -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 and Comparing Versions - -There are two methods for comparing versions. One uses comparison methods on -`Version` instances and the other is using Constraints. There are some important -differences to notes between these two methods of comparison. - - 1. When two versions are compared using functions such as `Compare`, `LessThan`, - and others it will follow the specification and always include prereleases - within the comparison. It will provide an answer valid with the comparison - spec section at https://semver.org/#spec-item-11 - 2. When constraint checking is used for checks or validation it will follow a - different set of rules that are common for ranges with tools like npm/js - and Rust/Cargo. This includes considering prereleases to be invalid if the - ranges does not include on. If you want to have it include pre-releases a - simple solution is to include `-0` in your range. - 3. Constraint ranges can have some complex rules including the shorthard use of - ~ and ^. For more details on those see the options below. - -There are differences between the two methods or checking versions because the -comparison methods on `Version` follow the specification while comparison ranges -are not part of the specification. Different packages and tools have taken it -upon themselves to come up with range rules. This has resulted in differences. -For example, npm/js and Cargo/Rust follow similar patterns which PHP has a -different pattern for ^. The comparison features in this package follow the -npm/js and Cargo/Rust lead because applications using it have followed similar -patters with their versions. - -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 parsable. - } - - v, err := semver.NewVersion("1.3") - if err != nil { - // Handle version not being parsable. - } - // 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 or space separated AND comparisons. These are then separated by || (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. This can also be written as -`">= 1.2, < 3.0.0 || >= 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 tilde operation. 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 once a stable -(1.0.0) release has occurred. Prior to a 1.0.0 release the minor versions acts -as the API stability level. 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` - - `^0.2.3` is equivalent to `>=0.2.3 <0.3.0` - - `^0.2` is equivalent to `>=0.2.0 <0.3.0` - - `^0.0.3` is equivalent to `>=0.0.3 <0.0.4` - - `^0.0` is equivalent to `>=0.0.0 <0.1.0` - - `^0` is equivalent to `>=0.0.0 <1.0.0` - -# 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, - - 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" - } -*/ -package semver diff --git a/vendor/github.com/Masterminds/semver/v3/version.go b/vendor/github.com/Masterminds/semver/v3/version.go deleted file mode 100644 index 7c4bed334..000000000 --- a/vendor/github.com/Masterminds/semver/v3/version.go +++ /dev/null @@ -1,639 +0,0 @@ -package semver - -import ( - "bytes" - "database/sql/driver" - "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 ( - // ErrInvalidSemVer is returned a version is found to be invalid when - // being parsed. - ErrInvalidSemVer = errors.New("Invalid Semantic Version") - - // ErrEmptyString is returned when an empty string is passed in for parsing. - ErrEmptyString = errors.New("Version string empty") - - // ErrInvalidCharacters is returned when invalid characters are found as - // part of a version - ErrInvalidCharacters = errors.New("Invalid characters in version") - - // ErrSegmentStartsZero is returned when a version segment starts with 0. - // This is invalid in SemVer. - ErrSegmentStartsZero = errors.New("Version segment starts with 0") - - // 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\-]+)*))?` - -// Version represents a single semantic version. -type Version struct { - major, minor, patch uint64 - pre string - metadata string - original string -} - -func init() { - versionRegex = regexp.MustCompile("^" + semVerRegex + "$") -} - -const ( - num string = "0123456789" - allowed string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-" + num -) - -// StrictNewVersion parses a given version and returns an instance of Version or -// an error if unable to parse the version. Only parses valid semantic versions. -// Performs checking that can find errors within the version. -// If you want to coerce a version such as 1 or 1.2 and parse it as the 1.x -// releases of semver did, use the NewVersion() function. -func StrictNewVersion(v string) (*Version, error) { - // Parsing here does not use RegEx in order to increase performance and reduce - // allocations. - - if len(v) == 0 { - return nil, ErrEmptyString - } - - // Split the parts into [0]major, [1]minor, and [2]patch,prerelease,build - parts := strings.SplitN(v, ".", 3) - if len(parts) != 3 { - return nil, ErrInvalidSemVer - } - - sv := &Version{ - original: v, - } - - // check for prerelease or build metadata - var extra []string - if strings.ContainsAny(parts[2], "-+") { - // Start with the build metadata first as it needs to be on the right - extra = strings.SplitN(parts[2], "+", 2) - if len(extra) > 1 { - // build metadata found - sv.metadata = extra[1] - parts[2] = extra[0] - } - - extra = strings.SplitN(parts[2], "-", 2) - if len(extra) > 1 { - // prerelease found - sv.pre = extra[1] - parts[2] = extra[0] - } - } - - // Validate the number segments are valid. This includes only having positive - // numbers and no leading 0's. - for _, p := range parts { - if !containsOnly(p, num) { - return nil, ErrInvalidCharacters - } - - if len(p) > 1 && p[0] == '0' { - return nil, ErrSegmentStartsZero - } - } - - // Extract the major, minor, and patch elements onto the returned Version - var err error - sv.major, err = strconv.ParseUint(parts[0], 10, 64) - if err != nil { - return nil, err - } - - sv.minor, err = strconv.ParseUint(parts[1], 10, 64) - if err != nil { - return nil, err - } - - sv.patch, err = strconv.ParseUint(parts[2], 10, 64) - if err != nil { - return nil, err - } - - // No prerelease or build metadata found so returning now as a fastpath. - if sv.pre == "" && sv.metadata == "" { - return sv, nil - } - - if sv.pre != "" { - if err = validatePrerelease(sv.pre); err != nil { - return nil, err - } - } - - if sv.metadata != "" { - if err = validateMetadata(sv.metadata); err != nil { - return nil, err - } - } - - return sv, nil -} - -// NewVersion parses a given version and returns an instance of Version or -// an error if unable to parse the version. If the version is SemVer-ish it -// attempts to convert it to SemVer. If you want to validate it was a strict -// semantic version at parse time see StrictNewVersion(). -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 err error - sv.major, err = strconv.ParseUint(m[1], 10, 64) - if err != nil { - return nil, fmt.Errorf("Error parsing version segment: %s", err) - } - - if m[2] != "" { - sv.minor, err = strconv.ParseUint(strings.TrimPrefix(m[2], "."), 10, 64) - if err != nil { - return nil, fmt.Errorf("Error parsing version segment: %s", err) - } - } else { - sv.minor = 0 - } - - if m[3] != "" { - sv.patch, err = strconv.ParseUint(strings.TrimPrefix(m[3], "."), 10, 64) - if err != nil { - return nil, fmt.Errorf("Error parsing version segment: %s", err) - } - } else { - sv.patch = 0 - } - - // Perform some basic due diligence on the extra parts to ensure they are - // valid. - - if sv.pre != "" { - if err = validatePrerelease(sv.pre); err != nil { - return nil, err - } - } - - if sv.metadata != "" { - if err = validateMetadata(sv.metadata); err != nil { - return nil, err - } - } - - return sv, nil -} - -// New creates a new instance of Version with each of the parts passed in as -// arguments instead of parsing a version string. -func New(major, minor, patch uint64, pre, metadata string) *Version { - v := Version{ - major: major, - minor: minor, - patch: patch, - pre: pre, - metadata: metadata, - original: "", - } - - v.original = v.String() - - return &v -} - -// 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() uint64 { - return v.major -} - -// Minor returns the minor version. -func (v Version) Minor() uint64 { - return v.minor -} - -// Patch returns the patch version. -func (v Version) Patch() uint64 { - 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 current 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 'hyphen' prefix. -func (v Version) SetPrerelease(prerelease string) (Version, error) { - vNext := v - if len(prerelease) > 0 { - if err := validatePrerelease(prerelease); err != nil { - return vNext, err - } - } - 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 { - if err := validateMetadata(metadata); err != nil { - return vNext, err - } - } - 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. Compare always takes into account -// prereleases. If you want to work with ranges using typical range syntaxes that -// skip prereleases if the range is not looking for them use constraints. -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 - return nil -} - -// MarshalJSON implements JSON.Marshaler interface. -func (v Version) MarshalJSON() ([]byte, error) { - return json.Marshal(v.String()) -} - -// UnmarshalText implements the encoding.TextUnmarshaler interface. -func (v *Version) UnmarshalText(text []byte) error { - temp, err := NewVersion(string(text)) - if err != nil { - return err - } - - *v = *temp - - return nil -} - -// MarshalText implements the encoding.TextMarshaler interface. -func (v Version) MarshalText() ([]byte, error) { - return []byte(v.String()), nil -} - -// Scan implements the SQL.Scanner interface. -func (v *Version) Scan(value interface{}) error { - var s string - s, _ = value.(string) - 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 - return nil -} - -// Value implements the Driver.Valuer interface. -func (v Version) Value() (driver.Value, error) { - return v.String(), nil -} - -func compareSegment(v, o uint64) 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 -} - -// Like strings.ContainsAny but does an only instead of any. -func containsOnly(s string, comp string) bool { - return strings.IndexFunc(s, func(r rune) bool { - return !strings.ContainsRune(comp, r) - }) == -1 -} - -// From the spec, "Identifiers MUST comprise only -// ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. -// Numeric identifiers MUST NOT include leading zeroes.". These segments can -// be dot separated. -func validatePrerelease(p string) error { - eparts := strings.Split(p, ".") - for _, p := range eparts { - if containsOnly(p, num) { - if len(p) > 1 && p[0] == '0' { - return ErrSegmentStartsZero - } - } else if !containsOnly(p, allowed) { - return ErrInvalidPrerelease - } - } - - return nil -} - -// From the spec, "Build metadata MAY be denoted by -// appending a plus sign and a series of dot separated identifiers immediately -// following the patch or pre-release version. Identifiers MUST comprise only -// ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty." -func validateMetadata(m string) error { - eparts := strings.Split(m, ".") - for _, p := range eparts { - if !containsOnly(p, allowed) { - return ErrInvalidMetadata - } - } - return nil -} diff --git a/vendor/github.com/Microsoft/go-winio/.gitattributes b/vendor/github.com/Microsoft/go-winio/.gitattributes deleted file mode 100644 index 94f480de9..000000000 --- a/vendor/github.com/Microsoft/go-winio/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -* text=auto eol=lf \ No newline at end of file diff --git a/vendor/github.com/Microsoft/go-winio/.gitignore b/vendor/github.com/Microsoft/go-winio/.gitignore deleted file mode 100644 index 815e20660..000000000 --- a/vendor/github.com/Microsoft/go-winio/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ -.vscode/ - -*.exe - -# testing -testdata - -# go workspaces -go.work -go.work.sum diff --git a/vendor/github.com/Microsoft/go-winio/.golangci.yml b/vendor/github.com/Microsoft/go-winio/.golangci.yml deleted file mode 100644 index 7b503d26a..000000000 --- a/vendor/github.com/Microsoft/go-winio/.golangci.yml +++ /dev/null @@ -1,149 +0,0 @@ -run: - skip-dirs: - - pkg/etw/sample - -linters: - enable: - # style - - containedctx # struct contains a context - - dupl # duplicate code - - errname # erorrs are named correctly - - nolintlint # "//nolint" directives are properly explained - - revive # golint replacement - - unconvert # unnecessary conversions - - wastedassign - - # bugs, performance, unused, etc ... - - contextcheck # function uses a non-inherited context - - errorlint # errors not wrapped for 1.13 - - exhaustive # check exhaustiveness of enum switch statements - - gofmt # files are gofmt'ed - - gosec # security - - nilerr # returns nil even with non-nil error - - unparam # unused function params - -issues: - exclude-rules: - # err is very often shadowed in nested scopes - - linters: - - govet - text: '^shadow: declaration of "err" shadows declaration' - - # ignore long lines for skip autogen directives - - linters: - - revive - text: "^line-length-limit: " - source: "^//(go:generate|sys) " - - #TODO: remove after upgrading to go1.18 - # ignore comment spacing for nolint and sys directives - - linters: - - revive - text: "^comment-spacings: no space between comment delimiter and comment text" - source: "//(cspell:|nolint:|sys |todo)" - - # not on go 1.18 yet, so no any - - linters: - - revive - text: "^use-any: since GO 1.18 'interface{}' can be replaced by 'any'" - - # allow unjustified ignores of error checks in defer statements - - linters: - - nolintlint - text: "^directive `//nolint:errcheck` should provide explanation" - source: '^\s*defer ' - - # allow unjustified ignores of error lints for io.EOF - - linters: - - nolintlint - text: "^directive `//nolint:errorlint` should provide explanation" - source: '[=|!]= io.EOF' - - -linters-settings: - exhaustive: - default-signifies-exhaustive: true - govet: - enable-all: true - disable: - # struct order is often for Win32 compat - # also, ignore pointer bytes/GC issues for now until performance becomes an issue - - fieldalignment - check-shadowing: true - nolintlint: - allow-leading-space: false - require-explanation: true - require-specific: true - revive: - # revive is more configurable than static check, so likely the preferred alternative to static-check - # (once the perf issue is solved: https://github.com/golangci/golangci-lint/issues/2997) - enable-all-rules: - true - # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md - rules: - # rules with required arguments - - name: argument-limit - disabled: true - - name: banned-characters - disabled: true - - name: cognitive-complexity - disabled: true - - name: cyclomatic - disabled: true - - name: file-header - disabled: true - - name: function-length - disabled: true - - name: function-result-limit - disabled: true - - name: max-public-structs - disabled: true - # geneally annoying rules - - name: add-constant # complains about any and all strings and integers - disabled: true - - name: confusing-naming # we frequently use "Foo()" and "foo()" together - disabled: true - - name: flag-parameter # excessive, and a common idiom we use - disabled: true - - name: unhandled-error # warns over common fmt.Print* and io.Close; rely on errcheck instead - disabled: true - # general config - - name: line-length-limit - arguments: - - 140 - - name: var-naming - arguments: - - [] - - - CID - - CRI - - CTRD - - DACL - - DLL - - DOS - - ETW - - FSCTL - - GCS - - GMSA - - HCS - - HV - - IO - - LCOW - - LDAP - - LPAC - - LTSC - - MMIO - - NT - - OCI - - PMEM - - PWSH - - RX - - SACl - - SID - - SMB - - TX - - VHD - - VHDX - - VMID - - VPCI - - WCOW - - WIM diff --git a/vendor/github.com/Microsoft/go-winio/CODEOWNERS b/vendor/github.com/Microsoft/go-winio/CODEOWNERS deleted file mode 100644 index ae1b4942b..000000000 --- a/vendor/github.com/Microsoft/go-winio/CODEOWNERS +++ /dev/null @@ -1 +0,0 @@ - * @microsoft/containerplat diff --git a/vendor/github.com/Microsoft/go-winio/LICENSE b/vendor/github.com/Microsoft/go-winio/LICENSE deleted file mode 100644 index b8b569d77..000000000 --- a/vendor/github.com/Microsoft/go-winio/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Microsoft - -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/Microsoft/go-winio/README.md b/vendor/github.com/Microsoft/go-winio/README.md deleted file mode 100644 index 7474b4f0b..000000000 --- a/vendor/github.com/Microsoft/go-winio/README.md +++ /dev/null @@ -1,89 +0,0 @@ -# go-winio [![Build Status](https://github.com/microsoft/go-winio/actions/workflows/ci.yml/badge.svg)](https://github.com/microsoft/go-winio/actions/workflows/ci.yml) - -This repository contains utilities for efficiently performing Win32 IO operations in -Go. Currently, this is focused on accessing named pipes and other file handles, and -for using named pipes as a net transport. - -This code relies on IO completion ports to avoid blocking IO on system threads, allowing Go -to reuse the thread to schedule another goroutine. This limits support to Windows Vista and -newer operating systems. This is similar to the implementation of network sockets in Go's net -package. - -Please see the LICENSE file for licensing information. - -## Contributing - -This project welcomes contributions and suggestions. -Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that -you have the right to, and actually do, grant us the rights to use your contribution. -For details, visit [Microsoft CLA](https://cla.microsoft.com). - -When you submit a pull request, a CLA-bot will automatically determine whether you need to -provide a CLA and decorate the PR appropriately (e.g., label, comment). -Simply follow the instructions provided by the bot. -You will only need to do this once across all repos using our CLA. - -Additionally, the pull request pipeline requires the following steps to be performed before -mergining. - -### Code Sign-Off - -We require that contributors sign their commits using [`git commit --signoff`][git-commit-s] -to certify they either authored the work themselves or otherwise have permission to use it in this project. - -A range of commits can be signed off using [`git rebase --signoff`][git-rebase-s]. - -Please see [the developer certificate](https://developercertificate.org) for more info, -as well as to make sure that you can attest to the rules listed. -Our CI uses the DCO Github app to ensure that all commits in a given PR are signed-off. - -### Linting - -Code must pass a linting stage, which uses [`golangci-lint`][lint]. -The linting settings are stored in [`.golangci.yaml`](./.golangci.yaml), and can be run -automatically with VSCode by adding the following to your workspace or folder settings: - -```json - "go.lintTool": "golangci-lint", - "go.lintOnSave": "package", -``` - -Additional editor [integrations options are also available][lint-ide]. - -Alternatively, `golangci-lint` can be [installed locally][lint-install] and run from the repo root: - -```shell -# use . or specify a path to only lint a package -# to show all lint errors, use flags "--max-issues-per-linter=0 --max-same-issues=0" -> golangci-lint run ./... -``` - -### Go Generate - -The pipeline checks that auto-generated code, via `go generate`, are up to date. - -This can be done for the entire repo: - -```shell -> go generate ./... -``` - -## Code of Conduct - -This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). -For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or -contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. - -## Special Thanks - -Thanks to [natefinch][natefinch] for the inspiration for this library. -See [npipe](https://github.com/natefinch/npipe) for another named pipe implementation. - -[lint]: https://golangci-lint.run/ -[lint-ide]: https://golangci-lint.run/usage/integrations/#editor-integration -[lint-install]: https://golangci-lint.run/usage/install/#local-installation - -[git-commit-s]: https://git-scm.com/docs/git-commit#Documentation/git-commit.txt--s -[git-rebase-s]: https://git-scm.com/docs/git-rebase#Documentation/git-rebase.txt---signoff - -[natefinch]: https://github.com/natefinch diff --git a/vendor/github.com/Microsoft/go-winio/SECURITY.md b/vendor/github.com/Microsoft/go-winio/SECURITY.md deleted file mode 100644 index 869fdfe2b..000000000 --- a/vendor/github.com/Microsoft/go-winio/SECURITY.md +++ /dev/null @@ -1,41 +0,0 @@ - - -## Security - -Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/). - -If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/opensource/security/definition), please report it to us as described below. - -## Reporting Security Issues - -**Please do not report security vulnerabilities through public GitHub issues.** - -Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/opensource/security/create-report). - -If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/opensource/security/pgpkey). - -You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://aka.ms/opensource/security/msrc). - -Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: - - * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) - * Full paths of source file(s) related to the manifestation of the issue - * The location of the affected source code (tag/branch/commit or direct URL) - * Any special configuration required to reproduce the issue - * Step-by-step instructions to reproduce the issue - * Proof-of-concept or exploit code (if possible) - * Impact of the issue, including how an attacker might exploit the issue - -This information will help us triage your report more quickly. - -If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/opensource/security/bounty) page for more details about our active programs. - -## Preferred Languages - -We prefer all communications to be in English. - -## Policy - -Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/opensource/security/cvd). - - diff --git a/vendor/github.com/Microsoft/go-winio/backup.go b/vendor/github.com/Microsoft/go-winio/backup.go deleted file mode 100644 index 09621c884..000000000 --- a/vendor/github.com/Microsoft/go-winio/backup.go +++ /dev/null @@ -1,290 +0,0 @@ -//go:build windows -// +build windows - -package winio - -import ( - "encoding/binary" - "errors" - "fmt" - "io" - "os" - "runtime" - "syscall" - "unicode/utf16" - - "golang.org/x/sys/windows" -) - -//sys backupRead(h syscall.Handle, b []byte, bytesRead *uint32, abort bool, processSecurity bool, context *uintptr) (err error) = BackupRead -//sys backupWrite(h syscall.Handle, b []byte, bytesWritten *uint32, abort bool, processSecurity bool, context *uintptr) (err error) = BackupWrite - -const ( - BackupData = uint32(iota + 1) - BackupEaData - BackupSecurity - BackupAlternateData - BackupLink - BackupPropertyData - BackupObjectId //revive:disable-line:var-naming ID, not Id - BackupReparseData - BackupSparseBlock - BackupTxfsData -) - -const ( - StreamSparseAttributes = uint32(8) -) - -//nolint:revive // var-naming: ALL_CAPS -const ( - WRITE_DAC = windows.WRITE_DAC - WRITE_OWNER = windows.WRITE_OWNER - ACCESS_SYSTEM_SECURITY = windows.ACCESS_SYSTEM_SECURITY -) - -// BackupHeader represents a backup stream of a file. -type BackupHeader struct { - //revive:disable-next-line:var-naming ID, not Id - Id uint32 // The backup stream ID - Attributes uint32 // Stream attributes - Size int64 // The size of the stream in bytes - Name string // The name of the stream (for BackupAlternateData only). - Offset int64 // The offset of the stream in the file (for BackupSparseBlock only). -} - -type win32StreamID struct { - StreamID uint32 - Attributes uint32 - Size uint64 - NameSize uint32 -} - -// BackupStreamReader reads from a stream produced by the BackupRead Win32 API and produces a series -// of BackupHeader values. -type BackupStreamReader struct { - r io.Reader - bytesLeft int64 -} - -// NewBackupStreamReader produces a BackupStreamReader from any io.Reader. -func NewBackupStreamReader(r io.Reader) *BackupStreamReader { - return &BackupStreamReader{r, 0} -} - -// Next returns the next backup stream and prepares for calls to Read(). It skips the remainder of the current stream if -// it was not completely read. -func (r *BackupStreamReader) Next() (*BackupHeader, error) { - if r.bytesLeft > 0 { //nolint:nestif // todo: flatten this - if s, ok := r.r.(io.Seeker); ok { - // Make sure Seek on io.SeekCurrent sometimes succeeds - // before trying the actual seek. - if _, err := s.Seek(0, io.SeekCurrent); err == nil { - if _, err = s.Seek(r.bytesLeft, io.SeekCurrent); err != nil { - return nil, err - } - r.bytesLeft = 0 - } - } - if _, err := io.Copy(io.Discard, r); err != nil { - return nil, err - } - } - var wsi win32StreamID - if err := binary.Read(r.r, binary.LittleEndian, &wsi); err != nil { - return nil, err - } - hdr := &BackupHeader{ - Id: wsi.StreamID, - Attributes: wsi.Attributes, - Size: int64(wsi.Size), - } - if wsi.NameSize != 0 { - name := make([]uint16, int(wsi.NameSize/2)) - if err := binary.Read(r.r, binary.LittleEndian, name); err != nil { - return nil, err - } - hdr.Name = syscall.UTF16ToString(name) - } - if wsi.StreamID == BackupSparseBlock { - if err := binary.Read(r.r, binary.LittleEndian, &hdr.Offset); err != nil { - return nil, err - } - hdr.Size -= 8 - } - r.bytesLeft = hdr.Size - return hdr, nil -} - -// Read reads from the current backup stream. -func (r *BackupStreamReader) Read(b []byte) (int, error) { - if r.bytesLeft == 0 { - return 0, io.EOF - } - if int64(len(b)) > r.bytesLeft { - b = b[:r.bytesLeft] - } - n, err := r.r.Read(b) - r.bytesLeft -= int64(n) - if err == io.EOF { - err = io.ErrUnexpectedEOF - } else if r.bytesLeft == 0 && err == nil { - err = io.EOF - } - return n, err -} - -// BackupStreamWriter writes a stream compatible with the BackupWrite Win32 API. -type BackupStreamWriter struct { - w io.Writer - bytesLeft int64 -} - -// NewBackupStreamWriter produces a BackupStreamWriter on top of an io.Writer. -func NewBackupStreamWriter(w io.Writer) *BackupStreamWriter { - return &BackupStreamWriter{w, 0} -} - -// WriteHeader writes the next backup stream header and prepares for calls to Write(). -func (w *BackupStreamWriter) WriteHeader(hdr *BackupHeader) error { - if w.bytesLeft != 0 { - return fmt.Errorf("missing %d bytes", w.bytesLeft) - } - name := utf16.Encode([]rune(hdr.Name)) - wsi := win32StreamID{ - StreamID: hdr.Id, - Attributes: hdr.Attributes, - Size: uint64(hdr.Size), - NameSize: uint32(len(name) * 2), - } - if hdr.Id == BackupSparseBlock { - // Include space for the int64 block offset - wsi.Size += 8 - } - if err := binary.Write(w.w, binary.LittleEndian, &wsi); err != nil { - return err - } - if len(name) != 0 { - if err := binary.Write(w.w, binary.LittleEndian, name); err != nil { - return err - } - } - if hdr.Id == BackupSparseBlock { - if err := binary.Write(w.w, binary.LittleEndian, hdr.Offset); err != nil { - return err - } - } - w.bytesLeft = hdr.Size - return nil -} - -// Write writes to the current backup stream. -func (w *BackupStreamWriter) Write(b []byte) (int, error) { - if w.bytesLeft < int64(len(b)) { - return 0, fmt.Errorf("too many bytes by %d", int64(len(b))-w.bytesLeft) - } - n, err := w.w.Write(b) - w.bytesLeft -= int64(n) - return n, err -} - -// BackupFileReader provides an io.ReadCloser interface on top of the BackupRead Win32 API. -type BackupFileReader struct { - f *os.File - includeSecurity bool - ctx uintptr -} - -// NewBackupFileReader returns a new BackupFileReader from a file handle. If includeSecurity is true, -// Read will attempt to read the security descriptor of the file. -func NewBackupFileReader(f *os.File, includeSecurity bool) *BackupFileReader { - r := &BackupFileReader{f, includeSecurity, 0} - return r -} - -// Read reads a backup stream from the file by calling the Win32 API BackupRead(). -func (r *BackupFileReader) Read(b []byte) (int, error) { - var bytesRead uint32 - err := backupRead(syscall.Handle(r.f.Fd()), b, &bytesRead, false, r.includeSecurity, &r.ctx) - if err != nil { - return 0, &os.PathError{Op: "BackupRead", Path: r.f.Name(), Err: err} - } - runtime.KeepAlive(r.f) - if bytesRead == 0 { - return 0, io.EOF - } - return int(bytesRead), nil -} - -// Close frees Win32 resources associated with the BackupFileReader. It does not close -// the underlying file. -func (r *BackupFileReader) Close() error { - if r.ctx != 0 { - _ = backupRead(syscall.Handle(r.f.Fd()), nil, nil, true, false, &r.ctx) - runtime.KeepAlive(r.f) - r.ctx = 0 - } - return nil -} - -// BackupFileWriter provides an io.WriteCloser interface on top of the BackupWrite Win32 API. -type BackupFileWriter struct { - f *os.File - includeSecurity bool - ctx uintptr -} - -// NewBackupFileWriter returns a new BackupFileWriter from a file handle. If includeSecurity is true, -// Write() will attempt to restore the security descriptor from the stream. -func NewBackupFileWriter(f *os.File, includeSecurity bool) *BackupFileWriter { - w := &BackupFileWriter{f, includeSecurity, 0} - return w -} - -// Write restores a portion of the file using the provided backup stream. -func (w *BackupFileWriter) Write(b []byte) (int, error) { - var bytesWritten uint32 - err := backupWrite(syscall.Handle(w.f.Fd()), b, &bytesWritten, false, w.includeSecurity, &w.ctx) - if err != nil { - return 0, &os.PathError{Op: "BackupWrite", Path: w.f.Name(), Err: err} - } - runtime.KeepAlive(w.f) - if int(bytesWritten) != len(b) { - return int(bytesWritten), errors.New("not all bytes could be written") - } - return len(b), nil -} - -// Close frees Win32 resources associated with the BackupFileWriter. It does not -// close the underlying file. -func (w *BackupFileWriter) Close() error { - if w.ctx != 0 { - _ = backupWrite(syscall.Handle(w.f.Fd()), nil, nil, true, false, &w.ctx) - runtime.KeepAlive(w.f) - w.ctx = 0 - } - return nil -} - -// OpenForBackup opens a file or directory, potentially skipping access checks if the backup -// or restore privileges have been acquired. -// -// If the file opened was a directory, it cannot be used with Readdir(). -func OpenForBackup(path string, access uint32, share uint32, createmode uint32) (*os.File, error) { - winPath, err := syscall.UTF16FromString(path) - if err != nil { - return nil, err - } - h, err := syscall.CreateFile(&winPath[0], - access, - share, - nil, - createmode, - syscall.FILE_FLAG_BACKUP_SEMANTICS|syscall.FILE_FLAG_OPEN_REPARSE_POINT, - 0) - if err != nil { - err = &os.PathError{Op: "open", Path: path, Err: err} - return nil, err - } - return os.NewFile(uintptr(h), path), nil -} diff --git a/vendor/github.com/Microsoft/go-winio/doc.go b/vendor/github.com/Microsoft/go-winio/doc.go deleted file mode 100644 index 1f5bfe2d5..000000000 --- a/vendor/github.com/Microsoft/go-winio/doc.go +++ /dev/null @@ -1,22 +0,0 @@ -// This package provides utilities for efficiently performing Win32 IO operations in Go. -// Currently, this package is provides support for genreal IO and management of -// - named pipes -// - files -// - [Hyper-V sockets] -// -// This code is similar to Go's [net] package, and uses IO completion ports to avoid -// blocking IO on system threads, allowing Go to reuse the thread to schedule other goroutines. -// -// This limits support to Windows Vista and newer operating systems. -// -// Additionally, this package provides support for: -// - creating and managing GUIDs -// - writing to [ETW] -// - opening and manageing VHDs -// - parsing [Windows Image files] -// - auto-generating Win32 API code -// -// [Hyper-V sockets]: https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/user-guide/make-integration-service -// [ETW]: https://docs.microsoft.com/en-us/windows-hardware/drivers/devtest/event-tracing-for-windows--etw- -// [Windows Image files]: https://docs.microsoft.com/en-us/windows-hardware/manufacture/desktop/work-with-windows-images -package winio diff --git a/vendor/github.com/Microsoft/go-winio/ea.go b/vendor/github.com/Microsoft/go-winio/ea.go deleted file mode 100644 index e104dbdfd..000000000 --- a/vendor/github.com/Microsoft/go-winio/ea.go +++ /dev/null @@ -1,137 +0,0 @@ -package winio - -import ( - "bytes" - "encoding/binary" - "errors" -) - -type fileFullEaInformation struct { - NextEntryOffset uint32 - Flags uint8 - NameLength uint8 - ValueLength uint16 -} - -var ( - fileFullEaInformationSize = binary.Size(&fileFullEaInformation{}) - - errInvalidEaBuffer = errors.New("invalid extended attribute buffer") - errEaNameTooLarge = errors.New("extended attribute name too large") - errEaValueTooLarge = errors.New("extended attribute value too large") -) - -// ExtendedAttribute represents a single Windows EA. -type ExtendedAttribute struct { - Name string - Value []byte - Flags uint8 -} - -func parseEa(b []byte) (ea ExtendedAttribute, nb []byte, err error) { - var info fileFullEaInformation - err = binary.Read(bytes.NewReader(b), binary.LittleEndian, &info) - if err != nil { - err = errInvalidEaBuffer - return ea, nb, err - } - - nameOffset := fileFullEaInformationSize - nameLen := int(info.NameLength) - valueOffset := nameOffset + int(info.NameLength) + 1 - valueLen := int(info.ValueLength) - nextOffset := int(info.NextEntryOffset) - if valueLen+valueOffset > len(b) || nextOffset < 0 || nextOffset > len(b) { - err = errInvalidEaBuffer - return ea, nb, err - } - - ea.Name = string(b[nameOffset : nameOffset+nameLen]) - ea.Value = b[valueOffset : valueOffset+valueLen] - ea.Flags = info.Flags - if info.NextEntryOffset != 0 { - nb = b[info.NextEntryOffset:] - } - return ea, nb, err -} - -// DecodeExtendedAttributes decodes a list of EAs from a FILE_FULL_EA_INFORMATION -// buffer retrieved from BackupRead, ZwQueryEaFile, etc. -func DecodeExtendedAttributes(b []byte) (eas []ExtendedAttribute, err error) { - for len(b) != 0 { - ea, nb, err := parseEa(b) - if err != nil { - return nil, err - } - - eas = append(eas, ea) - b = nb - } - return eas, err -} - -func writeEa(buf *bytes.Buffer, ea *ExtendedAttribute, last bool) error { - if int(uint8(len(ea.Name))) != len(ea.Name) { - return errEaNameTooLarge - } - if int(uint16(len(ea.Value))) != len(ea.Value) { - return errEaValueTooLarge - } - entrySize := uint32(fileFullEaInformationSize + len(ea.Name) + 1 + len(ea.Value)) - withPadding := (entrySize + 3) &^ 3 - nextOffset := uint32(0) - if !last { - nextOffset = withPadding - } - info := fileFullEaInformation{ - NextEntryOffset: nextOffset, - Flags: ea.Flags, - NameLength: uint8(len(ea.Name)), - ValueLength: uint16(len(ea.Value)), - } - - err := binary.Write(buf, binary.LittleEndian, &info) - if err != nil { - return err - } - - _, err = buf.Write([]byte(ea.Name)) - if err != nil { - return err - } - - err = buf.WriteByte(0) - if err != nil { - return err - } - - _, err = buf.Write(ea.Value) - if err != nil { - return err - } - - _, err = buf.Write([]byte{0, 0, 0}[0 : withPadding-entrySize]) - if err != nil { - return err - } - - return nil -} - -// EncodeExtendedAttributes encodes a list of EAs into a FILE_FULL_EA_INFORMATION -// buffer for use with BackupWrite, ZwSetEaFile, etc. -func EncodeExtendedAttributes(eas []ExtendedAttribute) ([]byte, error) { - var buf bytes.Buffer - for i := range eas { - last := false - if i == len(eas)-1 { - last = true - } - - err := writeEa(&buf, &eas[i], last) - if err != nil { - return nil, err - } - } - return buf.Bytes(), nil -} diff --git a/vendor/github.com/Microsoft/go-winio/file.go b/vendor/github.com/Microsoft/go-winio/file.go deleted file mode 100644 index 175a99d3f..000000000 --- a/vendor/github.com/Microsoft/go-winio/file.go +++ /dev/null @@ -1,331 +0,0 @@ -//go:build windows -// +build windows - -package winio - -import ( - "errors" - "io" - "runtime" - "sync" - "sync/atomic" - "syscall" - "time" - - "golang.org/x/sys/windows" -) - -//sys cancelIoEx(file syscall.Handle, o *syscall.Overlapped) (err error) = CancelIoEx -//sys createIoCompletionPort(file syscall.Handle, port syscall.Handle, key uintptr, threadCount uint32) (newport syscall.Handle, err error) = CreateIoCompletionPort -//sys getQueuedCompletionStatus(port syscall.Handle, bytes *uint32, key *uintptr, o **ioOperation, timeout uint32) (err error) = GetQueuedCompletionStatus -//sys setFileCompletionNotificationModes(h syscall.Handle, flags uint8) (err error) = SetFileCompletionNotificationModes -//sys wsaGetOverlappedResult(h syscall.Handle, o *syscall.Overlapped, bytes *uint32, wait bool, flags *uint32) (err error) = ws2_32.WSAGetOverlappedResult - -type atomicBool int32 - -func (b *atomicBool) isSet() bool { return atomic.LoadInt32((*int32)(b)) != 0 } -func (b *atomicBool) setFalse() { atomic.StoreInt32((*int32)(b), 0) } -func (b *atomicBool) setTrue() { atomic.StoreInt32((*int32)(b), 1) } - -//revive:disable-next-line:predeclared Keep "new" to maintain consistency with "atomic" pkg -func (b *atomicBool) swap(new bool) bool { - var newInt int32 - if new { - newInt = 1 - } - return atomic.SwapInt32((*int32)(b), newInt) == 1 -} - -var ( - ErrFileClosed = errors.New("file has already been closed") - ErrTimeout = &timeoutError{} -) - -type timeoutError struct{} - -func (*timeoutError) Error() string { return "i/o timeout" } -func (*timeoutError) Timeout() bool { return true } -func (*timeoutError) Temporary() bool { return true } - -type timeoutChan chan struct{} - -var ioInitOnce sync.Once -var ioCompletionPort syscall.Handle - -// ioResult contains the result of an asynchronous IO operation. -type ioResult struct { - bytes uint32 - err error -} - -// ioOperation represents an outstanding asynchronous Win32 IO. -type ioOperation struct { - o syscall.Overlapped - ch chan ioResult -} - -func initIO() { - h, err := createIoCompletionPort(syscall.InvalidHandle, 0, 0, 0xffffffff) - if err != nil { - panic(err) - } - ioCompletionPort = h - go ioCompletionProcessor(h) -} - -// win32File implements Reader, Writer, and Closer on a Win32 handle without blocking in a syscall. -// It takes ownership of this handle and will close it if it is garbage collected. -type win32File struct { - handle syscall.Handle - wg sync.WaitGroup - wgLock sync.RWMutex - closing atomicBool - socket bool - readDeadline deadlineHandler - writeDeadline deadlineHandler -} - -type deadlineHandler struct { - setLock sync.Mutex - channel timeoutChan - channelLock sync.RWMutex - timer *time.Timer - timedout atomicBool -} - -// makeWin32File makes a new win32File from an existing file handle. -func makeWin32File(h syscall.Handle) (*win32File, error) { - f := &win32File{handle: h} - ioInitOnce.Do(initIO) - _, err := createIoCompletionPort(h, ioCompletionPort, 0, 0xffffffff) - if err != nil { - return nil, err - } - err = setFileCompletionNotificationModes(h, windows.FILE_SKIP_COMPLETION_PORT_ON_SUCCESS|windows.FILE_SKIP_SET_EVENT_ON_HANDLE) - if err != nil { - return nil, err - } - f.readDeadline.channel = make(timeoutChan) - f.writeDeadline.channel = make(timeoutChan) - return f, nil -} - -func MakeOpenFile(h syscall.Handle) (io.ReadWriteCloser, error) { - // If we return the result of makeWin32File directly, it can result in an - // interface-wrapped nil, rather than a nil interface value. - f, err := makeWin32File(h) - if err != nil { - return nil, err - } - return f, nil -} - -// closeHandle closes the resources associated with a Win32 handle. -func (f *win32File) closeHandle() { - f.wgLock.Lock() - // Atomically set that we are closing, releasing the resources only once. - if !f.closing.swap(true) { - f.wgLock.Unlock() - // cancel all IO and wait for it to complete - _ = cancelIoEx(f.handle, nil) - f.wg.Wait() - // at this point, no new IO can start - syscall.Close(f.handle) - f.handle = 0 - } else { - f.wgLock.Unlock() - } -} - -// Close closes a win32File. -func (f *win32File) Close() error { - f.closeHandle() - return nil -} - -// IsClosed checks if the file has been closed. -func (f *win32File) IsClosed() bool { - return f.closing.isSet() -} - -// prepareIO prepares for a new IO operation. -// The caller must call f.wg.Done() when the IO is finished, prior to Close() returning. -func (f *win32File) prepareIO() (*ioOperation, error) { - f.wgLock.RLock() - if f.closing.isSet() { - f.wgLock.RUnlock() - return nil, ErrFileClosed - } - f.wg.Add(1) - f.wgLock.RUnlock() - c := &ioOperation{} - c.ch = make(chan ioResult) - return c, nil -} - -// ioCompletionProcessor processes completed async IOs forever. -func ioCompletionProcessor(h syscall.Handle) { - for { - var bytes uint32 - var key uintptr - var op *ioOperation - err := getQueuedCompletionStatus(h, &bytes, &key, &op, syscall.INFINITE) - if op == nil { - panic(err) - } - op.ch <- ioResult{bytes, err} - } -} - -// todo: helsaawy - create an asyncIO version that takes a context - -// asyncIO processes the return value from ReadFile or WriteFile, blocking until -// the operation has actually completed. -func (f *win32File) asyncIO(c *ioOperation, d *deadlineHandler, bytes uint32, err error) (int, error) { - if err != syscall.ERROR_IO_PENDING { //nolint:errorlint // err is Errno - return int(bytes), err - } - - if f.closing.isSet() { - _ = cancelIoEx(f.handle, &c.o) - } - - var timeout timeoutChan - if d != nil { - d.channelLock.Lock() - timeout = d.channel - d.channelLock.Unlock() - } - - var r ioResult - select { - case r = <-c.ch: - err = r.err - if err == syscall.ERROR_OPERATION_ABORTED { //nolint:errorlint // err is Errno - if f.closing.isSet() { - err = ErrFileClosed - } - } else if err != nil && f.socket { - // err is from Win32. Query the overlapped structure to get the winsock error. - var bytes, flags uint32 - err = wsaGetOverlappedResult(f.handle, &c.o, &bytes, false, &flags) - } - case <-timeout: - _ = cancelIoEx(f.handle, &c.o) - r = <-c.ch - err = r.err - if err == syscall.ERROR_OPERATION_ABORTED { //nolint:errorlint // err is Errno - err = ErrTimeout - } - } - - // runtime.KeepAlive is needed, as c is passed via native - // code to ioCompletionProcessor, c must remain alive - // until the channel read is complete. - // todo: (de)allocate *ioOperation via win32 heap functions, instead of needing to KeepAlive? - runtime.KeepAlive(c) - return int(r.bytes), err -} - -// Read reads from a file handle. -func (f *win32File) Read(b []byte) (int, error) { - c, err := f.prepareIO() - if err != nil { - return 0, err - } - defer f.wg.Done() - - if f.readDeadline.timedout.isSet() { - return 0, ErrTimeout - } - - var bytes uint32 - err = syscall.ReadFile(f.handle, b, &bytes, &c.o) - n, err := f.asyncIO(c, &f.readDeadline, bytes, err) - runtime.KeepAlive(b) - - // Handle EOF conditions. - if err == nil && n == 0 && len(b) != 0 { - return 0, io.EOF - } else if err == syscall.ERROR_BROKEN_PIPE { //nolint:errorlint // err is Errno - return 0, io.EOF - } else { - return n, err - } -} - -// Write writes to a file handle. -func (f *win32File) Write(b []byte) (int, error) { - c, err := f.prepareIO() - if err != nil { - return 0, err - } - defer f.wg.Done() - - if f.writeDeadline.timedout.isSet() { - return 0, ErrTimeout - } - - var bytes uint32 - err = syscall.WriteFile(f.handle, b, &bytes, &c.o) - n, err := f.asyncIO(c, &f.writeDeadline, bytes, err) - runtime.KeepAlive(b) - return n, err -} - -func (f *win32File) SetReadDeadline(deadline time.Time) error { - return f.readDeadline.set(deadline) -} - -func (f *win32File) SetWriteDeadline(deadline time.Time) error { - return f.writeDeadline.set(deadline) -} - -func (f *win32File) Flush() error { - return syscall.FlushFileBuffers(f.handle) -} - -func (f *win32File) Fd() uintptr { - return uintptr(f.handle) -} - -func (d *deadlineHandler) set(deadline time.Time) error { - d.setLock.Lock() - defer d.setLock.Unlock() - - if d.timer != nil { - if !d.timer.Stop() { - <-d.channel - } - d.timer = nil - } - d.timedout.setFalse() - - select { - case <-d.channel: - d.channelLock.Lock() - d.channel = make(chan struct{}) - d.channelLock.Unlock() - default: - } - - if deadline.IsZero() { - return nil - } - - timeoutIO := func() { - d.timedout.setTrue() - close(d.channel) - } - - now := time.Now() - duration := deadline.Sub(now) - if deadline.After(now) { - // Deadline is in the future, set a timer to wait - d.timer = time.AfterFunc(duration, timeoutIO) - } else { - // Deadline is in the past. Cancel all pending IO now. - timeoutIO() - } - return nil -} diff --git a/vendor/github.com/Microsoft/go-winio/fileinfo.go b/vendor/github.com/Microsoft/go-winio/fileinfo.go deleted file mode 100644 index 702950e72..000000000 --- a/vendor/github.com/Microsoft/go-winio/fileinfo.go +++ /dev/null @@ -1,92 +0,0 @@ -//go:build windows -// +build windows - -package winio - -import ( - "os" - "runtime" - "unsafe" - - "golang.org/x/sys/windows" -) - -// FileBasicInfo contains file access time and file attributes information. -type FileBasicInfo struct { - CreationTime, LastAccessTime, LastWriteTime, ChangeTime windows.Filetime - FileAttributes uint32 - _ uint32 // padding -} - -// GetFileBasicInfo retrieves times and attributes for a file. -func GetFileBasicInfo(f *os.File) (*FileBasicInfo, error) { - bi := &FileBasicInfo{} - if err := windows.GetFileInformationByHandleEx( - windows.Handle(f.Fd()), - windows.FileBasicInfo, - (*byte)(unsafe.Pointer(bi)), - uint32(unsafe.Sizeof(*bi)), - ); err != nil { - return nil, &os.PathError{Op: "GetFileInformationByHandleEx", Path: f.Name(), Err: err} - } - runtime.KeepAlive(f) - return bi, nil -} - -// SetFileBasicInfo sets times and attributes for a file. -func SetFileBasicInfo(f *os.File, bi *FileBasicInfo) error { - if err := windows.SetFileInformationByHandle( - windows.Handle(f.Fd()), - windows.FileBasicInfo, - (*byte)(unsafe.Pointer(bi)), - uint32(unsafe.Sizeof(*bi)), - ); err != nil { - return &os.PathError{Op: "SetFileInformationByHandle", Path: f.Name(), Err: err} - } - runtime.KeepAlive(f) - return nil -} - -// FileStandardInfo contains extended information for the file. -// FILE_STANDARD_INFO in WinBase.h -// https://docs.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-file_standard_info -type FileStandardInfo struct { - AllocationSize, EndOfFile int64 - NumberOfLinks uint32 - DeletePending, Directory bool -} - -// GetFileStandardInfo retrieves ended information for the file. -func GetFileStandardInfo(f *os.File) (*FileStandardInfo, error) { - si := &FileStandardInfo{} - if err := windows.GetFileInformationByHandleEx(windows.Handle(f.Fd()), - windows.FileStandardInfo, - (*byte)(unsafe.Pointer(si)), - uint32(unsafe.Sizeof(*si))); err != nil { - return nil, &os.PathError{Op: "GetFileInformationByHandleEx", Path: f.Name(), Err: err} - } - runtime.KeepAlive(f) - return si, nil -} - -// FileIDInfo contains the volume serial number and file ID for a file. This pair should be -// unique on a system. -type FileIDInfo struct { - VolumeSerialNumber uint64 - FileID [16]byte -} - -// GetFileID retrieves the unique (volume, file ID) pair for a file. -func GetFileID(f *os.File) (*FileIDInfo, error) { - fileID := &FileIDInfo{} - if err := windows.GetFileInformationByHandleEx( - windows.Handle(f.Fd()), - windows.FileIdInfo, - (*byte)(unsafe.Pointer(fileID)), - uint32(unsafe.Sizeof(*fileID)), - ); err != nil { - return nil, &os.PathError{Op: "GetFileInformationByHandleEx", Path: f.Name(), Err: err} - } - runtime.KeepAlive(f) - return fileID, nil -} diff --git a/vendor/github.com/Microsoft/go-winio/hvsock.go b/vendor/github.com/Microsoft/go-winio/hvsock.go deleted file mode 100644 index c88191658..000000000 --- a/vendor/github.com/Microsoft/go-winio/hvsock.go +++ /dev/null @@ -1,575 +0,0 @@ -//go:build windows -// +build windows - -package winio - -import ( - "context" - "errors" - "fmt" - "io" - "net" - "os" - "syscall" - "time" - "unsafe" - - "golang.org/x/sys/windows" - - "github.com/Microsoft/go-winio/internal/socket" - "github.com/Microsoft/go-winio/pkg/guid" -) - -const afHVSock = 34 // AF_HYPERV - -// Well known Service and VM IDs -// https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/user-guide/make-integration-service#vmid-wildcards - -// HvsockGUIDWildcard is the wildcard VmId for accepting connections from all partitions. -func HvsockGUIDWildcard() guid.GUID { // 00000000-0000-0000-0000-000000000000 - return guid.GUID{} -} - -// HvsockGUIDBroadcast is the wildcard VmId for broadcasting sends to all partitions. -func HvsockGUIDBroadcast() guid.GUID { // ffffffff-ffff-ffff-ffff-ffffffffffff - return guid.GUID{ - Data1: 0xffffffff, - Data2: 0xffff, - Data3: 0xffff, - Data4: [8]uint8{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, - } -} - -// HvsockGUIDLoopback is the Loopback VmId for accepting connections to the same partition as the connector. -func HvsockGUIDLoopback() guid.GUID { // e0e16197-dd56-4a10-9195-5ee7a155a838 - return guid.GUID{ - Data1: 0xe0e16197, - Data2: 0xdd56, - Data3: 0x4a10, - Data4: [8]uint8{0x91, 0x95, 0x5e, 0xe7, 0xa1, 0x55, 0xa8, 0x38}, - } -} - -// HvsockGUIDSiloHost is the address of a silo's host partition: -// - The silo host of a hosted silo is the utility VM. -// - The silo host of a silo on a physical host is the physical host. -func HvsockGUIDSiloHost() guid.GUID { // 36bd0c5c-7276-4223-88ba-7d03b654c568 - return guid.GUID{ - Data1: 0x36bd0c5c, - Data2: 0x7276, - Data3: 0x4223, - Data4: [8]byte{0x88, 0xba, 0x7d, 0x03, 0xb6, 0x54, 0xc5, 0x68}, - } -} - -// HvsockGUIDChildren is the wildcard VmId for accepting connections from the connector's child partitions. -func HvsockGUIDChildren() guid.GUID { // 90db8b89-0d35-4f79-8ce9-49ea0ac8b7cd - return guid.GUID{ - Data1: 0x90db8b89, - Data2: 0xd35, - Data3: 0x4f79, - Data4: [8]uint8{0x8c, 0xe9, 0x49, 0xea, 0xa, 0xc8, 0xb7, 0xcd}, - } -} - -// HvsockGUIDParent is the wildcard VmId for accepting connections from the connector's parent partition. -// Listening on this VmId accepts connection from: -// - Inside silos: silo host partition. -// - Inside hosted silo: host of the VM. -// - Inside VM: VM host. -// - Physical host: Not supported. -func HvsockGUIDParent() guid.GUID { // a42e7cda-d03f-480c-9cc2-a4de20abb878 - return guid.GUID{ - Data1: 0xa42e7cda, - Data2: 0xd03f, - Data3: 0x480c, - Data4: [8]uint8{0x9c, 0xc2, 0xa4, 0xde, 0x20, 0xab, 0xb8, 0x78}, - } -} - -// hvsockVsockServiceTemplate is the Service GUID used for the VSOCK protocol. -func hvsockVsockServiceTemplate() guid.GUID { // 00000000-facb-11e6-bd58-64006a7986d3 - return guid.GUID{ - Data2: 0xfacb, - Data3: 0x11e6, - Data4: [8]uint8{0xbd, 0x58, 0x64, 0x00, 0x6a, 0x79, 0x86, 0xd3}, - } -} - -// An HvsockAddr is an address for a AF_HYPERV socket. -type HvsockAddr struct { - VMID guid.GUID - ServiceID guid.GUID -} - -type rawHvsockAddr struct { - Family uint16 - _ uint16 - VMID guid.GUID - ServiceID guid.GUID -} - -var _ socket.RawSockaddr = &rawHvsockAddr{} - -// Network returns the address's network name, "hvsock". -func (*HvsockAddr) Network() string { - return "hvsock" -} - -func (addr *HvsockAddr) String() string { - return fmt.Sprintf("%s:%s", &addr.VMID, &addr.ServiceID) -} - -// VsockServiceID returns an hvsock service ID corresponding to the specified AF_VSOCK port. -func VsockServiceID(port uint32) guid.GUID { - g := hvsockVsockServiceTemplate() // make a copy - g.Data1 = port - return g -} - -func (addr *HvsockAddr) raw() rawHvsockAddr { - return rawHvsockAddr{ - Family: afHVSock, - VMID: addr.VMID, - ServiceID: addr.ServiceID, - } -} - -func (addr *HvsockAddr) fromRaw(raw *rawHvsockAddr) { - addr.VMID = raw.VMID - addr.ServiceID = raw.ServiceID -} - -// Sockaddr returns a pointer to and the size of this struct. -// -// Implements the [socket.RawSockaddr] interface, and allows use in -// [socket.Bind] and [socket.ConnectEx]. -func (r *rawHvsockAddr) Sockaddr() (unsafe.Pointer, int32, error) { - return unsafe.Pointer(r), int32(unsafe.Sizeof(rawHvsockAddr{})), nil -} - -// Sockaddr interface allows use with `sockets.Bind()` and `.ConnectEx()`. -func (r *rawHvsockAddr) FromBytes(b []byte) error { - n := int(unsafe.Sizeof(rawHvsockAddr{})) - - if len(b) < n { - return fmt.Errorf("got %d, want %d: %w", len(b), n, socket.ErrBufferSize) - } - - copy(unsafe.Slice((*byte)(unsafe.Pointer(r)), n), b[:n]) - if r.Family != afHVSock { - return fmt.Errorf("got %d, want %d: %w", r.Family, afHVSock, socket.ErrAddrFamily) - } - - return nil -} - -// HvsockListener is a socket listener for the AF_HYPERV address family. -type HvsockListener struct { - sock *win32File - addr HvsockAddr -} - -var _ net.Listener = &HvsockListener{} - -// HvsockConn is a connected socket of the AF_HYPERV address family. -type HvsockConn struct { - sock *win32File - local, remote HvsockAddr -} - -var _ net.Conn = &HvsockConn{} - -func newHVSocket() (*win32File, error) { - fd, err := syscall.Socket(afHVSock, syscall.SOCK_STREAM, 1) - if err != nil { - return nil, os.NewSyscallError("socket", err) - } - f, err := makeWin32File(fd) - if err != nil { - syscall.Close(fd) - return nil, err - } - f.socket = true - return f, nil -} - -// ListenHvsock listens for connections on the specified hvsock address. -func ListenHvsock(addr *HvsockAddr) (_ *HvsockListener, err error) { - l := &HvsockListener{addr: *addr} - sock, err := newHVSocket() - if err != nil { - return nil, l.opErr("listen", err) - } - sa := addr.raw() - err = socket.Bind(windows.Handle(sock.handle), &sa) - if err != nil { - return nil, l.opErr("listen", os.NewSyscallError("socket", err)) - } - err = syscall.Listen(sock.handle, 16) - if err != nil { - return nil, l.opErr("listen", os.NewSyscallError("listen", err)) - } - return &HvsockListener{sock: sock, addr: *addr}, nil -} - -func (l *HvsockListener) opErr(op string, err error) error { - return &net.OpError{Op: op, Net: "hvsock", Addr: &l.addr, Err: err} -} - -// Addr returns the listener's network address. -func (l *HvsockListener) Addr() net.Addr { - return &l.addr -} - -// Accept waits for the next connection and returns it. -func (l *HvsockListener) Accept() (_ net.Conn, err error) { - sock, err := newHVSocket() - if err != nil { - return nil, l.opErr("accept", err) - } - defer func() { - if sock != nil { - sock.Close() - } - }() - c, err := l.sock.prepareIO() - if err != nil { - return nil, l.opErr("accept", err) - } - defer l.sock.wg.Done() - - // AcceptEx, per documentation, requires an extra 16 bytes per address. - // - // https://docs.microsoft.com/en-us/windows/win32/api/mswsock/nf-mswsock-acceptex - const addrlen = uint32(16 + unsafe.Sizeof(rawHvsockAddr{})) - var addrbuf [addrlen * 2]byte - - var bytes uint32 - err = syscall.AcceptEx(l.sock.handle, sock.handle, &addrbuf[0], 0 /* rxdatalen */, addrlen, addrlen, &bytes, &c.o) - if _, err = l.sock.asyncIO(c, nil, bytes, err); err != nil { - return nil, l.opErr("accept", os.NewSyscallError("acceptex", err)) - } - - conn := &HvsockConn{ - sock: sock, - } - // The local address returned in the AcceptEx buffer is the same as the Listener socket's - // address. However, the service GUID reported by GetSockName is different from the Listeners - // socket, and is sometimes the same as the local address of the socket that dialed the - // address, with the service GUID.Data1 incremented, but othertimes is different. - // todo: does the local address matter? is the listener's address or the actual address appropriate? - conn.local.fromRaw((*rawHvsockAddr)(unsafe.Pointer(&addrbuf[0]))) - conn.remote.fromRaw((*rawHvsockAddr)(unsafe.Pointer(&addrbuf[addrlen]))) - - // initialize the accepted socket and update its properties with those of the listening socket - if err = windows.Setsockopt(windows.Handle(sock.handle), - windows.SOL_SOCKET, windows.SO_UPDATE_ACCEPT_CONTEXT, - (*byte)(unsafe.Pointer(&l.sock.handle)), int32(unsafe.Sizeof(l.sock.handle))); err != nil { - return nil, conn.opErr("accept", os.NewSyscallError("setsockopt", err)) - } - - sock = nil - return conn, nil -} - -// Close closes the listener, causing any pending Accept calls to fail. -func (l *HvsockListener) Close() error { - return l.sock.Close() -} - -// HvsockDialer configures and dials a Hyper-V Socket (ie, [HvsockConn]). -type HvsockDialer struct { - // Deadline is the time the Dial operation must connect before erroring. - Deadline time.Time - - // Retries is the number of additional connects to try if the connection times out, is refused, - // or the host is unreachable - Retries uint - - // RetryWait is the time to wait after a connection error to retry - RetryWait time.Duration - - rt *time.Timer // redial wait timer -} - -// Dial the Hyper-V socket at addr. -// -// See [HvsockDialer.Dial] for more information. -func Dial(ctx context.Context, addr *HvsockAddr) (conn *HvsockConn, err error) { - return (&HvsockDialer{}).Dial(ctx, addr) -} - -// Dial attempts to connect to the Hyper-V socket at addr, and returns a connection if successful. -// Will attempt (HvsockDialer).Retries if dialing fails, waiting (HvsockDialer).RetryWait between -// retries. -// -// Dialing can be cancelled either by providing (HvsockDialer).Deadline, or cancelling ctx. -func (d *HvsockDialer) Dial(ctx context.Context, addr *HvsockAddr) (conn *HvsockConn, err error) { - op := "dial" - // create the conn early to use opErr() - conn = &HvsockConn{ - remote: *addr, - } - - if !d.Deadline.IsZero() { - var cancel context.CancelFunc - ctx, cancel = context.WithDeadline(ctx, d.Deadline) - defer cancel() - } - - // preemptive timeout/cancellation check - if err = ctx.Err(); err != nil { - return nil, conn.opErr(op, err) - } - - sock, err := newHVSocket() - if err != nil { - return nil, conn.opErr(op, err) - } - defer func() { - if sock != nil { - sock.Close() - } - }() - - sa := addr.raw() - err = socket.Bind(windows.Handle(sock.handle), &sa) - if err != nil { - return nil, conn.opErr(op, os.NewSyscallError("bind", err)) - } - - c, err := sock.prepareIO() - if err != nil { - return nil, conn.opErr(op, err) - } - defer sock.wg.Done() - var bytes uint32 - for i := uint(0); i <= d.Retries; i++ { - err = socket.ConnectEx( - windows.Handle(sock.handle), - &sa, - nil, // sendBuf - 0, // sendDataLen - &bytes, - (*windows.Overlapped)(unsafe.Pointer(&c.o))) - _, err = sock.asyncIO(c, nil, bytes, err) - if i < d.Retries && canRedial(err) { - if err = d.redialWait(ctx); err == nil { - continue - } - } - break - } - if err != nil { - return nil, conn.opErr(op, os.NewSyscallError("connectex", err)) - } - - // update the connection properties, so shutdown can be used - if err = windows.Setsockopt( - windows.Handle(sock.handle), - windows.SOL_SOCKET, - windows.SO_UPDATE_CONNECT_CONTEXT, - nil, // optvalue - 0, // optlen - ); err != nil { - return nil, conn.opErr(op, os.NewSyscallError("setsockopt", err)) - } - - // get the local name - var sal rawHvsockAddr - err = socket.GetSockName(windows.Handle(sock.handle), &sal) - if err != nil { - return nil, conn.opErr(op, os.NewSyscallError("getsockname", err)) - } - conn.local.fromRaw(&sal) - - // one last check for timeout, since asyncIO doesn't check the context - if err = ctx.Err(); err != nil { - return nil, conn.opErr(op, err) - } - - conn.sock = sock - sock = nil - - return conn, nil -} - -// redialWait waits before attempting to redial, resetting the timer as appropriate. -func (d *HvsockDialer) redialWait(ctx context.Context) (err error) { - if d.RetryWait == 0 { - return nil - } - - if d.rt == nil { - d.rt = time.NewTimer(d.RetryWait) - } else { - // should already be stopped and drained - d.rt.Reset(d.RetryWait) - } - - select { - case <-ctx.Done(): - case <-d.rt.C: - return nil - } - - // stop and drain the timer - if !d.rt.Stop() { - <-d.rt.C - } - return ctx.Err() -} - -// assumes error is a plain, unwrapped syscall.Errno provided by direct syscall. -func canRedial(err error) bool { - //nolint:errorlint // guaranteed to be an Errno - switch err { - case windows.WSAECONNREFUSED, windows.WSAENETUNREACH, windows.WSAETIMEDOUT, - windows.ERROR_CONNECTION_REFUSED, windows.ERROR_CONNECTION_UNAVAIL: - return true - default: - return false - } -} - -func (conn *HvsockConn) opErr(op string, err error) error { - // translate from "file closed" to "socket closed" - if errors.Is(err, ErrFileClosed) { - err = socket.ErrSocketClosed - } - return &net.OpError{Op: op, Net: "hvsock", Source: &conn.local, Addr: &conn.remote, Err: err} -} - -func (conn *HvsockConn) Read(b []byte) (int, error) { - c, err := conn.sock.prepareIO() - if err != nil { - return 0, conn.opErr("read", err) - } - defer conn.sock.wg.Done() - buf := syscall.WSABuf{Buf: &b[0], Len: uint32(len(b))} - var flags, bytes uint32 - err = syscall.WSARecv(conn.sock.handle, &buf, 1, &bytes, &flags, &c.o, nil) - n, err := conn.sock.asyncIO(c, &conn.sock.readDeadline, bytes, err) - if err != nil { - var eno windows.Errno - if errors.As(err, &eno) { - err = os.NewSyscallError("wsarecv", eno) - } - return 0, conn.opErr("read", err) - } else if n == 0 { - err = io.EOF - } - return n, err -} - -func (conn *HvsockConn) Write(b []byte) (int, error) { - t := 0 - for len(b) != 0 { - n, err := conn.write(b) - if err != nil { - return t + n, err - } - t += n - b = b[n:] - } - return t, nil -} - -func (conn *HvsockConn) write(b []byte) (int, error) { - c, err := conn.sock.prepareIO() - if err != nil { - return 0, conn.opErr("write", err) - } - defer conn.sock.wg.Done() - buf := syscall.WSABuf{Buf: &b[0], Len: uint32(len(b))} - var bytes uint32 - err = syscall.WSASend(conn.sock.handle, &buf, 1, &bytes, 0, &c.o, nil) - n, err := conn.sock.asyncIO(c, &conn.sock.writeDeadline, bytes, err) - if err != nil { - var eno windows.Errno - if errors.As(err, &eno) { - err = os.NewSyscallError("wsasend", eno) - } - return 0, conn.opErr("write", err) - } - return n, err -} - -// Close closes the socket connection, failing any pending read or write calls. -func (conn *HvsockConn) Close() error { - return conn.sock.Close() -} - -func (conn *HvsockConn) IsClosed() bool { - return conn.sock.IsClosed() -} - -// shutdown disables sending or receiving on a socket. -func (conn *HvsockConn) shutdown(how int) error { - if conn.IsClosed() { - return socket.ErrSocketClosed - } - - err := syscall.Shutdown(conn.sock.handle, how) - if err != nil { - // If the connection was closed, shutdowns fail with "not connected" - if errors.Is(err, windows.WSAENOTCONN) || - errors.Is(err, windows.WSAESHUTDOWN) { - err = socket.ErrSocketClosed - } - return os.NewSyscallError("shutdown", err) - } - return nil -} - -// CloseRead shuts down the read end of the socket, preventing future read operations. -func (conn *HvsockConn) CloseRead() error { - err := conn.shutdown(syscall.SHUT_RD) - if err != nil { - return conn.opErr("closeread", err) - } - return nil -} - -// CloseWrite shuts down the write end of the socket, preventing future write operations and -// notifying the other endpoint that no more data will be written. -func (conn *HvsockConn) CloseWrite() error { - err := conn.shutdown(syscall.SHUT_WR) - if err != nil { - return conn.opErr("closewrite", err) - } - return nil -} - -// LocalAddr returns the local address of the connection. -func (conn *HvsockConn) LocalAddr() net.Addr { - return &conn.local -} - -// RemoteAddr returns the remote address of the connection. -func (conn *HvsockConn) RemoteAddr() net.Addr { - return &conn.remote -} - -// SetDeadline implements the net.Conn SetDeadline method. -func (conn *HvsockConn) SetDeadline(t time.Time) error { - // todo: implement `SetDeadline` for `win32File` - if err := conn.SetReadDeadline(t); err != nil { - return fmt.Errorf("set read deadline: %w", err) - } - if err := conn.SetWriteDeadline(t); err != nil { - return fmt.Errorf("set write deadline: %w", err) - } - return nil -} - -// SetReadDeadline implements the net.Conn SetReadDeadline method. -func (conn *HvsockConn) SetReadDeadline(t time.Time) error { - return conn.sock.SetReadDeadline(t) -} - -// SetWriteDeadline implements the net.Conn SetWriteDeadline method. -func (conn *HvsockConn) SetWriteDeadline(t time.Time) error { - return conn.sock.SetWriteDeadline(t) -} diff --git a/vendor/github.com/Microsoft/go-winio/internal/fs/doc.go b/vendor/github.com/Microsoft/go-winio/internal/fs/doc.go deleted file mode 100644 index 1f6538817..000000000 --- a/vendor/github.com/Microsoft/go-winio/internal/fs/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// This package contains Win32 filesystem functionality. -package fs diff --git a/vendor/github.com/Microsoft/go-winio/internal/fs/fs.go b/vendor/github.com/Microsoft/go-winio/internal/fs/fs.go deleted file mode 100644 index 509b3ec64..000000000 --- a/vendor/github.com/Microsoft/go-winio/internal/fs/fs.go +++ /dev/null @@ -1,202 +0,0 @@ -//go:build windows - -package fs - -import ( - "golang.org/x/sys/windows" - - "github.com/Microsoft/go-winio/internal/stringbuffer" -) - -//go:generate go run github.com/Microsoft/go-winio/tools/mkwinsyscall -output zsyscall_windows.go fs.go - -// https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew -//sys CreateFile(name string, access AccessMask, mode FileShareMode, sa *syscall.SecurityAttributes, createmode FileCreationDisposition, attrs FileFlagOrAttribute, templatefile windows.Handle) (handle windows.Handle, err error) [failretval==windows.InvalidHandle] = CreateFileW - -const NullHandle windows.Handle = 0 - -// AccessMask defines standard, specific, and generic rights. -// -// Bitmask: -// 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 -// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 -// +---------------+---------------+-------------------------------+ -// |G|G|G|G|Resvd|A| StandardRights| SpecificRights | -// |R|W|E|A| |S| | | -// +-+-------------+---------------+-------------------------------+ -// -// GR Generic Read -// GW Generic Write -// GE Generic Exectue -// GA Generic All -// Resvd Reserved -// AS Access Security System -// -// https://learn.microsoft.com/en-us/windows/win32/secauthz/access-mask -// -// https://learn.microsoft.com/en-us/windows/win32/secauthz/generic-access-rights -// -// https://learn.microsoft.com/en-us/windows/win32/fileio/file-access-rights-constants -type AccessMask = windows.ACCESS_MASK - -//nolint:revive // SNAKE_CASE is not idiomatic in Go, but aligned with Win32 API. -const ( - // Not actually any. - // - // For CreateFile: "query certain metadata such as file, directory, or device attributes without accessing that file or device" - // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew#parameters - FILE_ANY_ACCESS AccessMask = 0 - - // Specific Object Access - // from ntioapi.h - - FILE_READ_DATA AccessMask = (0x0001) // file & pipe - FILE_LIST_DIRECTORY AccessMask = (0x0001) // directory - - FILE_WRITE_DATA AccessMask = (0x0002) // file & pipe - FILE_ADD_FILE AccessMask = (0x0002) // directory - - FILE_APPEND_DATA AccessMask = (0x0004) // file - FILE_ADD_SUBDIRECTORY AccessMask = (0x0004) // directory - FILE_CREATE_PIPE_INSTANCE AccessMask = (0x0004) // named pipe - - FILE_READ_EA AccessMask = (0x0008) // file & directory - FILE_READ_PROPERTIES AccessMask = FILE_READ_EA - - FILE_WRITE_EA AccessMask = (0x0010) // file & directory - FILE_WRITE_PROPERTIES AccessMask = FILE_WRITE_EA - - FILE_EXECUTE AccessMask = (0x0020) // file - FILE_TRAVERSE AccessMask = (0x0020) // directory - - FILE_DELETE_CHILD AccessMask = (0x0040) // directory - - FILE_READ_ATTRIBUTES AccessMask = (0x0080) // all - - FILE_WRITE_ATTRIBUTES AccessMask = (0x0100) // all - - FILE_ALL_ACCESS AccessMask = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x1FF) - FILE_GENERIC_READ AccessMask = (STANDARD_RIGHTS_READ | FILE_READ_DATA | FILE_READ_ATTRIBUTES | FILE_READ_EA | SYNCHRONIZE) - FILE_GENERIC_WRITE AccessMask = (STANDARD_RIGHTS_WRITE | FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA | FILE_APPEND_DATA | SYNCHRONIZE) - FILE_GENERIC_EXECUTE AccessMask = (STANDARD_RIGHTS_EXECUTE | FILE_READ_ATTRIBUTES | FILE_EXECUTE | SYNCHRONIZE) - - SPECIFIC_RIGHTS_ALL AccessMask = 0x0000FFFF - - // Standard Access - // from ntseapi.h - - DELETE AccessMask = 0x0001_0000 - READ_CONTROL AccessMask = 0x0002_0000 - WRITE_DAC AccessMask = 0x0004_0000 - WRITE_OWNER AccessMask = 0x0008_0000 - SYNCHRONIZE AccessMask = 0x0010_0000 - - STANDARD_RIGHTS_REQUIRED AccessMask = 0x000F_0000 - - STANDARD_RIGHTS_READ AccessMask = READ_CONTROL - STANDARD_RIGHTS_WRITE AccessMask = READ_CONTROL - STANDARD_RIGHTS_EXECUTE AccessMask = READ_CONTROL - - STANDARD_RIGHTS_ALL AccessMask = 0x001F_0000 -) - -type FileShareMode uint32 - -//nolint:revive // SNAKE_CASE is not idiomatic in Go, but aligned with Win32 API. -const ( - FILE_SHARE_NONE FileShareMode = 0x00 - FILE_SHARE_READ FileShareMode = 0x01 - FILE_SHARE_WRITE FileShareMode = 0x02 - FILE_SHARE_DELETE FileShareMode = 0x04 - FILE_SHARE_VALID_FLAGS FileShareMode = 0x07 -) - -type FileCreationDisposition uint32 - -//nolint:revive // SNAKE_CASE is not idiomatic in Go, but aligned with Win32 API. -const ( - // from winbase.h - - CREATE_NEW FileCreationDisposition = 0x01 - CREATE_ALWAYS FileCreationDisposition = 0x02 - OPEN_EXISTING FileCreationDisposition = 0x03 - OPEN_ALWAYS FileCreationDisposition = 0x04 - TRUNCATE_EXISTING FileCreationDisposition = 0x05 -) - -// CreateFile and co. take flags or attributes together as one parameter. -// Define alias until we can use generics to allow both - -// https://learn.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants -type FileFlagOrAttribute uint32 - -//nolint:revive // SNAKE_CASE is not idiomatic in Go, but aligned with Win32 API. -const ( // from winnt.h - FILE_FLAG_WRITE_THROUGH FileFlagOrAttribute = 0x8000_0000 - FILE_FLAG_OVERLAPPED FileFlagOrAttribute = 0x4000_0000 - FILE_FLAG_NO_BUFFERING FileFlagOrAttribute = 0x2000_0000 - FILE_FLAG_RANDOM_ACCESS FileFlagOrAttribute = 0x1000_0000 - FILE_FLAG_SEQUENTIAL_SCAN FileFlagOrAttribute = 0x0800_0000 - FILE_FLAG_DELETE_ON_CLOSE FileFlagOrAttribute = 0x0400_0000 - FILE_FLAG_BACKUP_SEMANTICS FileFlagOrAttribute = 0x0200_0000 - FILE_FLAG_POSIX_SEMANTICS FileFlagOrAttribute = 0x0100_0000 - FILE_FLAG_OPEN_REPARSE_POINT FileFlagOrAttribute = 0x0020_0000 - FILE_FLAG_OPEN_NO_RECALL FileFlagOrAttribute = 0x0010_0000 - FILE_FLAG_FIRST_PIPE_INSTANCE FileFlagOrAttribute = 0x0008_0000 -) - -type FileSQSFlag = FileFlagOrAttribute - -//nolint:revive // SNAKE_CASE is not idiomatic in Go, but aligned with Win32 API. -const ( // from winbase.h - SECURITY_ANONYMOUS FileSQSFlag = FileSQSFlag(SecurityAnonymous << 16) - SECURITY_IDENTIFICATION FileSQSFlag = FileSQSFlag(SecurityIdentification << 16) - SECURITY_IMPERSONATION FileSQSFlag = FileSQSFlag(SecurityImpersonation << 16) - SECURITY_DELEGATION FileSQSFlag = FileSQSFlag(SecurityDelegation << 16) - - SECURITY_SQOS_PRESENT FileSQSFlag = 0x00100000 - SECURITY_VALID_SQOS_FLAGS FileSQSFlag = 0x001F0000 -) - -// GetFinalPathNameByHandle flags -// -// https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfinalpathnamebyhandlew#parameters -type GetFinalPathFlag uint32 - -//nolint:revive // SNAKE_CASE is not idiomatic in Go, but aligned with Win32 API. -const ( - GetFinalPathDefaultFlag GetFinalPathFlag = 0x0 - - FILE_NAME_NORMALIZED GetFinalPathFlag = 0x0 - FILE_NAME_OPENED GetFinalPathFlag = 0x8 - - VOLUME_NAME_DOS GetFinalPathFlag = 0x0 - VOLUME_NAME_GUID GetFinalPathFlag = 0x1 - VOLUME_NAME_NT GetFinalPathFlag = 0x2 - VOLUME_NAME_NONE GetFinalPathFlag = 0x4 -) - -// getFinalPathNameByHandle facilitates calling the Windows API GetFinalPathNameByHandle -// with the given handle and flags. It transparently takes care of creating a buffer of the -// correct size for the call. -// -// https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfinalpathnamebyhandlew -func GetFinalPathNameByHandle(h windows.Handle, flags GetFinalPathFlag) (string, error) { - b := stringbuffer.NewWString() - //TODO: can loop infinitely if Win32 keeps returning the same (or a larger) n? - for { - n, err := windows.GetFinalPathNameByHandle(h, b.Pointer(), b.Cap(), uint32(flags)) - if err != nil { - return "", err - } - // If the buffer wasn't large enough, n will be the total size needed (including null terminator). - // Resize and try again. - if n > b.Cap() { - b.ResizeTo(n) - continue - } - // If the buffer is large enough, n will be the size not including the null terminator. - // Convert to a Go string and return. - return b.String(), nil - } -} diff --git a/vendor/github.com/Microsoft/go-winio/internal/fs/security.go b/vendor/github.com/Microsoft/go-winio/internal/fs/security.go deleted file mode 100644 index 81760ac67..000000000 --- a/vendor/github.com/Microsoft/go-winio/internal/fs/security.go +++ /dev/null @@ -1,12 +0,0 @@ -package fs - -// https://learn.microsoft.com/en-us/windows/win32/api/winnt/ne-winnt-security_impersonation_level -type SecurityImpersonationLevel int32 // C default enums underlying type is `int`, which is Go `int32` - -// Impersonation levels -const ( - SecurityAnonymous SecurityImpersonationLevel = 0 - SecurityIdentification SecurityImpersonationLevel = 1 - SecurityImpersonation SecurityImpersonationLevel = 2 - SecurityDelegation SecurityImpersonationLevel = 3 -) diff --git a/vendor/github.com/Microsoft/go-winio/internal/fs/zsyscall_windows.go b/vendor/github.com/Microsoft/go-winio/internal/fs/zsyscall_windows.go deleted file mode 100644 index e2f7bb24e..000000000 --- a/vendor/github.com/Microsoft/go-winio/internal/fs/zsyscall_windows.go +++ /dev/null @@ -1,64 +0,0 @@ -//go:build windows - -// Code generated by 'go generate' using "github.com/Microsoft/go-winio/tools/mkwinsyscall"; DO NOT EDIT. - -package fs - -import ( - "syscall" - "unsafe" - - "golang.org/x/sys/windows" -) - -var _ unsafe.Pointer - -// Do the interface allocations only once for common -// Errno values. -const ( - errnoERROR_IO_PENDING = 997 -) - -var ( - errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) - errERROR_EINVAL error = syscall.EINVAL -) - -// errnoErr returns common boxed Errno values, to prevent -// allocations at runtime. -func errnoErr(e syscall.Errno) error { - switch e { - case 0: - return errERROR_EINVAL - case errnoERROR_IO_PENDING: - return errERROR_IO_PENDING - } - // TODO: add more here, after collecting data on the common - // error values see on Windows. (perhaps when running - // all.bat?) - return e -} - -var ( - modkernel32 = windows.NewLazySystemDLL("kernel32.dll") - - procCreateFileW = modkernel32.NewProc("CreateFileW") -) - -func CreateFile(name string, access AccessMask, mode FileShareMode, sa *syscall.SecurityAttributes, createmode FileCreationDisposition, attrs FileFlagOrAttribute, templatefile windows.Handle) (handle windows.Handle, err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(name) - if err != nil { - return - } - return _CreateFile(_p0, access, mode, sa, createmode, attrs, templatefile) -} - -func _CreateFile(name *uint16, access AccessMask, mode FileShareMode, sa *syscall.SecurityAttributes, createmode FileCreationDisposition, attrs FileFlagOrAttribute, templatefile windows.Handle) (handle windows.Handle, err error) { - r0, _, e1 := syscall.Syscall9(procCreateFileW.Addr(), 7, uintptr(unsafe.Pointer(name)), uintptr(access), uintptr(mode), uintptr(unsafe.Pointer(sa)), uintptr(createmode), uintptr(attrs), uintptr(templatefile), 0, 0) - handle = windows.Handle(r0) - if handle == windows.InvalidHandle { - err = errnoErr(e1) - } - return -} diff --git a/vendor/github.com/Microsoft/go-winio/internal/socket/rawaddr.go b/vendor/github.com/Microsoft/go-winio/internal/socket/rawaddr.go deleted file mode 100644 index 7e82f9afa..000000000 --- a/vendor/github.com/Microsoft/go-winio/internal/socket/rawaddr.go +++ /dev/null @@ -1,20 +0,0 @@ -package socket - -import ( - "unsafe" -) - -// RawSockaddr allows structs to be used with [Bind] and [ConnectEx]. The -// struct must meet the Win32 sockaddr requirements specified here: -// https://docs.microsoft.com/en-us/windows/win32/winsock/sockaddr-2 -// -// Specifically, the struct size must be least larger than an int16 (unsigned short) -// for the address family. -type RawSockaddr interface { - // Sockaddr returns a pointer to the RawSockaddr and its struct size, allowing - // for the RawSockaddr's data to be overwritten by syscalls (if necessary). - // - // It is the callers responsibility to validate that the values are valid; invalid - // pointers or size can cause a panic. - Sockaddr() (unsafe.Pointer, int32, error) -} diff --git a/vendor/github.com/Microsoft/go-winio/internal/socket/socket.go b/vendor/github.com/Microsoft/go-winio/internal/socket/socket.go deleted file mode 100644 index aeb7b7250..000000000 --- a/vendor/github.com/Microsoft/go-winio/internal/socket/socket.go +++ /dev/null @@ -1,179 +0,0 @@ -//go:build windows - -package socket - -import ( - "errors" - "fmt" - "net" - "sync" - "syscall" - "unsafe" - - "github.com/Microsoft/go-winio/pkg/guid" - "golang.org/x/sys/windows" -) - -//go:generate go run github.com/Microsoft/go-winio/tools/mkwinsyscall -output zsyscall_windows.go socket.go - -//sys getsockname(s windows.Handle, name unsafe.Pointer, namelen *int32) (err error) [failretval==socketError] = ws2_32.getsockname -//sys getpeername(s windows.Handle, name unsafe.Pointer, namelen *int32) (err error) [failretval==socketError] = ws2_32.getpeername -//sys bind(s windows.Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socketError] = ws2_32.bind - -const socketError = uintptr(^uint32(0)) - -var ( - // todo(helsaawy): create custom error types to store the desired vs actual size and addr family? - - ErrBufferSize = errors.New("buffer size") - ErrAddrFamily = errors.New("address family") - ErrInvalidPointer = errors.New("invalid pointer") - ErrSocketClosed = fmt.Errorf("socket closed: %w", net.ErrClosed) -) - -// todo(helsaawy): replace these with generics, ie: GetSockName[S RawSockaddr](s windows.Handle) (S, error) - -// GetSockName writes the local address of socket s to the [RawSockaddr] rsa. -// If rsa is not large enough, the [windows.WSAEFAULT] is returned. -func GetSockName(s windows.Handle, rsa RawSockaddr) error { - ptr, l, err := rsa.Sockaddr() - if err != nil { - return fmt.Errorf("could not retrieve socket pointer and size: %w", err) - } - - // although getsockname returns WSAEFAULT if the buffer is too small, it does not set - // &l to the correct size, so--apart from doubling the buffer repeatedly--there is no remedy - return getsockname(s, ptr, &l) -} - -// GetPeerName returns the remote address the socket is connected to. -// -// See [GetSockName] for more information. -func GetPeerName(s windows.Handle, rsa RawSockaddr) error { - ptr, l, err := rsa.Sockaddr() - if err != nil { - return fmt.Errorf("could not retrieve socket pointer and size: %w", err) - } - - return getpeername(s, ptr, &l) -} - -func Bind(s windows.Handle, rsa RawSockaddr) (err error) { - ptr, l, err := rsa.Sockaddr() - if err != nil { - return fmt.Errorf("could not retrieve socket pointer and size: %w", err) - } - - return bind(s, ptr, l) -} - -// "golang.org/x/sys/windows".ConnectEx and .Bind only accept internal implementations of the -// their sockaddr interface, so they cannot be used with HvsockAddr -// Replicate functionality here from -// https://cs.opensource.google/go/x/sys/+/master:windows/syscall_windows.go - -// The function pointers to `AcceptEx`, `ConnectEx` and `GetAcceptExSockaddrs` must be loaded at -// runtime via a WSAIoctl call: -// https://docs.microsoft.com/en-us/windows/win32/api/Mswsock/nc-mswsock-lpfn_connectex#remarks - -type runtimeFunc struct { - id guid.GUID - once sync.Once - addr uintptr - err error -} - -func (f *runtimeFunc) Load() error { - f.once.Do(func() { - var s windows.Handle - s, f.err = windows.Socket(windows.AF_INET, windows.SOCK_STREAM, windows.IPPROTO_TCP) - if f.err != nil { - return - } - defer windows.CloseHandle(s) //nolint:errcheck - - var n uint32 - f.err = windows.WSAIoctl(s, - windows.SIO_GET_EXTENSION_FUNCTION_POINTER, - (*byte)(unsafe.Pointer(&f.id)), - uint32(unsafe.Sizeof(f.id)), - (*byte)(unsafe.Pointer(&f.addr)), - uint32(unsafe.Sizeof(f.addr)), - &n, - nil, // overlapped - 0, // completionRoutine - ) - }) - return f.err -} - -var ( - // todo: add `AcceptEx` and `GetAcceptExSockaddrs` - WSAID_CONNECTEX = guid.GUID{ //revive:disable-line:var-naming ALL_CAPS - Data1: 0x25a207b9, - Data2: 0xddf3, - Data3: 0x4660, - Data4: [8]byte{0x8e, 0xe9, 0x76, 0xe5, 0x8c, 0x74, 0x06, 0x3e}, - } - - connectExFunc = runtimeFunc{id: WSAID_CONNECTEX} -) - -func ConnectEx( - fd windows.Handle, - rsa RawSockaddr, - sendBuf *byte, - sendDataLen uint32, - bytesSent *uint32, - overlapped *windows.Overlapped, -) error { - if err := connectExFunc.Load(); err != nil { - return fmt.Errorf("failed to load ConnectEx function pointer: %w", err) - } - ptr, n, err := rsa.Sockaddr() - if err != nil { - return err - } - return connectEx(fd, ptr, n, sendBuf, sendDataLen, bytesSent, overlapped) -} - -// BOOL LpfnConnectex( -// [in] SOCKET s, -// [in] const sockaddr *name, -// [in] int namelen, -// [in, optional] PVOID lpSendBuffer, -// [in] DWORD dwSendDataLength, -// [out] LPDWORD lpdwBytesSent, -// [in] LPOVERLAPPED lpOverlapped -// ) - -func connectEx( - s windows.Handle, - name unsafe.Pointer, - namelen int32, - sendBuf *byte, - sendDataLen uint32, - bytesSent *uint32, - overlapped *windows.Overlapped, -) (err error) { - // todo: after upgrading to 1.18, switch from syscall.Syscall9 to syscall.SyscallN - r1, _, e1 := syscall.Syscall9(connectExFunc.addr, - 7, - uintptr(s), - uintptr(name), - uintptr(namelen), - uintptr(unsafe.Pointer(sendBuf)), - uintptr(sendDataLen), - uintptr(unsafe.Pointer(bytesSent)), - uintptr(unsafe.Pointer(overlapped)), - 0, - 0) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return err -} diff --git a/vendor/github.com/Microsoft/go-winio/internal/socket/zsyscall_windows.go b/vendor/github.com/Microsoft/go-winio/internal/socket/zsyscall_windows.go deleted file mode 100644 index 6d2e1a9e4..000000000 --- a/vendor/github.com/Microsoft/go-winio/internal/socket/zsyscall_windows.go +++ /dev/null @@ -1,72 +0,0 @@ -//go:build windows - -// Code generated by 'go generate' using "github.com/Microsoft/go-winio/tools/mkwinsyscall"; DO NOT EDIT. - -package socket - -import ( - "syscall" - "unsafe" - - "golang.org/x/sys/windows" -) - -var _ unsafe.Pointer - -// Do the interface allocations only once for common -// Errno values. -const ( - errnoERROR_IO_PENDING = 997 -) - -var ( - errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) - errERROR_EINVAL error = syscall.EINVAL -) - -// errnoErr returns common boxed Errno values, to prevent -// allocations at runtime. -func errnoErr(e syscall.Errno) error { - switch e { - case 0: - return errERROR_EINVAL - case errnoERROR_IO_PENDING: - return errERROR_IO_PENDING - } - // TODO: add more here, after collecting data on the common - // error values see on Windows. (perhaps when running - // all.bat?) - return e -} - -var ( - modws2_32 = windows.NewLazySystemDLL("ws2_32.dll") - - procbind = modws2_32.NewProc("bind") - procgetpeername = modws2_32.NewProc("getpeername") - procgetsockname = modws2_32.NewProc("getsockname") -) - -func bind(s windows.Handle, name unsafe.Pointer, namelen int32) (err error) { - r1, _, e1 := syscall.Syscall(procbind.Addr(), 3, uintptr(s), uintptr(name), uintptr(namelen)) - if r1 == socketError { - err = errnoErr(e1) - } - return -} - -func getpeername(s windows.Handle, name unsafe.Pointer, namelen *int32) (err error) { - r1, _, e1 := syscall.Syscall(procgetpeername.Addr(), 3, uintptr(s), uintptr(name), uintptr(unsafe.Pointer(namelen))) - if r1 == socketError { - err = errnoErr(e1) - } - return -} - -func getsockname(s windows.Handle, name unsafe.Pointer, namelen *int32) (err error) { - r1, _, e1 := syscall.Syscall(procgetsockname.Addr(), 3, uintptr(s), uintptr(name), uintptr(unsafe.Pointer(namelen))) - if r1 == socketError { - err = errnoErr(e1) - } - return -} diff --git a/vendor/github.com/Microsoft/go-winio/internal/stringbuffer/wstring.go b/vendor/github.com/Microsoft/go-winio/internal/stringbuffer/wstring.go deleted file mode 100644 index 7ad505702..000000000 --- a/vendor/github.com/Microsoft/go-winio/internal/stringbuffer/wstring.go +++ /dev/null @@ -1,132 +0,0 @@ -package stringbuffer - -import ( - "sync" - "unicode/utf16" -) - -// TODO: worth exporting and using in mkwinsyscall? - -// Uint16BufferSize is the buffer size in the pool, chosen somewhat arbitrarily to accommodate -// large path strings: -// MAX_PATH (260) + size of volume GUID prefix (49) + null terminator = 310. -const MinWStringCap = 310 - -// use *[]uint16 since []uint16 creates an extra allocation where the slice header -// is copied to heap and then referenced via pointer in the interface header that sync.Pool -// stores. -var pathPool = sync.Pool{ // if go1.18+ adds Pool[T], use that to store []uint16 directly - New: func() interface{} { - b := make([]uint16, MinWStringCap) - return &b - }, -} - -func newBuffer() []uint16 { return *(pathPool.Get().(*[]uint16)) } - -// freeBuffer copies the slice header data, and puts a pointer to that in the pool. -// This avoids taking a pointer to the slice header in WString, which can be set to nil. -func freeBuffer(b []uint16) { pathPool.Put(&b) } - -// WString is a wide string buffer ([]uint16) meant for storing UTF-16 encoded strings -// for interacting with Win32 APIs. -// Sizes are specified as uint32 and not int. -// -// It is not thread safe. -type WString struct { - // type-def allows casting to []uint16 directly, use struct to prevent that and allow adding fields in the future. - - // raw buffer - b []uint16 -} - -// NewWString returns a [WString] allocated from a shared pool with an -// initial capacity of at least [MinWStringCap]. -// Since the buffer may have been previously used, its contents are not guaranteed to be empty. -// -// The buffer should be freed via [WString.Free] -func NewWString() *WString { - return &WString{ - b: newBuffer(), - } -} - -func (b *WString) Free() { - if b.empty() { - return - } - freeBuffer(b.b) - b.b = nil -} - -// ResizeTo grows the buffer to at least c and returns the new capacity, freeing the -// previous buffer back into pool. -func (b *WString) ResizeTo(c uint32) uint32 { - // allready sufficient (or n is 0) - if c <= b.Cap() { - return b.Cap() - } - - if c <= MinWStringCap { - c = MinWStringCap - } - // allocate at-least double buffer size, as is done in [bytes.Buffer] and other places - if c <= 2*b.Cap() { - c = 2 * b.Cap() - } - - b2 := make([]uint16, c) - if !b.empty() { - copy(b2, b.b) - freeBuffer(b.b) - } - b.b = b2 - return c -} - -// Buffer returns the underlying []uint16 buffer. -func (b *WString) Buffer() []uint16 { - if b.empty() { - return nil - } - return b.b -} - -// Pointer returns a pointer to the first uint16 in the buffer. -// If the [WString.Free] has already been called, the pointer will be nil. -func (b *WString) Pointer() *uint16 { - if b.empty() { - return nil - } - return &b.b[0] -} - -// String returns the returns the UTF-8 encoding of the UTF-16 string in the buffer. -// -// It assumes that the data is null-terminated. -func (b *WString) String() string { - // Using [windows.UTF16ToString] would require importing "golang.org/x/sys/windows" - // and would make this code Windows-only, which makes no sense. - // So copy UTF16ToString code into here. - // If other windows-specific code is added, switch to [windows.UTF16ToString] - - s := b.b - for i, v := range s { - if v == 0 { - s = s[:i] - break - } - } - return string(utf16.Decode(s)) -} - -// Cap returns the underlying buffer capacity. -func (b *WString) Cap() uint32 { - if b.empty() { - return 0 - } - return b.cap() -} - -func (b *WString) cap() uint32 { return uint32(cap(b.b)) } -func (b *WString) empty() bool { return b == nil || b.cap() == 0 } diff --git a/vendor/github.com/Microsoft/go-winio/pipe.go b/vendor/github.com/Microsoft/go-winio/pipe.go deleted file mode 100644 index 25cc81103..000000000 --- a/vendor/github.com/Microsoft/go-winio/pipe.go +++ /dev/null @@ -1,525 +0,0 @@ -//go:build windows -// +build windows - -package winio - -import ( - "context" - "errors" - "fmt" - "io" - "net" - "os" - "runtime" - "syscall" - "time" - "unsafe" - - "golang.org/x/sys/windows" - - "github.com/Microsoft/go-winio/internal/fs" -) - -//sys connectNamedPipe(pipe syscall.Handle, o *syscall.Overlapped) (err error) = ConnectNamedPipe -//sys createNamedPipe(name string, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *syscall.SecurityAttributes) (handle syscall.Handle, err error) [failretval==syscall.InvalidHandle] = CreateNamedPipeW -//sys getNamedPipeInfo(pipe syscall.Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error) = GetNamedPipeInfo -//sys getNamedPipeHandleState(pipe syscall.Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) = GetNamedPipeHandleStateW -//sys localAlloc(uFlags uint32, length uint32) (ptr uintptr) = LocalAlloc -//sys ntCreateNamedPipeFile(pipe *syscall.Handle, access uint32, oa *objectAttributes, iosb *ioStatusBlock, share uint32, disposition uint32, options uint32, typ uint32, readMode uint32, completionMode uint32, maxInstances uint32, inboundQuota uint32, outputQuota uint32, timeout *int64) (status ntStatus) = ntdll.NtCreateNamedPipeFile -//sys rtlNtStatusToDosError(status ntStatus) (winerr error) = ntdll.RtlNtStatusToDosErrorNoTeb -//sys rtlDosPathNameToNtPathName(name *uint16, ntName *unicodeString, filePart uintptr, reserved uintptr) (status ntStatus) = ntdll.RtlDosPathNameToNtPathName_U -//sys rtlDefaultNpAcl(dacl *uintptr) (status ntStatus) = ntdll.RtlDefaultNpAcl - -type ioStatusBlock struct { - Status, Information uintptr -} - -type objectAttributes struct { - Length uintptr - RootDirectory uintptr - ObjectName *unicodeString - Attributes uintptr - SecurityDescriptor *securityDescriptor - SecurityQoS uintptr -} - -type unicodeString struct { - Length uint16 - MaximumLength uint16 - Buffer uintptr -} - -type securityDescriptor struct { - Revision byte - Sbz1 byte - Control uint16 - Owner uintptr - Group uintptr - Sacl uintptr //revive:disable-line:var-naming SACL, not Sacl - Dacl uintptr //revive:disable-line:var-naming DACL, not Dacl -} - -type ntStatus int32 - -func (status ntStatus) Err() error { - if status >= 0 { - return nil - } - return rtlNtStatusToDosError(status) -} - -var ( - // ErrPipeListenerClosed is returned for pipe operations on listeners that have been closed. - ErrPipeListenerClosed = net.ErrClosed - - errPipeWriteClosed = errors.New("pipe has been closed for write") -) - -type win32Pipe struct { - *win32File - path string -} - -type win32MessageBytePipe struct { - win32Pipe - writeClosed bool - readEOF bool -} - -type pipeAddress string - -func (f *win32Pipe) LocalAddr() net.Addr { - return pipeAddress(f.path) -} - -func (f *win32Pipe) RemoteAddr() net.Addr { - return pipeAddress(f.path) -} - -func (f *win32Pipe) SetDeadline(t time.Time) error { - if err := f.SetReadDeadline(t); err != nil { - return err - } - return f.SetWriteDeadline(t) -} - -// CloseWrite closes the write side of a message pipe in byte mode. -func (f *win32MessageBytePipe) CloseWrite() error { - if f.writeClosed { - return errPipeWriteClosed - } - err := f.win32File.Flush() - if err != nil { - return err - } - _, err = f.win32File.Write(nil) - if err != nil { - return err - } - f.writeClosed = true - return nil -} - -// Write writes bytes to a message pipe in byte mode. Zero-byte writes are ignored, since -// they are used to implement CloseWrite(). -func (f *win32MessageBytePipe) Write(b []byte) (int, error) { - if f.writeClosed { - return 0, errPipeWriteClosed - } - if len(b) == 0 { - return 0, nil - } - return f.win32File.Write(b) -} - -// Read reads bytes from a message pipe in byte mode. A read of a zero-byte message on a message -// mode pipe will return io.EOF, as will all subsequent reads. -func (f *win32MessageBytePipe) Read(b []byte) (int, error) { - if f.readEOF { - return 0, io.EOF - } - n, err := f.win32File.Read(b) - if err == io.EOF { //nolint:errorlint - // If this was the result of a zero-byte read, then - // it is possible that the read was due to a zero-size - // message. Since we are simulating CloseWrite with a - // zero-byte message, ensure that all future Read() calls - // also return EOF. - f.readEOF = true - } else if err == syscall.ERROR_MORE_DATA { //nolint:errorlint // err is Errno - // ERROR_MORE_DATA indicates that the pipe's read mode is message mode - // and the message still has more bytes. Treat this as a success, since - // this package presents all named pipes as byte streams. - err = nil - } - return n, err -} - -func (pipeAddress) Network() string { - return "pipe" -} - -func (s pipeAddress) String() string { - return string(s) -} - -// tryDialPipe attempts to dial the pipe at `path` until `ctx` cancellation or timeout. -func tryDialPipe(ctx context.Context, path *string, access fs.AccessMask) (syscall.Handle, error) { - for { - select { - case <-ctx.Done(): - return syscall.Handle(0), ctx.Err() - default: - wh, err := fs.CreateFile(*path, - access, - 0, // mode - nil, // security attributes - fs.OPEN_EXISTING, - fs.FILE_FLAG_OVERLAPPED|fs.SECURITY_SQOS_PRESENT|fs.SECURITY_ANONYMOUS, - 0, // template file handle - ) - h := syscall.Handle(wh) - if err == nil { - return h, nil - } - if err != windows.ERROR_PIPE_BUSY { //nolint:errorlint // err is Errno - return h, &os.PathError{Err: err, Op: "open", Path: *path} - } - // Wait 10 msec and try again. This is a rather simplistic - // view, as we always try each 10 milliseconds. - time.Sleep(10 * time.Millisecond) - } - } -} - -// DialPipe connects to a named pipe by path, timing out if the connection -// takes longer than the specified duration. If timeout is nil, then we use -// a default timeout of 2 seconds. (We do not use WaitNamedPipe.) -func DialPipe(path string, timeout *time.Duration) (net.Conn, error) { - var absTimeout time.Time - if timeout != nil { - absTimeout = time.Now().Add(*timeout) - } else { - absTimeout = time.Now().Add(2 * time.Second) - } - ctx, cancel := context.WithDeadline(context.Background(), absTimeout) - defer cancel() - conn, err := DialPipeContext(ctx, path) - if errors.Is(err, context.DeadlineExceeded) { - return nil, ErrTimeout - } - return conn, err -} - -// DialPipeContext attempts to connect to a named pipe by `path` until `ctx` -// cancellation or timeout. -func DialPipeContext(ctx context.Context, path string) (net.Conn, error) { - return DialPipeAccess(ctx, path, syscall.GENERIC_READ|syscall.GENERIC_WRITE) -} - -// DialPipeAccess attempts to connect to a named pipe by `path` with `access` until `ctx` -// cancellation or timeout. -func DialPipeAccess(ctx context.Context, path string, access uint32) (net.Conn, error) { - var err error - var h syscall.Handle - h, err = tryDialPipe(ctx, &path, fs.AccessMask(access)) - if err != nil { - return nil, err - } - - var flags uint32 - err = getNamedPipeInfo(h, &flags, nil, nil, nil) - if err != nil { - return nil, err - } - - f, err := makeWin32File(h) - if err != nil { - syscall.Close(h) - return nil, err - } - - // If the pipe is in message mode, return a message byte pipe, which - // supports CloseWrite(). - if flags&windows.PIPE_TYPE_MESSAGE != 0 { - return &win32MessageBytePipe{ - win32Pipe: win32Pipe{win32File: f, path: path}, - }, nil - } - return &win32Pipe{win32File: f, path: path}, nil -} - -type acceptResponse struct { - f *win32File - err error -} - -type win32PipeListener struct { - firstHandle syscall.Handle - path string - config PipeConfig - acceptCh chan (chan acceptResponse) - closeCh chan int - doneCh chan int -} - -func makeServerPipeHandle(path string, sd []byte, c *PipeConfig, first bool) (syscall.Handle, error) { - path16, err := syscall.UTF16FromString(path) - if err != nil { - return 0, &os.PathError{Op: "open", Path: path, Err: err} - } - - var oa objectAttributes - oa.Length = unsafe.Sizeof(oa) - - var ntPath unicodeString - if err := rtlDosPathNameToNtPathName(&path16[0], - &ntPath, - 0, - 0, - ).Err(); err != nil { - return 0, &os.PathError{Op: "open", Path: path, Err: err} - } - defer localFree(ntPath.Buffer) - oa.ObjectName = &ntPath - oa.Attributes = windows.OBJ_CASE_INSENSITIVE - - // The security descriptor is only needed for the first pipe. - if first { - if sd != nil { - l := uint32(len(sd)) - sdb := localAlloc(0, l) - defer localFree(sdb) - copy((*[0xffff]byte)(unsafe.Pointer(sdb))[:], sd) - oa.SecurityDescriptor = (*securityDescriptor)(unsafe.Pointer(sdb)) - } else { - // Construct the default named pipe security descriptor. - var dacl uintptr - if err := rtlDefaultNpAcl(&dacl).Err(); err != nil { - return 0, fmt.Errorf("getting default named pipe ACL: %w", err) - } - defer localFree(dacl) - - sdb := &securityDescriptor{ - Revision: 1, - Control: windows.SE_DACL_PRESENT, - Dacl: dacl, - } - oa.SecurityDescriptor = sdb - } - } - - typ := uint32(windows.FILE_PIPE_REJECT_REMOTE_CLIENTS) - if c.MessageMode { - typ |= windows.FILE_PIPE_MESSAGE_TYPE - } - - disposition := uint32(windows.FILE_OPEN) - access := uint32(syscall.GENERIC_READ | syscall.GENERIC_WRITE | syscall.SYNCHRONIZE) - if first { - disposition = windows.FILE_CREATE - // By not asking for read or write access, the named pipe file system - // will put this pipe into an initially disconnected state, blocking - // client connections until the next call with first == false. - access = syscall.SYNCHRONIZE - } - - timeout := int64(-50 * 10000) // 50ms - - var ( - h syscall.Handle - iosb ioStatusBlock - ) - err = ntCreateNamedPipeFile(&h, - access, - &oa, - &iosb, - syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE, - disposition, - 0, - typ, - 0, - 0, - 0xffffffff, - uint32(c.InputBufferSize), - uint32(c.OutputBufferSize), - &timeout).Err() - if err != nil { - return 0, &os.PathError{Op: "open", Path: path, Err: err} - } - - runtime.KeepAlive(ntPath) - return h, nil -} - -func (l *win32PipeListener) makeServerPipe() (*win32File, error) { - h, err := makeServerPipeHandle(l.path, nil, &l.config, false) - if err != nil { - return nil, err - } - f, err := makeWin32File(h) - if err != nil { - syscall.Close(h) - return nil, err - } - return f, nil -} - -func (l *win32PipeListener) makeConnectedServerPipe() (*win32File, error) { - p, err := l.makeServerPipe() - if err != nil { - return nil, err - } - - // Wait for the client to connect. - ch := make(chan error) - go func(p *win32File) { - ch <- connectPipe(p) - }(p) - - select { - case err = <-ch: - if err != nil { - p.Close() - p = nil - } - case <-l.closeCh: - // Abort the connect request by closing the handle. - p.Close() - p = nil - err = <-ch - if err == nil || err == ErrFileClosed { //nolint:errorlint // err is Errno - err = ErrPipeListenerClosed - } - } - return p, err -} - -func (l *win32PipeListener) listenerRoutine() { - closed := false - for !closed { - select { - case <-l.closeCh: - closed = true - case responseCh := <-l.acceptCh: - var ( - p *win32File - err error - ) - for { - p, err = l.makeConnectedServerPipe() - // If the connection was immediately closed by the client, try - // again. - if err != windows.ERROR_NO_DATA { //nolint:errorlint // err is Errno - break - } - } - responseCh <- acceptResponse{p, err} - closed = err == ErrPipeListenerClosed //nolint:errorlint // err is Errno - } - } - syscall.Close(l.firstHandle) - l.firstHandle = 0 - // Notify Close() and Accept() callers that the handle has been closed. - close(l.doneCh) -} - -// PipeConfig contain configuration for the pipe listener. -type PipeConfig struct { - // SecurityDescriptor contains a Windows security descriptor in SDDL format. - SecurityDescriptor string - - // MessageMode determines whether the pipe is in byte or message mode. In either - // case the pipe is read in byte mode by default. The only practical difference in - // this implementation is that CloseWrite() is only supported for message mode pipes; - // CloseWrite() is implemented as a zero-byte write, but zero-byte writes are only - // transferred to the reader (and returned as io.EOF in this implementation) - // when the pipe is in message mode. - MessageMode bool - - // InputBufferSize specifies the size of the input buffer, in bytes. - InputBufferSize int32 - - // OutputBufferSize specifies the size of the output buffer, in bytes. - OutputBufferSize int32 -} - -// ListenPipe creates a listener on a Windows named pipe path, e.g. \\.\pipe\mypipe. -// The pipe must not already exist. -func ListenPipe(path string, c *PipeConfig) (net.Listener, error) { - var ( - sd []byte - err error - ) - if c == nil { - c = &PipeConfig{} - } - if c.SecurityDescriptor != "" { - sd, err = SddlToSecurityDescriptor(c.SecurityDescriptor) - if err != nil { - return nil, err - } - } - h, err := makeServerPipeHandle(path, sd, c, true) - if err != nil { - return nil, err - } - l := &win32PipeListener{ - firstHandle: h, - path: path, - config: *c, - acceptCh: make(chan (chan acceptResponse)), - closeCh: make(chan int), - doneCh: make(chan int), - } - go l.listenerRoutine() - return l, nil -} - -func connectPipe(p *win32File) error { - c, err := p.prepareIO() - if err != nil { - return err - } - defer p.wg.Done() - - err = connectNamedPipe(p.handle, &c.o) - _, err = p.asyncIO(c, nil, 0, err) - if err != nil && err != windows.ERROR_PIPE_CONNECTED { //nolint:errorlint // err is Errno - return err - } - return nil -} - -func (l *win32PipeListener) Accept() (net.Conn, error) { - ch := make(chan acceptResponse) - select { - case l.acceptCh <- ch: - response := <-ch - err := response.err - if err != nil { - return nil, err - } - if l.config.MessageMode { - return &win32MessageBytePipe{ - win32Pipe: win32Pipe{win32File: response.f, path: l.path}, - }, nil - } - return &win32Pipe{win32File: response.f, path: l.path}, nil - case <-l.doneCh: - return nil, ErrPipeListenerClosed - } -} - -func (l *win32PipeListener) Close() error { - select { - case l.closeCh <- 1: - <-l.doneCh - case <-l.doneCh: - } - return nil -} - -func (l *win32PipeListener) Addr() net.Addr { - return pipeAddress(l.path) -} diff --git a/vendor/github.com/Microsoft/go-winio/pkg/guid/guid.go b/vendor/github.com/Microsoft/go-winio/pkg/guid/guid.go deleted file mode 100644 index 48ce4e924..000000000 --- a/vendor/github.com/Microsoft/go-winio/pkg/guid/guid.go +++ /dev/null @@ -1,232 +0,0 @@ -// Package guid provides a GUID type. The backing structure for a GUID is -// identical to that used by the golang.org/x/sys/windows GUID type. -// There are two main binary encodings used for a GUID, the big-endian encoding, -// and the Windows (mixed-endian) encoding. See here for details: -// https://en.wikipedia.org/wiki/Universally_unique_identifier#Encoding -package guid - -import ( - "crypto/rand" - "crypto/sha1" //nolint:gosec // not used for secure application - "encoding" - "encoding/binary" - "fmt" - "strconv" -) - -//go:generate go run golang.org/x/tools/cmd/stringer -type=Variant -trimprefix=Variant -linecomment - -// Variant specifies which GUID variant (or "type") of the GUID. It determines -// how the entirety of the rest of the GUID is interpreted. -type Variant uint8 - -// The variants specified by RFC 4122 section 4.1.1. -const ( - // VariantUnknown specifies a GUID variant which does not conform to one of - // the variant encodings specified in RFC 4122. - VariantUnknown Variant = iota - VariantNCS - VariantRFC4122 // RFC 4122 - VariantMicrosoft - VariantFuture -) - -// Version specifies how the bits in the GUID were generated. For instance, a -// version 4 GUID is randomly generated, and a version 5 is generated from the -// hash of an input string. -type Version uint8 - -func (v Version) String() string { - return strconv.FormatUint(uint64(v), 10) -} - -var _ = (encoding.TextMarshaler)(GUID{}) -var _ = (encoding.TextUnmarshaler)(&GUID{}) - -// NewV4 returns a new version 4 (pseudorandom) GUID, as defined by RFC 4122. -func NewV4() (GUID, error) { - var b [16]byte - if _, err := rand.Read(b[:]); err != nil { - return GUID{}, err - } - - g := FromArray(b) - g.setVersion(4) // Version 4 means randomly generated. - g.setVariant(VariantRFC4122) - - return g, nil -} - -// NewV5 returns a new version 5 (generated from a string via SHA-1 hashing) -// GUID, as defined by RFC 4122. The RFC is unclear on the encoding of the name, -// and the sample code treats it as a series of bytes, so we do the same here. -// -// Some implementations, such as those found on Windows, treat the name as a -// big-endian UTF16 stream of bytes. If that is desired, the string can be -// encoded as such before being passed to this function. -func NewV5(namespace GUID, name []byte) (GUID, error) { - b := sha1.New() //nolint:gosec // not used for secure application - namespaceBytes := namespace.ToArray() - b.Write(namespaceBytes[:]) - b.Write(name) - - a := [16]byte{} - copy(a[:], b.Sum(nil)) - - g := FromArray(a) - g.setVersion(5) // Version 5 means generated from a string. - g.setVariant(VariantRFC4122) - - return g, nil -} - -func fromArray(b [16]byte, order binary.ByteOrder) GUID { - var g GUID - g.Data1 = order.Uint32(b[0:4]) - g.Data2 = order.Uint16(b[4:6]) - g.Data3 = order.Uint16(b[6:8]) - copy(g.Data4[:], b[8:16]) - return g -} - -func (g GUID) toArray(order binary.ByteOrder) [16]byte { - b := [16]byte{} - order.PutUint32(b[0:4], g.Data1) - order.PutUint16(b[4:6], g.Data2) - order.PutUint16(b[6:8], g.Data3) - copy(b[8:16], g.Data4[:]) - return b -} - -// FromArray constructs a GUID from a big-endian encoding array of 16 bytes. -func FromArray(b [16]byte) GUID { - return fromArray(b, binary.BigEndian) -} - -// ToArray returns an array of 16 bytes representing the GUID in big-endian -// encoding. -func (g GUID) ToArray() [16]byte { - return g.toArray(binary.BigEndian) -} - -// FromWindowsArray constructs a GUID from a Windows encoding array of bytes. -func FromWindowsArray(b [16]byte) GUID { - return fromArray(b, binary.LittleEndian) -} - -// ToWindowsArray returns an array of 16 bytes representing the GUID in Windows -// encoding. -func (g GUID) ToWindowsArray() [16]byte { - return g.toArray(binary.LittleEndian) -} - -func (g GUID) String() string { - return fmt.Sprintf( - "%08x-%04x-%04x-%04x-%012x", - g.Data1, - g.Data2, - g.Data3, - g.Data4[:2], - g.Data4[2:]) -} - -// FromString parses a string containing a GUID and returns the GUID. The only -// format currently supported is the `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` -// format. -func FromString(s string) (GUID, error) { - if len(s) != 36 { - return GUID{}, fmt.Errorf("invalid GUID %q", s) - } - if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' { - return GUID{}, fmt.Errorf("invalid GUID %q", s) - } - - var g GUID - - data1, err := strconv.ParseUint(s[0:8], 16, 32) - if err != nil { - return GUID{}, fmt.Errorf("invalid GUID %q", s) - } - g.Data1 = uint32(data1) - - data2, err := strconv.ParseUint(s[9:13], 16, 16) - if err != nil { - return GUID{}, fmt.Errorf("invalid GUID %q", s) - } - g.Data2 = uint16(data2) - - data3, err := strconv.ParseUint(s[14:18], 16, 16) - if err != nil { - return GUID{}, fmt.Errorf("invalid GUID %q", s) - } - g.Data3 = uint16(data3) - - for i, x := range []int{19, 21, 24, 26, 28, 30, 32, 34} { - v, err := strconv.ParseUint(s[x:x+2], 16, 8) - if err != nil { - return GUID{}, fmt.Errorf("invalid GUID %q", s) - } - g.Data4[i] = uint8(v) - } - - return g, nil -} - -func (g *GUID) setVariant(v Variant) { - d := g.Data4[0] - switch v { - case VariantNCS: - d = (d & 0x7f) - case VariantRFC4122: - d = (d & 0x3f) | 0x80 - case VariantMicrosoft: - d = (d & 0x1f) | 0xc0 - case VariantFuture: - d = (d & 0x0f) | 0xe0 - case VariantUnknown: - fallthrough - default: - panic(fmt.Sprintf("invalid variant: %d", v)) - } - g.Data4[0] = d -} - -// Variant returns the GUID variant, as defined in RFC 4122. -func (g GUID) Variant() Variant { - b := g.Data4[0] - if b&0x80 == 0 { - return VariantNCS - } else if b&0xc0 == 0x80 { - return VariantRFC4122 - } else if b&0xe0 == 0xc0 { - return VariantMicrosoft - } else if b&0xe0 == 0xe0 { - return VariantFuture - } - return VariantUnknown -} - -func (g *GUID) setVersion(v Version) { - g.Data3 = (g.Data3 & 0x0fff) | (uint16(v) << 12) -} - -// Version returns the GUID version, as defined in RFC 4122. -func (g GUID) Version() Version { - return Version((g.Data3 & 0xF000) >> 12) -} - -// MarshalText returns the textual representation of the GUID. -func (g GUID) MarshalText() ([]byte, error) { - return []byte(g.String()), nil -} - -// UnmarshalText takes the textual representation of a GUID, and unmarhals it -// into this GUID. -func (g *GUID) UnmarshalText(text []byte) error { - g2, err := FromString(string(text)) - if err != nil { - return err - } - *g = g2 - return nil -} diff --git a/vendor/github.com/Microsoft/go-winio/pkg/guid/guid_nonwindows.go b/vendor/github.com/Microsoft/go-winio/pkg/guid/guid_nonwindows.go deleted file mode 100644 index 805bd3548..000000000 --- a/vendor/github.com/Microsoft/go-winio/pkg/guid/guid_nonwindows.go +++ /dev/null @@ -1,16 +0,0 @@ -//go:build !windows -// +build !windows - -package guid - -// GUID represents a GUID/UUID. It has the same structure as -// golang.org/x/sys/windows.GUID so that it can be used with functions expecting -// that type. It is defined as its own type as that is only available to builds -// targeted at `windows`. The representation matches that used by native Windows -// code. -type GUID struct { - Data1 uint32 - Data2 uint16 - Data3 uint16 - Data4 [8]byte -} diff --git a/vendor/github.com/Microsoft/go-winio/pkg/guid/guid_windows.go b/vendor/github.com/Microsoft/go-winio/pkg/guid/guid_windows.go deleted file mode 100644 index 27e45ee5c..000000000 --- a/vendor/github.com/Microsoft/go-winio/pkg/guid/guid_windows.go +++ /dev/null @@ -1,13 +0,0 @@ -//go:build windows -// +build windows - -package guid - -import "golang.org/x/sys/windows" - -// GUID represents a GUID/UUID. It has the same structure as -// golang.org/x/sys/windows.GUID so that it can be used with functions expecting -// that type. It is defined as its own type so that stringification and -// marshaling can be supported. The representation matches that used by native -// Windows code. -type GUID windows.GUID diff --git a/vendor/github.com/Microsoft/go-winio/pkg/guid/variant_string.go b/vendor/github.com/Microsoft/go-winio/pkg/guid/variant_string.go deleted file mode 100644 index 4076d3132..000000000 --- a/vendor/github.com/Microsoft/go-winio/pkg/guid/variant_string.go +++ /dev/null @@ -1,27 +0,0 @@ -// Code generated by "stringer -type=Variant -trimprefix=Variant -linecomment"; DO NOT EDIT. - -package guid - -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[VariantUnknown-0] - _ = x[VariantNCS-1] - _ = x[VariantRFC4122-2] - _ = x[VariantMicrosoft-3] - _ = x[VariantFuture-4] -} - -const _Variant_name = "UnknownNCSRFC 4122MicrosoftFuture" - -var _Variant_index = [...]uint8{0, 7, 10, 18, 27, 33} - -func (i Variant) String() string { - if i >= Variant(len(_Variant_index)-1) { - return "Variant(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _Variant_name[_Variant_index[i]:_Variant_index[i+1]] -} diff --git a/vendor/github.com/Microsoft/go-winio/privilege.go b/vendor/github.com/Microsoft/go-winio/privilege.go deleted file mode 100644 index 0ff9dac90..000000000 --- a/vendor/github.com/Microsoft/go-winio/privilege.go +++ /dev/null @@ -1,197 +0,0 @@ -//go:build windows -// +build windows - -package winio - -import ( - "bytes" - "encoding/binary" - "fmt" - "runtime" - "sync" - "syscall" - "unicode/utf16" - - "golang.org/x/sys/windows" -) - -//sys adjustTokenPrivileges(token windows.Token, releaseAll bool, input *byte, outputSize uint32, output *byte, requiredSize *uint32) (success bool, err error) [true] = advapi32.AdjustTokenPrivileges -//sys impersonateSelf(level uint32) (err error) = advapi32.ImpersonateSelf -//sys revertToSelf() (err error) = advapi32.RevertToSelf -//sys openThreadToken(thread syscall.Handle, accessMask uint32, openAsSelf bool, token *windows.Token) (err error) = advapi32.OpenThreadToken -//sys getCurrentThread() (h syscall.Handle) = GetCurrentThread -//sys lookupPrivilegeValue(systemName string, name string, luid *uint64) (err error) = advapi32.LookupPrivilegeValueW -//sys lookupPrivilegeName(systemName string, luid *uint64, buffer *uint16, size *uint32) (err error) = advapi32.LookupPrivilegeNameW -//sys lookupPrivilegeDisplayName(systemName string, name *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) = advapi32.LookupPrivilegeDisplayNameW - -const ( - //revive:disable-next-line:var-naming ALL_CAPS - SE_PRIVILEGE_ENABLED = windows.SE_PRIVILEGE_ENABLED - - //revive:disable-next-line:var-naming ALL_CAPS - ERROR_NOT_ALL_ASSIGNED syscall.Errno = windows.ERROR_NOT_ALL_ASSIGNED - - SeBackupPrivilege = "SeBackupPrivilege" - SeRestorePrivilege = "SeRestorePrivilege" - SeSecurityPrivilege = "SeSecurityPrivilege" -) - -var ( - privNames = make(map[string]uint64) - privNameMutex sync.Mutex -) - -// PrivilegeError represents an error enabling privileges. -type PrivilegeError struct { - privileges []uint64 -} - -func (e *PrivilegeError) Error() string { - s := "Could not enable privilege " - if len(e.privileges) > 1 { - s = "Could not enable privileges " - } - for i, p := range e.privileges { - if i != 0 { - s += ", " - } - s += `"` - s += getPrivilegeName(p) - s += `"` - } - return s -} - -// RunWithPrivilege enables a single privilege for a function call. -func RunWithPrivilege(name string, fn func() error) error { - return RunWithPrivileges([]string{name}, fn) -} - -// RunWithPrivileges enables privileges for a function call. -func RunWithPrivileges(names []string, fn func() error) error { - privileges, err := mapPrivileges(names) - if err != nil { - return err - } - runtime.LockOSThread() - defer runtime.UnlockOSThread() - token, err := newThreadToken() - if err != nil { - return err - } - defer releaseThreadToken(token) - err = adjustPrivileges(token, privileges, SE_PRIVILEGE_ENABLED) - if err != nil { - return err - } - return fn() -} - -func mapPrivileges(names []string) ([]uint64, error) { - privileges := make([]uint64, 0, len(names)) - privNameMutex.Lock() - defer privNameMutex.Unlock() - for _, name := range names { - p, ok := privNames[name] - if !ok { - err := lookupPrivilegeValue("", name, &p) - if err != nil { - return nil, err - } - privNames[name] = p - } - privileges = append(privileges, p) - } - return privileges, nil -} - -// EnableProcessPrivileges enables privileges globally for the process. -func EnableProcessPrivileges(names []string) error { - return enableDisableProcessPrivilege(names, SE_PRIVILEGE_ENABLED) -} - -// DisableProcessPrivileges disables privileges globally for the process. -func DisableProcessPrivileges(names []string) error { - return enableDisableProcessPrivilege(names, 0) -} - -func enableDisableProcessPrivilege(names []string, action uint32) error { - privileges, err := mapPrivileges(names) - if err != nil { - return err - } - - p := windows.CurrentProcess() - var token windows.Token - err = windows.OpenProcessToken(p, windows.TOKEN_ADJUST_PRIVILEGES|windows.TOKEN_QUERY, &token) - if err != nil { - return err - } - - defer token.Close() - return adjustPrivileges(token, privileges, action) -} - -func adjustPrivileges(token windows.Token, privileges []uint64, action uint32) error { - var b bytes.Buffer - _ = binary.Write(&b, binary.LittleEndian, uint32(len(privileges))) - for _, p := range privileges { - _ = binary.Write(&b, binary.LittleEndian, p) - _ = binary.Write(&b, binary.LittleEndian, action) - } - prevState := make([]byte, b.Len()) - reqSize := uint32(0) - success, err := adjustTokenPrivileges(token, false, &b.Bytes()[0], uint32(len(prevState)), &prevState[0], &reqSize) - if !success { - return err - } - if err == ERROR_NOT_ALL_ASSIGNED { //nolint:errorlint // err is Errno - return &PrivilegeError{privileges} - } - return nil -} - -func getPrivilegeName(luid uint64) string { - var nameBuffer [256]uint16 - bufSize := uint32(len(nameBuffer)) - err := lookupPrivilegeName("", &luid, &nameBuffer[0], &bufSize) - if err != nil { - return fmt.Sprintf("", luid) - } - - var displayNameBuffer [256]uint16 - displayBufSize := uint32(len(displayNameBuffer)) - var langID uint32 - err = lookupPrivilegeDisplayName("", &nameBuffer[0], &displayNameBuffer[0], &displayBufSize, &langID) - if err != nil { - return fmt.Sprintf("", string(utf16.Decode(nameBuffer[:bufSize]))) - } - - return string(utf16.Decode(displayNameBuffer[:displayBufSize])) -} - -func newThreadToken() (windows.Token, error) { - err := impersonateSelf(windows.SecurityImpersonation) - if err != nil { - return 0, err - } - - var token windows.Token - err = openThreadToken(getCurrentThread(), syscall.TOKEN_ADJUST_PRIVILEGES|syscall.TOKEN_QUERY, false, &token) - if err != nil { - rerr := revertToSelf() - if rerr != nil { - panic(rerr) - } - return 0, err - } - return token, nil -} - -func releaseThreadToken(h windows.Token) { - err := revertToSelf() - if err != nil { - panic(err) - } - h.Close() -} diff --git a/vendor/github.com/Microsoft/go-winio/reparse.go b/vendor/github.com/Microsoft/go-winio/reparse.go deleted file mode 100644 index 67d1a104a..000000000 --- a/vendor/github.com/Microsoft/go-winio/reparse.go +++ /dev/null @@ -1,131 +0,0 @@ -//go:build windows -// +build windows - -package winio - -import ( - "bytes" - "encoding/binary" - "fmt" - "strings" - "unicode/utf16" - "unsafe" -) - -const ( - reparseTagMountPoint = 0xA0000003 - reparseTagSymlink = 0xA000000C -) - -type reparseDataBuffer struct { - ReparseTag uint32 - ReparseDataLength uint16 - Reserved uint16 - SubstituteNameOffset uint16 - SubstituteNameLength uint16 - PrintNameOffset uint16 - PrintNameLength uint16 -} - -// ReparsePoint describes a Win32 symlink or mount point. -type ReparsePoint struct { - Target string - IsMountPoint bool -} - -// UnsupportedReparsePointError is returned when trying to decode a non-symlink or -// mount point reparse point. -type UnsupportedReparsePointError struct { - Tag uint32 -} - -func (e *UnsupportedReparsePointError) Error() string { - return fmt.Sprintf("unsupported reparse point %x", e.Tag) -} - -// DecodeReparsePoint decodes a Win32 REPARSE_DATA_BUFFER structure containing either a symlink -// or a mount point. -func DecodeReparsePoint(b []byte) (*ReparsePoint, error) { - tag := binary.LittleEndian.Uint32(b[0:4]) - return DecodeReparsePointData(tag, b[8:]) -} - -func DecodeReparsePointData(tag uint32, b []byte) (*ReparsePoint, error) { - isMountPoint := false - switch tag { - case reparseTagMountPoint: - isMountPoint = true - case reparseTagSymlink: - default: - return nil, &UnsupportedReparsePointError{tag} - } - nameOffset := 8 + binary.LittleEndian.Uint16(b[4:6]) - if !isMountPoint { - nameOffset += 4 - } - nameLength := binary.LittleEndian.Uint16(b[6:8]) - name := make([]uint16, nameLength/2) - err := binary.Read(bytes.NewReader(b[nameOffset:nameOffset+nameLength]), binary.LittleEndian, &name) - if err != nil { - return nil, err - } - return &ReparsePoint{string(utf16.Decode(name)), isMountPoint}, nil -} - -func isDriveLetter(c byte) bool { - return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') -} - -// EncodeReparsePoint encodes a Win32 REPARSE_DATA_BUFFER structure describing a symlink or -// mount point. -func EncodeReparsePoint(rp *ReparsePoint) []byte { - // Generate an NT path and determine if this is a relative path. - var ntTarget string - relative := false - if strings.HasPrefix(rp.Target, `\\?\`) { - ntTarget = `\??\` + rp.Target[4:] - } else if strings.HasPrefix(rp.Target, `\\`) { - ntTarget = `\??\UNC\` + rp.Target[2:] - } else if len(rp.Target) >= 2 && isDriveLetter(rp.Target[0]) && rp.Target[1] == ':' { - ntTarget = `\??\` + rp.Target - } else { - ntTarget = rp.Target - relative = true - } - - // The paths must be NUL-terminated even though they are counted strings. - target16 := utf16.Encode([]rune(rp.Target + "\x00")) - ntTarget16 := utf16.Encode([]rune(ntTarget + "\x00")) - - size := int(unsafe.Sizeof(reparseDataBuffer{})) - 8 - size += len(ntTarget16)*2 + len(target16)*2 - - tag := uint32(reparseTagMountPoint) - if !rp.IsMountPoint { - tag = reparseTagSymlink - size += 4 // Add room for symlink flags - } - - data := reparseDataBuffer{ - ReparseTag: tag, - ReparseDataLength: uint16(size), - SubstituteNameOffset: 0, - SubstituteNameLength: uint16((len(ntTarget16) - 1) * 2), - PrintNameOffset: uint16(len(ntTarget16) * 2), - PrintNameLength: uint16((len(target16) - 1) * 2), - } - - var b bytes.Buffer - _ = binary.Write(&b, binary.LittleEndian, &data) - if !rp.IsMountPoint { - flags := uint32(0) - if relative { - flags |= 1 - } - _ = binary.Write(&b, binary.LittleEndian, flags) - } - - _ = binary.Write(&b, binary.LittleEndian, ntTarget16) - _ = binary.Write(&b, binary.LittleEndian, target16) - return b.Bytes() -} diff --git a/vendor/github.com/Microsoft/go-winio/sd.go b/vendor/github.com/Microsoft/go-winio/sd.go deleted file mode 100644 index 5550ef6b6..000000000 --- a/vendor/github.com/Microsoft/go-winio/sd.go +++ /dev/null @@ -1,144 +0,0 @@ -//go:build windows -// +build windows - -package winio - -import ( - "errors" - "syscall" - "unsafe" - - "golang.org/x/sys/windows" -) - -//sys lookupAccountName(systemName *uint16, accountName string, sid *byte, sidSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) = advapi32.LookupAccountNameW -//sys lookupAccountSid(systemName *uint16, sid *byte, name *uint16, nameSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) = advapi32.LookupAccountSidW -//sys convertSidToStringSid(sid *byte, str **uint16) (err error) = advapi32.ConvertSidToStringSidW -//sys convertStringSidToSid(str *uint16, sid **byte) (err error) = advapi32.ConvertStringSidToSidW -//sys convertStringSecurityDescriptorToSecurityDescriptor(str string, revision uint32, sd *uintptr, size *uint32) (err error) = advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW -//sys convertSecurityDescriptorToStringSecurityDescriptor(sd *byte, revision uint32, secInfo uint32, sddl **uint16, sddlSize *uint32) (err error) = advapi32.ConvertSecurityDescriptorToStringSecurityDescriptorW -//sys localFree(mem uintptr) = LocalFree -//sys getSecurityDescriptorLength(sd uintptr) (len uint32) = advapi32.GetSecurityDescriptorLength - -type AccountLookupError struct { - Name string - Err error -} - -func (e *AccountLookupError) Error() string { - if e.Name == "" { - return "lookup account: empty account name specified" - } - var s string - switch { - case errors.Is(e.Err, windows.ERROR_INVALID_SID): - s = "the security ID structure is invalid" - case errors.Is(e.Err, windows.ERROR_NONE_MAPPED): - s = "not found" - default: - s = e.Err.Error() - } - return "lookup account " + e.Name + ": " + s -} - -func (e *AccountLookupError) Unwrap() error { return e.Err } - -type SddlConversionError struct { - Sddl string - Err error -} - -func (e *SddlConversionError) Error() string { - return "convert " + e.Sddl + ": " + e.Err.Error() -} - -func (e *SddlConversionError) Unwrap() error { return e.Err } - -// LookupSidByName looks up the SID of an account by name -// -//revive:disable-next-line:var-naming SID, not Sid -func LookupSidByName(name string) (sid string, err error) { - if name == "" { - return "", &AccountLookupError{name, windows.ERROR_NONE_MAPPED} - } - - var sidSize, sidNameUse, refDomainSize uint32 - err = lookupAccountName(nil, name, nil, &sidSize, nil, &refDomainSize, &sidNameUse) - if err != nil && err != syscall.ERROR_INSUFFICIENT_BUFFER { //nolint:errorlint // err is Errno - return "", &AccountLookupError{name, err} - } - sidBuffer := make([]byte, sidSize) - refDomainBuffer := make([]uint16, refDomainSize) - err = lookupAccountName(nil, name, &sidBuffer[0], &sidSize, &refDomainBuffer[0], &refDomainSize, &sidNameUse) - if err != nil { - return "", &AccountLookupError{name, err} - } - var strBuffer *uint16 - err = convertSidToStringSid(&sidBuffer[0], &strBuffer) - if err != nil { - return "", &AccountLookupError{name, err} - } - sid = syscall.UTF16ToString((*[0xffff]uint16)(unsafe.Pointer(strBuffer))[:]) - localFree(uintptr(unsafe.Pointer(strBuffer))) - return sid, nil -} - -// LookupNameBySid looks up the name of an account by SID -// -//revive:disable-next-line:var-naming SID, not Sid -func LookupNameBySid(sid string) (name string, err error) { - if sid == "" { - return "", &AccountLookupError{sid, windows.ERROR_NONE_MAPPED} - } - - sidBuffer, err := windows.UTF16PtrFromString(sid) - if err != nil { - return "", &AccountLookupError{sid, err} - } - - var sidPtr *byte - if err = convertStringSidToSid(sidBuffer, &sidPtr); err != nil { - return "", &AccountLookupError{sid, err} - } - defer localFree(uintptr(unsafe.Pointer(sidPtr))) - - var nameSize, refDomainSize, sidNameUse uint32 - err = lookupAccountSid(nil, sidPtr, nil, &nameSize, nil, &refDomainSize, &sidNameUse) - if err != nil && err != windows.ERROR_INSUFFICIENT_BUFFER { //nolint:errorlint // err is Errno - return "", &AccountLookupError{sid, err} - } - - nameBuffer := make([]uint16, nameSize) - refDomainBuffer := make([]uint16, refDomainSize) - err = lookupAccountSid(nil, sidPtr, &nameBuffer[0], &nameSize, &refDomainBuffer[0], &refDomainSize, &sidNameUse) - if err != nil { - return "", &AccountLookupError{sid, err} - } - - name = windows.UTF16ToString(nameBuffer) - return name, nil -} - -func SddlToSecurityDescriptor(sddl string) ([]byte, error) { - var sdBuffer uintptr - err := convertStringSecurityDescriptorToSecurityDescriptor(sddl, 1, &sdBuffer, nil) - if err != nil { - return nil, &SddlConversionError{sddl, err} - } - defer localFree(sdBuffer) - sd := make([]byte, getSecurityDescriptorLength(sdBuffer)) - copy(sd, (*[0xffff]byte)(unsafe.Pointer(sdBuffer))[:len(sd)]) - return sd, nil -} - -func SecurityDescriptorToSddl(sd []byte) (string, error) { - var sddl *uint16 - // The returned string length seems to include an arbitrary number of terminating NULs. - // Don't use it. - err := convertSecurityDescriptorToStringSecurityDescriptor(&sd[0], 1, 0xff, &sddl, nil) - if err != nil { - return "", err - } - defer localFree(uintptr(unsafe.Pointer(sddl))) - return syscall.UTF16ToString((*[0xffff]uint16)(unsafe.Pointer(sddl))[:]), nil -} diff --git a/vendor/github.com/Microsoft/go-winio/syscall.go b/vendor/github.com/Microsoft/go-winio/syscall.go deleted file mode 100644 index a6ca111b3..000000000 --- a/vendor/github.com/Microsoft/go-winio/syscall.go +++ /dev/null @@ -1,5 +0,0 @@ -//go:build windows - -package winio - -//go:generate go run github.com/Microsoft/go-winio/tools/mkwinsyscall -output zsyscall_windows.go ./*.go diff --git a/vendor/github.com/Microsoft/go-winio/tools.go b/vendor/github.com/Microsoft/go-winio/tools.go deleted file mode 100644 index 2aa045843..000000000 --- a/vendor/github.com/Microsoft/go-winio/tools.go +++ /dev/null @@ -1,5 +0,0 @@ -//go:build tools - -package winio - -import _ "golang.org/x/tools/cmd/stringer" diff --git a/vendor/github.com/Microsoft/go-winio/zsyscall_windows.go b/vendor/github.com/Microsoft/go-winio/zsyscall_windows.go deleted file mode 100644 index 469b16f63..000000000 --- a/vendor/github.com/Microsoft/go-winio/zsyscall_windows.go +++ /dev/null @@ -1,419 +0,0 @@ -//go:build windows - -// Code generated by 'go generate' using "github.com/Microsoft/go-winio/tools/mkwinsyscall"; DO NOT EDIT. - -package winio - -import ( - "syscall" - "unsafe" - - "golang.org/x/sys/windows" -) - -var _ unsafe.Pointer - -// Do the interface allocations only once for common -// Errno values. -const ( - errnoERROR_IO_PENDING = 997 -) - -var ( - errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) - errERROR_EINVAL error = syscall.EINVAL -) - -// errnoErr returns common boxed Errno values, to prevent -// allocations at runtime. -func errnoErr(e syscall.Errno) error { - switch e { - case 0: - return errERROR_EINVAL - case errnoERROR_IO_PENDING: - return errERROR_IO_PENDING - } - // TODO: add more here, after collecting data on the common - // error values see on Windows. (perhaps when running - // all.bat?) - return e -} - -var ( - modadvapi32 = windows.NewLazySystemDLL("advapi32.dll") - modkernel32 = windows.NewLazySystemDLL("kernel32.dll") - modntdll = windows.NewLazySystemDLL("ntdll.dll") - modws2_32 = windows.NewLazySystemDLL("ws2_32.dll") - - procAdjustTokenPrivileges = modadvapi32.NewProc("AdjustTokenPrivileges") - procConvertSecurityDescriptorToStringSecurityDescriptorW = modadvapi32.NewProc("ConvertSecurityDescriptorToStringSecurityDescriptorW") - procConvertSidToStringSidW = modadvapi32.NewProc("ConvertSidToStringSidW") - procConvertStringSecurityDescriptorToSecurityDescriptorW = modadvapi32.NewProc("ConvertStringSecurityDescriptorToSecurityDescriptorW") - procConvertStringSidToSidW = modadvapi32.NewProc("ConvertStringSidToSidW") - procGetSecurityDescriptorLength = modadvapi32.NewProc("GetSecurityDescriptorLength") - procImpersonateSelf = modadvapi32.NewProc("ImpersonateSelf") - procLookupAccountNameW = modadvapi32.NewProc("LookupAccountNameW") - procLookupAccountSidW = modadvapi32.NewProc("LookupAccountSidW") - procLookupPrivilegeDisplayNameW = modadvapi32.NewProc("LookupPrivilegeDisplayNameW") - procLookupPrivilegeNameW = modadvapi32.NewProc("LookupPrivilegeNameW") - procLookupPrivilegeValueW = modadvapi32.NewProc("LookupPrivilegeValueW") - procOpenThreadToken = modadvapi32.NewProc("OpenThreadToken") - procRevertToSelf = modadvapi32.NewProc("RevertToSelf") - procBackupRead = modkernel32.NewProc("BackupRead") - procBackupWrite = modkernel32.NewProc("BackupWrite") - procCancelIoEx = modkernel32.NewProc("CancelIoEx") - procConnectNamedPipe = modkernel32.NewProc("ConnectNamedPipe") - procCreateIoCompletionPort = modkernel32.NewProc("CreateIoCompletionPort") - procCreateNamedPipeW = modkernel32.NewProc("CreateNamedPipeW") - procGetCurrentThread = modkernel32.NewProc("GetCurrentThread") - procGetNamedPipeHandleStateW = modkernel32.NewProc("GetNamedPipeHandleStateW") - procGetNamedPipeInfo = modkernel32.NewProc("GetNamedPipeInfo") - procGetQueuedCompletionStatus = modkernel32.NewProc("GetQueuedCompletionStatus") - procLocalAlloc = modkernel32.NewProc("LocalAlloc") - procLocalFree = modkernel32.NewProc("LocalFree") - procSetFileCompletionNotificationModes = modkernel32.NewProc("SetFileCompletionNotificationModes") - procNtCreateNamedPipeFile = modntdll.NewProc("NtCreateNamedPipeFile") - procRtlDefaultNpAcl = modntdll.NewProc("RtlDefaultNpAcl") - procRtlDosPathNameToNtPathName_U = modntdll.NewProc("RtlDosPathNameToNtPathName_U") - procRtlNtStatusToDosErrorNoTeb = modntdll.NewProc("RtlNtStatusToDosErrorNoTeb") - procWSAGetOverlappedResult = modws2_32.NewProc("WSAGetOverlappedResult") -) - -func adjustTokenPrivileges(token windows.Token, releaseAll bool, input *byte, outputSize uint32, output *byte, requiredSize *uint32) (success bool, err error) { - var _p0 uint32 - if releaseAll { - _p0 = 1 - } - r0, _, e1 := syscall.Syscall6(procAdjustTokenPrivileges.Addr(), 6, uintptr(token), uintptr(_p0), uintptr(unsafe.Pointer(input)), uintptr(outputSize), uintptr(unsafe.Pointer(output)), uintptr(unsafe.Pointer(requiredSize))) - success = r0 != 0 - if true { - err = errnoErr(e1) - } - return -} - -func convertSecurityDescriptorToStringSecurityDescriptor(sd *byte, revision uint32, secInfo uint32, sddl **uint16, sddlSize *uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procConvertSecurityDescriptorToStringSecurityDescriptorW.Addr(), 5, uintptr(unsafe.Pointer(sd)), uintptr(revision), uintptr(secInfo), uintptr(unsafe.Pointer(sddl)), uintptr(unsafe.Pointer(sddlSize)), 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func convertSidToStringSid(sid *byte, str **uint16) (err error) { - r1, _, e1 := syscall.Syscall(procConvertSidToStringSidW.Addr(), 2, uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(str)), 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func convertStringSecurityDescriptorToSecurityDescriptor(str string, revision uint32, sd *uintptr, size *uint32) (err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(str) - if err != nil { - return - } - return _convertStringSecurityDescriptorToSecurityDescriptor(_p0, revision, sd, size) -} - -func _convertStringSecurityDescriptorToSecurityDescriptor(str *uint16, revision uint32, sd *uintptr, size *uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procConvertStringSecurityDescriptorToSecurityDescriptorW.Addr(), 4, uintptr(unsafe.Pointer(str)), uintptr(revision), uintptr(unsafe.Pointer(sd)), uintptr(unsafe.Pointer(size)), 0, 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func convertStringSidToSid(str *uint16, sid **byte) (err error) { - r1, _, e1 := syscall.Syscall(procConvertStringSidToSidW.Addr(), 2, uintptr(unsafe.Pointer(str)), uintptr(unsafe.Pointer(sid)), 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func getSecurityDescriptorLength(sd uintptr) (len uint32) { - r0, _, _ := syscall.Syscall(procGetSecurityDescriptorLength.Addr(), 1, uintptr(sd), 0, 0) - len = uint32(r0) - return -} - -func impersonateSelf(level uint32) (err error) { - r1, _, e1 := syscall.Syscall(procImpersonateSelf.Addr(), 1, uintptr(level), 0, 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func lookupAccountName(systemName *uint16, accountName string, sid *byte, sidSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(accountName) - if err != nil { - return - } - return _lookupAccountName(systemName, _p0, sid, sidSize, refDomain, refDomainSize, sidNameUse) -} - -func _lookupAccountName(systemName *uint16, accountName *uint16, sid *byte, sidSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) { - r1, _, e1 := syscall.Syscall9(procLookupAccountNameW.Addr(), 7, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(accountName)), uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(sidSize)), uintptr(unsafe.Pointer(refDomain)), uintptr(unsafe.Pointer(refDomainSize)), uintptr(unsafe.Pointer(sidNameUse)), 0, 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func lookupAccountSid(systemName *uint16, sid *byte, name *uint16, nameSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) { - r1, _, e1 := syscall.Syscall9(procLookupAccountSidW.Addr(), 7, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(nameSize)), uintptr(unsafe.Pointer(refDomain)), uintptr(unsafe.Pointer(refDomainSize)), uintptr(unsafe.Pointer(sidNameUse)), 0, 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func lookupPrivilegeDisplayName(systemName string, name *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(systemName) - if err != nil { - return - } - return _lookupPrivilegeDisplayName(_p0, name, buffer, size, languageId) -} - -func _lookupPrivilegeDisplayName(systemName *uint16, name *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procLookupPrivilegeDisplayNameW.Addr(), 5, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(buffer)), uintptr(unsafe.Pointer(size)), uintptr(unsafe.Pointer(languageId)), 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func lookupPrivilegeName(systemName string, luid *uint64, buffer *uint16, size *uint32) (err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(systemName) - if err != nil { - return - } - return _lookupPrivilegeName(_p0, luid, buffer, size) -} - -func _lookupPrivilegeName(systemName *uint16, luid *uint64, buffer *uint16, size *uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procLookupPrivilegeNameW.Addr(), 4, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(luid)), uintptr(unsafe.Pointer(buffer)), uintptr(unsafe.Pointer(size)), 0, 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func lookupPrivilegeValue(systemName string, name string, luid *uint64) (err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(systemName) - if err != nil { - return - } - var _p1 *uint16 - _p1, err = syscall.UTF16PtrFromString(name) - if err != nil { - return - } - return _lookupPrivilegeValue(_p0, _p1, luid) -} - -func _lookupPrivilegeValue(systemName *uint16, name *uint16, luid *uint64) (err error) { - r1, _, e1 := syscall.Syscall(procLookupPrivilegeValueW.Addr(), 3, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(luid))) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func openThreadToken(thread syscall.Handle, accessMask uint32, openAsSelf bool, token *windows.Token) (err error) { - var _p0 uint32 - if openAsSelf { - _p0 = 1 - } - r1, _, e1 := syscall.Syscall6(procOpenThreadToken.Addr(), 4, uintptr(thread), uintptr(accessMask), uintptr(_p0), uintptr(unsafe.Pointer(token)), 0, 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func revertToSelf() (err error) { - r1, _, e1 := syscall.Syscall(procRevertToSelf.Addr(), 0, 0, 0, 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func backupRead(h syscall.Handle, b []byte, bytesRead *uint32, abort bool, processSecurity bool, context *uintptr) (err error) { - var _p0 *byte - if len(b) > 0 { - _p0 = &b[0] - } - var _p1 uint32 - if abort { - _p1 = 1 - } - var _p2 uint32 - if processSecurity { - _p2 = 1 - } - r1, _, e1 := syscall.Syscall9(procBackupRead.Addr(), 7, uintptr(h), uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), uintptr(unsafe.Pointer(bytesRead)), uintptr(_p1), uintptr(_p2), uintptr(unsafe.Pointer(context)), 0, 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func backupWrite(h syscall.Handle, b []byte, bytesWritten *uint32, abort bool, processSecurity bool, context *uintptr) (err error) { - var _p0 *byte - if len(b) > 0 { - _p0 = &b[0] - } - var _p1 uint32 - if abort { - _p1 = 1 - } - var _p2 uint32 - if processSecurity { - _p2 = 1 - } - r1, _, e1 := syscall.Syscall9(procBackupWrite.Addr(), 7, uintptr(h), uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), uintptr(unsafe.Pointer(bytesWritten)), uintptr(_p1), uintptr(_p2), uintptr(unsafe.Pointer(context)), 0, 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func cancelIoEx(file syscall.Handle, o *syscall.Overlapped) (err error) { - r1, _, e1 := syscall.Syscall(procCancelIoEx.Addr(), 2, uintptr(file), uintptr(unsafe.Pointer(o)), 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func connectNamedPipe(pipe syscall.Handle, o *syscall.Overlapped) (err error) { - r1, _, e1 := syscall.Syscall(procConnectNamedPipe.Addr(), 2, uintptr(pipe), uintptr(unsafe.Pointer(o)), 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func createIoCompletionPort(file syscall.Handle, port syscall.Handle, key uintptr, threadCount uint32) (newport syscall.Handle, err error) { - r0, _, e1 := syscall.Syscall6(procCreateIoCompletionPort.Addr(), 4, uintptr(file), uintptr(port), uintptr(key), uintptr(threadCount), 0, 0) - newport = syscall.Handle(r0) - if newport == 0 { - err = errnoErr(e1) - } - return -} - -func createNamedPipe(name string, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *syscall.SecurityAttributes) (handle syscall.Handle, err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(name) - if err != nil { - return - } - return _createNamedPipe(_p0, flags, pipeMode, maxInstances, outSize, inSize, defaultTimeout, sa) -} - -func _createNamedPipe(name *uint16, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *syscall.SecurityAttributes) (handle syscall.Handle, err error) { - r0, _, e1 := syscall.Syscall9(procCreateNamedPipeW.Addr(), 8, uintptr(unsafe.Pointer(name)), uintptr(flags), uintptr(pipeMode), uintptr(maxInstances), uintptr(outSize), uintptr(inSize), uintptr(defaultTimeout), uintptr(unsafe.Pointer(sa)), 0) - handle = syscall.Handle(r0) - if handle == syscall.InvalidHandle { - err = errnoErr(e1) - } - return -} - -func getCurrentThread() (h syscall.Handle) { - r0, _, _ := syscall.Syscall(procGetCurrentThread.Addr(), 0, 0, 0, 0) - h = syscall.Handle(r0) - return -} - -func getNamedPipeHandleState(pipe syscall.Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) { - r1, _, e1 := syscall.Syscall9(procGetNamedPipeHandleStateW.Addr(), 7, uintptr(pipe), uintptr(unsafe.Pointer(state)), uintptr(unsafe.Pointer(curInstances)), uintptr(unsafe.Pointer(maxCollectionCount)), uintptr(unsafe.Pointer(collectDataTimeout)), uintptr(unsafe.Pointer(userName)), uintptr(maxUserNameSize), 0, 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func getNamedPipeInfo(pipe syscall.Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procGetNamedPipeInfo.Addr(), 5, uintptr(pipe), uintptr(unsafe.Pointer(flags)), uintptr(unsafe.Pointer(outSize)), uintptr(unsafe.Pointer(inSize)), uintptr(unsafe.Pointer(maxInstances)), 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func getQueuedCompletionStatus(port syscall.Handle, bytes *uint32, key *uintptr, o **ioOperation, timeout uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procGetQueuedCompletionStatus.Addr(), 5, uintptr(port), uintptr(unsafe.Pointer(bytes)), uintptr(unsafe.Pointer(key)), uintptr(unsafe.Pointer(o)), uintptr(timeout), 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func localAlloc(uFlags uint32, length uint32) (ptr uintptr) { - r0, _, _ := syscall.Syscall(procLocalAlloc.Addr(), 2, uintptr(uFlags), uintptr(length), 0) - ptr = uintptr(r0) - return -} - -func localFree(mem uintptr) { - syscall.Syscall(procLocalFree.Addr(), 1, uintptr(mem), 0, 0) - return -} - -func setFileCompletionNotificationModes(h syscall.Handle, flags uint8) (err error) { - r1, _, e1 := syscall.Syscall(procSetFileCompletionNotificationModes.Addr(), 2, uintptr(h), uintptr(flags), 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func ntCreateNamedPipeFile(pipe *syscall.Handle, access uint32, oa *objectAttributes, iosb *ioStatusBlock, share uint32, disposition uint32, options uint32, typ uint32, readMode uint32, completionMode uint32, maxInstances uint32, inboundQuota uint32, outputQuota uint32, timeout *int64) (status ntStatus) { - r0, _, _ := syscall.Syscall15(procNtCreateNamedPipeFile.Addr(), 14, uintptr(unsafe.Pointer(pipe)), uintptr(access), uintptr(unsafe.Pointer(oa)), uintptr(unsafe.Pointer(iosb)), uintptr(share), uintptr(disposition), uintptr(options), uintptr(typ), uintptr(readMode), uintptr(completionMode), uintptr(maxInstances), uintptr(inboundQuota), uintptr(outputQuota), uintptr(unsafe.Pointer(timeout)), 0) - status = ntStatus(r0) - return -} - -func rtlDefaultNpAcl(dacl *uintptr) (status ntStatus) { - r0, _, _ := syscall.Syscall(procRtlDefaultNpAcl.Addr(), 1, uintptr(unsafe.Pointer(dacl)), 0, 0) - status = ntStatus(r0) - return -} - -func rtlDosPathNameToNtPathName(name *uint16, ntName *unicodeString, filePart uintptr, reserved uintptr) (status ntStatus) { - r0, _, _ := syscall.Syscall6(procRtlDosPathNameToNtPathName_U.Addr(), 4, uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(ntName)), uintptr(filePart), uintptr(reserved), 0, 0) - status = ntStatus(r0) - return -} - -func rtlNtStatusToDosError(status ntStatus) (winerr error) { - r0, _, _ := syscall.Syscall(procRtlNtStatusToDosErrorNoTeb.Addr(), 1, uintptr(status), 0, 0) - if r0 != 0 { - winerr = syscall.Errno(r0) - } - return -} - -func wsaGetOverlappedResult(h syscall.Handle, o *syscall.Overlapped, bytes *uint32, wait bool, flags *uint32) (err error) { - var _p0 uint32 - if wait { - _p0 = 1 - } - r1, _, e1 := syscall.Syscall6(procWSAGetOverlappedResult.Addr(), 5, uintptr(h), uintptr(unsafe.Pointer(o)), uintptr(unsafe.Pointer(bytes)), uintptr(_p0), uintptr(unsafe.Pointer(flags)), 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} diff --git a/vendor/github.com/Microsoft/hcsshim/LICENSE b/vendor/github.com/Microsoft/hcsshim/LICENSE deleted file mode 100644 index 49d21669a..000000000 --- a/vendor/github.com/Microsoft/hcsshim/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Microsoft - -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/Microsoft/hcsshim/osversion/osversion_windows.go b/vendor/github.com/Microsoft/hcsshim/osversion/osversion_windows.go deleted file mode 100644 index 6c435d2b6..000000000 --- a/vendor/github.com/Microsoft/hcsshim/osversion/osversion_windows.go +++ /dev/null @@ -1,59 +0,0 @@ -package osversion - -import ( - "fmt" - "sync" - - "golang.org/x/sys/windows" -) - -// OSVersion is a wrapper for Windows version information -// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724439(v=vs.85).aspx -type OSVersion struct { - Version uint32 - MajorVersion uint8 - MinorVersion uint8 - Build uint16 -} - -var ( - osv OSVersion - once sync.Once -) - -// Get gets the operating system version on Windows. -// The calling application must be manifested to get the correct version information. -func Get() OSVersion { - once.Do(func() { - var err error - osv = OSVersion{} - osv.Version, err = windows.GetVersion() - if err != nil { - // GetVersion never fails. - panic(err) - } - osv.MajorVersion = uint8(osv.Version & 0xFF) - osv.MinorVersion = uint8(osv.Version >> 8 & 0xFF) - osv.Build = uint16(osv.Version >> 16) - }) - return osv -} - -// Build gets the build-number on Windows -// The calling application must be manifested to get the correct version information. -func Build() uint16 { - return Get().Build -} - -// String returns the OSVersion formatted as a string. It implements the -// [fmt.Stringer] interface. -func (osv OSVersion) String() string { - return fmt.Sprintf("%d.%d.%d", osv.MajorVersion, osv.MinorVersion, osv.Build) -} - -// ToString returns the OSVersion formatted as a string. -// -// Deprecated: use [OSVersion.String]. -func (osv OSVersion) ToString() string { - return osv.String() -} diff --git a/vendor/github.com/Microsoft/hcsshim/osversion/platform_compat_windows.go b/vendor/github.com/Microsoft/hcsshim/osversion/platform_compat_windows.go deleted file mode 100644 index f8d411ad7..000000000 --- a/vendor/github.com/Microsoft/hcsshim/osversion/platform_compat_windows.go +++ /dev/null @@ -1,35 +0,0 @@ -package osversion - -// List of stable ABI compliant ltsc releases -// Note: List must be sorted in ascending order -var compatLTSCReleases = []uint16{ - V21H2Server, -} - -// CheckHostAndContainerCompat checks if given host and container -// OS versions are compatible. -// It includes support for stable ABI compliant versions as well. -// Every release after WS 2022 will support the previous ltsc -// container image. Stable ABI is in preview mode for windows 11 client. -// Refer: https://learn.microsoft.com/en-us/virtualization/windowscontainers/deploy-containers/version-compatibility?tabs=windows-server-2022%2Cwindows-10#windows-server-host-os-compatibility -func CheckHostAndContainerCompat(host, ctr OSVersion) bool { - // check major minor versions of host and guest - if host.MajorVersion != ctr.MajorVersion || - host.MinorVersion != ctr.MinorVersion { - return false - } - - // If host is < WS 2022, exact version match is required - if host.Build < V21H2Server { - return host.Build == ctr.Build - } - - var supportedLtscRelease uint16 - for i := len(compatLTSCReleases) - 1; i >= 0; i-- { - if host.Build >= compatLTSCReleases[i] { - supportedLtscRelease = compatLTSCReleases[i] - break - } - } - return ctr.Build >= supportedLtscRelease && ctr.Build <= host.Build -} diff --git a/vendor/github.com/Microsoft/hcsshim/osversion/windowsbuilds.go b/vendor/github.com/Microsoft/hcsshim/osversion/windowsbuilds.go deleted file mode 100644 index 446369591..000000000 --- a/vendor/github.com/Microsoft/hcsshim/osversion/windowsbuilds.go +++ /dev/null @@ -1,84 +0,0 @@ -package osversion - -// Windows Client and Server build numbers. -// -// See: -// https://learn.microsoft.com/en-us/windows/release-health/release-information -// https://learn.microsoft.com/en-us/windows/release-health/windows-server-release-info -// https://learn.microsoft.com/en-us/windows/release-health/windows11-release-information -const ( - // RS1 (version 1607, codename "Redstone 1") corresponds to Windows Server - // 2016 (ltsc2016) and Windows 10 (Anniversary Update). - RS1 = 14393 - // V1607 (version 1607, codename "Redstone 1") is an alias for [RS1]. - V1607 = RS1 - // LTSC2016 (Windows Server 2016) is an alias for [RS1]. - LTSC2016 = RS1 - - // RS2 (version 1703, codename "Redstone 2") was a client-only update, and - // corresponds to Windows 10 (Creators Update). - RS2 = 15063 - // V1703 (version 1703, codename "Redstone 2") is an alias for [RS2]. - V1703 = RS2 - - // RS3 (version 1709, codename "Redstone 3") corresponds to Windows Server - // 1709 (Semi-Annual Channel (SAC)), and Windows 10 (Fall Creators Update). - RS3 = 16299 - // V1709 (version 1709, codename "Redstone 3") is an alias for [RS3]. - V1709 = RS3 - - // RS4 (version 1803, codename "Redstone 4") corresponds to Windows Server - // 1803 (Semi-Annual Channel (SAC)), and Windows 10 (April 2018 Update). - RS4 = 17134 - // V1803 (version 1803, codename "Redstone 4") is an alias for [RS4]. - V1803 = RS4 - - // RS5 (version 1809, codename "Redstone 5") corresponds to Windows Server - // 2019 (ltsc2019), and Windows 10 (October 2018 Update). - RS5 = 17763 - // V1809 (version 1809, codename "Redstone 5") is an alias for [RS5]. - V1809 = RS5 - // LTSC2019 (Windows Server 2019) is an alias for [RS5]. - LTSC2019 = RS5 - - // V19H1 (version 1903, codename 19H1) corresponds to Windows Server 1903 (semi-annual - // channel). - V19H1 = 18362 - // V1903 (version 1903) is an alias for [V19H1]. - V1903 = V19H1 - - // V19H2 (version 1909, codename 19H2) corresponds to Windows Server 1909 (semi-annual - // channel). - V19H2 = 18363 - // V1909 (version 1909) is an alias for [V19H2]. - V1909 = V19H2 - - // V20H1 (version 2004, codename 20H1) corresponds to Windows Server 2004 (semi-annual - // channel). - V20H1 = 19041 - // V2004 (version 2004) is an alias for [V20H1]. - V2004 = V20H1 - - // V20H2 corresponds to Windows Server 20H2 (semi-annual channel). - V20H2 = 19042 - - // V21H1 corresponds to Windows Server 21H1 (semi-annual channel). - V21H1 = 19043 - - // V21H2Win10 corresponds to Windows 10 (November 2021 Update). - V21H2Win10 = 19044 - - // V21H2Server corresponds to Windows Server 2022 (ltsc2022). - V21H2Server = 20348 - // LTSC2022 (Windows Server 2022) is an alias for [V21H2Server] - LTSC2022 = V21H2Server - - // V21H2Win11 corresponds to Windows 11 (original release). - V21H2Win11 = 22000 - - // V22H2Win10 corresponds to Windows 10 (2022 Update). - V22H2Win10 = 19045 - - // V22H2Win11 corresponds to Windows 11 (2022 Update). - V22H2Win11 = 22621 -) diff --git a/vendor/github.com/aws/aws-sdk-go-v2/.gitignore b/vendor/github.com/aws/aws-sdk-go-v2/.gitignore deleted file mode 100644 index 5f8b8c94f..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -dist -/doc -/doc-staging -.yardoc -Gemfile.lock -/internal/awstesting/integration/smoke/**/importmarker__.go -/internal/awstesting/integration/smoke/_test/ -/vendor -/private/model/cli/gen-api/gen-api -.gradle/ -build/ -.idea/ -bin/ -.vscode/ diff --git a/vendor/github.com/aws/aws-sdk-go-v2/.golangci.toml b/vendor/github.com/aws/aws-sdk-go-v2/.golangci.toml deleted file mode 100644 index 8792d0ca6..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/.golangci.toml +++ /dev/null @@ -1,27 +0,0 @@ -[run] -concurrency = 4 -timeout = "1m" -issues-exit-code = 0 -modules-download-mode = "readonly" -allow-parallel-runners = true -skip-dirs = ["internal/repotools"] -skip-dirs-use-default = true -skip-files = ["service/transcribestreaming/eventstream_test.go"] -[output] -format = "github-actions" - -[linters-settings.cyclop] -skip-tests = false - -[linters-settings.errcheck] -check-blank = true - -[linters] -disable-all = true -enable = ["errcheck"] -fast = false - -[issues] -exclude-use-default = false - -# Refer config definitions at https://golangci-lint.run/usage/configuration/#config-file diff --git a/vendor/github.com/aws/aws-sdk-go-v2/.travis.yml b/vendor/github.com/aws/aws-sdk-go-v2/.travis.yml deleted file mode 100644 index 4b498a7a2..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/.travis.yml +++ /dev/null @@ -1,31 +0,0 @@ -language: go -sudo: true -dist: bionic - -branches: - only: - - main - -os: - - linux - - osx - # Travis doesn't work with windows and Go tip - #- windows - -go: - - tip - -matrix: - allow_failures: - - go: tip - -before_install: - - if [ "$TRAVIS_OS_NAME" = "windows" ]; then choco install make; fi - - (cd /tmp/; go get golang.org/x/lint/golint) - -env: - - EACHMODULE_CONCURRENCY=4 - -script: - - make ci-test-no-generate; - diff --git a/vendor/github.com/aws/aws-sdk-go-v2/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/CHANGELOG.md deleted file mode 100644 index 47da5cbbf..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/CHANGELOG.md +++ /dev/null @@ -1,10936 +0,0 @@ -# Release (2023-08-21) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2`: v1.21.0 - * **Feature**: Add support for polly SynthesizeSpeech GET request presigner -* `github.com/aws/aws-sdk-go-v2/service/cloud9`: [v1.18.6](service/cloud9/CHANGELOG.md#v1186-2023-08-21) - * **Documentation**: Doc only update to add Ubuntu 22.04 as an Image ID option for Cloud9 -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.114.0](service/ec2/CHANGELOG.md#v11140-2023-08-21) - * **Feature**: The DeleteKeyPair API has been updated to return the keyPairId when an existing key pair is deleted. -* `github.com/aws/aws-sdk-go-v2/service/finspace`: [v1.12.0](service/finspace/CHANGELOG.md#v1120-2023-08-21) - * **Feature**: Allow customers to manage outbound traffic from their Kx Environment when attaching a transit gateway by providing network acl entries. Allow the customer to choose how they want to update the databases on a cluster allowing updates to possibly be faster than usual. -* `github.com/aws/aws-sdk-go-v2/service/polly`: [v1.30.0](service/polly/CHANGELOG.md#v1300-2023-08-21) - * **Feature**: Add support for polly SynthesizeSpeech GET request presigner -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.51.0](service/rds/CHANGELOG.md#v1510-2023-08-21) - * **Feature**: Adding support for RDS Aurora Global Database Unplanned Failover -* `github.com/aws/aws-sdk-go-v2/service/route53domains`: [v1.17.3](service/route53domains/CHANGELOG.md#v1173-2023-08-21) - * **Documentation**: Fixed typos in description fields - -# Release (2023-08-18) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/codecommit`: [v1.16.0](service/codecommit/CHANGELOG.md#v1160-2023-08-18) - * **Feature**: Add new ListFileCommitHistory operation to retrieve commits which introduced changes to a specific file. -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.36.0](service/securityhub/CHANGELOG.md#v1360-2023-08-18) - * **Feature**: Added Inspector Lambda code Vulnerability section to ASFF, including GeneratorDetails, EpssScore, ExploitAvailable, and CodeVulnerabilities. - -# Release (2023-08-17) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2`: v1.20.2 - * **Bug Fix**: Sign `X-Amz-Server-Side-Encryption-Context` header to fix signing for PutObject requests that set `SSEKMSEncryptionContext`. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.113.0](service/ec2/CHANGELOG.md#v11130-2023-08-17) - * **Feature**: Adds support for SubnetConfigurations to allow users to select their own IPv4 and IPv6 addresses for Interface VPC endpoints -* `github.com/aws/aws-sdk-go-v2/service/gamelift`: [v1.22.0](service/gamelift/CHANGELOG.md#v1220-2023-08-17) - * **Feature**: Amazon GameLift updates its instance types support. -* `github.com/aws/aws-sdk-go-v2/service/s3control`: [v1.32.3](service/s3control/CHANGELOG.md#v1323-2023-08-17) - * **Announcement**: BREAKFIX: corrected function spelling in environment config from GetS3DisableMultRegionAccessPoints to GetS3DisableMultiRegionAccessPoints - * **Bug Fix**: Adds DisableMRAP option to config loader, and DisableMRAP client resolver to achieve parity with other S3 options in the config loader. Additionally, added breakfix to correct spelling. - -# Release (2023-08-16) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudwatch`: [v1.27.3](service/cloudwatch/CHANGELOG.md#v1273-2023-08-16) - * **Documentation**: Doc-only update to incorporate several doc bug fixes - -# Release (2023-08-15) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmeetings`: [v1.17.0](service/chimesdkmeetings/CHANGELOG.md#v1170-2023-08-15) - * **Feature**: Updated API documentation to include additional exceptions. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.112.0](service/ec2/CHANGELOG.md#v11120-2023-08-15) - * **Feature**: Documentation updates for Elastic Compute Cloud (EC2). -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.61.0](service/glue/CHANGELOG.md#v1610-2023-08-15) - * **Feature**: AWS Glue Crawlers can now accept SerDe overrides from a custom csv classifier. The two SerDe options are LazySimpleSerDe and OpenCSVSerDe. In case, the user wants crawler to do the selection, "None" can be selected for this purpose. -* `github.com/aws/aws-sdk-go-v2/service/pi`: [v1.19.0](service/pi/CHANGELOG.md#v1190-2023-08-15) - * **Feature**: AWS Performance Insights for Amazon RDS is launching Performance Analysis On Demand, a new feature that allows you to analyze database performance metrics and find out the performance issues. You can now use SDK to create, list, get, delete, and manage tags of performance analysis reports. -* `github.com/aws/aws-sdk-go-v2/service/route53domains`: [v1.17.0](service/route53domains/CHANGELOG.md#v1170-2023-08-15) - * **Feature**: Provide explanation if CheckDomainTransferability return false. Provide requestId if a request is already submitted. Add sensitive protection for customer information -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.102.0](service/sagemaker/CHANGELOG.md#v11020-2023-08-15) - * **Feature**: SageMaker Inference Recommender now provides SupportedResponseMIMETypes from DescribeInferenceRecommendationsJob response - -# Release (2023-08-14) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/mediapackage`: [v1.23.0](service/mediapackage/CHANGELOG.md#v1230-2023-08-14) - * **Feature**: Fix SDK logging of certain fields. -* `github.com/aws/aws-sdk-go-v2/service/omics`: [v1.8.0](service/omics/CHANGELOG.md#v180-2023-08-14) - * **Feature**: This release provides support for annotation store versioning and cross account sharing for Omics Analytics -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.33.4](service/transfer/CHANGELOG.md#v1334-2023-08-14) - * **Documentation**: Documentation updates for AWS Transfer Family - -# Release (2023-08-11) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/amplifybackend`: [v1.16.0](service/amplifybackend/CHANGELOG.md#v1160-2023-08-11) - * **Feature**: Adds sensitive trait to required input shapes. -* `github.com/aws/aws-sdk-go-v2/service/configservice`: [v1.36.0](service/configservice/CHANGELOG.md#v1360-2023-08-11) - * **Feature**: Updated ResourceType enum with new resource types onboarded by AWS Config in July 2023. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.111.0](service/ec2/CHANGELOG.md#v11110-2023-08-11) - * **Feature**: Amazon EC2 P5 instances, powered by the latest NVIDIA H100 Tensor Core GPUs, deliver the highest performance in EC2 for deep learning (DL) and HPC applications. M7i-flex and M7i instances are next-generation general purpose instances powered by custom 4th Generation Intel Xeon Scalable processors. -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.41.0](service/quicksight/CHANGELOG.md#v1410-2023-08-11) - * **Feature**: New Authentication method for Account subscription - IAM Identity Center. Hierarchy layout support, default column width support and related style properties for pivot table visuals. Non-additive topic field aggregations for Topic API -* `github.com/aws/aws-sdk-go-v2/service/ses`: [v1.16.3](service/ses/CHANGELOG.md#v1163-2023-08-11) - * **Documentation**: Doc only updates to include: 1) Clarified which part of an email address where it's okay to have Punycode when it contains non-ASCII characters for the SendRawEmail action and other actions where this is applicable. 2) Updated S3Action description with new MB max bucket size from 30 to 40. -* `github.com/aws/aws-sdk-go-v2/service/swf`: [v1.17.0](service/swf/CHANGELOG.md#v1170-2023-08-11) - * **Feature**: This release adds new API parameters to override workflow task list for workflow executions. - -# Release (2023-08-10) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudtrail`: [v1.28.3](service/cloudtrail/CHANGELOG.md#v1283-2023-08-10) - * **Documentation**: Documentation updates for CloudTrail. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.65.0](service/connect/CHANGELOG.md#v1650-2023-08-10) - * **Feature**: This release adds APIs to provision agents that are global / available in multiple AWS regions and distribute them across these regions by percentage. -* `github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2`: [v1.21.0](service/elasticloadbalancingv2/CHANGELOG.md#v1210-2023-08-10) - * **Feature**: This release enables configuring security groups for Network Load Balancers -* `github.com/aws/aws-sdk-go-v2/service/omics`: [v1.7.0](service/omics/CHANGELOG.md#v170-2023-08-10) - * **Feature**: This release adds instanceType to GetRunTask & ListRunTasks responses. -* `github.com/aws/aws-sdk-go-v2/service/secretsmanager`: [v1.21.0](service/secretsmanager/CHANGELOG.md#v1210-2023-08-10) - * **Feature**: Add additional InvalidRequestException to list of possible exceptions for ListSecret. -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.33.3](service/transfer/CHANGELOG.md#v1333-2023-08-10) - * **Documentation**: Documentation updates for AW Transfer Family - -# Release (2023-08-09) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/chimesdkvoice`: [v1.8.0](service/chimesdkvoice/CHANGELOG.md#v180-2023-08-09) - * **Feature**: Updating CreatePhoneNumberOrder, UpdatePhoneNumber and BatchUpdatePhoneNumbers APIs, adding phone number name -* `github.com/aws/aws-sdk-go-v2/service/fsx`: [v1.32.0](service/fsx/CHANGELOG.md#v1320-2023-08-09) - * **Feature**: For FSx for Lustre, add new data repository task type, RELEASE_DATA_FROM_FILESYSTEM, to release files that have been archived to S3. For FSx for Windows, enable support for configuring and updating SSD IOPS, and for updating storage type. For FSx for OpenZFS, add new deployment type, MULTI_AZ_1. -* `github.com/aws/aws-sdk-go-v2/service/globalaccelerator`: [v1.17.3](service/globalaccelerator/CHANGELOG.md#v1173-2023-08-09) - * **Documentation**: Documentation update for dualstack EC2 endpoint support -* `github.com/aws/aws-sdk-go-v2/service/guardduty`: [v1.26.0](service/guardduty/CHANGELOG.md#v1260-2023-08-09) - * **Feature**: Added autoEnable ALL to UpdateOrganizationConfiguration and DescribeOrganizationConfiguration APIs. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.101.0](service/sagemaker/CHANGELOG.md#v11010-2023-08-09) - * **Feature**: This release adds support for cross account access for SageMaker Model Cards through AWS RAM. - -# Release (2023-08-08) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/backup`: [v1.24.0](service/backup/CHANGELOG.md#v1240-2023-08-08) - * **Feature**: This release introduces a new logically air-gapped vault (Preview) in AWS Backup that stores immutable backup copies, which are locked by default and isolated with encryption using AWS owned keys. Logically air-gapped vault (Preview) allows secure recovery of application data across accounts. -* `github.com/aws/aws-sdk-go-v2/service/elasticache`: [v1.29.0](service/elasticache/CHANGELOG.md#v1290-2023-08-08) - * **Feature**: Added support for cluster mode in online migration and test migration API -* `github.com/aws/aws-sdk-go-v2/service/servicecatalog`: [v1.21.0](service/servicecatalog/CHANGELOG.md#v1210-2023-08-08) - * **Feature**: Introduce support for HashiCorp Terraform Cloud in Service Catalog by addying TERRAFORM_CLOUD product type in CreateProduct and CreateProvisioningArtifact API. - -# Release (2023-08-07) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/detective`: [v1.21.0](service/detective/CHANGELOG.md#v1210-2023-08-07) - * **Feature**: Updated the email validation regex to be in line with the TLD name specifications. -* `github.com/aws/aws-sdk-go-v2/service/ivsrealtime`: [v1.4.0](service/ivsrealtime/CHANGELOG.md#v140-2023-08-07) - * **Feature**: Add QUOTA_EXCEEDED and PUBLISHER_NOT_FOUND to EventErrorCode for stage health events. -* `github.com/aws/aws-sdk-go-v2/service/kinesisvideo`: [v1.18.0](service/kinesisvideo/CHANGELOG.md#v1180-2023-08-07) - * **Feature**: This release enables minimum of Images SamplingInterval to be as low as 200 milliseconds in Kinesis Video Stream Image feature. -* `github.com/aws/aws-sdk-go-v2/service/kinesisvideoarchivedmedia`: [v1.16.0](service/kinesisvideoarchivedmedia/CHANGELOG.md#v1160-2023-08-07) - * **Feature**: This release enables minimum of Images SamplingInterval to be as low as 200 milliseconds in Kinesis Video Stream Image feature. -* `github.com/aws/aws-sdk-go-v2/service/rekognition`: [v1.30.2](service/rekognition/CHANGELOG.md#v1302-2023-08-07) - * **Documentation**: This release adds code snippets for Amazon Rekognition Custom Labels. - -# Release (2023-08-04) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/acmpca`: [v1.22.2](service/acmpca/CHANGELOG.md#v1222-2023-08-04) - * **Documentation**: Documentation correction for AWS Private CA -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.64.0](service/connect/CHANGELOG.md#v1640-2023-08-04) - * **Feature**: Added a new API UpdateRoutingProfileAgentAvailabilityTimer to update agent availability timer of a routing profile. -* `github.com/aws/aws-sdk-go-v2/service/datasync`: [v1.28.0](service/datasync/CHANGELOG.md#v1280-2023-08-04) - * **Feature**: Display cloud storage used capacity at a cluster level. -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.29.2](service/ecs/CHANGELOG.md#v1292-2023-08-04) - * **Documentation**: This is a documentation update to address various tickets. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.100.0](service/sagemaker/CHANGELOG.md#v11000-2023-08-04) - * **Feature**: Including DataCaptureConfig key in the Amazon Sagemaker Search's transform job object - -# Release (2023-08-03) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/autoscaling`: [v1.30.2](service/autoscaling/CHANGELOG.md#v1302-2023-08-03) - * **Documentation**: Documentation changes related to Amazon EC2 Auto Scaling APIs. -* `github.com/aws/aws-sdk-go-v2/service/cloud9`: [v1.18.2](service/cloud9/CHANGELOG.md#v1182-2023-08-03) - * **Documentation**: Updated the deprecation date for Amazon Linux. Doc only update. -* `github.com/aws/aws-sdk-go-v2/service/databasemigrationservice`: [v1.30.0](service/databasemigrationservice/CHANGELOG.md#v1300-2023-08-03) - * **Feature**: The release makes public API for DMS Schema Conversion feature. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.110.0](service/ec2/CHANGELOG.md#v11100-2023-08-03) - * **Feature**: This release adds new parameter isPrimaryIPv6 to allow assigning an IPv6 address as a primary IPv6 address to a network interface which cannot be changed to give equivalent functionality available for network interfaces with primary IPv4 address. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.99.0](service/sagemaker/CHANGELOG.md#v1990-2023-08-03) - * **Feature**: Amazon SageMaker now supports running training jobs on p5.48xlarge instance types. - -# Release (2023-08-02) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/budgets`: [v1.16.0](service/budgets/CHANGELOG.md#v1160-2023-08-02) - * **Feature**: As part of CAE tagging integration we need to update our budget names regex filter to prevent customers from using "/action/" in their budget names. -* `github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider`: [v1.25.0](service/cognitoidentityprovider/CHANGELOG.md#v1250-2023-08-02) - * **Feature**: New feature that logs Cognito user pool error messages to CloudWatch logs. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.60.0](service/glue/CHANGELOG.md#v1600-2023-08-02) - * **Feature**: This release includes additional Glue Streaming KAKFA SASL property types. -* `github.com/aws/aws-sdk-go-v2/service/resiliencehub`: [v1.13.0](service/resiliencehub/CHANGELOG.md#v1130-2023-08-02) - * **Feature**: Drift Detection capability added when applications policy has moved from a meet to breach state. Customers will be able to exclude operational recommendations and receive credit in their resilience score. Customers can now add ARH permissions to an existing or new role. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.98.0](service/sagemaker/CHANGELOG.md#v1980-2023-08-02) - * **Feature**: SageMaker Inference Recommender introduces a new API GetScalingConfigurationRecommendation to recommend auto scaling policies based on completed Inference Recommender jobs. - -# Release (2023-08-01) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/batch`: [v1.26.0](service/batch/CHANGELOG.md#v1260-2023-08-01) - * **Feature**: This release adds support for price capacity optimized allocation strategy for Spot Instances. -* `github.com/aws/aws-sdk-go-v2/service/databasemigrationservice`: [v1.29.0](service/databasemigrationservice/CHANGELOG.md#v1290-2023-08-01) - * **Feature**: Adding new API describe-engine-versions which provides information about the lifecycle of a replication instance's version. -* `github.com/aws/aws-sdk-go-v2/service/internetmonitor`: [v1.5.0](service/internetmonitor/CHANGELOG.md#v150-2023-08-01) - * **Feature**: This release adds a new feature for Amazon CloudWatch Internet Monitor that enables customers to set custom thresholds, for performance and availability drops, for impact limited to a single city-network to trigger creation of a health event. -* `github.com/aws/aws-sdk-go-v2/service/medialive`: [v1.34.0](service/medialive/CHANGELOG.md#v1340-2023-08-01) - * **Feature**: AWS Elemental Link devices now report their Availability Zone. Link devices now support the ability to change their Availability Zone. -* `github.com/aws/aws-sdk-go-v2/service/polly`: [v1.29.0](service/polly/CHANGELOG.md#v1290-2023-08-01) - * **Feature**: Amazon Polly adds new French Belgian voice - Isabelle. Isabelle is available as Neural voice only. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.50.0](service/rds/CHANGELOG.md#v1500-2023-08-01) - * **Feature**: Added support for deleted clusters PiTR. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.97.0](service/sagemaker/CHANGELOG.md#v1970-2023-08-01) - * **Feature**: Add Stairs TrafficPattern and FlatInvocations to RecommendationJobStoppingConditions - -# Release (2023-07-31) - -## General Highlights -* **Feature**: Adds support for smithy-modeled endpoint resolution. A new rules-based endpoint resolution will be added to the SDK which will supercede and deprecate existing endpoint resolution. Specifically, EndpointResolver will be deprecated while BaseEndpoint and EndpointResolverV2 will take its place. For more information, please see the Endpoints section in our Developer Guide. -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/amplifyuibuilder`: [v1.12.0](service/amplifyuibuilder/CHANGELOG.md#v1120-2023-07-31) - * **Feature**: Amplify Studio releases GraphQL support for codegen job action. -* `github.com/aws/aws-sdk-go-v2/service/autoscaling`: [v1.30.0](service/autoscaling/CHANGELOG.md#v1300-2023-07-31) - * **Feature**: You can now configure an instance refresh to set its status to 'failed' when it detects that a specified CloudWatch alarm has gone into the ALARM state. You can also choose to roll back the instance refresh automatically when the alarm threshold is met. -* `github.com/aws/aws-sdk-go-v2/service/cleanrooms`: [v1.3.0](service/cleanrooms/CHANGELOG.md#v130-2023-07-31) - * **Feature**: This release introduces custom SQL queries - an expanded set of SQL you can run. This release adds analysis templates, a new resource for storing pre-defined custom SQL queries ahead of time. This release also adds the Custom analysis rule, which lets you approve analysis templates for querying. -* `github.com/aws/aws-sdk-go-v2/service/codestarconnections`: [v1.15.0](service/codestarconnections/CHANGELOG.md#v1150-2023-07-31) - * **Feature**: New integration with the Gitlab provider type. -* `github.com/aws/aws-sdk-go-v2/service/drs`: [v1.15.0](service/drs/CHANGELOG.md#v1150-2023-07-31) - * **Feature**: Add support for in-aws right sizing -* `github.com/aws/aws-sdk-go-v2/service/inspector2`: [v1.16.0](service/inspector2/CHANGELOG.md#v1160-2023-07-31) - * **Feature**: This release adds 1 new API: BatchGetFindingDetails to retrieve enhanced vulnerability intelligence details for findings. -* `github.com/aws/aws-sdk-go-v2/service/lookoutequipment`: [v1.18.0](service/lookoutequipment/CHANGELOG.md#v1180-2023-07-31) - * **Feature**: This release includes new import resource, model versioning and resource policy features. -* `github.com/aws/aws-sdk-go-v2/service/omics`: [v1.6.0](service/omics/CHANGELOG.md#v160-2023-07-31) - * **Feature**: Add CreationType filter for ListReadSets -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.49.0](service/rds/CHANGELOG.md#v1490-2023-07-31) - * **Feature**: This release adds support for Aurora MySQL local write forwarding, which allows for forwarding of write operations from reader DB instances to the writer DB instance. -* `github.com/aws/aws-sdk-go-v2/service/route53`: [v1.29.0](service/route53/CHANGELOG.md#v1290-2023-07-31) - * **Feature**: Amazon Route 53 now supports the Israel (Tel Aviv) Region (il-central-1) for latency records, geoproximity records, and private DNS for Amazon VPCs in that region. -* `github.com/aws/aws-sdk-go-v2/service/scheduler`: [v1.2.0](service/scheduler/CHANGELOG.md#v120-2023-07-31) - * **Feature**: This release introduces automatic deletion of schedules in EventBridge Scheduler. If configured, EventBridge Scheduler automatically deletes a schedule after the schedule has completed its last invocation. - -# Release (2023-07-28.2) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/applicationinsights`: [v1.18.0](service/applicationinsights/CHANGELOG.md#v1180-2023-07-282) - * **Feature**: This release enable customer to add/remove/update more than one workload for a component -* `github.com/aws/aws-sdk-go-v2/service/cloudformation`: [v1.33.0](service/cloudformation/CHANGELOG.md#v1330-2023-07-282) - * **Feature**: This SDK release is for the feature launch of AWS CloudFormation RetainExceptOnCreate. It adds a new parameter retainExceptOnCreate in the following APIs: CreateStack, UpdateStack, RollbackStack, ExecuteChangeSet. -* `github.com/aws/aws-sdk-go-v2/service/cloudfront`: [v1.27.0](service/cloudfront/CHANGELOG.md#v1270-2023-07-282) - * **Feature**: Add a new JavaScript runtime version for CloudFront Functions. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.62.0](service/connect/CHANGELOG.md#v1620-2023-07-282) - * **Feature**: This release adds support for new number types. -* `github.com/aws/aws-sdk-go-v2/service/kafka`: [v1.21.0](service/kafka/CHANGELOG.md#v1210-2023-07-282) - * **Feature**: Amazon MSK has introduced new versions of ListClusterOperations and DescribeClusterOperation APIs. These v2 APIs provide information and insights into the ongoing operations of both MSK Provisioned and MSK Serverless clusters. -* `github.com/aws/aws-sdk-go-v2/service/pinpoint`: [v1.21.0](service/pinpoint/CHANGELOG.md#v1210-2023-07-282) - * **Feature**: Added support for sending push notifications using the FCM v1 API with json credentials. Amazon Pinpoint customers can now deliver messages to Android devices using both FCM v1 API and the legacy FCM/GCM API - -# Release (2023-07-28) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/sqs`: [v1.23.4](service/sqs/CHANGELOG.md#v1234-2023-07-28) - * **Documentation**: Documentation changes related to SQS APIs. - -# Release (2023-07-27) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/autoscaling`: [v1.29.0](service/autoscaling/CHANGELOG.md#v1290-2023-07-27) - * **Feature**: This release updates validation for instance types used in the AllowedInstanceTypes and ExcludedInstanceTypes parameters of the InstanceRequirements property of a MixedInstancesPolicy. -* `github.com/aws/aws-sdk-go-v2/service/ebs`: [v1.17.0](service/ebs/CHANGELOG.md#v1170-2023-07-27) - * **Feature**: SDK and documentation updates for Amazon Elastic Block Store API -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.108.0](service/ec2/CHANGELOG.md#v11080-2023-07-27) - * **Feature**: SDK and documentation updates for Amazon Elastic Block Store APIs -* `github.com/aws/aws-sdk-go-v2/service/eks`: [v1.28.0](service/eks/CHANGELOG.md#v1280-2023-07-27) - * **Feature**: Add multiple customer error code to handle customer caused failure when managing EKS node groups -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.95.0](service/sagemaker/CHANGELOG.md#v1950-2023-07-27) - * **Feature**: Expose ProfilerConfig attribute in SageMaker Search API response. - -# Release (2023-07-26) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/entityresolution`: [v1.0.0](service/entityresolution/CHANGELOG.md#v100-2023-07-26) - * **Release**: New AWS service client module - * **Feature**: AWS Entity Resolution can effectively match a source record from a customer relationship management (CRM) system with a source record from a marketing system containing campaign information. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.58.0](service/glue/CHANGELOG.md#v1580-2023-07-26) - * **Feature**: Release Glue Studio Snowflake Connector Node for SDK/CLI -* `github.com/aws/aws-sdk-go-v2/service/healthlake`: [v1.16.4](service/healthlake/CHANGELOG.md#v1164-2023-07-26) - * **Documentation**: Updating the HealthLake service documentation. -* `github.com/aws/aws-sdk-go-v2/service/managedblockchainquery`: [v1.0.0](service/managedblockchainquery/CHANGELOG.md#v100-2023-07-26) - * **Release**: New AWS service client module - * **Feature**: Amazon Managed Blockchain (AMB) Query provides serverless access to standardized, multi-blockchain datasets with developer-friendly APIs. -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.39.1](service/mediaconvert/CHANGELOG.md#v1391-2023-07-26) - * **Documentation**: This release includes general updates to user documentation. -* `github.com/aws/aws-sdk-go-v2/service/omics`: [v1.5.2](service/omics/CHANGELOG.md#v152-2023-07-26) - * **Documentation**: The service is renaming as a part of AWS Health. -* `github.com/aws/aws-sdk-go-v2/service/opensearchserverless`: [v1.3.0](service/opensearchserverless/CHANGELOG.md#v130-2023-07-26) - * **Feature**: This release adds new collection type VectorSearch. -* `github.com/aws/aws-sdk-go-v2/service/polly`: [v1.27.0](service/polly/CHANGELOG.md#v1270-2023-07-26) - * **Feature**: Amazon Polly adds 1 new voice - Lisa (nl-BE) -* `github.com/aws/aws-sdk-go-v2/service/route53`: [v1.28.5](service/route53/CHANGELOG.md#v1285-2023-07-26) - * **Documentation**: Update that corrects the documents for received feedback. - -# Release (2023-07-25) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/billingconductor`: [v1.7.0](service/billingconductor/CHANGELOG.md#v170-2023-07-25) - * **Feature**: Added support for Auto-Assocate Billing Groups for CreateBillingGroup, UpdateBillingGroup, and ListBillingGroups. -* `github.com/aws/aws-sdk-go-v2/service/customerprofiles`: [v1.26.0](service/customerprofiles/CHANGELOG.md#v1260-2023-07-25) - * **Feature**: Amazon Connect Customer Profiles now supports rule-based resolution to match and merge similar profiles into unified profiles, helping companies deliver faster and more personalized customer service by providing access to relevant customer information for agents and automated experiences. -* `github.com/aws/aws-sdk-go-v2/service/datasync`: [v1.26.0](service/datasync/CHANGELOG.md#v1260-2023-07-25) - * **Feature**: AWS DataSync now supports Microsoft Azure Blob Storage locations. -* `github.com/aws/aws-sdk-go-v2/service/dynamodb`: [v1.20.2](service/dynamodb/CHANGELOG.md#v1202-2023-07-25) - * **Documentation**: Documentation updates for DynamoDB -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.107.0](service/ec2/CHANGELOG.md#v11070-2023-07-25) - * **Feature**: This release adds an instance's peak and baseline network bandwidth as well as the memory sizes of an instance's inference accelerators to DescribeInstanceTypes. -* `github.com/aws/aws-sdk-go-v2/service/emrserverless`: [v1.9.0](service/emrserverless/CHANGELOG.md#v190-2023-07-25) - * **Feature**: This release adds support for publishing application logs to CloudWatch. -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.38.0](service/lambda/CHANGELOG.md#v1380-2023-07-25) - * **Feature**: Add Python 3.11 (python3.11) support to AWS Lambda -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.48.0](service/rds/CHANGELOG.md#v1480-2023-07-25) - * **Feature**: This release adds support for monitoring storage optimization progress on the DescribeDBInstances API. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.94.0](service/sagemaker/CHANGELOG.md#v1940-2023-07-25) - * **Feature**: Mark ContentColumn and TargetLabelColumn as required Targets in TextClassificationJobConfig in CreateAutoMLJobV2API -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.34.0](service/securityhub/CHANGELOG.md#v1340-2023-07-25) - * **Feature**: Add support for CONTAINS and NOT_CONTAINS comparison operators for Automation Rules string filters and map filters -* `github.com/aws/aws-sdk-go-v2/service/sts`: [v1.20.0](service/sts/CHANGELOG.md#v1200-2023-07-25) - * **Feature**: API updates for the AWS Security Token Service -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.32.0](service/transfer/CHANGELOG.md#v1320-2023-07-25) - * **Feature**: This release adds support for SFTP Connectors. -* `github.com/aws/aws-sdk-go-v2/service/wisdom`: [v1.14.0](service/wisdom/CHANGELOG.md#v1140-2023-07-25) - * **Feature**: This release added two new data types: AssistantIntegrationConfiguration, and SessionIntegrationConfiguration to support Wisdom integration with Amazon Connect Chat - -# Release (2023-07-24) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/apigatewayv2`: [v1.13.15](service/apigatewayv2/CHANGELOG.md#v11315-2023-07-24) - * **Documentation**: Documentation updates for Amazon API Gateway. -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmediapipelines`: [v1.5.0](service/chimesdkmediapipelines/CHANGELOG.md#v150-2023-07-24) - * **Feature**: AWS Media Pipeline compositing enhancement and Media Insights Pipeline auto language identification. -* `github.com/aws/aws-sdk-go-v2/service/cloudformation`: [v1.32.0](service/cloudformation/CHANGELOG.md#v1320-2023-07-24) - * **Feature**: This release supports filtering by DRIFT_STATUS for existing API ListStackInstances and adds support for a new API ListStackInstanceResourceDrifts. Customers can now view resource drift information from their StackSet management accounts. -* `github.com/aws/aws-sdk-go-v2/service/costexplorer`: [v1.26.0](service/costexplorer/CHANGELOG.md#v1260-2023-07-24) - * **Feature**: This release introduces the new API 'GetSavingsPlanPurchaseRecommendationDetails', which retrieves the details for a Savings Plan recommendation. It also updates the existing API 'GetSavingsPlansPurchaseRecommendation' to include the recommendation detail ID. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.106.0](service/ec2/CHANGELOG.md#v11060-2023-07-24) - * **Feature**: Add "disabled" enum value to SpotInstanceState. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.57.0](service/glue/CHANGELOG.md#v1570-2023-07-24) - * **Feature**: Added support for Data Preparation Recipe node in Glue Studio jobs -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.39.0](service/quicksight/CHANGELOG.md#v1390-2023-07-24) - * **Feature**: This release launches new Snapshot APIs for CSV and PDF exports, adds support for info icon for filters and parameters in Exploration APIs, adds modeled exception to the DeleteAccountCustomization API, and introduces AttributeAggregationFunction's ability to add UNIQUE_VALUE aggregation in tooltips. - -# Release (2023-07-21) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.56.0](service/glue/CHANGELOG.md#v1560-2023-07-21) - * **Feature**: This release adds support for AWS Glue Crawler with Apache Hudi Tables, allowing Crawlers to discover Hudi Tables in S3 and register them in Glue Data Catalog for query engines to query against. -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.39.0](service/mediaconvert/CHANGELOG.md#v1390-2023-07-21) - * **Feature**: This release includes improvements to Preserve 444 handling, compatibility of HEVC sources without frame rates, and general improvements to MP4 outputs. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.47.0](service/rds/CHANGELOG.md#v1470-2023-07-21) - * **Feature**: Adds support for the DBSystemID parameter of CreateDBInstance to RDS Custom for Oracle. -* `github.com/aws/aws-sdk-go-v2/service/workspaces`: [v1.28.17](service/workspaces/CHANGELOG.md#v12817-2023-07-21) - * **Documentation**: Fixed VolumeEncryptionKey descriptions - -# Release (2023-07-20.2) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/codecatalyst`: [v1.4.0](service/codecatalyst/CHANGELOG.md#v140-2023-07-202) - * **Feature**: This release adds support for updating and deleting spaces and projects in Amazon CodeCatalyst. It also adds support for creating, getting, and deleting source repositories in CodeCatalyst projects. -* `github.com/aws/aws-sdk-go-v2/service/connectcases`: [v1.5.0](service/connectcases/CHANGELOG.md#v150-2023-07-202) - * **Feature**: This release adds the ability to assign a case to a queue or user. -* `github.com/aws/aws-sdk-go-v2/service/lexmodelsv2`: [v1.31.0](service/lexmodelsv2/CHANGELOG.md#v1310-2023-07-202) - * **Feature**: This release updates type for Channel field in SessionSpecification and UtteranceSpecification -* `github.com/aws/aws-sdk-go-v2/service/route53resolver`: [v1.18.0](service/route53resolver/CHANGELOG.md#v1180-2023-07-202) - * **Feature**: This release adds support for Route 53 On Outposts, a new feature that allows customers to run Route 53 Resolver and Resolver endpoints locally on their Outposts. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.93.0](service/sagemaker/CHANGELOG.md#v1930-2023-07-202) - * **Feature**: Cross account support for SageMaker Feature Store -* `github.com/aws/aws-sdk-go-v2/service/sagemakerfeaturestoreruntime`: [v1.16.0](service/sagemakerfeaturestoreruntime/CHANGELOG.md#v1160-2023-07-202) - * **Feature**: Cross account support for SageMaker Feature Store -* `github.com/aws/aws-sdk-go-v2/service/securitylake`: [v1.5.0](service/securitylake/CHANGELOG.md#v150-2023-07-202) - * **Feature**: Adding support for Tags on Create and Resource Tagging API. -* `github.com/aws/aws-sdk-go-v2/service/transcribe`: [v1.27.0](service/transcribe/CHANGELOG.md#v1270-2023-07-202) - * **Feature**: Added API argument --toxicity-detection to startTranscriptionJob API, which allows users to view toxicity scores of submitted audio. - -# Release (2023-07-20) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/savingsplans`: [v1.12.14](service/savingsplans/CHANGELOG.md#v11214-2023-07-20) - * **Documentation**: Savings Plans endpoints update - -# Release (2023-07-19) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudformation`: [v1.31.0](service/cloudformation/CHANGELOG.md#v1310-2023-07-19) - * **Feature**: SDK and documentation updates for GetTemplateSummary API (unrecognized resources) -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.105.1](service/ec2/CHANGELOG.md#v11051-2023-07-19) - * **Documentation**: Amazon EC2 documentation updates. -* `github.com/aws/aws-sdk-go-v2/service/grafana`: [v1.14.0](service/grafana/CHANGELOG.md#v1140-2023-07-19) - * **Feature**: Amazon Managed Grafana now supports grafanaVersion update for existing workspaces with UpdateWorkspaceConfiguration API. DescribeWorkspaceConfiguration API additionally returns grafanaVersion. A new ListVersions API lists available versions or, if given a workspaceId, the versions it can upgrade to. -* `github.com/aws/aws-sdk-go-v2/service/medicalimaging`: [v1.0.0](service/medicalimaging/CHANGELOG.md#v100-2023-07-19) - * **Release**: New AWS service client module - * **Feature**: General Availability (GA) release of AWS Health Imaging, enabling customers to store, transform, and analyze medical imaging data at petabyte-scale. -* `github.com/aws/aws-sdk-go-v2/service/ram`: [v1.19.0](service/ram/CHANGELOG.md#v1190-2023-07-19) - * **Feature**: This release adds support for securely sharing with AWS service principals. -* `github.com/aws/aws-sdk-go-v2/service/ssmsap`: [v1.3.0](service/ssmsap/CHANGELOG.md#v130-2023-07-19) - * **Feature**: Added support for SAP Hana High Availability discovery (primary and secondary nodes) and Backint agent installation with SSM for SAP. -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.36.0](service/wafv2/CHANGELOG.md#v1360-2023-07-19) - * **Feature**: Added the URI path to the custom aggregation keys that you can specify for a rate-based rule. - -# Release (2023-07-18) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/codegurusecurity`: [v1.0.3](service/codegurusecurity/CHANGELOG.md#v103-2023-07-18) - * **Documentation**: Documentation updates for CodeGuru Security. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.61.1](service/connect/CHANGELOG.md#v1611-2023-07-18) - * **Documentation**: GetMetricDataV2 API: Update to include Contact Lens Conversational Analytics Metrics -* `github.com/aws/aws-sdk-go-v2/service/lexmodelsv2`: [v1.30.0](service/lexmodelsv2/CHANGELOG.md#v1300-2023-07-18) - * **Feature**: This release adds support for Lex Developers to view analytics for their bots. -* `github.com/aws/aws-sdk-go-v2/service/m2`: [v1.6.0](service/m2/CHANGELOG.md#v160-2023-07-18) - * **Feature**: Allows UpdateEnvironment to update the environment to 0 host capacity. New GetSignedBluinsightsUrl API -* `github.com/aws/aws-sdk-go-v2/service/snowball`: [v1.20.0](service/snowball/CHANGELOG.md#v1200-2023-07-18) - * **Feature**: Adds support for RACK_5U_C. This is the first AWS Snow Family device designed to meet U.S. Military Ruggedization Standards (MIL-STD-810H) with 208 vCPU device in a portable, compact 5U, half-rack width form-factor. -* `github.com/aws/aws-sdk-go-v2/service/translate`: [v1.18.4](service/translate/CHANGELOG.md#v1184-2023-07-18) - * **Documentation**: Added DOCX word document support to TranslateDocument API - -# Release (2023-07-17) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/codeartifact`: [v1.18.8](service/codeartifact/CHANGELOG.md#v1188-2023-07-17) - * **Documentation**: Doc only update for AWS CodeArtifact -* `github.com/aws/aws-sdk-go-v2/service/docdb`: [v1.22.0](service/docdb/CHANGELOG.md#v1220-2023-07-17) - * **Feature**: Added major version upgrade option in ModifyDBCluster API -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.105.0](service/ec2/CHANGELOG.md#v11050-2023-07-17) - * **Feature**: Add Nitro TPM support on DescribeInstanceTypes -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.55.0](service/glue/CHANGELOG.md#v1550-2023-07-17) - * **Feature**: Adding new supported permission type flags to get-unfiltered endpoints that callers may pass to indicate support for enforcing Lake Formation fine-grained access control on nested column attributes. -* `github.com/aws/aws-sdk-go-v2/service/ivs`: [v1.24.0](service/ivs/CHANGELOG.md#v1240-2023-07-17) - * **Feature**: This release provides the flexibility to configure what renditions or thumbnail qualities to record when creating recording configuration. -* `github.com/aws/aws-sdk-go-v2/service/lakeformation`: [v1.22.0](service/lakeformation/CHANGELOG.md#v1220-2023-07-17) - * **Feature**: Adds supports for ReadOnlyAdmins and AllowFullTableExternalDataAccess. Adds NESTED_PERMISSION and NESTED_CELL_PERMISSION to SUPPORTED_PERMISSION_TYPES enum. Adds CREATE_LF_TAG on catalog resource and ALTER, DROP, and GRANT_WITH_LF_TAG_EXPRESSION on LF Tag resource. - -# Release (2023-07-13) - -## General Highlights -* **Feature**: Modify user agent syntax and introduce support for optional app identifier in UA header -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider`: [v1.23.0](service/cognitoidentityprovider/CHANGELOG.md#v1230-2023-07-13) - * **Feature**: API model updated in Amazon Cognito -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.61.0](service/connect/CHANGELOG.md#v1610-2023-07-13) - * **Feature**: Add support for deleting Queues and Routing Profiles. -* `github.com/aws/aws-sdk-go-v2/service/databasemigrationservice`: [v1.27.0](service/databasemigrationservice/CHANGELOG.md#v1270-2023-07-13) - * **Feature**: Enhanced PostgreSQL target endpoint settings for providing Babelfish support. -* `github.com/aws/aws-sdk-go-v2/service/datasync`: [v1.25.0](service/datasync/CHANGELOG.md#v1250-2023-07-13) - * **Feature**: Added LunCount to the response object of DescribeStorageSystemResourcesResponse, LunCount represents the number of LUNs on a storage system resource. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.104.0](service/ec2/CHANGELOG.md#v11040-2023-07-13) - * **Feature**: This release adds support for the C7gn and Hpc7g instances. C7gn instances are powered by AWS Graviton3 processors and the fifth-generation AWS Nitro Cards. Hpc7g instances are powered by AWS Graviton 3E processors and provide up to 200 Gbps network bandwidth. -* `github.com/aws/aws-sdk-go-v2/service/fsx`: [v1.30.0](service/fsx/CHANGELOG.md#v1300-2023-07-13) - * **Feature**: Amazon FSx for NetApp ONTAP now supports SnapLock, an ONTAP feature that enables you to protect your files in a volume by transitioning them to a write once, read many (WORM) state. -* `github.com/aws/aws-sdk-go-v2/service/iam`: [v1.21.1](service/iam/CHANGELOG.md#v1211-2023-07-13) - * **Documentation**: Documentation updates for AWS Identity and Access Management (IAM). -* `github.com/aws/aws-sdk-go-v2/service/mediatailor`: [v1.25.0](service/mediatailor/CHANGELOG.md#v1250-2023-07-13) - * **Feature**: Adds categories to MediaTailor channel assembly alerts -* `github.com/aws/aws-sdk-go-v2/service/personalize`: [v1.25.0](service/personalize/CHANGELOG.md#v1250-2023-07-13) - * **Feature**: This release provides ability to customers to change schema associated with their datasets in Amazon Personalize -* `github.com/aws/aws-sdk-go-v2/service/proton`: [v1.22.0](service/proton/CHANGELOG.md#v1220-2023-07-13) - * **Feature**: This release adds support for deployment history for Proton provisioned resources -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.37.0](service/s3/CHANGELOG.md#v1370-2023-07-13) - * **Feature**: S3 Inventory now supports Object Access Control List and Object Owner as available object metadata fields in inventory reports. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.92.0](service/sagemaker/CHANGELOG.md#v1920-2023-07-13) - * **Feature**: Amazon SageMaker Canvas adds WorkspeceSettings support for CanvasAppSettings -* `github.com/aws/aws-sdk-go-v2/service/secretsmanager`: [v1.19.11](service/secretsmanager/CHANGELOG.md#v11911-2023-07-13) - * **Documentation**: Documentation updates for Secrets Manager - -# Release (2023-07-07) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs`: [v1.22.0](service/cloudwatchlogs/CHANGELOG.md#v1220-2023-07-07) - * **Feature**: Add CMK encryption support for CloudWatch Logs Insights query result data -* `github.com/aws/aws-sdk-go-v2/service/databasemigrationservice`: [v1.26.0](service/databasemigrationservice/CHANGELOG.md#v1260-2023-07-07) - * **Feature**: Releasing DMS Serverless. Adding support for PostgreSQL 15.x as source and target endpoint. Adding support for DocDB Elastic Clusters with sharded collections, PostgreSQL datatype mapping customization and disabling hostname validation of the certificate authority in Kafka endpoint settings -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.54.0](service/glue/CHANGELOG.md#v1540-2023-07-07) - * **Feature**: This release enables customers to create new Apache Iceberg tables and associated metadata in Amazon S3 by using native AWS Glue CreateTable operation. -* `github.com/aws/aws-sdk-go-v2/service/medialive`: [v1.32.0](service/medialive/CHANGELOG.md#v1320-2023-07-07) - * **Feature**: This release enables the use of Thumbnails in AWS Elemental MediaLive. -* `github.com/aws/aws-sdk-go-v2/service/mediatailor`: [v1.24.0](service/mediatailor/CHANGELOG.md#v1240-2023-07-07) - * **Feature**: The AWS Elemental MediaTailor SDK for Channel Assembly has added support for EXT-X-CUE-OUT and EXT-X-CUE-IN tags to specify ad breaks in HLS outputs, including support for EXT-OATCLS, EXT-X-ASSET, and EXT-X-CUE-OUT-CONT accessory tags. - -# Release (2023-07-06) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.103.0](service/ec2/CHANGELOG.md#v11030-2023-07-06) - * **Feature**: Add Nitro Enclaves support on DescribeInstanceTypes -* `github.com/aws/aws-sdk-go-v2/service/location`: [v1.25.0](service/location/CHANGELOG.md#v1250-2023-07-06) - * **Feature**: This release adds support for authenticating with Amazon Location Service's Places & Routes APIs with an API Key. Also, with this release developers can publish tracked device position updates to Amazon EventBridge. -* `github.com/aws/aws-sdk-go-v2/service/outposts`: [v1.28.0](service/outposts/CHANGELOG.md#v1280-2023-07-06) - * **Feature**: Added paginator support to several APIs. Added the ISOLATED enum value to AssetState. -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.38.0](service/quicksight/CHANGELOG.md#v1380-2023-07-06) - * **Feature**: This release includes below three changes: small multiples axes improvement, field based coloring, removed required trait from Aggregation function for TopBottomFilter. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.46.1](service/rds/CHANGELOG.md#v1461-2023-07-06) - * **Documentation**: Updates Amazon RDS documentation for creating DB instances and creating Aurora global clusters. - -# Release (2023-07-05) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/comprehendmedical`: [v1.16.3](service/comprehendmedical/CHANGELOG.md#v1163-2023-07-05) - * **Documentation**: Update to Amazon Comprehend Medical documentation. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.60.1](service/connect/CHANGELOG.md#v1601-2023-07-05) - * **Documentation**: GetMetricDataV2 API: Channels filters do not count towards overall limitation of 100 filter values. -* `github.com/aws/aws-sdk-go-v2/service/kms`: [v1.23.0](service/kms/CHANGELOG.md#v1230-2023-07-05) - * **Feature**: Added Dry Run Feature to cryptographic and cross-account mutating KMS APIs (14 in all). This feature allows users to test their permissions and parameters before making the actual API call. -* `github.com/aws/aws-sdk-go-v2/service/mgn`: [v1.19.0](service/mgn/CHANGELOG.md#v1190-2023-07-05) - * **Feature**: This release introduces the Global view feature and new Replication state APIs. -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.33.2](service/securityhub/CHANGELOG.md#v1332-2023-07-05) - * **Documentation**: Documentation updates for AWS Security Hub - -# Release (2023-07-03) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/batch`: [v1.24.0](service/batch/CHANGELOG.md#v1240-2023-07-03) - * **Feature**: This feature allows customers to use AWS Batch with Linux with ARM64 CPU Architecture and X86_64 CPU Architecture with Windows OS on Fargate Platform. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.91.0](service/sagemaker/CHANGELOG.md#v1910-2023-07-03) - * **Feature**: SageMaker Inference Recommender now accepts new fields SupportedEndpointType and ServerlessConfiguration to support serverless endpoints. - -# Release (2023-06-30) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.28.0](service/ecs/CHANGELOG.md#v1280-2023-06-30) - * **Feature**: Added new field "credentialspecs" to the ecs task definition to support gMSA of windows/linux in both domainless and domain-joined mode -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.38.1](service/mediaconvert/CHANGELOG.md#v1381-2023-06-30) - * **Documentation**: This release includes improved color handling of overlays and general updates to user documentation. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.90.0](service/sagemaker/CHANGELOG.md#v1900-2023-06-30) - * **Feature**: This release adds support for rolling deployment in SageMaker Inference. -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.31.0](service/transfer/CHANGELOG.md#v1310-2023-06-30) - * **Feature**: Add outbound Basic authentication support to AS2 connectors -* `github.com/aws/aws-sdk-go-v2/service/verifiedpermissions`: [v1.0.4](service/verifiedpermissions/CHANGELOG.md#v104-2023-06-30) - * **Documentation**: This release corrects several broken links in the documentation. - -# Release (2023-06-29) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/appstream`: [v1.21.0](service/appstream/CHANGELOG.md#v1210-2023-06-29) - * **Feature**: This release introduces app block builder, allowing customers to provision a resource to package applications into an app block -* `github.com/aws/aws-sdk-go-v2/service/chime`: [v1.24.0](service/chime/CHANGELOG.md#v1240-2023-06-29) - * **Feature**: The Amazon Chime SDK APIs in the Chime namespace are no longer supported. Customers should use APIs in the dedicated Amazon Chime SDK namespaces: ChimeSDKIdentity, ChimeSDKMediaPipelines, ChimeSDKMeetings, ChimeSDKMessaging, and ChimeSDKVoice. -* `github.com/aws/aws-sdk-go-v2/service/cleanrooms`: [v1.2.0](service/cleanrooms/CHANGELOG.md#v120-2023-06-29) - * **Feature**: This release adds support for the OR operator in RSQL join match conditions and the ability to control which operators (AND, OR) are allowed in a join match condition. -* `github.com/aws/aws-sdk-go-v2/service/dynamodb`: [v1.20.0](service/dynamodb/CHANGELOG.md#v1200-2023-06-29) - * **Feature**: This release adds ReturnValuesOnConditionCheckFailure parameter to PutItem, UpdateItem, DeleteItem, ExecuteStatement, BatchExecuteStatement and ExecuteTransaction APIs. When set to ALL_OLD, API returns a copy of the item as it was when a conditional write failed -* `github.com/aws/aws-sdk-go-v2/service/gamelift`: [v1.20.0](service/gamelift/CHANGELOG.md#v1200-2023-06-29) - * **Feature**: Amazon GameLift now supports game builds that use the Amazon Linux 2023 (AL2023) operating system. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.53.0](service/glue/CHANGELOG.md#v1530-2023-06-29) - * **Feature**: This release adds support for AWS Glue Crawler with Iceberg Tables, allowing Crawlers to discover Iceberg Tables in S3 and register them in Glue Data Catalog for query engines to query against. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.89.0](service/sagemaker/CHANGELOG.md#v1890-2023-06-29) - * **Feature**: Adding support for timeseries forecasting in the CreateAutoMLJobV2 API. - -# Release (2023-06-28) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/internetmonitor`: [v1.3.0](service/internetmonitor/CHANGELOG.md#v130-2023-06-28) - * **Feature**: This release adds a new feature for Amazon CloudWatch Internet Monitor that enables customers to set custom thresholds, for performance and availability drops, for triggering when to create a health event. -* `github.com/aws/aws-sdk-go-v2/service/kinesisanalyticsv2`: [v1.17.0](service/kinesisanalyticsv2/CHANGELOG.md#v1170-2023-06-28) - * **Feature**: Support for new runtime environment in Kinesis Data Analytics Studio: Zeppelin-0.10, Apache Flink-1.15 -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.37.0](service/lambda/CHANGELOG.md#v1370-2023-06-28) - * **Feature**: Surface ResourceConflictException in DeleteEventSourceMapping -* `github.com/aws/aws-sdk-go-v2/service/omics`: [v1.5.0](service/omics/CHANGELOG.md#v150-2023-06-28) - * **Feature**: Add Common Workflow Language (CWL) as a supported language for Omics workflows -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.46.0](service/rds/CHANGELOG.md#v1460-2023-06-28) - * **Feature**: Amazon Relational Database Service (RDS) now supports joining a RDS for SQL Server instance to a self-managed Active Directory. -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.36.0](service/s3/CHANGELOG.md#v1360-2023-06-28) - * **Feature**: The S3 LISTObjects, ListObjectsV2 and ListObjectVersions API now supports a new optional header x-amz-optional-object-attributes. If header contains RestoreStatus as the value, then S3 will include Glacier restore status i.e. isRestoreInProgress and RestoreExpiryDate in List response. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.88.0](service/sagemaker/CHANGELOG.md#v1880-2023-06-28) - * **Feature**: This release adds support for Model Cards Model Registry integration. - -# Release (2023-06-27) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/appfabric`: [v1.0.0](service/appfabric/CHANGELOG.md#v100-2023-06-27) - * **Release**: New AWS service client module - * **Feature**: Initial release of AWS AppFabric for connecting SaaS applications for better productivity and security. -* `github.com/aws/aws-sdk-go-v2/service/appflow`: [v1.32.0](service/appflow/CHANGELOG.md#v1320-2023-06-27) - * **Feature**: This release adds support to bypass SSO with the SAPOData connector when connecting to an SAP instance. -* `github.com/aws/aws-sdk-go-v2/service/emrserverless`: [v1.8.0](service/emrserverless/CHANGELOG.md#v180-2023-06-27) - * **Feature**: This release adds support to update the release label of an EMR Serverless application to upgrade it to a different version of Amazon EMR via UpdateApplication API. -* `github.com/aws/aws-sdk-go-v2/service/ivs`: [v1.23.0](service/ivs/CHANGELOG.md#v1230-2023-06-27) - * **Feature**: IVS customers can now revoke the viewer session associated with an auth token, to prevent and stop playback using that token. -* `github.com/aws/aws-sdk-go-v2/service/kinesisvideo`: [v1.16.0](service/kinesisvideo/CHANGELOG.md#v1160-2023-06-27) - * **Feature**: General Availability (GA) release of Kinesis Video Streams at Edge, enabling customers to provide a configuration for the Kinesis Video Streams EdgeAgent running on an on-premise IoT device. Customers can now locally record from cameras and stream videos to the cloud on a configured schedule. -* `github.com/aws/aws-sdk-go-v2/service/macie2`: [v1.28.0](service/macie2/CHANGELOG.md#v1280-2023-06-27) - * **Feature**: This release adds support for configuring new classification jobs to use the set of managed data identifiers that we recommend for jobs. For the managed data identifier selection type (managedDataIdentifierSelector), specify RECOMMENDED. -* `github.com/aws/aws-sdk-go-v2/service/privatenetworks`: [v1.3.0](service/privatenetworks/CHANGELOG.md#v130-2023-06-27) - * **Feature**: This release allows Private5G customers to choose different commitment plans (60-days, 1-year, 3-years) when placing new orders, enables automatic renewal option for 1-year and 3-years commitments. It also allows customers to update the commitment plan of an existing radio unit. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.87.0](service/sagemaker/CHANGELOG.md#v1870-2023-06-27) - * **Feature**: Introducing TTL for online store records in feature groups. -* `github.com/aws/aws-sdk-go-v2/service/sagemakerfeaturestoreruntime`: [v1.15.0](service/sagemakerfeaturestoreruntime/CHANGELOG.md#v1150-2023-06-27) - * **Feature**: Introducing TTL for online store records for feature groups. -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.36.7](service/ssm/CHANGELOG.md#v1367-2023-06-27) - * **Documentation**: Systems Manager doc-only update for June 2023. -* `github.com/aws/aws-sdk-go-v2/service/verifiedpermissions`: [v1.0.3](service/verifiedpermissions/CHANGELOG.md#v103-2023-06-27) - * **Documentation**: This update fixes several broken links to the Cedar documentation. - -# Release (2023-06-26) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.60.0](service/connect/CHANGELOG.md#v1600-2023-06-26) - * **Feature**: This release provides a way to search for existing tags within an instance. Before tagging a resource, ensure consistency by searching for pre-existing key:value pairs. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.52.0](service/glue/CHANGELOG.md#v1520-2023-06-26) - * **Feature**: Timestamp Starting Position For Kinesis and Kafka Data Sources in a Glue Streaming Job -* `github.com/aws/aws-sdk-go-v2/service/guardduty`: [v1.24.0](service/guardduty/CHANGELOG.md#v1240-2023-06-26) - * **Feature**: Add support for user.extra.sessionName in Kubernetes Audit Logs Findings. -* `github.com/aws/aws-sdk-go-v2/service/iam`: [v1.21.0](service/iam/CHANGELOG.md#v1210-2023-06-26) - * **Feature**: Support for a new API "GetMFADevice" to present MFA device metadata such as device certifications -* `github.com/aws/aws-sdk-go-v2/service/pinpoint`: [v1.20.0](service/pinpoint/CHANGELOG.md#v1200-2023-06-26) - * **Feature**: Added time zone estimation support for journeys - -# Release (2023-06-23) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/devopsguru`: [v1.24.0](service/devopsguru/CHANGELOG.md#v1240-2023-06-23) - * **Feature**: This release adds support for encryption via customer managed keys. -* `github.com/aws/aws-sdk-go-v2/service/fsx`: [v1.29.3](service/fsx/CHANGELOG.md#v1293-2023-06-23) - * **Documentation**: Update to Amazon FSx documentation. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.45.3](service/rds/CHANGELOG.md#v1453-2023-06-23) - * **Documentation**: Documentation improvements for create, describe, and modify DB clusters and DB instances. -* `github.com/aws/aws-sdk-go-v2/service/verifiedpermissions`: [v1.0.2](service/verifiedpermissions/CHANGELOG.md#v102-2023-06-23) - * **Documentation**: Added improved descriptions and new code samples to SDK documentation. - -# Release (2023-06-22) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/chimesdkidentity`: [v1.12.0](service/chimesdkidentity/CHANGELOG.md#v1120-2023-06-22) - * **Feature**: AppInstanceBots can be configured to be invoked or not using the Target or the CHIME.mentions attribute for ChannelMessages -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmessaging`: [v1.16.0](service/chimesdkmessaging/CHANGELOG.md#v1160-2023-06-22) - * **Feature**: ChannelMessages can be made visible to sender and intended recipient rather than all channel members with the target attribute. For example, a user can send messages to a bot and receive messages back in a group channel without other members seeing them. -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.41.0](service/kendra/CHANGELOG.md#v1410-2023-06-22) - * **Feature**: Introducing Amazon Kendra Retrieve API that can be used to retrieve relevant passages or text excerpts given an input query. -* `github.com/aws/aws-sdk-go-v2/service/sfn`: [v1.18.0](service/sfn/CHANGELOG.md#v1180-2023-06-22) - * **Feature**: Adds support for Versions and Aliases. Adds 8 operations: PublishStateMachineVersion, DeleteStateMachineVersion, ListStateMachineVersions, CreateStateMachineAlias, DescribeStateMachineAlias, UpdateStateMachineAlias, DeleteStateMachineAlias, ListStateMachineAliases - -# Release (2023-06-21) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/dynamodb`: [v1.19.11](service/dynamodb/CHANGELOG.md#v11911-2023-06-21) - * **Documentation**: Documentation updates for DynamoDB -* `github.com/aws/aws-sdk-go-v2/service/emr`: [v1.27.0](service/emr/CHANGELOG.md#v1270-2023-06-21) - * **Feature**: This release introduces a new Amazon EMR EPI called ListSupportedInstanceTypes that returns a list of all instance types supported by a given EMR release. -* `github.com/aws/aws-sdk-go-v2/service/inspector2`: [v1.15.0](service/inspector2/CHANGELOG.md#v1150-2023-06-21) - * **Feature**: This release adds support for Software Bill of Materials (SBOM) export and the general availability of code scanning for AWS Lambda functions. -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.38.0](service/mediaconvert/CHANGELOG.md#v1380-2023-06-21) - * **Feature**: This release introduces the bandwidth reduction filter for the HEVC encoder, increases the limits of outputs per job, and updates support for the Nagra SDK to version 1.14.7. -* `github.com/aws/aws-sdk-go-v2/service/mq`: [v1.15.0](service/mq/CHANGELOG.md#v1150-2023-06-21) - * **Feature**: The Cross Region Disaster Recovery feature allows to replicate a brokers state from one region to another in order to provide customers with multi-region resiliency in the event of a regional outage. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.86.0](service/sagemaker/CHANGELOG.md#v1860-2023-06-21) - * **Feature**: This release provides support in SageMaker for output files in training jobs to be uploaded without compression and enable customer to deploy uncompressed model from S3 to real-time inference Endpoints. In addition, ml.trn1n.32xlarge is added to supported instance type list in training job. -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.30.0](service/transfer/CHANGELOG.md#v1300-2023-06-21) - * **Feature**: This release adds a new parameter StructuredLogDestinations to CreateServer, UpdateServer APIs. - -# Release (2023-06-20) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/appflow`: [v1.31.0](service/appflow/CHANGELOG.md#v1310-2023-06-20) - * **Feature**: This release adds new API to reset connector metadata cache -* `github.com/aws/aws-sdk-go-v2/service/configservice`: [v1.34.0](service/configservice/CHANGELOG.md#v1340-2023-06-20) - * **Feature**: Updated ResourceType enum with new resource types onboarded by AWS Config in May 2023. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.102.0](service/ec2/CHANGELOG.md#v11020-2023-06-20) - * **Feature**: Adds support for targeting Dedicated Host allocations by assetIds in AWS Outposts -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.36.0](service/lambda/CHANGELOG.md#v1360-2023-06-20) - * **Feature**: This release adds RecursiveInvocationException to the Invoke API and InvokeWithResponseStream API. -* `github.com/aws/aws-sdk-go-v2/service/redshift`: [v1.28.0](service/redshift/CHANGELOG.md#v1280-2023-06-20) - * **Feature**: Added support for custom domain names for Redshift Provisioned clusters. This feature enables customers to create a custom domain name and use ACM to generate fully secure connections to it. - -# Release (2023-06-19) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudformation`: [v1.30.0](service/cloudformation/CHANGELOG.md#v1300-2023-06-19) - * **Feature**: Specify desired CloudFormation behavior in the event of ChangeSet execution failure using the CreateChangeSet OnStackFailure parameter -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.101.0](service/ec2/CHANGELOG.md#v11010-2023-06-19) - * **Feature**: API changes to AWS Verified Access to include data from trust providers in logs -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.27.4](service/ecs/CHANGELOG.md#v1274-2023-06-19) - * **Documentation**: Documentation only update to address various tickets. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.51.0](service/glue/CHANGELOG.md#v1510-2023-06-19) - * **Feature**: This release adds support for creating cross region table/database resource links -* `github.com/aws/aws-sdk-go-v2/service/pricing`: [v1.20.0](service/pricing/CHANGELOG.md#v1200-2023-06-19) - * **Feature**: This release updates the PriceListArn regex pattern. -* `github.com/aws/aws-sdk-go-v2/service/route53domains`: [v1.15.0](service/route53domains/CHANGELOG.md#v1150-2023-06-19) - * **Feature**: Update MaxItems upper bound to 1000 for ListPricesRequest -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.85.0](service/sagemaker/CHANGELOG.md#v1850-2023-06-19) - * **Feature**: Amazon Sagemaker Autopilot releases CreateAutoMLJobV2 and DescribeAutoMLJobV2 for Autopilot customers with ImageClassification, TextClassification and Tabular problem type config support. - -# Release (2023-06-16) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/applicationdiscoveryservice`: [v1.16.0](service/applicationdiscoveryservice/CHANGELOG.md#v1160-2023-06-16) - * **Feature**: Add Amazon EC2 instance recommendations export -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.59.0](service/connect/CHANGELOG.md#v1590-2023-06-16) - * **Feature**: Updates the *InstanceStorageConfig APIs to support a new ResourceType: SCREEN_RECORDINGS to enable screen recording and specify the storage configurations for publishing the recordings. Also updates DescribeInstance and ListInstances APIs to include InstanceAccessUrl attribute in the API response. -* `github.com/aws/aws-sdk-go-v2/service/iam`: [v1.20.3](service/iam/CHANGELOG.md#v1203-2023-06-16) - * **Documentation**: Documentation updates for AWS Identity and Access Management (IAM). -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.35.0](service/s3/CHANGELOG.md#v1350-2023-06-16) - * **Feature**: This release adds SDK support for request-payer request header and request-charged response header in the "GetBucketAccelerateConfiguration", "ListMultipartUploads", "ListObjects", "ListObjectsV2" and "ListObjectVersions" S3 APIs. - -# Release (2023-06-15) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/auditmanager`: [v1.25.0](service/auditmanager/CHANGELOG.md#v1250-2023-06-15) - * **Feature**: This release introduces 2 Audit Manager features: CSV exports and new manual evidence options. You can now export your evidence finder results in CSV format. In addition, you can now add manual evidence to a control by entering free-form text or uploading a file from your browser. -* `github.com/aws/aws-sdk-go-v2/service/efs`: [v1.20.3](service/efs/CHANGELOG.md#v1203-2023-06-15) - * **Documentation**: Documentation updates for EFS. -* `github.com/aws/aws-sdk-go-v2/service/guardduty`: [v1.23.2](service/guardduty/CHANGELOG.md#v1232-2023-06-15) - * **Documentation**: Updated descriptions for some APIs. -* `github.com/aws/aws-sdk-go-v2/service/location`: [v1.24.0](service/location/CHANGELOG.md#v1240-2023-06-15) - * **Feature**: Amazon Location Service adds categories to places, including filtering on those categories in searches. Also, you can now add metadata properties to your geofences. - -# Release (2023-06-13) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudtrail`: [v1.27.0](service/cloudtrail/CHANGELOG.md#v1270-2023-06-13) - * **Feature**: This feature allows users to view dashboards for CloudTrail Lake event data stores. -* `github.com/aws/aws-sdk-go-v2/service/codegurusecurity`: [v1.0.0](service/codegurusecurity/CHANGELOG.md#v100-2023-06-13) - * **Release**: New AWS service client module - * **Feature**: Initial release of Amazon CodeGuru Security APIs -* `github.com/aws/aws-sdk-go-v2/service/drs`: [v1.14.0](service/drs/CHANGELOG.md#v1140-2023-06-13) - * **Feature**: Added APIs to support network replication and recovery using AWS Elastic Disaster Recovery. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.100.0](service/ec2/CHANGELOG.md#v11000-2023-06-13) - * **Feature**: This release introduces a new feature, EC2 Instance Connect Endpoint, that enables you to connect to a resource over TCP, without requiring the resource to have a public IPv4 address. -* `github.com/aws/aws-sdk-go-v2/service/imagebuilder`: [v1.23.5](service/imagebuilder/CHANGELOG.md#v1235-2023-06-13) - * **Documentation**: Change the Image Builder ImagePipeline dateNextRun field to more accurately describe the data. -* `github.com/aws/aws-sdk-go-v2/service/lightsail`: [v1.27.0](service/lightsail/CHANGELOG.md#v1270-2023-06-13) - * **Feature**: This release adds pagination for the Get Certificates API operation. -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.34.0](service/s3/CHANGELOG.md#v1340-2023-06-13) - * **Feature**: Integrate double encryption feature to SDKs. - * **Bug Fix**: Fix HeadObject to return types.Nound when an object does not exist. Fixes [2084](https://github.com/aws/aws-sdk-go-v2/issues/2084) -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.33.0](service/securityhub/CHANGELOG.md#v1330-2023-06-13) - * **Feature**: Add support for Security Hub Automation Rules -* `github.com/aws/aws-sdk-go-v2/service/simspaceweaver`: [v1.3.0](service/simspaceweaver/CHANGELOG.md#v130-2023-06-13) - * **Feature**: This release fixes using aws-us-gov ARNs in API calls and adds documentation for snapshot APIs. -* `github.com/aws/aws-sdk-go-v2/service/verifiedpermissions`: [v1.0.0](service/verifiedpermissions/CHANGELOG.md#v100-2023-06-13) - * **Release**: New AWS service client module - * **Feature**: GA release of Amazon Verified Permissions. -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.35.0](service/wafv2/CHANGELOG.md#v1350-2023-06-13) - * **Feature**: You can now detect and block fraudulent account creation attempts with the new AWS WAF Fraud Control account creation fraud prevention (ACFP) managed rule group AWSManagedRulesACFPRuleSet. -* `github.com/aws/aws-sdk-go-v2/service/wellarchitected`: [v1.21.0](service/wellarchitected/CHANGELOG.md#v1210-2023-06-13) - * **Feature**: AWS Well-Architected now supports Profiles that help customers prioritize which questions to focus on first by providing a list of prioritized questions that are better aligned with their business goals and outcomes. - -# Release (2023-06-12) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/amplifyuibuilder`: [v1.11.0](service/amplifyuibuilder/CHANGELOG.md#v1110-2023-06-12) - * **Feature**: AWS Amplify UIBuilder is launching Codegen UI, a new feature that enables you to generate your amplify uibuilder components and forms. -* `github.com/aws/aws-sdk-go-v2/service/dynamodb`: [v1.19.8](service/dynamodb/CHANGELOG.md#v1198-2023-06-12) - * **Documentation**: Documentation updates for DynamoDB -* `github.com/aws/aws-sdk-go-v2/service/dynamodbstreams`: [v1.14.12](service/dynamodbstreams/CHANGELOG.md#v11412-2023-06-12) - * **Documentation**: Documentation updates for DynamoDB Streams -* `github.com/aws/aws-sdk-go-v2/service/fsx`: [v1.29.0](service/fsx/CHANGELOG.md#v1290-2023-06-12) - * **Feature**: Amazon FSx for NetApp ONTAP now supports joining a storage virtual machine (SVM) to Active Directory after the SVM has been created. -* `github.com/aws/aws-sdk-go-v2/service/opensearch`: [v1.18.0](service/opensearch/CHANGELOG.md#v1180-2023-06-12) - * **Feature**: This release adds support for SkipUnavailable connection property for cross cluster search -* `github.com/aws/aws-sdk-go-v2/service/rekognition`: [v1.29.0](service/rekognition/CHANGELOG.md#v1290-2023-06-12) - * **Feature**: This release adds support for improved accuracy with user vector in Amazon Rekognition Face Search. Adds new APIs: AssociateFaces, CreateUser, DeleteUser, DisassociateFaces, ListUsers, SearchUsers, SearchUsersByImage. Also adds new face metadata that can be stored: user vector. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.84.0](service/sagemaker/CHANGELOG.md#v1840-2023-06-12) - * **Feature**: Sagemaker Neo now supports compilation for inferentia2 (ML_INF2) and Trainium1 (ML_TRN1) as available targets. With these devices, you can run your workloads at highest performance with lowest cost. inferentia2 (ML_INF2) is available in CMH and Trainium1 (ML_TRN1) is available in IAD currently - -# Release (2023-06-09) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/acmpca`: [v1.21.13](service/acmpca/CHANGELOG.md#v12113-2023-06-09) - * **Documentation**: Document-only update to refresh CLI documentation for AWS Private CA. No change to the service. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.58.0](service/connect/CHANGELOG.md#v1580-2023-06-09) - * **Feature**: This release adds search APIs for Prompts, Quick Connects and Hours of Operations, which can be used to search for those resources within a Connect Instance. - -# Release (2023-06-08) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/athena`: [v1.30.0](service/athena/CHANGELOG.md#v1300-2023-06-08) - * **Feature**: You can now define custom spark properties at start of the session for use cases like cluster encryption, table formats, and general Spark tuning. -* `github.com/aws/aws-sdk-go-v2/service/comprehendmedical`: [v1.16.0](service/comprehendmedical/CHANGELOG.md#v1160-2023-06-08) - * **Feature**: This release supports a new set of entities and traits. -* `github.com/aws/aws-sdk-go-v2/service/paymentcryptography`: [v1.0.0](service/paymentcryptography/CHANGELOG.md#v100-2023-06-08) - * **Release**: New AWS service client module - * **Feature**: Initial release of AWS Payment Cryptography Control Plane service for creating and managing cryptographic keys used during card payment processing. -* `github.com/aws/aws-sdk-go-v2/service/paymentcryptographydata`: [v1.0.0](service/paymentcryptographydata/CHANGELOG.md#v100-2023-06-08) - * **Release**: New AWS service client module - * **Feature**: Initial release of AWS Payment Cryptography DataPlane Plane service for performing cryptographic operations typically used during card payment processing. -* `github.com/aws/aws-sdk-go-v2/service/servicecatalog`: [v1.19.0](service/servicecatalog/CHANGELOG.md#v1190-2023-06-08) - * **Feature**: New parameter added in ServiceCatalog DescribeProvisioningArtifact api - IncludeProvisioningArtifactParameters. This parameter can be used to return information about the parameters used to provision the product -* `github.com/aws/aws-sdk-go-v2/service/timestreamwrite`: [v1.17.0](service/timestreamwrite/CHANGELOG.md#v1170-2023-06-08) - * **Feature**: This release adds the capability for customers to define how their data should be partitioned, optimizing for certain access patterns. This definition will take place as a part of the table creation. - -# Release (2023-06-07) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudformation`: [v1.29.0](service/cloudformation/CHANGELOG.md#v1290-2023-06-07) - * **Feature**: AWS CloudFormation StackSets is updating the deployment experience for all stackset operations to skip suspended AWS accounts during deployments. StackSets will skip target AWS accounts that are suspended and set the Detailed Status of the corresponding stack instances as SKIPPED_SUSPENDED_ACCOUNT -* `github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs`: [v1.21.0](service/cloudwatchlogs/CHANGELOG.md#v1210-2023-06-07) - * **Feature**: This change adds support for account level data protection policies using 3 new APIs, PutAccountPolicy, DeleteAccountPolicy and DescribeAccountPolicy. DescribeLogGroup API has been modified to indicate if account level policy is applied to the LogGroup via "inheritedProperties" list in the response. -* `github.com/aws/aws-sdk-go-v2/service/customerprofiles`: [v1.25.0](service/customerprofiles/CHANGELOG.md#v1250-2023-06-07) - * **Feature**: This release introduces event stream related APIs. -* `github.com/aws/aws-sdk-go-v2/service/directconnect`: [v1.18.15](service/directconnect/CHANGELOG.md#v11815-2023-06-07) - * **Documentation**: This update corrects the jumbo frames mtu values from 9100 to 8500 for transit virtual interfaces. -* `github.com/aws/aws-sdk-go-v2/service/emrcontainers`: [v1.19.0](service/emrcontainers/CHANGELOG.md#v1190-2023-06-07) - * **Feature**: EMR on EKS adds support for log rotation of Spark container logs with EMR-6.11.0 onwards, to the StartJobRun API. -* `github.com/aws/aws-sdk-go-v2/service/iotdeviceadvisor`: [v1.19.0](service/iotdeviceadvisor/CHANGELOG.md#v1190-2023-06-07) - * **Feature**: AWS IoT Core Device Advisor now supports new Qualification Suite test case list. With this update, customers can more easily create new qualification test suite with an empty rootGroup input. - -# Release (2023-06-06) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.57.1](service/connect/CHANGELOG.md#v1571-2023-06-06) - * **Documentation**: GetMetricDataV2 API is now available in AWS GovCloud(US) region. -* `github.com/aws/aws-sdk-go-v2/service/emr`: [v1.26.0](service/emr/CHANGELOG.md#v1260-2023-06-06) - * **Feature**: This release provides customers the ability to specify an allocation strategies amongst PRICE_CAPACITY_OPTIMIZED, CAPACITY_OPTIMIZED, LOWEST_PRICE, DIVERSIFIED for Spot instances in Instance Feet cluster. This enables customers to choose an allocation strategy best suited for their workload. -* `github.com/aws/aws-sdk-go-v2/service/iam`: [v1.20.0](service/iam/CHANGELOG.md#v1200-2023-06-06) - * **Feature**: This release updates the AccountAlias regex pattern with the same length restrictions enforced by the length constraint. -* `github.com/aws/aws-sdk-go-v2/service/inspector2`: [v1.14.0](service/inspector2/CHANGELOG.md#v1140-2023-06-06) - * **Feature**: Adds new response properties and request parameters for 'last scanned at' on the ListCoverage operation. This feature allows you to search and view the date of which your resources were last scanned by Inspector. -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.38.0](service/iot/CHANGELOG.md#v1380-2023-06-06) - * **Feature**: Adding IoT Device Management Software Package Catalog APIs to register, store, and report system software packages, along with their versions and metadata in a centralized location. -* `github.com/aws/aws-sdk-go-v2/service/lexmodelsv2`: [v1.29.0](service/lexmodelsv2/CHANGELOG.md#v1290-2023-06-06) - * **Feature**: This release adds support for Lex Developers to create test sets and to execute those test-sets against their bots. -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.37.0](service/quicksight/CHANGELOG.md#v1370-2023-06-06) - * **Feature**: QuickSight support for pivot table field collapse state, radar chart range scale and multiple scope options in conditional formatting. -* `github.com/aws/aws-sdk-go-v2/service/signer`: [v1.15.0](service/signer/CHANGELOG.md#v1150-2023-06-06) - * **Feature**: AWS Signer is launching Container Image Signing, a new feature that enables you to sign and verify container images. This feature enables you to validate that only container images you approve are used in your enterprise. -* `github.com/aws/aws-sdk-go-v2/service/sqs`: [v1.23.0](service/sqs/CHANGELOG.md#v1230-2023-06-06) - * **Feature**: Amazon SQS adds three new APIs - StartMessageMoveTask, CancelMessageMoveTask, and ListMessageMoveTasks to automate redriving messages from dead-letter queues to source queues or a custom destination. - -# Release (2023-06-05) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudformation`: [v1.28.0](service/cloudformation/CHANGELOG.md#v1280-2023-06-05) - * **Feature**: AWS CloudFormation StackSets provides customers with three new APIs to activate, deactivate, and describe AWS Organizations trusted access which is needed to get started with service-managed StackSets. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.99.0](service/ec2/CHANGELOG.md#v1990-2023-06-05) - * **Feature**: Making InstanceTagAttribute as the required parameter for the DeregisterInstanceEventNotificationAttributes and RegisterInstanceEventNotificationAttributes APIs. -* `github.com/aws/aws-sdk-go-v2/service/finspace`: [v1.10.0](service/finspace/CHANGELOG.md#v1100-2023-06-05) - * **Feature**: Releasing new Managed kdb Insights APIs -* `github.com/aws/aws-sdk-go-v2/service/frauddetector`: [v1.25.0](service/frauddetector/CHANGELOG.md#v1250-2023-06-05) - * **Feature**: Added new variable types, new DateTime data type, and new rules engine functions for interacting and working with DateTime data types. -* `github.com/aws/aws-sdk-go-v2/service/keyspaces`: [v1.3.0](service/keyspaces/CHANGELOG.md#v130-2023-06-05) - * **Feature**: This release adds support for MRR GA launch, and includes multiregion support in create-keyspace, get-keyspace, and list-keyspace. -* `github.com/aws/aws-sdk-go-v2/service/kms`: [v1.22.0](service/kms/CHANGELOG.md#v1220-2023-06-05) - * **Feature**: This release includes feature to import customer's asymmetric (RSA and ECC) and HMAC keys into KMS. It also includes feature to allow customers to specify number of days to schedule a KMS key deletion as a policy condition key. -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.35.0](service/lambda/CHANGELOG.md#v1350-2023-06-05) - * **Feature**: Add Ruby 3.2 (ruby3.2) Runtime support to AWS Lambda. -* `github.com/aws/aws-sdk-go-v2/service/mwaa`: [v1.16.0](service/mwaa/CHANGELOG.md#v1160-2023-06-05) - * **Feature**: This release adds ROLLING_BACK and CREATING_SNAPSHOT environment statuses for Amazon MWAA environments. - -# Release (2023-06-02) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/athena`: [v1.29.0](service/athena/CHANGELOG.md#v1290-2023-06-02) - * **Feature**: This release introduces the DeleteCapacityReservation API and the ability to manage capacity reservations using CloudFormation -* `github.com/aws/aws-sdk-go-v2/service/cloudtrail`: [v1.26.0](service/cloudtrail/CHANGELOG.md#v1260-2023-06-02) - * **Feature**: This feature allows users to start and stop event ingestion on a CloudTrail Lake event data store. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.83.0](service/sagemaker/CHANGELOG.md#v1830-2023-06-02) - * **Feature**: This release adds Selective Execution feature that allows SageMaker Pipelines users to run selected steps in a pipeline. -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.34.0](service/wafv2/CHANGELOG.md#v1340-2023-06-02) - * **Feature**: Added APIs to describe managed products. The APIs retrieve information about rule groups that are managed by AWS and by AWS Marketplace sellers. - -# Release (2023-06-01) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/alexaforbusiness`: [v1.15.11](service/alexaforbusiness/CHANGELOG.md#v11511-2023-06-01) - * **Documentation**: Alexa for Business has been deprecated and is no longer supported. -* `github.com/aws/aws-sdk-go-v2/service/appflow`: [v1.30.0](service/appflow/CHANGELOG.md#v1300-2023-06-01) - * **Feature**: Added ability to select DataTransferApiType for DescribeConnector and CreateFlow requests when using Async supported connectors. Added supportedDataTransferType to DescribeConnector/DescribeConnectors/ListConnector response. -* `github.com/aws/aws-sdk-go-v2/service/customerprofiles`: [v1.24.0](service/customerprofiles/CHANGELOG.md#v1240-2023-06-01) - * **Feature**: This release introduces calculated attribute related APIs. -* `github.com/aws/aws-sdk-go-v2/service/ivs`: [v1.22.0](service/ivs/CHANGELOG.md#v1220-2023-06-01) - * **Feature**: API Update for IVS Advanced Channel type -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.82.1](service/sagemaker/CHANGELOG.md#v1821-2023-06-01) - * **Documentation**: Amazon Sagemaker Autopilot adds support for Parquet file input to NLP text classification jobs. -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.33.1](service/wafv2/CHANGELOG.md#v1331-2023-06-01) - * **Documentation**: Corrected the information for the header order FieldToMatch setting - -# Release (2023-05-31) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/configservice`: [v1.33.0](service/configservice/CHANGELOG.md#v1330-2023-05-31) - * **Feature**: Resource Types Exclusion feature launch by AWS Config -* `github.com/aws/aws-sdk-go-v2/service/frauddetector`: [v1.24.0](service/frauddetector/CHANGELOG.md#v1240-2023-05-31) - * **Feature**: This release enables publishing event predictions from Amazon Fraud Detector (AFD) to Amazon EventBridge. For example, after getting predictions from AFD, Amazon EventBridge rules can be configured to trigger notification through an SNS topic, send a message with SES, or trigger Lambda workflows. -* `github.com/aws/aws-sdk-go-v2/service/healthlake`: [v1.16.0](service/healthlake/CHANGELOG.md#v1160-2023-05-31) - * **Feature**: This release adds a new request parameter to the CreateFHIRDatastore API operation. IdentityProviderConfiguration specifies how you want to authenticate incoming requests to your Healthlake Data Store. -* `github.com/aws/aws-sdk-go-v2/service/m2`: [v1.5.0](service/m2/CHANGELOG.md#v150-2023-05-31) - * **Feature**: Adds an optional create-only 'roleArn' property to Application resources. Enables PS and PO data set org types. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.45.0](service/rds/CHANGELOG.md#v1450-2023-05-31) - * **Feature**: This release adds support for changing the engine for Oracle using the ModifyDbInstance API -* `github.com/aws/aws-sdk-go-v2/service/servicecatalog`: [v1.18.5](service/servicecatalog/CHANGELOG.md#v1185-2023-05-31) - * **Documentation**: Documentation updates for ServiceCatalog. -* `github.com/aws/aws-sdk-go-v2/service/workspacesweb`: [v1.10.0](service/workspacesweb/CHANGELOG.md#v1100-2023-05-31) - * **Feature**: WorkSpaces Web now allows you to control which IP addresses your WorkSpaces Web portal may be accessed from. - -# Release (2023-05-30) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/chimesdkvoice`: [v1.6.0](service/chimesdkvoice/CHANGELOG.md#v160-2023-05-30) - * **Feature**: Added optional CallLeg field to StartSpeakerSearchTask API request -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.50.0](service/glue/CHANGELOG.md#v1500-2023-05-30) - * **Feature**: Added Runtime parameter to allow selection of Ray Runtime -* `github.com/aws/aws-sdk-go-v2/service/groundstation`: [v1.18.3](service/groundstation/CHANGELOG.md#v1183-2023-05-30) - * **Documentation**: Updating description of GetMinuteUsage to be clearer. -* `github.com/aws/aws-sdk-go-v2/service/iotfleetwise`: [v1.4.0](service/iotfleetwise/CHANGELOG.md#v140-2023-05-30) - * **Feature**: Campaigns now support selecting Timestream or S3 as the data destination, Signal catalogs now support "Deprecation" keyword released in VSS v2.1 and "Comment" keyword released in VSS v3.0 -* `github.com/aws/aws-sdk-go-v2/service/location`: [v1.23.0](service/location/CHANGELOG.md#v1230-2023-05-30) - * **Feature**: This release adds API support for political views for the maps service APIs: CreateMap, UpdateMap, DescribeMap. -* `github.com/aws/aws-sdk-go-v2/service/memorydb`: [v1.13.0](service/memorydb/CHANGELOG.md#v1130-2023-05-30) - * **Feature**: Amazon MemoryDB for Redis now supports AWS Identity and Access Management authentication access to Redis clusters starting with redis-engine version 7.0 -* `github.com/aws/aws-sdk-go-v2/service/personalize`: [v1.24.0](service/personalize/CHANGELOG.md#v1240-2023-05-30) - * **Feature**: This release provides support for the exclusion of certain columns for training when creating a solution and creating or updating a recommender with Amazon Personalize. -* `github.com/aws/aws-sdk-go-v2/service/polly`: [v1.26.0](service/polly/CHANGELOG.md#v1260-2023-05-30) - * **Feature**: Amazon Polly adds 2 new voices - Sofie (da-DK) and Niamh (en-IE) -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.32.0](service/securityhub/CHANGELOG.md#v1320-2023-05-30) - * **Feature**: Added new resource detail objects to ASFF, including resources for AwsGuardDutyDetector, AwsAmazonMqBroker, AwsEventSchemasRegistry, AwsAppSyncGraphQlApi and AwsStepFunctionStateMachine. -* `github.com/aws/aws-sdk-go-v2/service/securitylake`: [v1.4.0](service/securitylake/CHANGELOG.md#v140-2023-05-30) - * **Feature**: Log sources are now versioned. AWS log sources and custom sources will now come with a version identifier that enables producers to vend multiple schema versions to subscribers. Security Lake API have been refactored to more closely align with AWS API conventions. -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.33.0](service/wafv2/CHANGELOG.md#v1330-2023-05-30) - * **Feature**: This SDK release provides customers the ability to use Header Order as a field to match. - -# Release (2023-05-26) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.57.0](service/connect/CHANGELOG.md#v1570-2023-05-26) - * **Feature**: Documentation update for a new Initiation Method value in DescribeContact API -* `github.com/aws/aws-sdk-go-v2/service/iotwireless`: [v1.28.0](service/iotwireless/CHANGELOG.md#v1280-2023-05-26) - * **Feature**: Add Multicast Group support in Network Analyzer Configuration. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.82.0](service/sagemaker/CHANGELOG.md#v1820-2023-05-26) - * **Feature**: Added ml.p4d and ml.inf1 as supported instance type families for SageMaker Notebook Instances. - -# Release (2023-05-25) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/applicationautoscaling`: [v1.21.0](service/applicationautoscaling/CHANGELOG.md#v1210-2023-05-25) - * **Feature**: With this release, ElastiCache customers will be able to use predefined metricType "ElastiCacheDatabaseCapacityUsageCountedForEvictPercentage" for their ElastiCache instances. -* `github.com/aws/aws-sdk-go-v2/service/codepipeline`: [v1.15.0](service/codepipeline/CHANGELOG.md#v1150-2023-05-25) - * **Feature**: Add PollingDisabledAt time information in PipelineMetadata object of GetPipeline API. -* `github.com/aws/aws-sdk-go-v2/service/gamelift`: [v1.19.0](service/gamelift/CHANGELOG.md#v1190-2023-05-25) - * **Feature**: GameLift FleetIQ users can now filter game server claim requests to exclude servers on instances that are draining. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.49.0](service/glue/CHANGELOG.md#v1490-2023-05-25) - * **Feature**: Added ability to create data quality rulesets for shared, cross-account Glue Data Catalog tables. Added support for dataset comparison rules through a new parameter called AdditionalDataSources. Enhanced the data quality results with a map containing profiled metric values. -* `github.com/aws/aws-sdk-go-v2/service/migrationhubrefactorspaces`: [v1.10.0](service/migrationhubrefactorspaces/CHANGELOG.md#v1100-2023-05-25) - * **Feature**: This SDK update allows for path parameter syntax to be passed to the CreateRoute API. Path parameter syntax require parameters to be enclosed in {} characters. This update also includes a new AppendSourcePath field which lets users forward the source path to the Service URL endpoint. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.81.0](service/sagemaker/CHANGELOG.md#v1810-2023-05-25) - * **Feature**: Amazon SageMaker Automatic Model Tuning now supports enabling Autotune for tuning jobs which can choose tuning job configurations. - -# Release (2023-05-24) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/appsync`: [v1.21.0](service/appsync/CHANGELOG.md#v1210-2023-05-24) - * **Feature**: This release introduces AppSync Merged APIs, which provide the ability to compose multiple source APIs into a single federated/merged API. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.56.0](service/connect/CHANGELOG.md#v1560-2023-05-24) - * **Feature**: Amazon Connect Evaluation Capabilities: validation improvements -* `github.com/aws/aws-sdk-go-v2/service/costandusagereportservice`: [v1.16.0](service/costandusagereportservice/CHANGELOG.md#v1160-2023-05-24) - * **Feature**: Add support for split cost allocation data on a report. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.80.0](service/sagemaker/CHANGELOG.md#v1800-2023-05-24) - * **Feature**: SageMaker now provides an instantaneous deployment recommendation through the DescribeModel API - -# Release (2023-05-23) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/fms`: [v1.24.0](service/fms/CHANGELOG.md#v1240-2023-05-23) - * **Feature**: Fixes issue that could cause calls to GetAdminScope and ListAdminAccountsForOrganization to return a 500 Internal Server error. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.79.0](service/sagemaker/CHANGELOG.md#v1790-2023-05-23) - * **Feature**: Added ModelNameEquals, ModelPackageVersionArnEquals in request and ModelName, SamplePayloadUrl, ModelPackageVersionArn in response of ListInferenceRecommendationsJobs API. Added Invocation timestamps in response of DescribeInferenceRecommendationsJob API & ListInferenceRecommendationsJobSteps API. -* `github.com/aws/aws-sdk-go-v2/service/translate`: [v1.18.0](service/translate/CHANGELOG.md#v1180-2023-05-23) - * **Feature**: Added support for calling TranslateDocument API. - -# Release (2023-05-22) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/backup`: [v1.22.0](service/backup/CHANGELOG.md#v1220-2023-05-22) - * **Feature**: Added support for tags on restore. -* `github.com/aws/aws-sdk-go-v2/service/pinpoint`: [v1.19.2](service/pinpoint/CHANGELOG.md#v1192-2023-05-22) - * **Documentation**: Amazon Pinpoint is deprecating the tags parameter in the UpdateSegment, UpdateCampaign, UpdateEmailTemplate, UpdateSmsTemplate, UpdatePushTemplate, UpdateInAppTemplate and UpdateVoiceTemplate. Amazon Pinpoint will end support tags parameter by May 22, 2023. -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.36.0](service/quicksight/CHANGELOG.md#v1360-2023-05-22) - * **Feature**: Add support for Asset Bundle, Geospatial Heatmaps. - -# Release (2023-05-19) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/backup`: [v1.21.0](service/backup/CHANGELOG.md#v1210-2023-05-19) - * **Feature**: Add ResourceArn, ResourceType, and BackupVaultName to ListRecoveryPointsByLegalHold API response. -* `github.com/aws/aws-sdk-go-v2/service/connectcases`: [v1.4.0](service/connectcases/CHANGELOG.md#v140-2023-05-19) - * **Feature**: This release adds the ability to create fields with type Url through the CreateField API. For more information see https://docs.aws.amazon.com/cases/latest/APIReference/Welcome.html -* `github.com/aws/aws-sdk-go-v2/service/mediapackagev2`: [v1.0.0](service/mediapackagev2/CHANGELOG.md#v100-2023-05-19) - * **Release**: New AWS service client module - * **Feature**: Adds support for the MediaPackage Live v2 API -* `github.com/aws/aws-sdk-go-v2/service/sesv2`: [v1.18.0](service/sesv2/CHANGELOG.md#v1180-2023-05-19) - * **Feature**: This release allows customers to update scaling mode property of dedicated IP pools with PutDedicatedIpPoolScalingAttributes call. - -# Release (2023-05-18) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/athena`: [v1.28.0](service/athena/CHANGELOG.md#v1280-2023-05-18) - * **Feature**: Removing SparkProperties from EngineConfiguration object for StartSession API call -* `github.com/aws/aws-sdk-go-v2/service/cloudtrail`: [v1.25.0](service/cloudtrail/CHANGELOG.md#v1250-2023-05-18) - * **Feature**: Add ConflictException to PutEventSelectors, add (Channel/EDS)ARNInvalidException to Tag APIs. These exceptions provide customers with more specific error messages instead of internal errors. -* `github.com/aws/aws-sdk-go-v2/service/computeoptimizer`: [v1.24.0](service/computeoptimizer/CHANGELOG.md#v1240-2023-05-18) - * **Feature**: In this launch, we add support for showing integration status with external metric providers such as Instana, Datadog ...etc in GetEC2InstanceRecommendations and ExportEC2InstanceRecommendations apis -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.55.0](service/connect/CHANGELOG.md#v1550-2023-05-18) - * **Feature**: You can programmatically create and manage prompts using APIs, for example, to extract prompts stored within Amazon Connect and add them to your Amazon S3 bucket. AWS CloudTrail, AWS CloudFormation and tagging are supported. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.98.0](service/ec2/CHANGELOG.md#v1980-2023-05-18) - * **Feature**: Add support for i4g.large, i4g.xlarge, i4g.2xlarge, i4g.4xlarge, i4g.8xlarge and i4g.16xlarge instances powered by AWS Graviton2 processors that deliver up to 15% better compute performance than our other storage-optimized instances. -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.27.1](service/ecs/CHANGELOG.md#v1271-2023-05-18) - * **Documentation**: Documentation only release to address various tickets. -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.37.0](service/mediaconvert/CHANGELOG.md#v1370-2023-05-18) - * **Feature**: This release introduces a new MXF Profile for XDCAM which is strictly compliant with the SMPTE RDD 9 standard and improved handling of output name modifiers. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.44.1](service/rds/CHANGELOG.md#v1441-2023-05-18) - * **Documentation**: RDS documentation update for the EngineVersion parameter of ModifyDBSnapshot -* `github.com/aws/aws-sdk-go-v2/service/sagemakergeospatial`: [v1.3.0](service/sagemakergeospatial/CHANGELOG.md#v130-2023-05-18) - * **Feature**: This release makes ExecutionRoleArn a required field in the StartEarthObservationJob API. - -# Release (2023-05-16) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/detective`: [v1.19.0](service/detective/CHANGELOG.md#v1190-2023-05-16) - * **Feature**: Added and updated API operations in Detective to support the integration of ASFF Security Hub findings. -* `github.com/aws/aws-sdk-go-v2/service/directconnect`: [v1.18.14](service/directconnect/CHANGELOG.md#v11814-2023-05-16) - * **Documentation**: This release includes an update to the mtu value for CreateTransitVirtualInterface from 9001 mtu to 8500 mtu. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.48.0](service/glue/CHANGELOG.md#v1480-2023-05-16) - * **Feature**: Add Support for Tags for Custom Entity Types -* `github.com/aws/aws-sdk-go-v2/service/secretsmanager`: [v1.19.8](service/secretsmanager/CHANGELOG.md#v1198-2023-05-16) - * **Documentation**: Documentation updates for Secrets Manager -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.32.0](service/wafv2/CHANGELOG.md#v1320-2023-05-16) - * **Feature**: My AWS Service (placeholder) - You can now rate limit web requests based on aggregation keys other than IP addresses, and you can aggregate using combinations of keys. You can also rate limit all requests that match a scope-down statement, without further aggregation. - -# Release (2023-05-15) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/athena`: [v1.27.0](service/athena/CHANGELOG.md#v1270-2023-05-15) - * **Feature**: You can now define custom spark properties at start of the session for use cases like cluster encryption, table formats, and general Spark tuning. -* `github.com/aws/aws-sdk-go-v2/service/codecatalyst`: [v1.3.0](service/codecatalyst/CHANGELOG.md#v130-2023-05-15) - * **Feature**: With this release, the users can list the active sessions connected to their Dev Environment on AWS CodeCatalyst -* `github.com/aws/aws-sdk-go-v2/service/rekognition`: [v1.28.0](service/rekognition/CHANGELOG.md#v1280-2023-05-15) - * **Feature**: This release adds a new EyeDirection attribute in Amazon Rekognition DetectFaces and IndexFaces APIs which predicts the yaw and pitch angles of a person's eye gaze direction for each face detected in the image. -* `github.com/aws/aws-sdk-go-v2/service/rolesanywhere`: [v1.2.0](service/rolesanywhere/CHANGELOG.md#v120-2023-05-15) - * **Feature**: Adds support for custom notification settings in a trust anchor. Introduces PutNotificationSettings and ResetNotificationSettings API's. Updates DurationSeconds max value to 3600. -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.29.0](service/transfer/CHANGELOG.md#v1290-2023-05-15) - * **Feature**: This release introduces the ability to require both password and SSH key when users authenticate to your Transfer Family servers that use the SFTP protocol. - -# Release (2023-05-11) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.54.2](service/connect/CHANGELOG.md#v1542-2023-05-11) - * **Documentation**: This release updates GetMetricDataV2 API, to support metric data up-to last 35 days -* `github.com/aws/aws-sdk-go-v2/service/elasticache`: [v1.27.0](service/elasticache/CHANGELOG.md#v1270-2023-05-11) - * **Feature**: Added support to modify the cluster mode configuration for the existing ElastiCache ReplicationGroups. Customers can now modify the configuration from cluster mode disabled to cluster mode enabled. -* `github.com/aws/aws-sdk-go-v2/service/elasticsearchservice`: [v1.19.0](service/elasticsearchservice/CHANGELOG.md#v1190-2023-05-11) - * **Feature**: This release fixes DescribePackages API error with null filter value parameter. -* `github.com/aws/aws-sdk-go-v2/service/health`: [v1.17.0](service/health/CHANGELOG.md#v1170-2023-05-11) - * **Feature**: Add support for regional endpoints -* `github.com/aws/aws-sdk-go-v2/service/ivsrealtime`: [v1.2.0](service/ivsrealtime/CHANGELOG.md#v120-2023-05-11) - * **Feature**: Add methods for inspecting and debugging stages: ListStageSessions, GetStageSession, ListParticipants, GetParticipant, and ListParticipantEvents. -* `github.com/aws/aws-sdk-go-v2/service/omics`: [v1.4.0](service/omics/CHANGELOG.md#v140-2023-05-11) - * **Feature**: This release provides support for Ready2Run and GPU workflows, an improved read set filter, the direct upload of read sets into Omics Storage, and annotation parsing for analytics stores. -* `github.com/aws/aws-sdk-go-v2/service/support`: [v1.15.0](service/support/CHANGELOG.md#v1150-2023-05-11) - * **Feature**: This release adds 2 new Support APIs, DescribeCreateCaseOptions and DescribeSupportedLanguages. You can use these new APIs to get available support languages. - -# Release (2023-05-10) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/emr`: [v1.25.0](service/emr/CHANGELOG.md#v1250-2023-05-10) - * **Feature**: EMR Studio now supports programmatically executing a Notebooks on an EMR on EKS cluster. In addition, notebooks can now be executed by specifying its location in S3. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.44.0](service/rds/CHANGELOG.md#v1440-2023-05-10) - * **Feature**: Amazon Relational Database Service (RDS) updates for the new Aurora I/O-Optimized storage type for Amazon Aurora DB clusters -* `github.com/aws/aws-sdk-go-v2/service/swf`: [v1.15.0](service/swf/CHANGELOG.md#v1150-2023-05-10) - * **Feature**: This release adds a new API parameter to exclude old history events from decision tasks. - -# Release (2023-05-09) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/applicationautoscaling`: [v1.20.0](service/applicationautoscaling/CHANGELOG.md#v1200-2023-05-09) - * **Feature**: With this release, Amazon SageMaker Serverless Inference customers can use Application Auto Scaling to auto scale the provisioned concurrency of their serverless endpoints. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.47.0](service/glue/CHANGELOG.md#v1470-2023-05-09) - * **Feature**: This release adds AmazonRedshift Source and Target nodes in addition to DynamicTransform OutputSchemas -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.78.0](service/sagemaker/CHANGELOG.md#v1780-2023-05-09) - * **Feature**: This release includes support for (1) Provisioned Concurrency for Amazon SageMaker Serverless Inference and (2) UpdateEndpointWeightsAndCapacities API for Serverless endpoints. - -# Release (2023-05-08) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.46.0](service/glue/CHANGELOG.md#v1460-2023-05-08) - * **Feature**: Support large worker types G.4x and G.8x for Glue Spark -* `github.com/aws/aws-sdk-go-v2/service/guardduty`: [v1.23.0](service/guardduty/CHANGELOG.md#v1230-2023-05-08) - * **Feature**: Add AccessDeniedException 403 Error message code to support 3 Tagging related APIs -* `github.com/aws/aws-sdk-go-v2/service/iotsitewise`: [v1.29.0](service/iotsitewise/CHANGELOG.md#v1290-2023-05-08) - * **Feature**: Provide support for 20,000 max results for GetAssetPropertyValueHistory/BatchGetAssetPropertyValueHistory and 15 minute aggregate resolution for GetAssetPropertyAggregates/BatchGetAssetPropertyAggregates -* `github.com/aws/aws-sdk-go-v2/service/sts`: [v1.19.0](service/sts/CHANGELOG.md#v1190-2023-05-08) - * **Feature**: Documentation updates for AWS Security Token Service. - -# Release (2023-05-05) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.97.0](service/ec2/CHANGELOG.md#v1970-2023-05-05) - * **Feature**: This release adds support the inf2 and trn1n instances. inf2 instances are purpose built for deep learning inference while trn1n instances are powered by AWS Trainium accelerators and they build on the capabilities of Trainium-powered trn1 instances. -* `github.com/aws/aws-sdk-go-v2/service/inspector2`: [v1.13.0](service/inspector2/CHANGELOG.md#v1130-2023-05-05) - * **Feature**: Amazon Inspector now allows customers to search its vulnerability intelligence database if any of the Inspector scanning types are activated. -* `github.com/aws/aws-sdk-go-v2/service/mediatailor`: [v1.23.0](service/mediatailor/CHANGELOG.md#v1230-2023-05-05) - * **Feature**: This release adds support for AFTER_LIVE_EDGE mode configuration for avail suppression, and adding a fill-policy setting that sets the avail suppression to PARTIAL_AVAIL or FULL_AVAIL_ONLY when AFTER_LIVE_EDGE is enabled. -* `github.com/aws/aws-sdk-go-v2/service/sqs`: [v1.22.0](service/sqs/CHANGELOG.md#v1220-2023-05-05) - * **Feature**: Revert previous SQS protocol change. - -# Release (2023-05-04) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudwatch`: [v1.26.0](service/cloudwatch/CHANGELOG.md#v1260-2023-05-04) - * **Feature**: Adds support for filtering by metric names in CloudWatch Metric Streams. -* `github.com/aws/aws-sdk-go-v2/service/configservice`: [v1.32.0](service/configservice/CHANGELOG.md#v1320-2023-05-04) - * **Feature**: Updated ResourceType enum with new resource types onboarded by AWS Config in April 2023. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.54.1](service/connect/CHANGELOG.md#v1541-2023-05-04) - * **Documentation**: Remove unused InvalidParameterException from CreateParticipant API -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.27.0](service/ecs/CHANGELOG.md#v1270-2023-05-04) - * **Feature**: Documentation update for new error type NamespaceNotFoundException for CreateCluster and UpdateCluster -* `github.com/aws/aws-sdk-go-v2/service/networkfirewall`: [v1.28.0](service/networkfirewall/CHANGELOG.md#v1280-2023-05-04) - * **Feature**: This release adds support for the Suricata REJECT option in midstream exception configurations. -* `github.com/aws/aws-sdk-go-v2/service/opensearch`: [v1.17.0](service/opensearch/CHANGELOG.md#v1170-2023-05-04) - * **Feature**: DescribeDomainNodes: A new API that provides configuration information for nodes part of the domain -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.35.0](service/quicksight/CHANGELOG.md#v1350-2023-05-04) - * **Feature**: Add support for Topic, Dataset parameters and VPC -* `github.com/aws/aws-sdk-go-v2/service/rekognition`: [v1.27.0](service/rekognition/CHANGELOG.md#v1270-2023-05-04) - * **Feature**: This release adds a new attribute FaceOccluded. Additionally, you can now select attributes individually (e.g. ["DEFAULT", "FACE_OCCLUDED", "AGE_RANGE"] instead of ["ALL"]), which can reduce response time. -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.33.1](service/s3/CHANGELOG.md#v1331-2023-05-04) - * **Documentation**: Documentation updates for Amazon S3 -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.77.0](service/sagemaker/CHANGELOG.md#v1770-2023-05-04) - * **Feature**: We added support for ml.inf2 and ml.trn1 family of instances on Amazon SageMaker for deploying machine learning (ML) models for Real-time and Asynchronous inference. You can use these instances to achieve high performance at a low cost for generative artificial intelligence (AI) models. -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.31.0](service/securityhub/CHANGELOG.md#v1310-2023-05-04) - * **Feature**: Add support for Finding History. -* `github.com/aws/aws-sdk-go-v2/service/sqs`: [v1.21.0](service/sqs/CHANGELOG.md#v1210-2023-05-04) - * **Feature**: This release enables customers to call SQS using AWS JSON-1.0 protocol. - -# Release (2023-05-03) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/appsync`: [v1.20.0](service/appsync/CHANGELOG.md#v1200-2023-05-03) - * **Feature**: Private API support for AWS AppSync. With Private APIs, you can now create GraphQL APIs that can only be accessed from your Amazon Virtual Private Cloud ("VPC"). -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.96.0](service/ec2/CHANGELOG.md#v1960-2023-05-03) - * **Feature**: Adds an SDK paginator for GetNetworkInsightsAccessScopeAnalysisFindings -* `github.com/aws/aws-sdk-go-v2/service/inspector2`: [v1.12.0](service/inspector2/CHANGELOG.md#v1120-2023-05-03) - * **Feature**: This feature provides deep inspection for linux based instance -* `github.com/aws/aws-sdk-go-v2/service/iottwinmaker`: [v1.12.0](service/iottwinmaker/CHANGELOG.md#v1120-2023-05-03) - * **Feature**: This release adds a field for GetScene API to return error code and message from dependency services. -* `github.com/aws/aws-sdk-go-v2/service/networkfirewall`: [v1.27.0](service/networkfirewall/CHANGELOG.md#v1270-2023-05-03) - * **Feature**: AWS Network Firewall now supports policy level HOME_NET variable overrides. -* `github.com/aws/aws-sdk-go-v2/service/opensearch`: [v1.16.0](service/opensearch/CHANGELOG.md#v1160-2023-05-03) - * **Feature**: Amazon OpenSearch Service adds the option to deploy a domain across multiple Availability Zones, with each AZ containing a complete copy of data and with nodes in one AZ acting as a standby. This option provides 99.99% availability and consistent performance in the event of infrastructure failure. -* `github.com/aws/aws-sdk-go-v2/service/wellarchitected`: [v1.20.0](service/wellarchitected/CHANGELOG.md#v1200-2023-05-03) - * **Feature**: This release deepens integration with AWS Service Catalog AppRegistry to improve workload resource discovery. - -# Release (2023-05-02) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/appflow`: [v1.29.0](service/appflow/CHANGELOG.md#v1290-2023-05-02) - * **Feature**: This release adds new API to cancel flow executions. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.54.0](service/connect/CHANGELOG.md#v1540-2023-05-02) - * **Feature**: Amazon Connect Service Rules API update: Added OnContactEvaluationSubmit event source to support user configuring evaluation form rules. -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.26.3](service/ecs/CHANGELOG.md#v1263-2023-05-02) - * **Documentation**: Documentation only update to address Amazon ECS tickets. -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.40.0](service/kendra/CHANGELOG.md#v1400-2023-05-02) - * **Feature**: AWS Kendra now supports configuring document fields/attributes via the GetQuerySuggestions API. You can now base query suggestions on the contents of document fields. -* `github.com/aws/aws-sdk-go-v2/service/resiliencehub`: [v1.11.0](service/resiliencehub/CHANGELOG.md#v1110-2023-05-02) - * **Feature**: This release will improve resource level transparency in applications by discovering previously hidden resources. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.76.0](service/sagemaker/CHANGELOG.md#v1760-2023-05-02) - * **Feature**: Amazon Sagemaker Autopilot supports training models with sample weights and additional objective metrics. - -# Release (2023-05-01) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/computeoptimizer`: [v1.23.0](service/computeoptimizer/CHANGELOG.md#v1230-2023-05-01) - * **Feature**: support for tag filtering within compute optimizer. ability to filter recommendation results by tag and tag key value pairs. ability to filter by inferred workload type added. -* `github.com/aws/aws-sdk-go-v2/service/kms`: [v1.21.0](service/kms/CHANGELOG.md#v1210-2023-05-01) - * **Feature**: This release makes the NitroEnclave request parameter Recipient and the response field for CiphertextForRecipient available in AWS SDKs. It also adds the regex pattern for CloudHsmClusterId validation. - -# Release (2023-04-28) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/appflow`: [v1.28.0](service/appflow/CHANGELOG.md#v1280-2023-04-28) - * **Feature**: Adds Jwt Support for Salesforce Credentials. -* `github.com/aws/aws-sdk-go-v2/service/athena`: [v1.26.0](service/athena/CHANGELOG.md#v1260-2023-04-28) - * **Feature**: You can now use capacity reservations on Amazon Athena to run SQL queries on fully-managed compute capacity. -* `github.com/aws/aws-sdk-go-v2/service/directconnect`: [v1.18.12](service/directconnect/CHANGELOG.md#v11812-2023-04-28) - * **Documentation**: This release corrects the jumbo frames MTU from 9100 to 8500. -* `github.com/aws/aws-sdk-go-v2/service/efs`: [v1.20.0](service/efs/CHANGELOG.md#v1200-2023-04-28) - * **Feature**: This release adds PAUSED and PAUSING state as a returned value for DescribeReplicationConfigurations response. -* `github.com/aws/aws-sdk-go-v2/service/grafana`: [v1.13.0](service/grafana/CHANGELOG.md#v1130-2023-04-28) - * **Feature**: This release adds support for the grafanaVersion parameter in CreateWorkspace. -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.37.0](service/iot/CHANGELOG.md#v1370-2023-04-28) - * **Feature**: This release allows AWS IoT Core users to specify a TLS security policy when creating and updating AWS IoT Domain Configurations. -* `github.com/aws/aws-sdk-go-v2/service/rekognition`: [v1.26.0](service/rekognition/CHANGELOG.md#v1260-2023-04-28) - * **Feature**: Added support for aggregating moderation labels by video segment timestamps for Stored Video Content Moderation APIs and added additional information about the job to all Stored Video Get API responses. -* `github.com/aws/aws-sdk-go-v2/service/simspaceweaver`: [v1.2.0](service/simspaceweaver/CHANGELOG.md#v120-2023-04-28) - * **Feature**: Added a new CreateSnapshot API. For the StartSimulation API, SchemaS3Location is now optional, added a new SnapshotS3Location parameter. For the DescribeSimulation API, added SNAPSHOT_IN_PROGRESS simulation state, deprecated SchemaError, added new fields: StartError and SnapshotS3Location. -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.31.0](service/wafv2/CHANGELOG.md#v1310-2023-04-28) - * **Feature**: You can now associate a web ACL with a Verified Access instance. -* `github.com/aws/aws-sdk-go-v2/service/workspaces`: [v1.28.11](service/workspaces/CHANGELOG.md#v12811-2023-04-28) - * **Documentation**: Added Windows 11 to support Microsoft_Office_2019 - -# Release (2023-04-27) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.95.0](service/ec2/CHANGELOG.md#v1950-2023-04-27) - * **Feature**: This release adds support for AMD SEV-SNP on EC2 instances. -* `github.com/aws/aws-sdk-go-v2/service/emrcontainers`: [v1.18.0](service/emrcontainers/CHANGELOG.md#v1180-2023-04-27) - * **Feature**: This release adds GetManagedEndpointSessionCredentials, a new API that allows customers to generate an auth token to connect to a managed endpoint, enabling features such as self-hosted Jupyter notebooks for EMR on EKS. -* `github.com/aws/aws-sdk-go-v2/service/guardduty`: [v1.22.0](service/guardduty/CHANGELOG.md#v1220-2023-04-27) - * **Feature**: Added API support to initiate on-demand malware scan on specific resources. -* `github.com/aws/aws-sdk-go-v2/service/iotdeviceadvisor`: [v1.18.0](service/iotdeviceadvisor/CHANGELOG.md#v1180-2023-04-27) - * **Feature**: AWS IoT Core Device Advisor now supports MQTT over WebSocket. With this update, customers can run all three test suites of AWS IoT Core Device Advisor - qualification, custom, and long duration tests - using Signature Version 4 for MQTT over WebSocket. -* `github.com/aws/aws-sdk-go-v2/service/kafka`: [v1.20.0](service/kafka/CHANGELOG.md#v1200-2023-04-27) - * **Feature**: Amazon MSK has added new APIs that allows multi-VPC private connectivity and cluster policy support for Amazon MSK clusters that simplify connectivity and access between your Apache Kafka clients hosted in different VPCs and AWS accounts and your Amazon MSK clusters. -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.34.0](service/lambda/CHANGELOG.md#v1340-2023-04-27) - * **Feature**: Add Java 17 (java17) support to AWS Lambda -* `github.com/aws/aws-sdk-go-v2/service/osis`: [v1.0.1](service/osis/CHANGELOG.md#v101-2023-04-27) - * **Documentation**: Documentation updates for OpenSearch Ingestion -* `github.com/aws/aws-sdk-go-v2/service/qldb`: [v1.15.10](service/qldb/CHANGELOG.md#v11510-2023-04-27) - * **Documentation**: Documentation updates for Amazon QLDB -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.75.0](service/sagemaker/CHANGELOG.md#v1750-2023-04-27) - * **Feature**: Added ml.p4d.24xlarge and ml.p4de.24xlarge as supported instances for SageMaker Studio - -# Release (2023-04-26) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/osis`: [v1.0.0](service/osis/CHANGELOG.md#v100-2023-04-26) - * **Release**: New AWS service client module - * **Feature**: Initial release for OpenSearch Ingestion - -# Release (2023-04-25) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmessaging`: [v1.15.0](service/chimesdkmessaging/CHANGELOG.md#v1150-2023-04-25) - * **Feature**: Remove non actionable field from UpdateChannelReadMarker and DeleteChannelRequest. Add precise exceptions to DeleteChannel and DeleteStreamingConfigurations error cases. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.53.0](service/connect/CHANGELOG.md#v1530-2023-04-25) - * **Feature**: Amazon Connect, Contact Lens Evaluation API release including ability to manage forms and to submit contact evaluations. -* `github.com/aws/aws-sdk-go-v2/service/datasync`: [v1.24.0](service/datasync/CHANGELOG.md#v1240-2023-04-25) - * **Feature**: This release adds 13 new APIs to support AWS DataSync Discovery GA. -* `github.com/aws/aws-sdk-go-v2/service/directoryservice`: [v1.17.0](service/directoryservice/CHANGELOG.md#v1170-2023-04-25) - * **Feature**: New field added in AWS Managed Microsoft AD DescribeSettings response and regex pattern update for UpdateSettings value. Added length validation to RemoteDomainName. -* `github.com/aws/aws-sdk-go-v2/service/pinpoint`: [v1.19.0](service/pinpoint/CHANGELOG.md#v1190-2023-04-25) - * **Feature**: Adds support for journey runs and querying journey execution metrics based on journey runs. Adds execution metrics to campaign activities. Updates docs for Advanced Quiet Time. - -# Release (2023-04-24) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2`: v1.18.0 - * **Feature**: add recursion detection middleware to all SDK requests to avoid recursion invocation in Lambda -* `github.com/aws/aws-sdk-go-v2/service/appflow`: [v1.27.0](service/appflow/CHANGELOG.md#v1270-2023-04-24) - * **Feature**: Increased the max length for RefreshToken and AuthCode from 2048 to 4096. -* `github.com/aws/aws-sdk-go-v2/service/codecatalyst`: [v1.2.5](service/codecatalyst/CHANGELOG.md#v125-2023-04-24) - * **Documentation**: Documentation updates for Amazon CodeCatalyst. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.94.0](service/ec2/CHANGELOG.md#v1940-2023-04-24) - * **Feature**: API changes to AWS Verified Access related to identity providers' information. -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.36.0](service/mediaconvert/CHANGELOG.md#v1360-2023-04-24) - * **Feature**: This release introduces a noise reduction pre-filter, linear interpolation deinterlace mode, video pass-through, updated default job settings, and expanded LC-AAC Stereo audio bitrate ranges. -* `github.com/aws/aws-sdk-go-v2/service/rekognition`: [v1.25.0](service/rekognition/CHANGELOG.md#v1250-2023-04-24) - * **Feature**: Added new status result to Liveness session status. -* `github.com/aws/aws-sdk-go-v2/service/route53`: [v1.28.0](service/route53/CHANGELOG.md#v1280-2023-04-24) - * **Feature**: added paginator for listResourceRecordSets -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.33.0](service/s3/CHANGELOG.md#v1330-2023-04-24) - * **Feature**: added custom paginators for listMultipartUploads and ListObjectVersions - -# Release (2023-04-21) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.52.0](service/connect/CHANGELOG.md#v1520-2023-04-21) - * **Feature**: This release adds a new API CreateParticipant. For Amazon Connect Chat, you can use this new API to customize chat flow experiences. -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.26.1](service/ecs/CHANGELOG.md#v1261-2023-04-21) - * **Documentation**: Documentation update to address various Amazon ECS tickets. -* `github.com/aws/aws-sdk-go-v2/service/fms`: [v1.23.0](service/fms/CHANGELOG.md#v1230-2023-04-21) - * **Feature**: AWS Firewall Manager adds support for multiple administrators. You can now delegate more than one administrator per organization. - -# Release (2023-04-20) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/chime`: [v1.23.0](service/chime/CHANGELOG.md#v1230-2023-04-20) - * **Feature**: Adds support for Hindi and Thai languages and additional Amazon Transcribe parameters to the StartMeetingTranscription API. -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmediapipelines`: [v1.4.0](service/chimesdkmediapipelines/CHANGELOG.md#v140-2023-04-20) - * **Feature**: This release adds support for specifying the recording file format in an S3 recording sink configuration. -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmeetings`: [v1.15.0](service/chimesdkmeetings/CHANGELOG.md#v1150-2023-04-20) - * **Feature**: Adds support for Hindi and Thai languages and additional Amazon Transcribe parameters to the StartMeetingTranscription API. -* `github.com/aws/aws-sdk-go-v2/service/gamelift`: [v1.18.0](service/gamelift/CHANGELOG.md#v1180-2023-04-20) - * **Feature**: Amazon GameLift supports creating Builds for Windows 2016 operating system. -* `github.com/aws/aws-sdk-go-v2/service/guardduty`: [v1.21.0](service/guardduty/CHANGELOG.md#v1210-2023-04-20) - * **Feature**: This release adds support for the new Lambda Protection feature. -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.36.0](service/iot/CHANGELOG.md#v1360-2023-04-20) - * **Feature**: Support additional OTA states in GetOTAUpdate API -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.74.0](service/sagemaker/CHANGELOG.md#v1740-2023-04-20) - * **Feature**: Amazon SageMaker Canvas adds ModelRegisterSettings support for CanvasAppSettings. -* `github.com/aws/aws-sdk-go-v2/service/snowball`: [v1.19.0](service/snowball/CHANGELOG.md#v1190-2023-04-20) - * **Feature**: Adds support for Amazon S3 compatible storage. AWS Snow Family customers can now use Amazon S3 compatible storage on Snowball Edge devices. Also adds support for V3_5S. This is a refreshed AWS Snowball Edge Storage Optimized device type with 210TB SSD (customer usable). -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.30.0](service/wafv2/CHANGELOG.md#v1300-2023-04-20) - * **Feature**: You can now create encrypted API keys to use in a client application integration of the JavaScript CAPTCHA API . You can also retrieve a list of your API keys and the JavaScript application integration URL. - -# Release (2023-04-19) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/comprehend`: [v1.24.0](service/comprehend/CHANGELOG.md#v1240-2023-04-19) - * **Feature**: This release supports native document models for custom classification, in addition to plain-text models. You train native document models using documents (PDF, Word, images) in their native format. -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.26.0](service/ecs/CHANGELOG.md#v1260-2023-04-19) - * **Feature**: This release supports the Account Setting "TagResourceAuthorization" that allows for enhanced Tagging security controls. -* `github.com/aws/aws-sdk-go-v2/service/ram`: [v1.18.0](service/ram/CHANGELOG.md#v1180-2023-04-19) - * **Feature**: This release adds support for customer managed permissions. Customer managed permissions enable customers to author and manage tailored permissions for resources shared using RAM. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.43.1](service/rds/CHANGELOG.md#v1431-2023-04-19) - * **Documentation**: Adds support for the ImageId parameter of CreateCustomDBEngineVersion to RDS Custom for Oracle -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.32.0](service/s3/CHANGELOG.md#v1320-2023-04-19) - * **Feature**: Provides support for "Snow" Storage class. -* `github.com/aws/aws-sdk-go-v2/service/secretsmanager`: [v1.19.4](service/secretsmanager/CHANGELOG.md#v1194-2023-04-19) - * **Documentation**: Documentation updates for Secrets Manager - -# Release (2023-04-17) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/appflow`: [v1.26.0](service/appflow/CHANGELOG.md#v1260-2023-04-17) - * **Feature**: This release adds a Client Token parameter to the following AppFlow APIs: Create/Update Connector Profile, Create/Update Flow, Start Flow, Register Connector, Update Connector Registration. The Client Token parameter allows idempotent operations for these APIs. -* `github.com/aws/aws-sdk-go-v2/service/drs`: [v1.13.0](service/drs/CHANGELOG.md#v1130-2023-04-17) - * **Feature**: Changed existing APIs and added new APIs to support using an account-level launch configuration template with AWS Elastic Disaster Recovery. -* `github.com/aws/aws-sdk-go-v2/service/dynamodb`: [v1.19.5](service/dynamodb/CHANGELOG.md#v1195-2023-04-17) - * **Documentation**: Documentation updates for DynamoDB API -* `github.com/aws/aws-sdk-go-v2/service/emrserverless`: [v1.7.0](service/emrserverless/CHANGELOG.md#v170-2023-04-17) - * **Feature**: The GetJobRun API has been updated to include the job's billed resource utilization. This utilization shows the aggregate vCPU, memory and storage that AWS has billed for the job run. The billed resources include a 1-minute minimum usage for workers, plus additional storage over 20 GB per worker. -* `github.com/aws/aws-sdk-go-v2/service/internetmonitor`: [v1.2.0](service/internetmonitor/CHANGELOG.md#v120-2023-04-17) - * **Feature**: This release includes a new configurable value, TrafficPercentageToMonitor, which allows users to adjust the amount of traffic monitored by percentage -* `github.com/aws/aws-sdk-go-v2/service/iotwireless`: [v1.27.0](service/iotwireless/CHANGELOG.md#v1270-2023-04-17) - * **Feature**: Supports the new feature of LoRaWAN roaming, allows to configure MaxEirp for LoRaWAN gateway, and allows to configure PingSlotPeriod for LoRaWAN multicast group -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.33.0](service/lambda/CHANGELOG.md#v1330-2023-04-17) - * **Feature**: Add Python 3.10 (python3.10) support to AWS Lambda - -# Release (2023-04-14) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.25.1](service/ecs/CHANGELOG.md#v1251-2023-04-14) - * **Documentation**: This release supports ephemeral storage for AWS Fargate Windows containers. -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.32.0](service/lambda/CHANGELOG.md#v1320-2023-04-14) - * **Feature**: This release adds SnapStart related exceptions to InvokeWithResponseStream API. IAM access related documentation is also added for this API. -* `github.com/aws/aws-sdk-go-v2/service/migrationhubrefactorspaces`: [v1.9.8](service/migrationhubrefactorspaces/CHANGELOG.md#v198-2023-04-14) - * **Documentation**: Doc only update for Refactor Spaces environments without network bridge feature. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.43.0](service/rds/CHANGELOG.md#v1430-2023-04-14) - * **Feature**: This release adds support of modifying the engine mode of database clusters. - -# Release (2023-04-13) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/chimesdkvoice`: [v1.5.0](service/chimesdkvoice/CHANGELOG.md#v150-2023-04-13) - * **Feature**: This release adds tagging support for Voice Connectors and SIP Media Applications -* `github.com/aws/aws-sdk-go-v2/service/mediaconnect`: [v1.19.0](service/mediaconnect/CHANGELOG.md#v1190-2023-04-13) - * **Feature**: Gateway is a new feature of AWS Elemental MediaConnect. Gateway allows the deployment of on-premises resources for the purpose of transporting live video to and from the AWS Cloud. - -# Release (2023-04-12) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/groundstation`: [v1.18.0](service/groundstation/CHANGELOG.md#v1180-2023-04-12) - * **Feature**: AWS Ground Station Wideband DigIF GA Release -* `github.com/aws/aws-sdk-go-v2/service/managedblockchain`: [v1.15.5](service/managedblockchain/CHANGELOG.md#v1155-2023-04-12) - * **Documentation**: Removal of the Ropsten network. The Ethereum foundation ceased support of Ropsten on December 31st, 2022.. - -# Release (2023-04-11) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/ecrpublic`: [v1.16.0](service/ecrpublic/CHANGELOG.md#v1160-2023-04-11) - * **Feature**: This release will allow using registry alias as registryId in BatchDeleteImage request. -* `github.com/aws/aws-sdk-go-v2/service/emrserverless`: [v1.6.0](service/emrserverless/CHANGELOG.md#v160-2023-04-11) - * **Feature**: This release extends GetJobRun API to return job run timeout (executionTimeoutMinutes) specified during StartJobRun call (or default timeout of 720 minutes if none was specified). -* `github.com/aws/aws-sdk-go-v2/service/eventbridge`: [v1.19.0](service/eventbridge/CHANGELOG.md#v1190-2023-04-11) - * **Feature**: EventBridge PutTarget support for multiple SQL arguments on RedshiftDataParameters -* `github.com/aws/aws-sdk-go-v2/service/iotdataplane`: [v1.15.0](service/iotdataplane/CHANGELOG.md#v1150-2023-04-11) - * **Feature**: This release adds support for MQTT5 user properties when calling the AWS IoT GetRetainedMessage API -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.29.0](service/wafv2/CHANGELOG.md#v1290-2023-04-11) - * **Feature**: For web ACLs that protect CloudFront protections, the default request body inspection size is now 16 KB, and you can use the new association configuration to increase the inspection size further, up to 64 KB. Sizes over 16 KB can incur additional costs. - -# Release (2023-04-10) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.51.0](service/connect/CHANGELOG.md#v1510-2023-04-10) - * **Feature**: This release adds the ability to configure an agent's routing profile to receive contacts from multiple channels at the same time via extending the UpdateRoutingProfileConcurrency, CreateRoutingProfile and DescribeRoutingProfile APIs. -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.25.0](service/ecs/CHANGELOG.md#v1250-2023-04-10) - * **Feature**: This release adds support for enabling FIPS compliance on Amazon ECS Fargate tasks -* `github.com/aws/aws-sdk-go-v2/service/marketplacecatalog`: [v1.16.0](service/marketplacecatalog/CHANGELOG.md#v1160-2023-04-10) - * **Feature**: Added three new APIs to support resource sharing: GetResourcePolicy, PutResourcePolicy, and DeleteResourcePolicy. Added new OwnershipType field to ListEntities request to let users filter on entities that are shared with them. Increased max page size of ListEntities response from 20 to 50 results. -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.35.0](service/mediaconvert/CHANGELOG.md#v1350-2023-04-10) - * **Feature**: AWS Elemental MediaConvert SDK now supports conversion of 608 paint-on captions to pop-on captions for SCC sources. -* `github.com/aws/aws-sdk-go-v2/service/omics`: [v1.3.0](service/omics/CHANGELOG.md#v130-2023-04-10) - * **Feature**: Remove unexpected API changes. -* `github.com/aws/aws-sdk-go-v2/service/rekognition`: [v1.24.0](service/rekognition/CHANGELOG.md#v1240-2023-04-10) - * **Feature**: This release adds support for Face Liveness APIs in Amazon Rekognition. Updates UpdateStreamProcessor to return ResourceInUseException Exception. Minor updates to API documentation. - -# Release (2023-04-07) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/dlm`: [v1.15.0](service/dlm/CHANGELOG.md#v1150-2023-04-07) - * **Announcement**: This release includes breaking changes for the timestamp trait on the data lifecycle management client. - * **Feature**: Updated timestamp format for GetLifecyclePolicy API - * **Bug Fix**: Correct timestamp type for data lifecycle manager. -* `github.com/aws/aws-sdk-go-v2/service/docdb`: [v1.21.0](service/docdb/CHANGELOG.md#v1210-2023-04-07) - * **Feature**: This release adds a new parameter 'DBClusterParameterGroupName' to 'RestoreDBClusterFromSnapshot' API to associate the name of the DB cluster parameter group while performing restore. -* `github.com/aws/aws-sdk-go-v2/service/fsx`: [v1.28.8](service/fsx/CHANGELOG.md#v1288-2023-04-07) - * **Documentation**: Amazon FSx for Lustre now supports creating data repository associations on Persistent_1 and Scratch_2 file systems. -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.31.0](service/lambda/CHANGELOG.md#v1310-2023-04-07) - * **Feature**: This release adds a new Lambda InvokeWithResponseStream API to support streaming Lambda function responses. The release also adds a new InvokeMode parameter to Function Url APIs to control whether the response will be streamed or buffered. -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.34.0](service/quicksight/CHANGELOG.md#v1340-2023-04-07) - * **Feature**: This release has two changes: adding the OR condition to tag-based RLS rules in CreateDataSet and UpdateDataSet; adding RefreshSchedule and Incremental RefreshProperties operations for users to programmatically configure SPICE dataset ingestions. -* `github.com/aws/aws-sdk-go-v2/service/redshiftdata`: [v1.19.3](service/redshiftdata/CHANGELOG.md#v1193-2023-04-07) - * **Documentation**: Update documentation of API descriptions as needed in support of temporary credentials with IAM identity. -* `github.com/aws/aws-sdk-go-v2/service/servicecatalog`: [v1.18.1](service/servicecatalog/CHANGELOG.md#v1181-2023-04-07) - * **Documentation**: Updates description for property - -# Release (2023-04-06) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudformation`: [v1.27.0](service/cloudformation/CHANGELOG.md#v1270-2023-04-06) - * **Feature**: Including UPDATE_COMPLETE as a failed status for DeleteStack waiter. -* `github.com/aws/aws-sdk-go-v2/service/greengrassv2`: [v1.22.0](service/greengrassv2/CHANGELOG.md#v1220-2023-04-06) - * **Feature**: Add support for SUCCEEDED value in coreDeviceExecutionStatus field. Documentation updates for Greengrass V2. -* `github.com/aws/aws-sdk-go-v2/service/proton`: [v1.21.0](service/proton/CHANGELOG.md#v1210-2023-04-06) - * **Feature**: This release adds support for the AWS Proton service sync feature. Service sync enables managing an AWS Proton service (creating and updating instances) and all of it's corresponding service instances from a Git repository. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.42.1](service/rds/CHANGELOG.md#v1421-2023-04-06) - * **Documentation**: Adds and updates the SDK examples - -# Release (2023-04-05) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/configservice`: [v1.31.0](service/configservice/CHANGELOG.md#v1310-2023-04-05) - * **Feature**: This release adds resourceType enums for types released in March 2023. -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.24.3](service/ecs/CHANGELOG.md#v1243-2023-04-05) - * **Documentation**: This is a document only updated to add information about Amazon Elastic Inference (EI). -* `github.com/aws/aws-sdk-go-v2/service/identitystore`: [v1.16.7](service/identitystore/CHANGELOG.md#v1167-2023-04-05) - * **Documentation**: Documentation updates for Identity Store CLI command reference. -* `github.com/aws/aws-sdk-go-v2/service/ivsrealtime`: [v1.1.0](service/ivsrealtime/CHANGELOG.md#v110-2023-04-05) - * **Feature**: Fix ParticipantToken ExpirationTime format -* `github.com/aws/aws-sdk-go-v2/service/networkfirewall`: [v1.26.0](service/networkfirewall/CHANGELOG.md#v1260-2023-04-05) - * **Feature**: AWS Network Firewall now supports IPv6-only subnets. -* `github.com/aws/aws-sdk-go-v2/service/servicecatalog`: [v1.18.0](service/servicecatalog/CHANGELOG.md#v1180-2023-04-05) - * **Feature**: removed incorrect product type value -* `github.com/aws/aws-sdk-go-v2/service/vpclattice`: [v1.0.1](service/vpclattice/CHANGELOG.md#v101-2023-04-05) - * **Documentation**: This release removes the entities in the API doc model package for auth policies. - -# Release (2023-04-04) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/amplifyuibuilder`: [v1.10.0](service/amplifyuibuilder/CHANGELOG.md#v1100-2023-04-04) - * **Feature**: Support StorageField and custom displays for data-bound options in form builder. Support non-string operands for predicates in collections. Support choosing client to get token from. -* `github.com/aws/aws-sdk-go-v2/service/autoscaling`: [v1.28.1](service/autoscaling/CHANGELOG.md#v1281-2023-04-04) - * **Documentation**: Documentation updates for Amazon EC2 Auto Scaling -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.93.0](service/ec2/CHANGELOG.md#v1930-2023-04-04) - * **Feature**: C6in, M6in, M6idn, R6in and R6idn bare metal instances are powered by 3rd Generation Intel Xeon Scalable processors and offer up to 200 Gbps of network bandwidth. -* `github.com/aws/aws-sdk-go-v2/service/elasticinference`: [v1.13.0](service/elasticinference/CHANGELOG.md#v1130-2023-04-04) - * **Feature**: Updated public documentation for the Describe and Tagging APIs. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.73.0](service/sagemaker/CHANGELOG.md#v1730-2023-04-04) - * **Feature**: Amazon SageMaker Asynchronous Inference now allows customer's to receive failure model responses in S3 and receive success/failure model responses in SNS notifications. -* `github.com/aws/aws-sdk-go-v2/service/sagemakerruntime`: [v1.19.0](service/sagemakerruntime/CHANGELOG.md#v1190-2023-04-04) - * **Feature**: Amazon SageMaker Asynchronous Inference now provides customers a FailureLocation as a response parameter in InvokeEndpointAsync API to capture the model failure responses. -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.28.0](service/wafv2/CHANGELOG.md#v1280-2023-04-04) - * **Feature**: This release rolls back association config feature for webACLs that protect CloudFront protections. - -# Release (2023-04-03) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.45.0](service/glue/CHANGELOG.md#v1450-2023-04-03) - * **Feature**: Add support for database-level federation -* `github.com/aws/aws-sdk-go-v2/service/lakeformation`: [v1.21.0](service/lakeformation/CHANGELOG.md#v1210-2023-04-03) - * **Feature**: Add support for database-level federation -* `github.com/aws/aws-sdk-go-v2/service/licensemanager`: [v1.18.0](service/licensemanager/CHANGELOG.md#v1180-2023-04-03) - * **Feature**: This release adds grant override options to the CreateGrantVersion API. These options can be used to specify grant replacement behavior during grant activation. -* `github.com/aws/aws-sdk-go-v2/service/mwaa`: [v1.15.0](service/mwaa/CHANGELOG.md#v1150-2023-04-03) - * **Feature**: This Amazon MWAA release adds the ability to customize the Apache Airflow environment by launching a shell script at startup. This shell script is hosted in your environment's Amazon S3 bucket. Amazon MWAA runs the script before installing requirements and initializing the Apache Airflow process. -* `github.com/aws/aws-sdk-go-v2/service/servicecatalog`: [v1.17.0](service/servicecatalog/CHANGELOG.md#v1170-2023-04-03) - * **Feature**: This release introduces Service Catalog support for Terraform open source. It enables 1. The notify* APIs to Service Catalog. These APIs are used by the terraform engine to notify the result of the provisioning engine execution. 2. Adds a new TERRAFORM_OPEN_SOURCE product type in CreateProduct API. -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.27.0](service/wafv2/CHANGELOG.md#v1270-2023-04-03) - * **Feature**: For web ACLs that protect CloudFront protections, the default request body inspection size is now 16 KB, and you can use the new association configuration to increase the inspection size further, up to 64 KB. Sizes over 16 KB can incur additional costs. - -# Release (2023-03-31) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.92.1](service/ec2/CHANGELOG.md#v1921-2023-03-31) - * **Documentation**: Documentation updates for EC2 On Demand Capacity Reservations -* `github.com/aws/aws-sdk-go-v2/service/internetmonitor`: [v1.1.0](service/internetmonitor/CHANGELOG.md#v110-2023-03-31) - * **Feature**: This release adds a new feature for Amazon CloudWatch Internet Monitor that enables customers to deliver internet measurements to Amazon S3 buckets as well as CloudWatch Logs. -* `github.com/aws/aws-sdk-go-v2/service/resiliencehub`: [v1.10.1](service/resiliencehub/CHANGELOG.md#v1101-2023-03-31) - * **Documentation**: Adding EKS related documentation for appTemplateBody -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.31.1](service/s3/CHANGELOG.md#v1311-2023-03-31) - * **Documentation**: Documentation updates for Amazon S3 -* `github.com/aws/aws-sdk-go-v2/service/sagemakerfeaturestoreruntime`: [v1.14.0](service/sagemakerfeaturestoreruntime/CHANGELOG.md#v1140-2023-03-31) - * **Feature**: In this release, you can now chose between soft delete and hard delete when calling the DeleteRecord API, so you have more flexibility when it comes to managing online store data. - -# Release (2023-03-30) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/athena`: [v1.25.0](service/athena/CHANGELOG.md#v1250-2023-03-30) - * **Feature**: Make DefaultExecutorDpuSize and CoordinatorDpuSize fields optional in StartSession -* `github.com/aws/aws-sdk-go-v2/service/autoscaling`: [v1.28.0](service/autoscaling/CHANGELOG.md#v1280-2023-03-30) - * **Feature**: Amazon EC2 Auto Scaling now supports Elastic Load Balancing traffic sources with the AttachTrafficSources, DetachTrafficSources, and DescribeTrafficSources APIs. This release also introduces a new activity status, "WaitingForConnectionDraining", for VPC Lattice to the DescribeScalingActivities API. -* `github.com/aws/aws-sdk-go-v2/service/batch`: [v1.23.0](service/batch/CHANGELOG.md#v1230-2023-03-30) - * **Feature**: This feature allows Batch on EKS to support configuration of Pod Labels through Metadata for Batch on EKS Jobs. -* `github.com/aws/aws-sdk-go-v2/service/computeoptimizer`: [v1.22.0](service/computeoptimizer/CHANGELOG.md#v1220-2023-03-30) - * **Feature**: This release adds support for HDD EBS volume types and io2 Block Express. We are also adding support for 61 new instance types and instances that have non consecutive runtime. -* `github.com/aws/aws-sdk-go-v2/service/drs`: [v1.12.0](service/drs/CHANGELOG.md#v1120-2023-03-30) - * **Feature**: Adding a field to the replication configuration APIs to support the auto replicate new disks feature. We also deprecated RetryDataReplication. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.92.0](service/ec2/CHANGELOG.md#v1920-2023-03-30) - * **Feature**: This release adds support for Tunnel Endpoint Lifecycle control, a new feature that provides Site-to-Site VPN customers with better visibility and control of their VPN tunnel maintenance updates. -* `github.com/aws/aws-sdk-go-v2/service/emr`: [v1.24.0](service/emr/CHANGELOG.md#v1240-2023-03-30) - * **Feature**: Updated DescribeCluster and ListClusters API responses to include ErrorDetail that specifies error code, programmatically accessible error data,and an error message. ErrorDetail provides the underlying reason for cluster failure and recommends actions to simplify troubleshooting of EMR clusters. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.44.0](service/glue/CHANGELOG.md#v1440-2023-03-30) - * **Feature**: This release adds support for AWS Glue Data Quality, which helps you evaluate and monitor the quality of your data and includes the API for creating, deleting, or updating data quality rulesets, runs and evaluations. -* `github.com/aws/aws-sdk-go-v2/service/guardduty`: [v1.20.0](service/guardduty/CHANGELOG.md#v1200-2023-03-30) - * **Feature**: Added EKS Runtime Monitoring feature support to existing detector, finding APIs and introducing new Coverage APIs -* `github.com/aws/aws-sdk-go-v2/service/imagebuilder`: [v1.23.0](service/imagebuilder/CHANGELOG.md#v1230-2023-03-30) - * **Feature**: Adds support for new image workflow details and image vulnerability detection. -* `github.com/aws/aws-sdk-go-v2/service/ivs`: [v1.21.0](service/ivs/CHANGELOG.md#v1210-2023-03-30) - * **Feature**: Amazon Interactive Video Service (IVS) now offers customers the ability to configure IVS channels to allow insecure RTMP ingest. -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.39.0](service/kendra/CHANGELOG.md#v1390-2023-03-30) - * **Feature**: AWS Kendra now supports featured results for a query. -* `github.com/aws/aws-sdk-go-v2/service/networkfirewall`: [v1.25.0](service/networkfirewall/CHANGELOG.md#v1250-2023-03-30) - * **Feature**: AWS Network Firewall added TLS inspection configurations to allow TLS traffic inspection. -* `github.com/aws/aws-sdk-go-v2/service/sagemakergeospatial`: [v1.2.0](service/sagemakergeospatial/CHANGELOG.md#v120-2023-03-30) - * **Feature**: Amazon SageMaker geospatial capabilities now supports server-side encryption with customer managed KMS key and SageMaker notebooks with a SageMaker geospatial image in a Amazon SageMaker Domain with VPC only mode. -* `github.com/aws/aws-sdk-go-v2/service/vpclattice`: [v1.0.0](service/vpclattice/CHANGELOG.md#v100-2023-03-30) - * **Release**: New AWS service client module - * **Feature**: General Availability (GA) release of Amazon VPC Lattice -* `github.com/aws/aws-sdk-go-v2/service/wellarchitected`: [v1.19.0](service/wellarchitected/CHANGELOG.md#v1190-2023-03-30) - * **Feature**: AWS Well-Architected SDK now supports getting consolidated report metrics and generating a consolidated report PDF. - -# Release (2023-03-29) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/opensearchserverless`: [v1.2.0](service/opensearchserverless/CHANGELOG.md#v120-2023-03-29) - * **Feature**: This release includes two new exception types "ServiceQuotaExceededException" and "OcuLimitExceededException". -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.42.0](service/rds/CHANGELOG.md#v1420-2023-03-29) - * **Feature**: Add support for creating a read replica DB instance from a Multi-AZ DB cluster. - -# Release (2023-03-28) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/ssmcontacts`: [v1.15.0](service/ssmcontacts/CHANGELOG.md#v1150-2023-03-28) - * **Feature**: This release adds 12 new APIs as part of Oncall Schedule feature release, adds support for a new contact type: ONCALL_SCHEDULE. Check public documentation for AWS ssm-contacts for more information -* `github.com/aws/aws-sdk-go-v2/service/ssmincidents`: [v1.21.0](service/ssmincidents/CHANGELOG.md#v1210-2023-03-28) - * **Feature**: Increased maximum length of "TriggerDetails.rawData" to 10K characters and "IncidentSummary" to 8K characters. - -# Release (2023-03-27) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/athena`: [v1.24.0](service/athena/CHANGELOG.md#v1240-2023-03-27) - * **Feature**: Enforces a minimal level of encryption for the workgroup for query and calculation results that are written to Amazon S3. When enabled, workgroup users can set encryption only to the minimum level set by the administrator or higher when they submit queries. -* `github.com/aws/aws-sdk-go-v2/service/chimesdkvoice`: [v1.4.0](service/chimesdkvoice/CHANGELOG.md#v140-2023-03-27) - * **Feature**: Documentation updates for Amazon Chime SDK Voice. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.50.0](service/connect/CHANGELOG.md#v1500-2023-03-27) - * **Feature**: This release introduces support for RelatedContactId in the StartChatContact API. Interactive message and interactive message response have been added to the list of supported message content types for this API as well. -* `github.com/aws/aws-sdk-go-v2/service/connectparticipant`: [v1.15.7](service/connectparticipant/CHANGELOG.md#v1157-2023-03-27) - * **Documentation**: This release provides an update to the SendMessage API to handle interactive message response content-types. -* `github.com/aws/aws-sdk-go-v2/service/iotwireless`: [v1.26.0](service/iotwireless/CHANGELOG.md#v1260-2023-03-27) - * **Feature**: Introducing new APIs that enable Sidewalk devices to communicate with AWS IoT Core through Sidewalk gateways. This will empower AWS customers to connect Sidewalk devices with other AWS IoT Services, creating possibilities for seamless integration and advanced device management. -* `github.com/aws/aws-sdk-go-v2/service/medialive`: [v1.31.0](service/medialive/CHANGELOG.md#v1310-2023-03-27) - * **Feature**: AWS Elemental MediaLive now supports ID3 tag insertion for audio only HLS output groups. AWS Elemental Link devices now support tagging. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.72.1](service/sagemaker/CHANGELOG.md#v1721-2023-03-27) - * **Documentation**: Fixed some improperly rendered links in SDK documentation. -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.30.0](service/securityhub/CHANGELOG.md#v1300-2023-03-27) - * **Feature**: Added new resource detail objects to ASFF, including resources for AwsEksCluster, AWSS3Bucket, AwsEc2RouteTable and AwsEC2Instance. -* `github.com/aws/aws-sdk-go-v2/service/servicecatalogappregistry`: [v1.17.0](service/servicecatalogappregistry/CHANGELOG.md#v1170-2023-03-27) - * **Feature**: In this release, we started supporting ARN in applicationSpecifier and attributeGroupSpecifier. GetAttributeGroup, ListAttributeGroups and ListAttributeGroupsForApplication APIs will now have CreatedBy field in the response. -* `github.com/aws/aws-sdk-go-v2/service/voiceid`: [v1.13.0](service/voiceid/CHANGELOG.md#v1130-2023-03-27) - * **Feature**: Amazon Connect Voice ID now supports multiple fraudster watchlists. Every domain has a default watchlist where all existing fraudsters are placed by default. Custom watchlists may now be created, managed, and evaluated against for known fraudster detection. - -# Release (2023-03-24) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudwatch`: [v1.25.7](service/cloudwatch/CHANGELOG.md#v1257-2023-03-24) - * **Documentation**: Doc-only update to correct alarm actions list -* `github.com/aws/aws-sdk-go-v2/service/comprehend`: [v1.23.0](service/comprehend/CHANGELOG.md#v1230-2023-03-24) - * **Feature**: This release adds a new field (FlywheelArn) to the EntitiesDetectionJobProperties object. The FlywheelArn field is returned in the DescribeEntitiesDetectionJob and ListEntitiesDetectionJobs responses when the EntitiesDetection job is started with a FlywheelArn instead of an EntityRecognizerArn . -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.41.0](service/rds/CHANGELOG.md#v1410-2023-03-24) - * **Feature**: Added error code CreateCustomDBEngineVersionFault for when the create custom engine version for Custom engines fails. - -# Release (2023-03-23) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/batch`: [v1.22.0](service/batch/CHANGELOG.md#v1220-2023-03-23) - * **Feature**: This feature allows Batch to support configuration of ephemeral storage size for jobs running on FARGATE -* `github.com/aws/aws-sdk-go-v2/service/chimesdkidentity`: [v1.11.0](service/chimesdkidentity/CHANGELOG.md#v1110-2023-03-23) - * **Feature**: AppInstanceBots can be used to add a bot powered by Amazon Lex to chat channels. ExpirationSettings provides automatic resource deletion for AppInstanceUsers. -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmediapipelines`: [v1.3.0](service/chimesdkmediapipelines/CHANGELOG.md#v130-2023-03-23) - * **Feature**: This release adds Amazon Chime SDK call analytics. Call analytics include voice analytics, which provides speaker search and voice tone analysis. These capabilities can be used with Amazon Transcribe and Transcribe Call Analytics to generate machine-learning-powered insights from real-time audio. -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmessaging`: [v1.14.0](service/chimesdkmessaging/CHANGELOG.md#v1140-2023-03-23) - * **Feature**: ExpirationSettings provides automatic resource deletion for Channels. -* `github.com/aws/aws-sdk-go-v2/service/chimesdkvoice`: [v1.3.0](service/chimesdkvoice/CHANGELOG.md#v130-2023-03-23) - * **Feature**: This release adds Amazon Chime SDK call analytics. Call analytics include voice analytics, which provides speaker search and voice tone analysis. These capabilities can be used with Amazon Transcribe and Transcribe Call Analytics to generate machine-learning-powered insights from real-time audio. -* `github.com/aws/aws-sdk-go-v2/service/codeartifact`: [v1.18.0](service/codeartifact/CHANGELOG.md#v1180-2023-03-23) - * **Feature**: Repository CreationTime is added to the CreateRepository and ListRepositories API responses. -* `github.com/aws/aws-sdk-go-v2/service/guardduty`: [v1.19.0](service/guardduty/CHANGELOG.md#v1190-2023-03-23) - * **Feature**: Adds AutoEnableOrganizationMembers attribute to DescribeOrganizationConfiguration and UpdateOrganizationConfiguration APIs. -* `github.com/aws/aws-sdk-go-v2/service/ivsrealtime`: [v1.0.0](service/ivsrealtime/CHANGELOG.md#v100-2023-03-23) - * **Release**: New AWS service client module - * **Feature**: Initial release of the Amazon Interactive Video Service RealTime API. -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.34.0](service/mediaconvert/CHANGELOG.md#v1340-2023-03-23) - * **Feature**: AWS Elemental MediaConvert SDK now supports passthrough of ID3v2 tags for audio inputs to audio-only HLS outputs. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.72.0](service/sagemaker/CHANGELOG.md#v1720-2023-03-23) - * **Feature**: Amazon SageMaker Autopilot adds two new APIs - CreateAutoMLJobV2 and DescribeAutoMLJobV2. Amazon SageMaker Notebook Instances now supports the ml.geospatial.interactive instance type. -* `github.com/aws/aws-sdk-go-v2/service/servicediscovery`: [v1.21.0](service/servicediscovery/CHANGELOG.md#v1210-2023-03-23) - * **Feature**: Reverted the throttling exception RequestLimitExceeded for AWS Cloud Map APIs introduced in SDK version 1.12.424 2023-03-09 to previous exception specified in the ErrorCode. -* `github.com/aws/aws-sdk-go-v2/service/textract`: [v1.21.0](service/textract/CHANGELOG.md#v1210-2023-03-23) - * **Feature**: The AnalyzeDocument - Tables feature adds support for new elements in the API: table titles, footers, section titles, summary cells/tables, and table type. - -# Release (2023-03-22) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/iam`: [v1.19.8](service/iam/CHANGELOG.md#v1198-2023-03-22) - * **Documentation**: Documentation updates for AWS Identity and Access Management (IAM). -* `github.com/aws/aws-sdk-go-v2/service/iottwinmaker`: [v1.11.0](service/iottwinmaker/CHANGELOG.md#v1110-2023-03-22) - * **Feature**: This release adds support of adding metadata when creating a new scene or updating an existing scene. -* `github.com/aws/aws-sdk-go-v2/service/networkmanager`: [v1.17.8](service/networkmanager/CHANGELOG.md#v1178-2023-03-22) - * **Documentation**: This release includes an update to create-transit-gateway-route-table-attachment, showing example usage for TransitGatewayRouteTableArn. -* `github.com/aws/aws-sdk-go-v2/service/resiliencehub`: [v1.10.0](service/resiliencehub/CHANGELOG.md#v1100-2023-03-22) - * **Feature**: This release provides customers with the ability to import resources from within an EKS cluster and assess the resiliency of EKS cluster workloads. -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.36.0](service/ssm/CHANGELOG.md#v1360-2023-03-22) - * **Feature**: This Patch Manager release supports creating, updating, and deleting Patch Baselines for AmazonLinux2023, AlmaLinux. - -# Release (2023-03-21) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmessaging`: [v1.13.0](service/chimesdkmessaging/CHANGELOG.md#v1130-2023-03-21) - * **Feature**: Amazon Chime SDK messaging customers can now manage streaming configuration for messaging data for archival and analysis. -* `github.com/aws/aws-sdk-go-v2/service/cleanrooms`: [v1.1.0](service/cleanrooms/CHANGELOG.md#v110-2023-03-21) - * **Feature**: GA Release of AWS Clean Rooms, Added Tagging Functionality -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.91.0](service/ec2/CHANGELOG.md#v1910-2023-03-21) - * **Feature**: This release adds support for AWS Network Firewall, AWS PrivateLink, and Gateway Load Balancers to Amazon VPC Reachability Analyzer, and it makes the path destination optional as long as a destination address in the filter at source is provided. -* `github.com/aws/aws-sdk-go-v2/service/internal/s3shared`: [v1.14.0](service/internal/s3shared/CHANGELOG.md#v1140-2023-03-21) - * **Feature**: port v1 sdk 100-continue http header customization for s3 PutObject/UploadPart request and enable user config -* `github.com/aws/aws-sdk-go-v2/service/iotsitewise`: [v1.28.0](service/iotsitewise/CHANGELOG.md#v1280-2023-03-21) - * **Feature**: Provide support for tagging of data streams and enabling tag based authorization for property alias -* `github.com/aws/aws-sdk-go-v2/service/mgn`: [v1.18.0](service/mgn/CHANGELOG.md#v1180-2023-03-21) - * **Feature**: This release introduces the Import and export feature and expansion of the post-launch actions -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.31.0](service/s3/CHANGELOG.md#v1310-2023-03-21) - * **Feature**: port v1 sdk 100-continue http header customization for s3 PutObject/UploadPart request and enable user config - -# Release (2023-03-20) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/applicationautoscaling`: [v1.19.0](service/applicationautoscaling/CHANGELOG.md#v1190-2023-03-20) - * **Feature**: With this release customers can now tag their Application Auto Scaling registered targets with key-value pairs and manage IAM permissions for all the tagged resources centrally. -* `github.com/aws/aws-sdk-go-v2/service/neptune`: [v1.20.0](service/neptune/CHANGELOG.md#v1200-2023-03-20) - * **Feature**: This release makes following few changes. db-cluster-identifier is now a required parameter of create-db-instance. describe-db-cluster will now return PendingModifiedValues and GlobalClusterIdentifier fields in the response. -* `github.com/aws/aws-sdk-go-v2/service/s3outposts`: [v1.16.0](service/s3outposts/CHANGELOG.md#v1160-2023-03-20) - * **Feature**: S3 On Outposts added support for endpoint status, and a failed endpoint reason, if any -* `github.com/aws/aws-sdk-go-v2/service/workdocs`: [v1.14.0](service/workdocs/CHANGELOG.md#v1140-2023-03-20) - * **Feature**: This release adds a new API, SearchResources, which enable users to search through metadata and content of folders, documents, document versions and comments in a WorkDocs site. - -# Release (2023-03-17) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/billingconductor`: [v1.6.0](service/billingconductor/CHANGELOG.md#v160-2023-03-17) - * **Feature**: This release adds a new filter to ListAccountAssociations API and a new filter to ListBillingGroups API. -* `github.com/aws/aws-sdk-go-v2/service/configservice`: [v1.30.0](service/configservice/CHANGELOG.md#v1300-2023-03-17) - * **Feature**: This release adds resourceType enums for types released from October 2022 through February 2023. -* `github.com/aws/aws-sdk-go-v2/service/databasemigrationservice`: [v1.25.0](service/databasemigrationservice/CHANGELOG.md#v1250-2023-03-17) - * **Feature**: S3 setting to create AWS Glue Data Catalog. Oracle setting to control conversion of timestamp column. Support for Kafka SASL Plain authentication. Setting to map boolean from PostgreSQL to Redshift. SQL Server settings to force lob lookup on inline LOBs and to control access of database logs. - -# Release (2023-03-16) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/config`: [v1.18.18](config/CHANGELOG.md#v11818-2023-03-16) - * **Bug Fix**: Allow RoleARN to be set as functional option on STS WebIdentityRoleOptions. Fixes aws/aws-sdk-go-v2#2015. -* `github.com/aws/aws-sdk-go-v2/service/guardduty`: [v1.18.0](service/guardduty/CHANGELOG.md#v1180-2023-03-16) - * **Feature**: Updated 9 APIs for feature enablement to reflect expansion of GuardDuty to features. Added new APIs and updated existing APIs to support RDS Protection GA. -* `github.com/aws/aws-sdk-go-v2/service/resourceexplorer2`: [v1.2.7](service/resourceexplorer2/CHANGELOG.md#v127-2023-03-16) - * **Documentation**: Documentation updates for APIs. -* `github.com/aws/aws-sdk-go-v2/service/sagemakerruntime`: [v1.18.7](service/sagemakerruntime/CHANGELOG.md#v1187-2023-03-16) - * **Documentation**: Documentation updates for SageMaker Runtime - -# Release (2023-03-15) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/migrationhubstrategy`: [v1.9.0](service/migrationhubstrategy/CHANGELOG.md#v190-2023-03-15) - * **Feature**: This release adds the binary analysis that analyzes IIS application DLLs on Windows and Java applications on Linux to provide anti-pattern report without configuring access to the source code. -* `github.com/aws/aws-sdk-go-v2/service/s3control`: [v1.31.0](service/s3control/CHANGELOG.md#v1310-2023-03-15) - * **Feature**: Added support for S3 Object Lambda aliases. -* `github.com/aws/aws-sdk-go-v2/service/securitylake`: [v1.3.0](service/securitylake/CHANGELOG.md#v130-2023-03-15) - * **Feature**: Make Create/Get/ListSubscribers APIs return resource share ARN and name so they can be used to validate the RAM resource share to accept. GetDatalake can be used to track status of UpdateDatalake and DeleteDatalake requests. - -# Release (2023-03-14) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/feature/ec2/imds`: [v1.13.0](feature/ec2/imds/CHANGELOG.md#v1130-2023-03-14) - * **Feature**: Add flag to disable IMDSv1 fallback -* `github.com/aws/aws-sdk-go-v2/service/applicationautoscaling`: [v1.18.0](service/applicationautoscaling/CHANGELOG.md#v1180-2023-03-14) - * **Feature**: Application Auto Scaling customers can now use mathematical functions to customize the metric used with Target Tracking policies within the policy configuration itself, saving the cost and effort of publishing the customizations as a separate metric. -* `github.com/aws/aws-sdk-go-v2/service/dataexchange`: [v1.19.0](service/dataexchange/CHANGELOG.md#v1190-2023-03-14) - * **Feature**: This release enables data providers to license direct access to S3 objects encrypted with Customer Managed Keys (CMK) in AWS KMS through AWS Data Exchange. Subscribers can use these keys to decrypt, then use the encrypted S3 objects shared with them, without creating or managing copies. -* `github.com/aws/aws-sdk-go-v2/service/directconnect`: [v1.18.7](service/directconnect/CHANGELOG.md#v1187-2023-03-14) - * **Documentation**: describe-direct-connect-gateway-associations includes a new status, updating, indicating that the association is currently in-process of updating. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.90.0](service/ec2/CHANGELOG.md#v1900-2023-03-14) - * **Feature**: This release adds a new DnsOptions key (PrivateDnsOnlyForInboundResolverEndpoint) to CreateVpcEndpoint and ModifyVpcEndpoint APIs. -* `github.com/aws/aws-sdk-go-v2/service/iam`: [v1.19.6](service/iam/CHANGELOG.md#v1196-2023-03-14) - * **Documentation**: Documentation only updates to correct customer-reported issues -* `github.com/aws/aws-sdk-go-v2/service/keyspaces`: [v1.2.0](service/keyspaces/CHANGELOG.md#v120-2023-03-14) - * **Feature**: Adding support for client-side timestamps -* `github.com/aws/aws-sdk-go-v2/service/support`: [v1.14.6](service/support/CHANGELOG.md#v1146-2023-03-14) - * **Announcement**: Model regenerated with support for null string values to properly implement `support` service operations `DescribeTrustedAdvisorCheckRefreshStatuses` and `DescribeTrustedAdvisorCheckSummaries` - -# Release (2023-03-13) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/appintegrations`: [v1.15.0](service/appintegrations/CHANGELOG.md#v1150-2023-03-13) - * **Feature**: Adds FileConfiguration to Amazon AppIntegrations CreateDataIntegration supporting scheduled downloading of third party files into Amazon Connect from sources such as Microsoft SharePoint. -* `github.com/aws/aws-sdk-go-v2/service/lakeformation`: [v1.20.2](service/lakeformation/CHANGELOG.md#v1202-2023-03-13) - * **Documentation**: This release updates the documentation regarding Get/Update DataCellsFilter -* `github.com/aws/aws-sdk-go-v2/service/s3control`: [v1.30.0](service/s3control/CHANGELOG.md#v1300-2023-03-13) - * **Feature**: Added support for cross-account Multi-Region Access Points. Added support for S3 Replication for S3 on Outposts. -* `github.com/aws/aws-sdk-go-v2/service/tnb`: [v1.1.0](service/tnb/CHANGELOG.md#v110-2023-03-13) - * **Feature**: This release adds tagging support to the following Network Instance APIs : Instantiate, Update, Terminate. -* `github.com/aws/aws-sdk-go-v2/service/wisdom`: [v1.13.0](service/wisdom/CHANGELOG.md#v1130-2023-03-13) - * **Feature**: This release extends Wisdom CreateKnowledgeBase API to support SharePoint connector type by removing the @required trait for objectField - -# Release (2023-03-10) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/ivschat`: [v1.4.0](service/ivschat/CHANGELOG.md#v140-2023-03-10) - * **Feature**: This release adds a new exception returned when calling AWS IVS chat UpdateLoggingConfiguration. Now UpdateLoggingConfiguration can return ConflictException when invalid updates are made in sequence to Logging Configurations. -* `github.com/aws/aws-sdk-go-v2/service/secretsmanager`: [v1.19.0](service/secretsmanager/CHANGELOG.md#v1190-2023-03-10) - * **Feature**: The type definitions of SecretString and SecretBinary now have a minimum length of 1 in the model to match the exception thrown when you pass in empty values. - -# Release (2023-03-09) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/codeartifact`: [v1.17.0](service/codeartifact/CHANGELOG.md#v1170-2023-03-09) - * **Feature**: This release introduces the generic package format, a mechanism for storing arbitrary binary assets. It also adds a new API, PublishPackageVersion, to allow for publishing generic packages. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.49.0](service/connect/CHANGELOG.md#v1490-2023-03-09) - * **Feature**: This release adds a new API, GetMetricDataV2, which returns metric data for Amazon Connect. -* `github.com/aws/aws-sdk-go-v2/service/evidently`: [v1.11.0](service/evidently/CHANGELOG.md#v1110-2023-03-09) - * **Feature**: Updated entity override documentation -* `github.com/aws/aws-sdk-go-v2/service/networkmanager`: [v1.17.5](service/networkmanager/CHANGELOG.md#v1175-2023-03-09) - * **Documentation**: This update provides example usage for TransitGatewayRouteTableArn. -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.33.0](service/quicksight/CHANGELOG.md#v1330-2023-03-09) - * **Feature**: This release has two changes: add state persistence feature for embedded dashboard and console in GenerateEmbedUrlForRegisteredUser API; add properties for hidden collapsed row dimensions in PivotTableOptions. -* `github.com/aws/aws-sdk-go-v2/service/redshiftdata`: [v1.19.0](service/redshiftdata/CHANGELOG.md#v1190-2023-03-09) - * **Feature**: Added support for Redshift Serverless workgroup-arn wherever the WorkgroupName parameter is available. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.71.0](service/sagemaker/CHANGELOG.md#v1710-2023-03-09) - * **Feature**: Amazon SageMaker Inference now allows SSM access to customer's model container by setting the "EnableSSMAccess" parameter for a ProductionVariant in CreateEndpointConfig API. -* `github.com/aws/aws-sdk-go-v2/service/servicediscovery`: [v1.20.0](service/servicediscovery/CHANGELOG.md#v1200-2023-03-09) - * **Feature**: Updated all AWS Cloud Map APIs to provide consistent throttling exception (RequestLimitExceeded) -* `github.com/aws/aws-sdk-go-v2/service/sesv2`: [v1.17.0](service/sesv2/CHANGELOG.md#v1170-2023-03-09) - * **Feature**: This release introduces a new recommendation in Virtual Deliverability Manager Advisor, which detects missing or misconfigured Brand Indicator for Message Identification (BIMI) DNS records for customer sending identities. - -# Release (2023-03-08) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/athena`: [v1.23.0](service/athena/CHANGELOG.md#v1230-2023-03-08) - * **Feature**: A new field SubstatementType is added to GetQueryExecution API, so customers have an error free way to detect the query type and interpret the result. -* `github.com/aws/aws-sdk-go-v2/service/dynamodb`: [v1.19.0](service/dynamodb/CHANGELOG.md#v1190-2023-03-08) - * **Feature**: Adds deletion protection support to DynamoDB tables. Tables with deletion protection enabled cannot be deleted. Deletion protection is disabled by default, can be enabled via the CreateTable or UpdateTable APIs, and is visible in TableDescription. This setting is not replicated for Global Tables. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.89.0](service/ec2/CHANGELOG.md#v1890-2023-03-08) - * **Feature**: Introducing Amazon EC2 C7g, M7g and R7g instances, powered by the latest generation AWS Graviton3 processors and deliver up to 25% better performance over Graviton2-based instances. -* `github.com/aws/aws-sdk-go-v2/service/lakeformation`: [v1.20.0](service/lakeformation/CHANGELOG.md#v1200-2023-03-08) - * **Feature**: This release adds two new API support "GetDataCellsFiler" and "UpdateDataCellsFilter", and also updates the corresponding documentation. -* `github.com/aws/aws-sdk-go-v2/service/mediapackage`: [v1.21.0](service/mediapackage/CHANGELOG.md#v1210-2023-03-08) - * **Feature**: This release provides the date and time live resources were created. -* `github.com/aws/aws-sdk-go-v2/service/mediapackagevod`: [v1.22.0](service/mediapackagevod/CHANGELOG.md#v1220-2023-03-08) - * **Feature**: This release provides the date and time VOD resources were created. -* `github.com/aws/aws-sdk-go-v2/service/route53resolver`: [v1.17.0](service/route53resolver/CHANGELOG.md#v1170-2023-03-08) - * **Feature**: Add dual-stack and IPv6 support for Route 53 Resolver Endpoint,Add IPv6 target IP in Route 53 Resolver Forwarding Rule -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.70.0](service/sagemaker/CHANGELOG.md#v1700-2023-03-08) - * **Feature**: There needs to be a user identity to specify the SageMaker user who perform each action regarding the entity. However, these is a not a unified concept of user identity across SageMaker service that could be used today. - -# Release (2023-03-07) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/databasemigrationservice`: [v1.24.0](service/databasemigrationservice/CHANGELOG.md#v1240-2023-03-07) - * **Feature**: This release adds DMS Fleet Advisor Target Recommendation APIs and exposes functionality for DMS Fleet Advisor. It adds functionality to start Target Recommendation calculation. -* `github.com/aws/aws-sdk-go-v2/service/location`: [v1.22.1](service/location/CHANGELOG.md#v1221-2023-03-07) - * **Documentation**: Documentation update for the release of 3 additional map styles for use with Open Data Maps: Open Data Standard Dark, Open Data Visualization Light & Open Data Visualization Dark. - -# Release (2023-03-06) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/account`: [v1.10.0](service/account/CHANGELOG.md#v1100-2023-03-06) - * **Feature**: AWS Account alternate contact email addresses can now have a length of 254 characters and contain the character "|". -* `github.com/aws/aws-sdk-go-v2/service/ivs`: [v1.20.6](service/ivs/CHANGELOG.md#v1206-2023-03-06) - * **Documentation**: Updated text description in DeleteChannel, Stream, and StreamSummary. - -# Release (2023-03-03) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/dynamodb`: [v1.18.6](service/dynamodb/CHANGELOG.md#v1186-2023-03-03) - * **Documentation**: Documentation updates for DynamoDB. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.88.0](service/ec2/CHANGELOG.md#v1880-2023-03-03) - * **Feature**: This release adds support for a new boot mode for EC2 instances called 'UEFI Preferred'. -* `github.com/aws/aws-sdk-go-v2/service/macie2`: [v1.27.1](service/macie2/CHANGELOG.md#v1271-2023-03-03) - * **Documentation**: Documentation updates for Amazon Macie -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.33.0](service/mediaconvert/CHANGELOG.md#v1330-2023-03-03) - * **Feature**: The AWS Elemental MediaConvert SDK has improved handling for different input and output color space combinations. -* `github.com/aws/aws-sdk-go-v2/service/medialive`: [v1.30.0](service/medialive/CHANGELOG.md#v1300-2023-03-03) - * **Feature**: AWS Elemental MediaLive adds support for Nielsen watermark timezones. -* `github.com/aws/aws-sdk-go-v2/service/transcribe`: [v1.26.0](service/transcribe/CHANGELOG.md#v1260-2023-03-03) - * **Feature**: Amazon Transcribe now supports role access for these API operations: CreateVocabulary, UpdateVocabulary, CreateVocabularyFilter, and UpdateVocabularyFilter. - -# Release (2023-03-02) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.35.0](service/iot/CHANGELOG.md#v1350-2023-03-02) - * **Feature**: A recurring maintenance window is an optional configuration used for rolling out the job document to all devices in the target group observing a predetermined start time, duration, and frequency that the maintenance window occurs. -* `github.com/aws/aws-sdk-go-v2/service/migrationhubstrategy`: [v1.8.0](service/migrationhubstrategy/CHANGELOG.md#v180-2023-03-02) - * **Feature**: This release updates the File Import API to allow importing servers already discovered by customers with reduced pre-requisites. -* `github.com/aws/aws-sdk-go-v2/service/organizations`: [v1.19.0](service/organizations/CHANGELOG.md#v1190-2023-03-02) - * **Feature**: This release introduces a new reason code, ACCOUNT_CREATION_NOT_COMPLETE, to ConstraintViolationException in CreateOrganization API. -* `github.com/aws/aws-sdk-go-v2/service/pi`: [v1.17.0](service/pi/CHANGELOG.md#v1170-2023-03-02) - * **Feature**: This release adds a new field PeriodAlignment to allow the customer specifying the returned timestamp of time periods to be either the start or end time. -* `github.com/aws/aws-sdk-go-v2/service/pipes`: [v1.2.0](service/pipes/CHANGELOG.md#v120-2023-03-02) - * **Feature**: This release fixes some input parameter range and patterns. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.69.0](service/sagemaker/CHANGELOG.md#v1690-2023-03-02) - * **Feature**: Add a new field "EndpointMetrics" in SageMaker Inference Recommender "ListInferenceRecommendationsJobSteps" API response. - -# Release (2023-03-01) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/codecatalyst`: [v1.2.0](service/codecatalyst/CHANGELOG.md#v120-2023-03-01) - * **Feature**: Published Dev Environments StopDevEnvironmentSession API -* `github.com/aws/aws-sdk-go-v2/service/pricing`: [v1.19.0](service/pricing/CHANGELOG.md#v1190-2023-03-01) - * **Feature**: This release adds 2 new APIs - ListPriceLists which returns a list of applicable price lists, and GetPriceListFileUrl which outputs a URL to retrieve your price lists from the generated file from ListPriceLists -* `github.com/aws/aws-sdk-go-v2/service/s3outposts`: [v1.15.0](service/s3outposts/CHANGELOG.md#v1150-2023-03-01) - * **Feature**: S3 on Outposts introduces a new API ListOutpostsWithS3, with this API you can list all your Outposts with S3 capacity. - -# Release (2023-02-28) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/comprehend`: [v1.22.0](service/comprehend/CHANGELOG.md#v1220-2023-02-28) - * **Feature**: Amazon Comprehend now supports flywheels to help you train and manage new model versions for custom models. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.87.0](service/ec2/CHANGELOG.md#v1870-2023-02-28) - * **Feature**: This release allows IMDS support to be set to v2-only on an existing AMI, so that all future instances launched from that AMI will use IMDSv2 by default. -* `github.com/aws/aws-sdk-go-v2/service/kms`: [v1.20.6](service/kms/CHANGELOG.md#v1206-2023-02-28) - * **Documentation**: AWS KMS is deprecating the RSAES_PKCS1_V1_5 wrapping algorithm option in the GetParametersForImport API that is used in the AWS KMS Import Key Material feature. AWS KMS will end support for this wrapping algorithm by October 1, 2023. -* `github.com/aws/aws-sdk-go-v2/service/lightsail`: [v1.26.0](service/lightsail/CHANGELOG.md#v1260-2023-02-28) - * **Feature**: This release adds Lightsail for Research feature support, such as GUI session access, cost estimates, stop instance on idle, and disk auto mount. -* `github.com/aws/aws-sdk-go-v2/service/managedblockchain`: [v1.15.0](service/managedblockchain/CHANGELOG.md#v1150-2023-02-28) - * **Feature**: This release adds support for tagging to the accessor resource in Amazon Managed Blockchain -* `github.com/aws/aws-sdk-go-v2/service/omics`: [v1.2.0](service/omics/CHANGELOG.md#v120-2023-02-28) - * **Feature**: Minor model changes to accomodate batch imports feature - -# Release (2023-02-27) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/devopsguru`: [v1.23.0](service/devopsguru/CHANGELOG.md#v1230-2023-02-27) - * **Feature**: This release adds the description field on ListAnomaliesForInsight and DescribeAnomaly API responses for proactive anomalies. -* `github.com/aws/aws-sdk-go-v2/service/drs`: [v1.11.0](service/drs/CHANGELOG.md#v1110-2023-02-27) - * **Feature**: New fields were added to reflect availability zone data in source server and recovery instance description commands responses, as well as source server launch status. -* `github.com/aws/aws-sdk-go-v2/service/internetmonitor`: [v1.0.0](service/internetmonitor/CHANGELOG.md#v100-2023-02-27) - * **Release**: New AWS service client module - * **Feature**: CloudWatch Internet Monitor is a a new service within CloudWatch that will help application developers and network engineers continuously monitor internet performance metrics such as availability and performance between their AWS-hosted applications and end-users of these applications -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.30.0](service/lambda/CHANGELOG.md#v1300-2023-02-27) - * **Feature**: This release adds the ability to create ESMs with Document DB change streams as event source. For more information see https://docs.aws.amazon.com/lambda/latest/dg/with-documentdb.html. -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.32.0](service/mediaconvert/CHANGELOG.md#v1320-2023-02-27) - * **Feature**: The AWS Elemental MediaConvert SDK has added support for HDR10 to SDR tone mapping, and animated GIF video input sources. -* `github.com/aws/aws-sdk-go-v2/service/timestreamwrite`: [v1.16.0](service/timestreamwrite/CHANGELOG.md#v1160-2023-02-27) - * **Feature**: This release adds the ability to ingest batched historical data or migrate data in bulk from S3 into Timestream using CSV files. - -# Release (2023-02-24) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.48.0](service/connect/CHANGELOG.md#v1480-2023-02-24) - * **Feature**: StartTaskContact API now supports linked task creation with a new optional RelatedContactId parameter -* `github.com/aws/aws-sdk-go-v2/service/connectcases`: [v1.3.0](service/connectcases/CHANGELOG.md#v130-2023-02-24) - * **Feature**: This release adds the ability to delete domains through the DeleteDomain API. For more information see https://docs.aws.amazon.com/cases/latest/APIReference/Welcome.html -* `github.com/aws/aws-sdk-go-v2/service/redshift`: [v1.27.5](service/redshift/CHANGELOG.md#v1275-2023-02-24) - * **Documentation**: Documentation updates for Redshift API bringing it in line with IAM best practices. -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.29.0](service/securityhub/CHANGELOG.md#v1290-2023-02-24) - * **Feature**: New Security Hub APIs and updates to existing APIs that help you consolidate control findings and enable and disable controls across all supported standards -* `github.com/aws/aws-sdk-go-v2/service/servicecatalog`: [v1.16.5](service/servicecatalog/CHANGELOG.md#v1165-2023-02-24) - * **Documentation**: Documentation updates for Service Catalog - -# Release (2023-02-23) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/appflow`: [v1.25.0](service/appflow/CHANGELOG.md#v1250-2023-02-23) - * **Feature**: This release enables the customers to choose whether to use Private Link for Metadata and Authorization call when using a private Salesforce connections -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.24.0](service/ecs/CHANGELOG.md#v1240-2023-02-23) - * **Feature**: This release supports deleting Amazon ECS task definitions that are in the INACTIVE state. -* `github.com/aws/aws-sdk-go-v2/service/grafana`: [v1.12.3](service/grafana/CHANGELOG.md#v1123-2023-02-23) - * **Documentation**: Doc-only update. Updated information on attached role policies for customer provided roles -* `github.com/aws/aws-sdk-go-v2/service/guardduty`: [v1.17.6](service/guardduty/CHANGELOG.md#v1176-2023-02-23) - * **Documentation**: Updated API and data types descriptions for CreateFilter, UpdateFilter, and TriggerDetails. -* `github.com/aws/aws-sdk-go-v2/service/iotwireless`: [v1.25.0](service/iotwireless/CHANGELOG.md#v1250-2023-02-23) - * **Feature**: In this release, we add additional capabilities for the FUOTA which allows user to configure the fragment size, the sending interval and the redundancy ratio of the FUOTA tasks -* `github.com/aws/aws-sdk-go-v2/service/location`: [v1.22.0](service/location/CHANGELOG.md#v1220-2023-02-23) - * **Feature**: This release adds support for using Maps APIs with an API Key in addition to AWS Cognito. This includes support for adding, listing, updating and deleting API Keys. -* `github.com/aws/aws-sdk-go-v2/service/macie2`: [v1.27.0](service/macie2/CHANGELOG.md#v1270-2023-02-23) - * **Feature**: This release adds support for a new finding type, Policy:IAMUser/S3BucketSharedWithCloudFront, and S3 bucket metadata that indicates if a bucket is shared with an Amazon CloudFront OAI or OAC. -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.26.0](service/wafv2/CHANGELOG.md#v1260-2023-02-23) - * **Feature**: You can now associate an AWS WAF v2 web ACL with an AWS App Runner service. - -# Release (2023-02-22) - -## General Highlights -* **Bug Fix**: Prevent nil pointer dereference when retrieving error codes. -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/chimesdkvoice`: [v1.2.0](service/chimesdkvoice/CHANGELOG.md#v120-2023-02-22) - * **Feature**: This release introduces support for Voice Connector media metrics in the Amazon Chime SDK Voice namespace -* `github.com/aws/aws-sdk-go-v2/service/cloudfront`: [v1.26.0](service/cloudfront/CHANGELOG.md#v1260-2023-02-22) - * **Feature**: CloudFront now supports block lists in origin request policies so that you can forward all headers, cookies, or query string from viewer requests to the origin *except* for those specified in the block list. -* `github.com/aws/aws-sdk-go-v2/service/datasync`: [v1.23.0](service/datasync/CHANGELOG.md#v1230-2023-02-22) - * **Feature**: AWS DataSync has relaxed the minimum length constraint of AccessKey for Object Storage locations to 1. -* `github.com/aws/aws-sdk-go-v2/service/opensearch`: [v1.15.0](service/opensearch/CHANGELOG.md#v1150-2023-02-22) - * **Feature**: This release lets customers configure Off-peak window and software update related properties for a new/existing domain. It enhances the capabilities of StartServiceSoftwareUpdate API; adds 2 new APIs - ListScheduledActions & UpdateScheduledAction; and allows Auto-tune to make use of Off-peak window. -* `github.com/aws/aws-sdk-go-v2/service/rum`: [v1.10.0](service/rum/CHANGELOG.md#v1100-2023-02-22) - * **Feature**: CloudWatch RUM now supports CloudWatch Custom Metrics -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.35.5](service/ssm/CHANGELOG.md#v1355-2023-02-22) - * **Documentation**: Document only update for Feb 2023 - -# Release (2023-02-21) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.32.0](service/quicksight/CHANGELOG.md#v1320-2023-02-21) - * **Feature**: S3 data sources now accept a custom IAM role. -* `github.com/aws/aws-sdk-go-v2/service/resiliencehub`: [v1.9.0](service/resiliencehub/CHANGELOG.md#v190-2023-02-21) - * **Feature**: In this release we improved resilience hub application creation and maintenance by introducing new resource and app component crud APIs, improving visibility and maintenance of application input sources and added support for additional information attributes to be provided by customers. -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.28.4](service/securityhub/CHANGELOG.md#v1284-2023-02-21) - * **Documentation**: Documentation updates for AWS Security Hub -* `github.com/aws/aws-sdk-go-v2/service/tnb`: [v1.0.0](service/tnb/CHANGELOG.md#v100-2023-02-21) - * **Release**: New AWS service client module - * **Feature**: This is the initial SDK release for AWS Telco Network Builder (TNB). AWS Telco Network Builder is a network automation service that helps you deploy and manage telecom networks. - -# Release (2023-02-20) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2`: v1.17.5 - * **Bug Fix**: fix int overflow bug on 32 bit architecture -* `github.com/aws/aws-sdk-go-v2/service/auditmanager`: [v1.24.0](service/auditmanager/CHANGELOG.md#v1240-2023-02-20) - * **Feature**: This release introduces a ServiceQuotaExceededException to the UpdateAssessmentFrameworkShare API operation. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.47.0](service/connect/CHANGELOG.md#v1470-2023-02-20) - * **Feature**: Reasons for failed diff has been approved by SDK Reviewer - -# Release (2023-02-17) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/apprunner`: [v1.17.0](service/apprunner/CHANGELOG.md#v1170-2023-02-17) - * **Feature**: This release supports removing MaxSize limit for AutoScalingConfiguration. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.43.0](service/glue/CHANGELOG.md#v1430-2023-02-17) - * **Feature**: Release of Delta Lake Data Lake Format for Glue Studio Service - -# Release (2023-02-16) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/emr`: [v1.23.0](service/emr/CHANGELOG.md#v1230-2023-02-16) - * **Feature**: This release provides customers the ability to define a timeout period for procuring capacity during a resize operation for Instance Fleet clusters. Customers can specify this timeout using the ResizeSpecifications parameter supported by RunJobFlow, ModifyInstanceFleet and AddInstanceFleet APIs. -* `github.com/aws/aws-sdk-go-v2/service/grafana`: [v1.12.0](service/grafana/CHANGELOG.md#v1120-2023-02-16) - * **Feature**: With this release Amazon Managed Grafana now supports inbound Network Access Control that helps you to restrict user access to your Grafana workspaces -* `github.com/aws/aws-sdk-go-v2/service/ivs`: [v1.20.3](service/ivs/CHANGELOG.md#v1203-2023-02-16) - * **Documentation**: Doc-only update. Updated text description in DeleteChannel, Stream, and StreamSummary. -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.25.1](service/wafv2/CHANGELOG.md#v1251-2023-02-16) - * **Documentation**: Added a notice for account takeover prevention (ATP). The interface incorrectly lets you to configure ATP response inspection in regional web ACLs in Region US East (N. Virginia), without returning an error. ATP response inspection is only available in web ACLs that protect CloudFront distributions. - -# Release (2023-02-15) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/accessanalyzer`: [v1.19.3](service/accessanalyzer/CHANGELOG.md#v1193-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/account`: [v1.9.1](service/account/CHANGELOG.md#v191-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/acm`: [v1.17.3](service/acm/CHANGELOG.md#v1173-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/acmpca`: [v1.21.2](service/acmpca/CHANGELOG.md#v1212-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/alexaforbusiness`: [v1.15.2](service/alexaforbusiness/CHANGELOG.md#v1152-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/amp`: [v1.16.2](service/amp/CHANGELOG.md#v1162-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/amplify`: [v1.13.2](service/amplify/CHANGELOG.md#v1132-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/amplifybackend`: [v1.14.2](service/amplifybackend/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/amplifyuibuilder`: [v1.9.2](service/amplifyuibuilder/CHANGELOG.md#v192-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/apigateway`: [v1.16.3](service/apigateway/CHANGELOG.md#v1163-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/apigatewaymanagementapi`: [v1.11.2](service/apigatewaymanagementapi/CHANGELOG.md#v1112-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/apigatewayv2`: [v1.13.3](service/apigatewayv2/CHANGELOG.md#v1133-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/appconfig`: [v1.17.1](service/appconfig/CHANGELOG.md#v1171-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/appconfigdata`: [v1.6.1](service/appconfigdata/CHANGELOG.md#v161-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/appflow`: [v1.24.2](service/appflow/CHANGELOG.md#v1242-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/appintegrations`: [v1.14.2](service/appintegrations/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/applicationautoscaling`: [v1.17.3](service/applicationautoscaling/CHANGELOG.md#v1173-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/applicationcostprofiler`: [v1.10.2](service/applicationcostprofiler/CHANGELOG.md#v1102-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/applicationdiscoveryservice`: [v1.15.2](service/applicationdiscoveryservice/CHANGELOG.md#v1152-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/applicationinsights`: [v1.17.3](service/applicationinsights/CHANGELOG.md#v1173-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/appmesh`: [v1.17.2](service/appmesh/CHANGELOG.md#v1172-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/apprunner`: [v1.16.2](service/apprunner/CHANGELOG.md#v1162-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/appstream`: [v1.20.2](service/appstream/CHANGELOG.md#v1202-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/appsync`: [v1.19.2](service/appsync/CHANGELOG.md#v1192-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/arczonalshift`: [v1.1.3](service/arczonalshift/CHANGELOG.md#v113-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/athena`: [v1.22.2](service/athena/CHANGELOG.md#v1222-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/auditmanager`: [v1.23.2](service/auditmanager/CHANGELOG.md#v1232-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/autoscalingplans`: [v1.13.2](service/autoscalingplans/CHANGELOG.md#v1132-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/backup`: [v1.20.1](service/backup/CHANGELOG.md#v1201-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/backupgateway`: [v1.9.2](service/backupgateway/CHANGELOG.md#v192-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/backupstorage`: [v1.1.2](service/backupstorage/CHANGELOG.md#v112-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/batch`: [v1.21.3](service/batch/CHANGELOG.md#v1213-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/billingconductor`: [v1.5.2](service/billingconductor/CHANGELOG.md#v152-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/braket`: [v1.17.2](service/braket/CHANGELOG.md#v1172-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/budgets`: [v1.14.2](service/budgets/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/chime`: [v1.22.2](service/chime/CHANGELOG.md#v1222-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/chimesdkidentity`: [v1.10.2](service/chimesdkidentity/CHANGELOG.md#v1102-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmediapipelines`: [v1.2.2](service/chimesdkmediapipelines/CHANGELOG.md#v122-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmeetings`: [v1.14.3](service/chimesdkmeetings/CHANGELOG.md#v1143-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmessaging`: [v1.12.2](service/chimesdkmessaging/CHANGELOG.md#v1122-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/chimesdkvoice`: [v1.1.2](service/chimesdkvoice/CHANGELOG.md#v112-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/cleanrooms`: [v1.0.2](service/cleanrooms/CHANGELOG.md#v102-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/cloud9`: [v1.17.2](service/cloud9/CHANGELOG.md#v1172-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/cloudcontrol`: [v1.11.3](service/cloudcontrol/CHANGELOG.md#v1113-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/clouddirectory`: [v1.13.2](service/clouddirectory/CHANGELOG.md#v1132-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/cloudhsm`: [v1.13.2](service/cloudhsm/CHANGELOG.md#v1132-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/cloudhsmv2`: [v1.14.2](service/cloudhsmv2/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/cloudsearchdomain`: [v1.12.2](service/cloudsearchdomain/CHANGELOG.md#v1122-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/cloudtrail`: [v1.24.0](service/cloudtrail/CHANGELOG.md#v1240-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Feature**: This release adds an InsufficientEncryptionPolicyException type to the StartImport endpoint - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/cloudtraildata`: [v1.0.2](service/cloudtraildata/CHANGELOG.md#v102-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/cloudwatchevents`: [v1.15.3](service/cloudwatchevents/CHANGELOG.md#v1153-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs`: [v1.20.3](service/cloudwatchlogs/CHANGELOG.md#v1203-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/codeartifact`: [v1.16.2](service/codeartifact/CHANGELOG.md#v1162-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/codebuild`: [v1.20.3](service/codebuild/CHANGELOG.md#v1203-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/codecatalyst`: [v1.1.2](service/codecatalyst/CHANGELOG.md#v112-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/codecommit`: [v1.14.2](service/codecommit/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/codedeploy`: [v1.16.3](service/codedeploy/CHANGELOG.md#v1163-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/codeguruprofiler`: [v1.13.2](service/codeguruprofiler/CHANGELOG.md#v1132-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/codegurureviewer`: [v1.17.2](service/codegurureviewer/CHANGELOG.md#v1172-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/codepipeline`: [v1.14.2](service/codepipeline/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/codestar`: [v1.13.2](service/codestar/CHANGELOG.md#v1132-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/codestarconnections`: [v1.14.2](service/codestarconnections/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/codestarnotifications`: [v1.14.2](service/codestarnotifications/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/cognitoidentity`: [v1.15.2](service/cognitoidentity/CHANGELOG.md#v1152-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider`: [v1.22.2](service/cognitoidentityprovider/CHANGELOG.md#v1222-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/cognitosync`: [v1.12.2](service/cognitosync/CHANGELOG.md#v1122-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/comprehend`: [v1.21.2](service/comprehend/CHANGELOG.md#v1212-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/comprehendmedical`: [v1.15.2](service/comprehendmedical/CHANGELOG.md#v1152-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/computeoptimizer`: [v1.21.1](service/computeoptimizer/CHANGELOG.md#v1211-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/configservice`: [v1.29.3](service/configservice/CHANGELOG.md#v1293-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.46.1](service/connect/CHANGELOG.md#v1461-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/connectcampaigns`: [v1.2.3](service/connectcampaigns/CHANGELOG.md#v123-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/connectcases`: [v1.2.3](service/connectcases/CHANGELOG.md#v123-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/connectcontactlens`: [v1.13.2](service/connectcontactlens/CHANGELOG.md#v1132-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/connectparticipant`: [v1.15.2](service/connectparticipant/CHANGELOG.md#v1152-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/controltower`: [v1.1.2](service/controltower/CHANGELOG.md#v112-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/costandusagereportservice`: [v1.15.2](service/costandusagereportservice/CHANGELOG.md#v1152-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/costexplorer`: [v1.25.2](service/costexplorer/CHANGELOG.md#v1252-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/customerprofiles`: [v1.23.1](service/customerprofiles/CHANGELOG.md#v1231-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/databasemigrationservice`: [v1.23.3](service/databasemigrationservice/CHANGELOG.md#v1233-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/databrew`: [v1.21.3](service/databrew/CHANGELOG.md#v1213-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/dataexchange`: [v1.18.2](service/dataexchange/CHANGELOG.md#v1182-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/datapipeline`: [v1.14.2](service/datapipeline/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/datasync`: [v1.22.1](service/datasync/CHANGELOG.md#v1221-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/dax`: [v1.12.2](service/dax/CHANGELOG.md#v1122-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/detective`: [v1.18.2](service/detective/CHANGELOG.md#v1182-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/devicefarm`: [v1.15.2](service/devicefarm/CHANGELOG.md#v1152-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/devopsguru`: [v1.22.2](service/devopsguru/CHANGELOG.md#v1222-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/directconnect`: [v1.18.3](service/directconnect/CHANGELOG.md#v1183-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/directoryservice`: [v1.16.3](service/directoryservice/CHANGELOG.md#v1163-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/dlm`: [v1.14.4](service/dlm/CHANGELOG.md#v1144-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/docdbelastic`: [v1.1.2](service/docdbelastic/CHANGELOG.md#v112-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/drs`: [v1.10.2](service/drs/CHANGELOG.md#v1102-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/dynamodb`: [v1.18.3](service/dynamodb/CHANGELOG.md#v1183-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/dynamodbstreams`: [v1.14.3](service/dynamodbstreams/CHANGELOG.md#v1143-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/ebs`: [v1.16.4](service/ebs/CHANGELOG.md#v1164-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/ec2instanceconnect`: [v1.15.2](service/ec2instanceconnect/CHANGELOG.md#v1152-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/ecr`: [v1.18.3](service/ecr/CHANGELOG.md#v1183-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/ecrpublic`: [v1.15.2](service/ecrpublic/CHANGELOG.md#v1152-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.23.3](service/ecs/CHANGELOG.md#v1233-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/efs`: [v1.19.4](service/efs/CHANGELOG.md#v1194-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. - * **Documentation**: Documentation update for EFS to support IAM best practices. -* `github.com/aws/aws-sdk-go-v2/service/eks`: [v1.27.3](service/eks/CHANGELOG.md#v1273-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/elasticinference`: [v1.12.2](service/elasticinference/CHANGELOG.md#v1122-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/elasticsearchservice`: [v1.18.3](service/elasticsearchservice/CHANGELOG.md#v1183-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/elastictranscoder`: [v1.14.2](service/elastictranscoder/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/emr`: [v1.22.3](service/emr/CHANGELOG.md#v1223-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/emrcontainers`: [v1.17.1](service/emrcontainers/CHANGELOG.md#v1171-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/emrserverless`: [v1.5.2](service/emrserverless/CHANGELOG.md#v152-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/eventbridge`: [v1.18.3](service/eventbridge/CHANGELOG.md#v1183-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/evidently`: [v1.10.2](service/evidently/CHANGELOG.md#v1102-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/finspace`: [v1.9.2](service/finspace/CHANGELOG.md#v192-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/finspacedata`: [v1.14.2](service/finspacedata/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/firehose`: [v1.16.3](service/firehose/CHANGELOG.md#v1163-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/fis`: [v1.14.2](service/fis/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/fms`: [v1.22.3](service/fms/CHANGELOG.md#v1223-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/forecast`: [v1.25.2](service/forecast/CHANGELOG.md#v1252-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/forecastquery`: [v1.13.2](service/forecastquery/CHANGELOG.md#v1132-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/frauddetector`: [v1.23.0](service/frauddetector/CHANGELOG.md#v1230-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Feature**: This release introduces Lists feature which allows customers to reference a set of values in Fraud Detector's rules. With Lists, customers can dynamically manage these attributes in real time. Lists can be created/deleted and its contents can be modified using the Fraud Detector API. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/fsx`: [v1.28.3](service/fsx/CHANGELOG.md#v1283-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/gamelift`: [v1.17.2](service/gamelift/CHANGELOG.md#v1172-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/gamesparks`: [v1.2.2](service/gamesparks/CHANGELOG.md#v122-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/glacier`: [v1.14.3](service/glacier/CHANGELOG.md#v1143-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/globalaccelerator`: [v1.16.2](service/globalaccelerator/CHANGELOG.md#v1162-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.42.0](service/glue/CHANGELOG.md#v1420-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Feature**: Fix DirectJDBCSource not showing up in CLI code gen - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/grafana`: [v1.11.2](service/grafana/CHANGELOG.md#v1112-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/greengrass`: [v1.15.3](service/greengrass/CHANGELOG.md#v1153-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/greengrassv2`: [v1.21.3](service/greengrassv2/CHANGELOG.md#v1213-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/groundstation`: [v1.17.2](service/groundstation/CHANGELOG.md#v1172-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/guardduty`: [v1.17.3](service/guardduty/CHANGELOG.md#v1173-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/health`: [v1.16.2](service/health/CHANGELOG.md#v1162-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/healthlake`: [v1.15.2](service/healthlake/CHANGELOG.md#v1152-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/honeycode`: [v1.13.2](service/honeycode/CHANGELOG.md#v1132-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/identitystore`: [v1.16.2](service/identitystore/CHANGELOG.md#v1162-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/imagebuilder`: [v1.22.2](service/imagebuilder/CHANGELOG.md#v1222-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/inspector`: [v1.13.2](service/inspector/CHANGELOG.md#v1132-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/inspector2`: [v1.11.3](service/inspector2/CHANGELOG.md#v1113-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.34.2](service/iot/CHANGELOG.md#v1342-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/iot1clickdevicesservice`: [v1.11.2](service/iot1clickdevicesservice/CHANGELOG.md#v1112-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/iot1clickprojects`: [v1.12.2](service/iot1clickprojects/CHANGELOG.md#v1122-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/iotanalytics`: [v1.14.2](service/iotanalytics/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/iotdataplane`: [v1.14.2](service/iotdataplane/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/iotdeviceadvisor`: [v1.17.2](service/iotdeviceadvisor/CHANGELOG.md#v1172-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/iotevents`: [v1.15.2](service/iotevents/CHANGELOG.md#v1152-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/ioteventsdata`: [v1.13.2](service/ioteventsdata/CHANGELOG.md#v1132-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/iotfleethub`: [v1.13.2](service/iotfleethub/CHANGELOG.md#v1132-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/iotfleetwise`: [v1.3.2](service/iotfleetwise/CHANGELOG.md#v132-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/iotjobsdataplane`: [v1.12.2](service/iotjobsdataplane/CHANGELOG.md#v1122-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/iotroborunner`: [v1.1.2](service/iotroborunner/CHANGELOG.md#v112-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/iotsecuretunneling`: [v1.15.2](service/iotsecuretunneling/CHANGELOG.md#v1152-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/iotsitewise`: [v1.27.2](service/iotsitewise/CHANGELOG.md#v1272-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/iotthingsgraph`: [v1.14.2](service/iotthingsgraph/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/iottwinmaker`: [v1.10.2](service/iottwinmaker/CHANGELOG.md#v1102-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/iotwireless`: [v1.24.2](service/iotwireless/CHANGELOG.md#v1242-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/ivs`: [v1.20.2](service/ivs/CHANGELOG.md#v1202-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/ivschat`: [v1.3.2](service/ivschat/CHANGELOG.md#v132-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/kafka`: [v1.19.2](service/kafka/CHANGELOG.md#v1192-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/kafkaconnect`: [v1.9.2](service/kafkaconnect/CHANGELOG.md#v192-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.38.3](service/kendra/CHANGELOG.md#v1383-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/kendraranking`: [v1.0.4](service/kendraranking/CHANGELOG.md#v104-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/keyspaces`: [v1.1.2](service/keyspaces/CHANGELOG.md#v112-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/kinesis`: [v1.17.4](service/kinesis/CHANGELOG.md#v1174-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/kinesisanalytics`: [v1.14.2](service/kinesisanalytics/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/kinesisanalyticsv2`: [v1.16.2](service/kinesisanalyticsv2/CHANGELOG.md#v1162-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/kinesisvideo`: [v1.15.3](service/kinesisvideo/CHANGELOG.md#v1153-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/kinesisvideoarchivedmedia`: [v1.14.3](service/kinesisvideoarchivedmedia/CHANGELOG.md#v1143-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/kinesisvideomedia`: [v1.11.3](service/kinesisvideomedia/CHANGELOG.md#v1113-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/kinesisvideosignaling`: [v1.11.3](service/kinesisvideosignaling/CHANGELOG.md#v1113-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/kinesisvideowebrtcstorage`: [v1.2.3](service/kinesisvideowebrtcstorage/CHANGELOG.md#v123-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/kms`: [v1.20.3](service/kms/CHANGELOG.md#v1203-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/lakeformation`: [v1.19.2](service/lakeformation/CHANGELOG.md#v1192-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.29.2](service/lambda/CHANGELOG.md#v1292-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/lexmodelbuildingservice`: [v1.17.2](service/lexmodelbuildingservice/CHANGELOG.md#v1172-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/lexmodelsv2`: [v1.28.1](service/lexmodelsv2/CHANGELOG.md#v1281-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/lexruntimeservice`: [v1.13.2](service/lexruntimeservice/CHANGELOG.md#v1132-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/lexruntimev2`: [v1.17.1](service/lexruntimev2/CHANGELOG.md#v1171-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/licensemanager`: [v1.17.2](service/licensemanager/CHANGELOG.md#v1172-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/licensemanagerlinuxsubscriptions`: [v1.1.2](service/licensemanagerlinuxsubscriptions/CHANGELOG.md#v112-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/licensemanagerusersubscriptions`: [v1.2.2](service/licensemanagerusersubscriptions/CHANGELOG.md#v122-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/lightsail`: [v1.25.3](service/lightsail/CHANGELOG.md#v1253-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/location`: [v1.21.2](service/location/CHANGELOG.md#v1212-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/lookoutequipment`: [v1.17.2](service/lookoutequipment/CHANGELOG.md#v1172-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/lookoutmetrics`: [v1.19.2](service/lookoutmetrics/CHANGELOG.md#v1192-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/lookoutvision`: [v1.15.2](service/lookoutvision/CHANGELOG.md#v1152-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/m2`: [v1.4.2](service/m2/CHANGELOG.md#v142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/machinelearning`: [v1.15.2](service/machinelearning/CHANGELOG.md#v1152-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/macie`: [v1.15.2](service/macie/CHANGELOG.md#v1152-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/macie2`: [v1.26.2](service/macie2/CHANGELOG.md#v1262-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/managedblockchain`: [v1.14.2](service/managedblockchain/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/marketplacecatalog`: [v1.15.2](service/marketplacecatalog/CHANGELOG.md#v1152-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/marketplacecommerceanalytics`: [v1.12.2](service/marketplacecommerceanalytics/CHANGELOG.md#v1122-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/marketplaceentitlementservice`: [v1.12.2](service/marketplaceentitlementservice/CHANGELOG.md#v1122-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/marketplacemetering`: [v1.14.3](service/marketplacemetering/CHANGELOG.md#v1143-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/mediaconnect`: [v1.18.2](service/mediaconnect/CHANGELOG.md#v1182-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.31.1](service/mediaconvert/CHANGELOG.md#v1311-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/medialive`: [v1.29.2](service/medialive/CHANGELOG.md#v1292-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/mediapackage`: [v1.20.2](service/mediapackage/CHANGELOG.md#v1202-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/mediapackagevod`: [v1.21.2](service/mediapackagevod/CHANGELOG.md#v1212-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/mediastore`: [v1.13.2](service/mediastore/CHANGELOG.md#v1132-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/mediastoredata`: [v1.13.2](service/mediastoredata/CHANGELOG.md#v1132-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/mediatailor`: [v1.22.2](service/mediatailor/CHANGELOG.md#v1222-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/memorydb`: [v1.12.2](service/memorydb/CHANGELOG.md#v1122-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/mgn`: [v1.17.2](service/mgn/CHANGELOG.md#v1172-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/migrationhub`: [v1.13.2](service/migrationhub/CHANGELOG.md#v1132-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/migrationhubconfig`: [v1.13.2](service/migrationhubconfig/CHANGELOG.md#v1132-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/migrationhuborchestrator`: [v1.1.2](service/migrationhuborchestrator/CHANGELOG.md#v112-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/migrationhubrefactorspaces`: [v1.9.1](service/migrationhubrefactorspaces/CHANGELOG.md#v191-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/migrationhubstrategy`: [v1.7.2](service/migrationhubstrategy/CHANGELOG.md#v172-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/mobile`: [v1.12.2](service/mobile/CHANGELOG.md#v1122-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/mq`: [v1.14.2](service/mq/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/mturk`: [v1.14.2](service/mturk/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/mwaa`: [v1.14.2](service/mwaa/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/networkfirewall`: [v1.24.2](service/networkfirewall/CHANGELOG.md#v1242-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/networkmanager`: [v1.17.2](service/networkmanager/CHANGELOG.md#v1172-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/nimble`: [v1.16.2](service/nimble/CHANGELOG.md#v1162-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/oam`: [v1.1.3](service/oam/CHANGELOG.md#v113-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/omics`: [v1.1.2](service/omics/CHANGELOG.md#v112-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/opensearch`: [v1.14.2](service/opensearch/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/opensearchserverless`: [v1.1.3](service/opensearchserverless/CHANGELOG.md#v113-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/opsworks`: [v1.14.2](service/opsworks/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/opsworkscm`: [v1.15.2](service/opsworkscm/CHANGELOG.md#v1152-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/organizations`: [v1.18.2](service/organizations/CHANGELOG.md#v1182-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/outposts`: [v1.27.2](service/outposts/CHANGELOG.md#v1272-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/panorama`: [v1.11.2](service/panorama/CHANGELOG.md#v1112-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/personalize`: [v1.23.2](service/personalize/CHANGELOG.md#v1232-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/personalizeevents`: [v1.13.2](service/personalizeevents/CHANGELOG.md#v1132-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/personalizeruntime`: [v1.13.2](service/personalizeruntime/CHANGELOG.md#v1132-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/pi`: [v1.16.3](service/pi/CHANGELOG.md#v1163-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/pinpoint`: [v1.18.2](service/pinpoint/CHANGELOG.md#v1182-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/pinpointemail`: [v1.12.2](service/pinpointemail/CHANGELOG.md#v1122-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/pinpointsmsvoice`: [v1.11.2](service/pinpointsmsvoice/CHANGELOG.md#v1112-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/pinpointsmsvoicev2`: [v1.1.2](service/pinpointsmsvoicev2/CHANGELOG.md#v112-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/pipes`: [v1.1.2](service/pipes/CHANGELOG.md#v112-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/polly`: [v1.25.1](service/polly/CHANGELOG.md#v1251-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/pricing`: [v1.18.2](service/pricing/CHANGELOG.md#v1182-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/privatenetworks`: [v1.2.0](service/privatenetworks/CHANGELOG.md#v120-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Feature**: This release introduces a new StartNetworkResourceUpdate API, which enables return/replacement of hardware from a NetworkSite. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/proton`: [v1.20.1](service/proton/CHANGELOG.md#v1201-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/qldb`: [v1.15.2](service/qldb/CHANGELOG.md#v1152-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/qldbsession`: [v1.14.2](service/qldbsession/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.31.2](service/quicksight/CHANGELOG.md#v1312-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/ram`: [v1.17.3](service/ram/CHANGELOG.md#v1173-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/rbin`: [v1.8.3](service/rbin/CHANGELOG.md#v183-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.40.3](service/rds/CHANGELOG.md#v1403-2023-02-15) - * **Documentation**: Database Activity Stream support for RDS for SQL Server. -* `github.com/aws/aws-sdk-go-v2/service/rdsdata`: [v1.13.2](service/rdsdata/CHANGELOG.md#v1132-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/redshiftdata`: [v1.18.2](service/redshiftdata/CHANGELOG.md#v1182-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/redshiftserverless`: [v1.4.3](service/redshiftserverless/CHANGELOG.md#v143-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/rekognition`: [v1.23.2](service/rekognition/CHANGELOG.md#v1232-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/resiliencehub`: [v1.8.2](service/resiliencehub/CHANGELOG.md#v182-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/resourceexplorer2`: [v1.2.3](service/resourceexplorer2/CHANGELOG.md#v123-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/resourcegroups`: [v1.14.3](service/resourcegroups/CHANGELOG.md#v1143-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi`: [v1.14.3](service/resourcegroupstaggingapi/CHANGELOG.md#v1143-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/robomaker`: [v1.18.2](service/robomaker/CHANGELOG.md#v1182-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/rolesanywhere`: [v1.1.2](service/rolesanywhere/CHANGELOG.md#v112-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/route53domains`: [v1.14.2](service/route53domains/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/route53recoverycluster`: [v1.11.2](service/route53recoverycluster/CHANGELOG.md#v1112-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/route53recoverycontrolconfig`: [v1.11.2](service/route53recoverycontrolconfig/CHANGELOG.md#v1112-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/route53recoveryreadiness`: [v1.9.2](service/route53recoveryreadiness/CHANGELOG.md#v192-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/route53resolver`: [v1.16.3](service/route53resolver/CHANGELOG.md#v1163-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/rum`: [v1.9.2](service/rum/CHANGELOG.md#v192-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/s3outposts`: [v1.14.2](service/s3outposts/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.68.1](service/sagemaker/CHANGELOG.md#v1681-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/sagemakera2iruntime`: [v1.15.2](service/sagemakera2iruntime/CHANGELOG.md#v1152-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/sagemakeredge`: [v1.13.2](service/sagemakeredge/CHANGELOG.md#v1132-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/sagemakerfeaturestoreruntime`: [v1.13.2](service/sagemakerfeaturestoreruntime/CHANGELOG.md#v1132-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/sagemakergeospatial`: [v1.1.2](service/sagemakergeospatial/CHANGELOG.md#v112-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/sagemakermetrics`: [v1.0.5](service/sagemakermetrics/CHANGELOG.md#v105-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/sagemakerruntime`: [v1.18.3](service/sagemakerruntime/CHANGELOG.md#v1183-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/savingsplans`: [v1.12.2](service/savingsplans/CHANGELOG.md#v1122-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/scheduler`: [v1.1.2](service/scheduler/CHANGELOG.md#v112-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/schemas`: [v1.15.2](service/schemas/CHANGELOG.md#v1152-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/secretsmanager`: [v1.18.4](service/secretsmanager/CHANGELOG.md#v1184-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.28.2](service/securityhub/CHANGELOG.md#v1282-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/securitylake`: [v1.2.2](service/securitylake/CHANGELOG.md#v122-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/serverlessapplicationrepository`: [v1.12.2](service/serverlessapplicationrepository/CHANGELOG.md#v1122-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/servicecatalog`: [v1.16.2](service/servicecatalog/CHANGELOG.md#v1162-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/servicecatalogappregistry`: [v1.16.3](service/servicecatalogappregistry/CHANGELOG.md#v1163-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/servicediscovery`: [v1.19.2](service/servicediscovery/CHANGELOG.md#v1192-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/servicequotas`: [v1.14.3](service/servicequotas/CHANGELOG.md#v1143-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/sesv2`: [v1.16.2](service/sesv2/CHANGELOG.md#v1162-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/sfn`: [v1.17.3](service/sfn/CHANGELOG.md#v1173-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/shield`: [v1.18.2](service/shield/CHANGELOG.md#v1182-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/signer`: [v1.14.2](service/signer/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/simspaceweaver`: [v1.1.2](service/simspaceweaver/CHANGELOG.md#v112-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/sms`: [v1.13.2](service/sms/CHANGELOG.md#v1132-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/snowball`: [v1.18.1](service/snowball/CHANGELOG.md#v1181-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/snowdevicemanagement`: [v1.9.2](service/snowdevicemanagement/CHANGELOG.md#v192-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.35.3](service/ssm/CHANGELOG.md#v1353-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/ssmcontacts`: [v1.14.2](service/ssmcontacts/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/ssmincidents`: [v1.20.2](service/ssmincidents/CHANGELOG.md#v1202-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/ssmsap`: [v1.2.2](service/ssmsap/CHANGELOG.md#v122-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/sso`: [v1.12.2](service/sso/CHANGELOG.md#v1122-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/ssoadmin`: [v1.16.2](service/ssoadmin/CHANGELOG.md#v1162-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/ssooidc`: [v1.14.2](service/ssooidc/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/storagegateway`: [v1.18.3](service/storagegateway/CHANGELOG.md#v1183-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/support`: [v1.14.2](service/support/CHANGELOG.md#v1142-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/supportapp`: [v1.2.2](service/supportapp/CHANGELOG.md#v122-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/swf`: [v1.14.4](service/swf/CHANGELOG.md#v1144-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/synthetics`: [v1.17.3](service/synthetics/CHANGELOG.md#v1173-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/textract`: [v1.20.2](service/textract/CHANGELOG.md#v1202-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/timestreamquery`: [v1.15.2](service/timestreamquery/CHANGELOG.md#v1152-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/timestreamwrite`: [v1.15.2](service/timestreamwrite/CHANGELOG.md#v1152-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/transcribe`: [v1.25.2](service/transcribe/CHANGELOG.md#v1252-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/transcribestreaming`: [v1.9.2](service/transcribestreaming/CHANGELOG.md#v192-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.28.3](service/transfer/CHANGELOG.md#v1283-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/translate`: [v1.17.2](service/translate/CHANGELOG.md#v1172-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/voiceid`: [v1.12.2](service/voiceid/CHANGELOG.md#v1122-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/waf`: [v1.12.2](service/waf/CHANGELOG.md#v1122-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/wafregional`: [v1.13.3](service/wafregional/CHANGELOG.md#v1133-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.25.0](service/wafv2/CHANGELOG.md#v1250-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Feature**: For protected CloudFront distributions, you can now use the AWS WAF Fraud Control account takeover prevention (ATP) managed rule group to block new login attempts from clients that have recently submitted too many failed login attempts. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/wellarchitected`: [v1.18.2](service/wellarchitected/CHANGELOG.md#v1182-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/wisdom`: [v1.12.2](service/wisdom/CHANGELOG.md#v1122-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/workdocs`: [v1.13.3](service/workdocs/CHANGELOG.md#v1133-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/worklink`: [v1.13.2](service/worklink/CHANGELOG.md#v1132-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/workmail`: [v1.18.2](service/workmail/CHANGELOG.md#v1182-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/workmailmessageflow`: [v1.12.2](service/workmailmessageflow/CHANGELOG.md#v1122-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/workspaces`: [v1.28.3](service/workspaces/CHANGELOG.md#v1283-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/workspacesweb`: [v1.9.2](service/workspacesweb/CHANGELOG.md#v192-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. -* `github.com/aws/aws-sdk-go-v2/service/xray`: [v1.16.3](service/xray/CHANGELOG.md#v1163-2023-02-15) - * **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. - * **Bug Fix**: Correct error type parsing for restJson services. - -# Release (2023-02-14) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/appconfig`: [v1.17.0](service/appconfig/CHANGELOG.md#v1170-2023-02-14) - * **Feature**: AWS AppConfig now offers the option to set a version label on hosted configuration versions. Version labels allow you to identify specific hosted configuration versions based on an alternate versioning scheme that you define. -* `github.com/aws/aws-sdk-go-v2/service/datasync`: [v1.22.0](service/datasync/CHANGELOG.md#v1220-2023-02-14) - * **Feature**: With this launch, we are giving customers the ability to use older SMB protocol versions, enabling them to use DataSync to copy data to and from their legacy storage arrays. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.86.0](service/ec2/CHANGELOG.md#v1860-2023-02-14) - * **Feature**: With this release customers can turn host maintenance on or off when allocating or modifying a supported dedicated host. Host maintenance is turned on by default for supported hosts. - -# Release (2023-02-13) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/account`: [v1.9.0](service/account/CHANGELOG.md#v190-2023-02-13) - * **Feature**: This release of the Account Management API enables customers to view and manage whether AWS Opt-In Regions are enabled or disabled for their Account. For more information, see https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-regions.html -* `github.com/aws/aws-sdk-go-v2/service/appconfigdata`: [v1.6.0](service/appconfigdata/CHANGELOG.md#v160-2023-02-13) - * **Feature**: AWS AppConfig now offers the option to set a version label on hosted configuration versions. If a labeled hosted configuration version is deployed, its version label is available in the GetLatestConfiguration response. -* `github.com/aws/aws-sdk-go-v2/service/snowball`: [v1.18.0](service/snowball/CHANGELOG.md#v1180-2023-02-13) - * **Feature**: Adds support for EKS Anywhere on Snowball. AWS Snow Family customers can now install EKS Anywhere service on Snowball Edge Compute Optimized devices. - -# Release (2023-02-10) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/autoscaling`: [v1.27.0](service/autoscaling/CHANGELOG.md#v1270-2023-02-10) - * **Feature**: You can now either terminate/replace, ignore, or wait for EC2 Auto Scaling instances on standby or protected from scale in. Also, you can also roll back changes from a failed instance refresh. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.46.0](service/connect/CHANGELOG.md#v1460-2023-02-10) - * **Feature**: This update provides the Wisdom session ARN for contacts enabled for Wisdom in the chat channel. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.85.0](service/ec2/CHANGELOG.md#v1850-2023-02-10) - * **Feature**: Adds support for waiters that automatically poll for an imported snapshot until it reaches the completed state. -* `github.com/aws/aws-sdk-go-v2/service/polly`: [v1.25.0](service/polly/CHANGELOG.md#v1250-2023-02-10) - * **Feature**: Amazon Polly adds two new neural Japanese voices - Kazuha, Tomoko -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.68.0](service/sagemaker/CHANGELOG.md#v1680-2023-02-10) - * **Feature**: Amazon SageMaker Autopilot adds support for selecting algorithms in CreateAutoMLJob API. -* `github.com/aws/aws-sdk-go-v2/service/sns`: [v1.20.2](service/sns/CHANGELOG.md#v1202-2023-02-10) - * **Documentation**: This release adds support for SNS X-Ray active tracing as well as other updates. - -# Release (2023-02-09) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmeetings`: [v1.14.2](service/chimesdkmeetings/CHANGELOG.md#v1142-2023-02-09) - * **Documentation**: Documentation updates for Chime Meetings SDK -* `github.com/aws/aws-sdk-go-v2/service/emrcontainers`: [v1.17.0](service/emrcontainers/CHANGELOG.md#v1170-2023-02-09) - * **Feature**: EMR on EKS allows configuring retry policies for job runs through the StartJobRun API. Using retry policies, a job cause a driver pod to be restarted automatically if it fails or is deleted. The job's status can be seen in the DescribeJobRun and ListJobRun APIs and monitored using CloudWatch events. -* `github.com/aws/aws-sdk-go-v2/service/lexmodelsv2`: [v1.28.0](service/lexmodelsv2/CHANGELOG.md#v1280-2023-02-09) - * **Feature**: AWS Lex now supports Network of Bots. -* `github.com/aws/aws-sdk-go-v2/service/lexruntimev2`: [v1.17.0](service/lexruntimev2/CHANGELOG.md#v1170-2023-02-09) - * **Feature**: AWS Lex now supports Network of Bots. -* `github.com/aws/aws-sdk-go-v2/service/lightsail`: [v1.25.2](service/lightsail/CHANGELOG.md#v1252-2023-02-09) - * **Documentation**: Documentation updates for Lightsail -* `github.com/aws/aws-sdk-go-v2/service/migrationhubrefactorspaces`: [v1.9.0](service/migrationhubrefactorspaces/CHANGELOG.md#v190-2023-02-09) - * **Feature**: This release adds support for creating environments with a network fabric type of NONE -* `github.com/aws/aws-sdk-go-v2/service/workdocs`: [v1.13.2](service/workdocs/CHANGELOG.md#v1132-2023-02-09) - * **Documentation**: Doc only update for the WorkDocs APIs. -* `github.com/aws/aws-sdk-go-v2/service/workspaces`: [v1.28.2](service/workspaces/CHANGELOG.md#v1282-2023-02-09) - * **Documentation**: Removed Windows Server 2016 BYOL and made changes based on IAM campaign. - -# Release (2023-02-08) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/backup`: [v1.20.0](service/backup/CHANGELOG.md#v1200-2023-02-08) - * **Feature**: This release added one attribute (resource name) in the output model of our 9 existing APIs in AWS backup so that customers will see the resource name at the output. No input required from Customers. -* `github.com/aws/aws-sdk-go-v2/service/cloudfront`: [v1.25.0](service/cloudfront/CHANGELOG.md#v1250-2023-02-08) - * **Feature**: CloudFront Origin Access Control extends support to AWS Elemental MediaStore origins. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.41.0](service/glue/CHANGELOG.md#v1410-2023-02-08) - * **Feature**: DirectJDBCSource + Glue 4.0 streaming options - -# Release (2023-02-07) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.28.2](service/transfer/CHANGELOG.md#v1282-2023-02-07) - * **Documentation**: Updated the documentation for the ImportCertificate API call, and added examples. - -# Release (2023-02-06) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/computeoptimizer`: [v1.21.0](service/computeoptimizer/CHANGELOG.md#v1210-2023-02-06) - * **Feature**: AWS Compute optimizer can now infer if Kafka is running on an instance. -* `github.com/aws/aws-sdk-go-v2/service/customerprofiles`: [v1.23.0](service/customerprofiles/CHANGELOG.md#v1230-2023-02-06) - * **Feature**: This release deprecates the PartyType and Gender enum data types from the Profile model and replaces them with new PartyTypeString and GenderString attributes, which accept any string of length up to 255. -* `github.com/aws/aws-sdk-go-v2/service/frauddetector`: [v1.22.0](service/frauddetector/CHANGELOG.md#v1220-2023-02-06) - * **Feature**: My AWS Service (Amazon Fraud Detector) - This release introduces Cold Start Model Training which optimizes training for small datasets and adds intelligent methods for treating unlabeled data. You can now train Online Fraud Insights or Transaction Fraud Insights models with minimal historical-data. -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.31.0](service/mediaconvert/CHANGELOG.md#v1310-2023-02-06) - * **Feature**: The AWS Elemental MediaConvert SDK has added improved scene change detection capabilities and a bandwidth reduction filter, along with video quality enhancements, to the AVC encoder. -* `github.com/aws/aws-sdk-go-v2/service/outposts`: [v1.27.0](service/outposts/CHANGELOG.md#v1270-2023-02-06) - * **Feature**: Adds OrderType to Order structure. Adds PreviousOrderId and PreviousLineItemId to LineItem structure. Adds new line item status REPLACED. Increases maximum length of pagination token. - -# Release (2023-02-03) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/autoscaling`: [v1.26.2](service/autoscaling/CHANGELOG.md#v1262-2023-02-03) - * **Dependency Update**: Upgrade smithy to 1.27.2 and correct empty query list serialization. -* `github.com/aws/aws-sdk-go-v2/service/cloudformation`: [v1.26.2](service/cloudformation/CHANGELOG.md#v1262-2023-02-03) - * **Dependency Update**: Upgrade smithy to 1.27.2 and correct empty query list serialization. -* `github.com/aws/aws-sdk-go-v2/service/cloudsearch`: [v1.14.1](service/cloudsearch/CHANGELOG.md#v1141-2023-02-03) - * **Dependency Update**: Upgrade smithy to 1.27.2 and correct empty query list serialization. -* `github.com/aws/aws-sdk-go-v2/service/cloudwatch`: [v1.25.2](service/cloudwatch/CHANGELOG.md#v1252-2023-02-03) - * **Dependency Update**: Upgrade smithy to 1.27.2 and correct empty query list serialization. -* `github.com/aws/aws-sdk-go-v2/service/docdb`: [v1.20.2](service/docdb/CHANGELOG.md#v1202-2023-02-03) - * **Dependency Update**: Upgrade smithy to 1.27.2 and correct empty query list serialization. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.84.1](service/ec2/CHANGELOG.md#v1841-2023-02-03) - * **Dependency Update**: Upgrade smithy to 1.27.2 and correct empty query list serialization. -* `github.com/aws/aws-sdk-go-v2/service/elasticache`: [v1.26.2](service/elasticache/CHANGELOG.md#v1262-2023-02-03) - * **Dependency Update**: Upgrade smithy to 1.27.2 and correct empty query list serialization. -* `github.com/aws/aws-sdk-go-v2/service/elasticbeanstalk`: [v1.15.1](service/elasticbeanstalk/CHANGELOG.md#v1151-2023-02-03) - * **Dependency Update**: Upgrade smithy to 1.27.2 and correct empty query list serialization. -* `github.com/aws/aws-sdk-go-v2/service/elasticloadbalancing`: [v1.15.2](service/elasticloadbalancing/CHANGELOG.md#v1152-2023-02-03) - * **Dependency Update**: Upgrade smithy to 1.27.2 and correct empty query list serialization. -* `github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2`: [v1.19.3](service/elasticloadbalancingv2/CHANGELOG.md#v1193-2023-02-03) - * **Dependency Update**: Upgrade smithy to 1.27.2 and correct empty query list serialization. -* `github.com/aws/aws-sdk-go-v2/service/iam`: [v1.19.2](service/iam/CHANGELOG.md#v1192-2023-02-03) - * **Dependency Update**: Upgrade smithy to 1.27.2 and correct empty query list serialization. -* `github.com/aws/aws-sdk-go-v2/service/neptune`: [v1.19.2](service/neptune/CHANGELOG.md#v1192-2023-02-03) - * **Dependency Update**: Upgrade smithy to 1.27.2 and correct empty query list serialization. -* `github.com/aws/aws-sdk-go-v2/service/proton`: [v1.20.0](service/proton/CHANGELOG.md#v1200-2023-02-03) - * **Feature**: Add new GetResourcesSummary API -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.40.2](service/rds/CHANGELOG.md#v1402-2023-02-03) - * **Dependency Update**: Upgrade smithy to 1.27.2 and correct empty query list serialization. -* `github.com/aws/aws-sdk-go-v2/service/redshift`: [v1.27.2](service/redshift/CHANGELOG.md#v1272-2023-02-03) - * **Documentation**: Corrects descriptions of the parameters for the API operations RestoreFromClusterSnapshot, RestoreTableFromClusterSnapshot, and CreateCluster. - * **Dependency Update**: Upgrade smithy to 1.27.2 and correct empty query list serialization. -* `github.com/aws/aws-sdk-go-v2/service/ses`: [v1.15.1](service/ses/CHANGELOG.md#v1151-2023-02-03) - * **Dependency Update**: Upgrade smithy to 1.27.2 and correct empty query list serialization. -* `github.com/aws/aws-sdk-go-v2/service/sns`: [v1.20.1](service/sns/CHANGELOG.md#v1201-2023-02-03) - * **Dependency Update**: Upgrade smithy to 1.27.2 and correct empty query list serialization. -* `github.com/aws/aws-sdk-go-v2/service/sqs`: [v1.20.2](service/sqs/CHANGELOG.md#v1202-2023-02-03) - * **Dependency Update**: Upgrade smithy to 1.27.2 and correct empty query list serialization. -* `github.com/aws/aws-sdk-go-v2/service/sts`: [v1.18.3](service/sts/CHANGELOG.md#v1183-2023-02-03) - * **Dependency Update**: Upgrade smithy to 1.27.2 and correct empty query list serialization. - -# Release (2023-02-02) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/appconfig`: [v1.16.0](service/appconfig/CHANGELOG.md#v1160-2023-02-02) - * **Feature**: AWS AppConfig introduces KMS customer-managed key (CMK) encryption of configuration data, along with AWS Secrets Manager as a new configuration data source. S3 objects using SSE-KMS encryption and SSM Parameter Store SecureStrings are also now supported. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.84.0](service/ec2/CHANGELOG.md#v1840-2023-02-02) - * **Feature**: Documentation updates for EC2. -* `github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2`: [v1.19.2](service/elasticloadbalancingv2/CHANGELOG.md#v1192-2023-02-02) - * **Documentation**: The GWLB Flex Health Check project updates the default values of healthy-threshold-count from 3 to 5 and unhealthy-threshold-count from 3 to 2 -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.31.0](service/quicksight/CHANGELOG.md#v1310-2023-02-02) - * **Feature**: QuickSight support for Radar Chart and Dashboard Publish Options - -# Release (2023-02-01) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/devopsguru`: [v1.22.0](service/devopsguru/CHANGELOG.md#v1220-2023-02-01) - * **Feature**: This release adds filter support ListAnomalyForInsight API. -* `github.com/aws/aws-sdk-go-v2/service/forecast`: [v1.25.0](service/forecast/CHANGELOG.md#v1250-2023-02-01) - * **Feature**: This release will enable customer select INCREMENTAL as ImportModel in Forecast's CreateDatasetImportJob API. Verified latest SDK containing required attribute, following https://w.amazon.com/bin/view/AWS-Seer/Launch/Trebuchet/ -* `github.com/aws/aws-sdk-go-v2/service/iam`: [v1.19.1](service/iam/CHANGELOG.md#v1191-2023-02-01) - * **Documentation**: Documentation updates for AWS Identity and Access Management (IAM). -* `github.com/aws/aws-sdk-go-v2/service/mediatailor`: [v1.22.0](service/mediatailor/CHANGELOG.md#v1220-2023-02-01) - * **Feature**: The AWS Elemental MediaTailor SDK for Channel Assembly has added support for program updates, and the ability to clip the end of VOD sources in programs. -* `github.com/aws/aws-sdk-go-v2/service/sns`: [v1.20.0](service/sns/CHANGELOG.md#v1200-2023-02-01) - * **Feature**: Additional attributes added for set-topic-attributes. - -# Release (2023-01-31) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/appsync`: [v1.19.0](service/appsync/CHANGELOG.md#v1190-2023-01-31) - * **Feature**: This release introduces the feature to support EventBridge as AppSync data source. -* `github.com/aws/aws-sdk-go-v2/service/cloudtrail`: [v1.23.0](service/cloudtrail/CHANGELOG.md#v1230-2023-01-31) - * **Feature**: Add new "Channel" APIs to enable users to manage channels used for CloudTrail Lake integrations, and "Resource Policy" APIs to enable users to manage the resource-based permissions policy attached to a channel. -* `github.com/aws/aws-sdk-go-v2/service/cloudtraildata`: [v1.0.0](service/cloudtraildata/CHANGELOG.md#v100-2023-01-31) - * **Release**: New AWS service client module - * **Feature**: Add CloudTrail Data Service to enable users to ingest activity events from non-AWS sources into CloudTrail Lake. -* `github.com/aws/aws-sdk-go-v2/service/codeartifact`: [v1.16.0](service/codeartifact/CHANGELOG.md#v1160-2023-01-31) - * **Feature**: This release introduces a new DeletePackage API, which enables deletion of a package and all of its versions from a repository. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.83.0](service/ec2/CHANGELOG.md#v1830-2023-01-31) - * **Feature**: This launch allows customers to associate up to 8 IP addresses to their NAT Gateways to increase the limit on concurrent connections to a single destination by eight times from 55K to 440K. -* `github.com/aws/aws-sdk-go-v2/service/groundstation`: [v1.17.0](service/groundstation/CHANGELOG.md#v1170-2023-01-31) - * **Feature**: DigIF Expansion changes to the Customer APIs. -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.34.0](service/iot/CHANGELOG.md#v1340-2023-01-31) - * **Feature**: Added support for IoT Rules Engine Cloudwatch Logs action batch mode. -* `github.com/aws/aws-sdk-go-v2/service/opensearch`: [v1.14.0](service/opensearch/CHANGELOG.md#v1140-2023-01-31) - * **Feature**: Amazon OpenSearch Service adds the option for a VPC endpoint connection between two domains when the local domain uses OpenSearch version 1.3 or 2.3. You can now use remote reindex to copy indices from one VPC domain to another without a reverse proxy. -* `github.com/aws/aws-sdk-go-v2/service/polly`: [v1.24.0](service/polly/CHANGELOG.md#v1240-2023-01-31) - * **Feature**: Amazon Polly adds two new neural American English voices - Ruth, Stephen -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.67.0](service/sagemaker/CHANGELOG.md#v1670-2023-01-31) - * **Feature**: Amazon SageMaker Automatic Model Tuning now supports more completion criteria for Hyperparameter Optimization. -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.28.0](service/securityhub/CHANGELOG.md#v1280-2023-01-31) - * **Feature**: New fields have been added to the AWS Security Finding Format. Compliance.SecurityControlId is a unique identifier for a security control across standards. Compliance.AssociatedStandards contains all enabled standards in which a security control is enabled. - -# Release (2023-01-30) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudformation`: [v1.26.0](service/cloudformation/CHANGELOG.md#v1260-2023-01-30) - * **Feature**: This feature provides a method of obtaining which regions a stackset has stack instances deployed in. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.82.0](service/ec2/CHANGELOG.md#v1820-2023-01-30) - * **Feature**: We add Prefix Lists as a new route destination option for LocalGatewayRoutes. This will allow customers to create routes to Prefix Lists. Prefix List routes will allow customers to group individual CIDR routes with the same target into a single route. - -# Release (2023-01-27) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/appstream`: [v1.20.0](service/appstream/CHANGELOG.md#v1200-2023-01-27) - * **Feature**: Fixing the issue where Appstream waiters hang for fleet_started and fleet_stopped. -* `github.com/aws/aws-sdk-go-v2/service/mediatailor`: [v1.21.0](service/mediatailor/CHANGELOG.md#v1210-2023-01-27) - * **Feature**: This release introduces the As Run logging type, along with API and documentation updates. -* `github.com/aws/aws-sdk-go-v2/service/outposts`: [v1.26.0](service/outposts/CHANGELOG.md#v1260-2023-01-27) - * **Feature**: Adding support for payment term in GetOrder, CreateOrder responses. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.66.0](service/sagemaker/CHANGELOG.md#v1660-2023-01-27) - * **Feature**: This release supports running SageMaker Training jobs with container images that are in a private Docker registry. -* `github.com/aws/aws-sdk-go-v2/service/sagemakerruntime`: [v1.18.0](service/sagemakerruntime/CHANGELOG.md#v1180-2023-01-27) - * **Feature**: Amazon SageMaker Runtime which supports InvokeEndpointAsync asynchronously can now invoke endpoints with custom timeout values. Asynchronous invocations support longer processing times. - -# Release (2023-01-26) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/eventbridge`: [v1.18.0](service/eventbridge/CHANGELOG.md#v1180-2023-01-26) - * **Feature**: Minor comments for Redshift Serverless workgroup target support. - -# Release (2023-01-25) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.81.0](service/ec2/CHANGELOG.md#v1810-2023-01-25) - * **Feature**: This release adds new functionality that allows customers to provision IPv6 CIDR blocks through Amazon VPC IP Address Manager (IPAM) as well as allowing customers to utilize IPAM Resource Discovery APIs. -* `github.com/aws/aws-sdk-go-v2/service/m2`: [v1.4.0](service/m2/CHANGELOG.md#v140-2023-01-25) - * **Feature**: Add returnCode, batchJobIdentifier in GetBatchJobExecution response, for user to view the batch job execution result & unique identifier from engine. Also removed unused headers from REST APIs -* `github.com/aws/aws-sdk-go-v2/service/polly`: [v1.23.0](service/polly/CHANGELOG.md#v1230-2023-01-25) - * **Feature**: Add 5 new neural voices - Sergio (es-ES), Andres (es-MX), Remi (fr-FR), Adriano (it-IT) and Thiago (pt-BR). -* `github.com/aws/aws-sdk-go-v2/service/redshiftserverless`: [v1.4.1](service/redshiftserverless/CHANGELOG.md#v141-2023-01-25) - * **Documentation**: Added query monitoring rules as possible parameters for create and update workgroup operations. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.65.0](service/sagemaker/CHANGELOG.md#v1650-2023-01-25) - * **Feature**: SageMaker Inference Recommender now decouples from Model Registry and could accept Model Name to invoke inference recommendations job; Inference Recommender now provides CPU/Memory Utilization metrics data in recommendation output. -* `github.com/aws/aws-sdk-go-v2/service/sts`: [v1.18.2](service/sts/CHANGELOG.md#v1182-2023-01-25) - * **Documentation**: Doc only change to update wording in a key topic - -# Release (2023-01-24) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/route53`: [v1.27.0](service/route53/CHANGELOG.md#v1270-2023-01-24) - * **Feature**: Amazon Route 53 now supports the Asia Pacific (Melbourne) Region (ap-southeast-4) for latency records, geoproximity records, and private DNS for Amazon VPCs in that region. -* `github.com/aws/aws-sdk-go-v2/service/ssmsap`: [v1.2.0](service/ssmsap/CHANGELOG.md#v120-2023-01-24) - * **Feature**: This release provides updates to documentation and support for listing operations performed by AWS Systems Manager for SAP. - -# Release (2023-01-23) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.29.0](service/lambda/CHANGELOG.md#v1290-2023-01-23) - * **Feature**: Release Lambda RuntimeManagementConfig, enabling customers to better manage runtime updates to their Lambda functions. This release adds two new APIs, GetRuntimeManagementConfig and PutRuntimeManagementConfig, as well as support on existing Create/Get/Update function APIs. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.64.0](service/sagemaker/CHANGELOG.md#v1640-2023-01-23) - * **Feature**: Amazon SageMaker Inference now supports P4de instance types. - -# Release (2023-01-20) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.80.0](service/ec2/CHANGELOG.md#v1800-2023-01-20) - * **Feature**: C6in, M6in, M6idn, R6in and R6idn instances are powered by 3rd Generation Intel Xeon Scalable processors (code named Ice Lake) with an all-core turbo frequency of 3.5 GHz. -* `github.com/aws/aws-sdk-go-v2/service/ivs`: [v1.20.0](service/ivs/CHANGELOG.md#v1200-2023-01-20) - * **Feature**: API and Doc update. Update to arns field in BatchGetStreamKey. Also updates to operations and structures. -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.30.0](service/quicksight/CHANGELOG.md#v1300-2023-01-20) - * **Feature**: This release adds support for data bars in QuickSight table and increases pivot table field well limit. - -# Release (2023-01-19) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/appflow`: [v1.24.0](service/appflow/CHANGELOG.md#v1240-2023-01-19) - * **Feature**: Adding support for Salesforce Pardot connector in Amazon AppFlow. -* `github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs`: [v1.20.0](service/cloudwatchlogs/CHANGELOG.md#v1200-2023-01-19) - * **Feature**: Bug fix - Removed the regex pattern validation from CoralModel to avoid potential security issue. -* `github.com/aws/aws-sdk-go-v2/service/codeartifact`: [v1.15.0](service/codeartifact/CHANGELOG.md#v1150-2023-01-19) - * **Feature**: Documentation updates for CodeArtifact -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.45.0](service/connect/CHANGELOG.md#v1450-2023-01-19) - * **Feature**: Amazon Connect Chat introduces Persistent Chat, allowing customers to resume previous conversations with context and transcripts carried over from previous chats, eliminating the need to repeat themselves and allowing agents to provide personalized service with access to entire conversation history. -* `github.com/aws/aws-sdk-go-v2/service/connectparticipant`: [v1.15.0](service/connectparticipant/CHANGELOG.md#v1150-2023-01-19) - * **Feature**: This release updates Amazon Connect Participant's GetTranscript api to provide transcripts of past chats on a persistent chat session. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.79.0](service/ec2/CHANGELOG.md#v1790-2023-01-19) - * **Feature**: Adds SSM Parameter Resource Aliasing support to EC2 Launch Templates. Launch Templates can now store parameter aliases in place of AMI Resource IDs. CreateLaunchTemplateVersion and DescribeLaunchTemplateVersions now support a convenience flag, ResolveAlias, to return the resolved parameter value. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.40.0](service/glue/CHANGELOG.md#v1400-2023-01-19) - * **Feature**: Release Glue Studio Hudi Data Lake Format for SDK/CLI -* `github.com/aws/aws-sdk-go-v2/service/groundstation`: [v1.16.0](service/groundstation/CHANGELOG.md#v1160-2023-01-19) - * **Feature**: Add configurable prepass and postpass times for DataflowEndpointGroup. Add Waiter to allow customers to wait for a contact that was reserved through ReserveContact -* `github.com/aws/aws-sdk-go-v2/service/medialive`: [v1.29.0](service/medialive/CHANGELOG.md#v1290-2023-01-19) - * **Feature**: AWS Elemental MediaLive adds support for SCTE 35 preRollMilliSeconds. -* `github.com/aws/aws-sdk-go-v2/service/opensearch`: [v1.13.0](service/opensearch/CHANGELOG.md#v1130-2023-01-19) - * **Feature**: This release adds the enhanced dry run option, that checks for validation errors that might occur when deploying configuration changes and provides a summary of these errors, if any. The feature will also indicate whether a blue/green deployment will be required to apply a change. -* `github.com/aws/aws-sdk-go-v2/service/panorama`: [v1.11.0](service/panorama/CHANGELOG.md#v1110-2023-01-19) - * **Feature**: Added AllowMajorVersionUpdate option to OTAJobConfig to make appliance software major version updates opt-in. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.63.0](service/sagemaker/CHANGELOG.md#v1630-2023-01-19) - * **Feature**: HyperParameterTuningJobs now allow passing environment variables into the corresponding TrainingJobs - -# Release (2023-01-18) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudwatch`: [v1.25.0](service/cloudwatch/CHANGELOG.md#v1250-2023-01-18) - * **Feature**: Enable cross-account streams in CloudWatch Metric Streams via Observability Access Manager. -* `github.com/aws/aws-sdk-go-v2/service/efs`: [v1.19.1](service/efs/CHANGELOG.md#v1191-2023-01-18) - * **Documentation**: Documentation updates for EFS access points limit increase -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.24.2](service/wafv2/CHANGELOG.md#v1242-2023-01-18) - * **Documentation**: Improved the visibility of the guidance for updating AWS WAF resources, such as web ACLs and rule groups. - -# Release (2023-01-17) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/billingconductor`: [v1.5.0](service/billingconductor/CHANGELOG.md#v150-2023-01-17) - * **Feature**: This release adds support for SKU Scope for pricing plans. -* `github.com/aws/aws-sdk-go-v2/service/imagebuilder`: [v1.22.0](service/imagebuilder/CHANGELOG.md#v1220-2023-01-17) - * **Feature**: Add support for AWS Marketplace product IDs as input during CreateImageRecipe for the parent-image parameter. Add support for listing third-party components. -* `github.com/aws/aws-sdk-go-v2/service/networkfirewall`: [v1.24.0](service/networkfirewall/CHANGELOG.md#v1240-2023-01-17) - * **Feature**: Network Firewall now allows creation of dual stack endpoints, enabling inspection of IPv6 traffic. - -# Release (2023-01-13) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.44.0](service/connect/CHANGELOG.md#v1440-2023-01-13) - * **Feature**: This release updates the responses of UpdateContactFlowContent, UpdateContactFlowMetadata, UpdateContactFlowName and DeleteContactFlow API with empty responses. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.78.0](service/ec2/CHANGELOG.md#v1780-2023-01-13) - * **Feature**: Documentation updates for EC2. -* `github.com/aws/aws-sdk-go-v2/service/outposts`: [v1.25.0](service/outposts/CHANGELOG.md#v1250-2023-01-13) - * **Feature**: This release adds POWER_30_KVA as an option for PowerDrawKva. PowerDrawKva is part of the RackPhysicalProperties structure in the CreateSite request. -* `github.com/aws/aws-sdk-go-v2/service/resourcegroups`: [v1.14.0](service/resourcegroups/CHANGELOG.md#v1140-2023-01-13) - * **Feature**: AWS Resource Groups customers can now turn on Group Lifecycle Events in their AWS account. When you turn this on, Resource Groups monitors your groups for changes to group state or membership. Those changes are sent to Amazon EventBridge as events that you can respond to using rules you create. - -# Release (2023-01-12) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cleanrooms`: [v1.0.0](service/cleanrooms/CHANGELOG.md#v100-2023-01-12) - * **Release**: New AWS service client module - * **Feature**: Initial release of AWS Clean Rooms -* `github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs`: [v1.19.0](service/cloudwatchlogs/CHANGELOG.md#v1190-2023-01-12) - * **Feature**: Bug fix: logGroupName is now not a required field in GetLogEvents, FilterLogEvents, GetLogGroupFields, and DescribeLogStreams APIs as logGroupIdentifier can be provided instead -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.28.0](service/lambda/CHANGELOG.md#v1280-2023-01-12) - * **Feature**: Add support for MaximumConcurrency parameter for SQS event source. Customers can now limit the maximum concurrent invocations for their SQS Event Source Mapping. -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.30.0](service/mediaconvert/CHANGELOG.md#v1300-2023-01-12) - * **Feature**: The AWS Elemental MediaConvert SDK has added support for compact DASH manifest generation, audio normalization using TruePeak measurements, and the ability to clip the sample range in the color corrector. -* `github.com/aws/aws-sdk-go-v2/service/secretsmanager`: [v1.18.1](service/secretsmanager/CHANGELOG.md#v1181-2023-01-12) - * **Documentation**: Update documentation for new ListSecrets and DescribeSecret parameters - -# Release (2023-01-11) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.38.0](service/kendra/CHANGELOG.md#v1380-2023-01-11) - * **Feature**: This release adds support to new document types - RTF, XML, XSLT, MS_EXCEL, CSV, JSON, MD - -# Release (2023-01-10) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/location`: [v1.21.0](service/location/CHANGELOG.md#v1210-2023-01-10) - * **Feature**: This release adds support for two new route travel models, Bicycle and Motorcycle which can be used with Grab data source. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.40.0](service/rds/CHANGELOG.md#v1400-2023-01-10) - * **Feature**: This release adds support for configuring allocated storage on the CreateDBInstanceReadReplica, RestoreDBInstanceFromDBSnapshot, and RestoreDBInstanceToPointInTime APIs. - -# Release (2023-01-09) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/ecrpublic`: [v1.15.0](service/ecrpublic/CHANGELOG.md#v1150-2023-01-09) - * **Feature**: This release for Amazon ECR Public makes several change to bring the SDK into sync with the API. -* `github.com/aws/aws-sdk-go-v2/service/kendraranking`: [v1.0.0](service/kendraranking/CHANGELOG.md#v100-2023-01-09) - * **Release**: New AWS service client module - * **Feature**: Introducing Amazon Kendra Intelligent Ranking, a new set of Kendra APIs that leverages Kendra semantic ranking capabilities to improve the quality of search results from other search services (i.e. OpenSearch, ElasticSearch, Solr). -* `github.com/aws/aws-sdk-go-v2/service/networkfirewall`: [v1.23.0](service/networkfirewall/CHANGELOG.md#v1230-2023-01-09) - * **Feature**: Network Firewall now supports the Suricata rule action reject, in addition to the actions pass, drop, and alert. -* `github.com/aws/aws-sdk-go-v2/service/workspacesweb`: [v1.9.0](service/workspacesweb/CHANGELOG.md#v190-2023-01-09) - * **Feature**: This release adds support for a new portal authentication type: AWS IAM Identity Center (successor to AWS Single Sign-On). - -# Release (2023-01-06) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/acmpca`: [v1.21.0](service/acmpca/CHANGELOG.md#v1210-2023-01-06) - * **Feature**: Added revocation parameter validation: bucket names must match S3 bucket naming rules and CNAMEs conform to RFC2396 restrictions on the use of special characters in URIs. -* `github.com/aws/aws-sdk-go-v2/service/auditmanager`: [v1.23.0](service/auditmanager/CHANGELOG.md#v1230-2023-01-06) - * **Feature**: This release introduces a new data retention option in your Audit Manager settings. You can now use the DeregistrationPolicy parameter to specify if you want to delete your data when you deregister Audit Manager. - -# Release (2023-01-05) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/accessanalyzer`: [v1.19.0](service/accessanalyzer/CHANGELOG.md#v1190-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/account`: [v1.8.0](service/account/CHANGELOG.md#v180-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/acm`: [v1.17.0](service/acm/CHANGELOG.md#v1170-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/acmpca`: [v1.20.0](service/acmpca/CHANGELOG.md#v1200-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/alexaforbusiness`: [v1.15.0](service/alexaforbusiness/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/amp`: [v1.16.0](service/amp/CHANGELOG.md#v1160-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/amplify`: [v1.13.0](service/amplify/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/amplifybackend`: [v1.14.0](service/amplifybackend/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). - * **Feature**: Updated GetBackendAPIModels response to include ModelIntrospectionSchema json string -* `github.com/aws/aws-sdk-go-v2/service/amplifyuibuilder`: [v1.9.0](service/amplifyuibuilder/CHANGELOG.md#v190-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/apigateway`: [v1.16.0](service/apigateway/CHANGELOG.md#v1160-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/apigatewaymanagementapi`: [v1.11.0](service/apigatewaymanagementapi/CHANGELOG.md#v1110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/apigatewayv2`: [v1.13.0](service/apigatewayv2/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/appconfig`: [v1.15.0](service/appconfig/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/appconfigdata`: [v1.5.0](service/appconfigdata/CHANGELOG.md#v150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/appflow`: [v1.23.0](service/appflow/CHANGELOG.md#v1230-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/appintegrations`: [v1.14.0](service/appintegrations/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/applicationautoscaling`: [v1.17.0](service/applicationautoscaling/CHANGELOG.md#v1170-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/applicationcostprofiler`: [v1.10.0](service/applicationcostprofiler/CHANGELOG.md#v1100-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/applicationdiscoveryservice`: [v1.15.0](service/applicationdiscoveryservice/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/applicationinsights`: [v1.17.0](service/applicationinsights/CHANGELOG.md#v1170-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/appmesh`: [v1.17.0](service/appmesh/CHANGELOG.md#v1170-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/apprunner`: [v1.16.0](service/apprunner/CHANGELOG.md#v1160-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). - * **Feature**: This release adds support of securely referencing secrets and configuration data that are stored in Secrets Manager and SSM Parameter Store by adding them as environment secrets in your App Runner service. -* `github.com/aws/aws-sdk-go-v2/service/appstream`: [v1.19.0](service/appstream/CHANGELOG.md#v1190-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/appsync`: [v1.18.0](service/appsync/CHANGELOG.md#v1180-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/arczonalshift`: [v1.1.0](service/arczonalshift/CHANGELOG.md#v110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/athena`: [v1.22.0](service/athena/CHANGELOG.md#v1220-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/auditmanager`: [v1.22.0](service/auditmanager/CHANGELOG.md#v1220-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/autoscaling`: [v1.26.0](service/autoscaling/CHANGELOG.md#v1260-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/autoscalingplans`: [v1.13.0](service/autoscalingplans/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/backup`: [v1.19.0](service/backup/CHANGELOG.md#v1190-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/backupgateway`: [v1.9.0](service/backupgateway/CHANGELOG.md#v190-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/backupstorage`: [v1.1.0](service/backupstorage/CHANGELOG.md#v110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/batch`: [v1.21.0](service/batch/CHANGELOG.md#v1210-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/billingconductor`: [v1.4.0](service/billingconductor/CHANGELOG.md#v140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/braket`: [v1.17.0](service/braket/CHANGELOG.md#v1170-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/budgets`: [v1.14.0](service/budgets/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/chime`: [v1.22.0](service/chime/CHANGELOG.md#v1220-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/chimesdkidentity`: [v1.10.0](service/chimesdkidentity/CHANGELOG.md#v1100-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmediapipelines`: [v1.2.0](service/chimesdkmediapipelines/CHANGELOG.md#v120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmeetings`: [v1.14.0](service/chimesdkmeetings/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmessaging`: [v1.12.0](service/chimesdkmessaging/CHANGELOG.md#v1120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/chimesdkvoice`: [v1.1.0](service/chimesdkvoice/CHANGELOG.md#v110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/cloud9`: [v1.17.0](service/cloud9/CHANGELOG.md#v1170-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/cloudcontrol`: [v1.11.0](service/cloudcontrol/CHANGELOG.md#v1110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/clouddirectory`: [v1.13.0](service/clouddirectory/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/cloudformation`: [v1.25.0](service/cloudformation/CHANGELOG.md#v1250-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/cloudfront`: [v1.24.0](service/cloudfront/CHANGELOG.md#v1240-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/cloudhsm`: [v1.13.0](service/cloudhsm/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/cloudhsmv2`: [v1.14.0](service/cloudhsmv2/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/cloudsearch`: [v1.14.0](service/cloudsearch/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/cloudsearchdomain`: [v1.12.0](service/cloudsearchdomain/CHANGELOG.md#v1120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/cloudtrail`: [v1.22.0](service/cloudtrail/CHANGELOG.md#v1220-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/cloudwatch`: [v1.24.0](service/cloudwatch/CHANGELOG.md#v1240-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/cloudwatchevents`: [v1.15.0](service/cloudwatchevents/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs`: [v1.18.0](service/cloudwatchlogs/CHANGELOG.md#v1180-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/codeartifact`: [v1.14.0](service/codeartifact/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/codebuild`: [v1.20.0](service/codebuild/CHANGELOG.md#v1200-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/codecatalyst`: [v1.1.0](service/codecatalyst/CHANGELOG.md#v110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/codecommit`: [v1.14.0](service/codecommit/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/codedeploy`: [v1.16.0](service/codedeploy/CHANGELOG.md#v1160-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/codeguruprofiler`: [v1.13.0](service/codeguruprofiler/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/codegurureviewer`: [v1.17.0](service/codegurureviewer/CHANGELOG.md#v1170-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/codepipeline`: [v1.14.0](service/codepipeline/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/codestar`: [v1.13.0](service/codestar/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/codestarconnections`: [v1.14.0](service/codestarconnections/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/codestarnotifications`: [v1.14.0](service/codestarnotifications/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/cognitoidentity`: [v1.15.0](service/cognitoidentity/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider`: [v1.22.0](service/cognitoidentityprovider/CHANGELOG.md#v1220-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/cognitosync`: [v1.12.0](service/cognitosync/CHANGELOG.md#v1120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/comprehend`: [v1.21.0](service/comprehend/CHANGELOG.md#v1210-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/comprehendmedical`: [v1.15.0](service/comprehendmedical/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/computeoptimizer`: [v1.20.0](service/computeoptimizer/CHANGELOG.md#v1200-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/configservice`: [v1.29.0](service/configservice/CHANGELOG.md#v1290-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.43.0](service/connect/CHANGELOG.md#v1430-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). - * **Feature**: Documentation update for a new Initiation Method value in DescribeContact API -* `github.com/aws/aws-sdk-go-v2/service/connectcampaigns`: [v1.2.0](service/connectcampaigns/CHANGELOG.md#v120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/connectcases`: [v1.2.0](service/connectcases/CHANGELOG.md#v120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/connectcontactlens`: [v1.13.0](service/connectcontactlens/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/connectparticipant`: [v1.14.0](service/connectparticipant/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/controltower`: [v1.1.0](service/controltower/CHANGELOG.md#v110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/costandusagereportservice`: [v1.15.0](service/costandusagereportservice/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/costexplorer`: [v1.25.0](service/costexplorer/CHANGELOG.md#v1250-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/customerprofiles`: [v1.22.0](service/customerprofiles/CHANGELOG.md#v1220-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/databasemigrationservice`: [v1.23.0](service/databasemigrationservice/CHANGELOG.md#v1230-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/databrew`: [v1.21.0](service/databrew/CHANGELOG.md#v1210-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/dataexchange`: [v1.18.0](service/dataexchange/CHANGELOG.md#v1180-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/datapipeline`: [v1.14.0](service/datapipeline/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/datasync`: [v1.21.0](service/datasync/CHANGELOG.md#v1210-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/dax`: [v1.12.0](service/dax/CHANGELOG.md#v1120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/detective`: [v1.18.0](service/detective/CHANGELOG.md#v1180-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/devicefarm`: [v1.15.0](service/devicefarm/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/devopsguru`: [v1.21.0](service/devopsguru/CHANGELOG.md#v1210-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/directconnect`: [v1.18.0](service/directconnect/CHANGELOG.md#v1180-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/directoryservice`: [v1.16.0](service/directoryservice/CHANGELOG.md#v1160-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/dlm`: [v1.14.0](service/dlm/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/docdb`: [v1.20.0](service/docdb/CHANGELOG.md#v1200-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/docdbelastic`: [v1.1.0](service/docdbelastic/CHANGELOG.md#v110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/drs`: [v1.10.0](service/drs/CHANGELOG.md#v1100-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/dynamodb`: [v1.18.0](service/dynamodb/CHANGELOG.md#v1180-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/dynamodbstreams`: [v1.14.0](service/dynamodbstreams/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/ebs`: [v1.16.0](service/ebs/CHANGELOG.md#v1160-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/ec2instanceconnect`: [v1.15.0](service/ec2instanceconnect/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/ecr`: [v1.18.0](service/ecr/CHANGELOG.md#v1180-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/ecrpublic`: [v1.14.0](service/ecrpublic/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.23.0](service/ecs/CHANGELOG.md#v1230-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/efs`: [v1.19.0](service/efs/CHANGELOG.md#v1190-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/eks`: [v1.27.0](service/eks/CHANGELOG.md#v1270-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/elasticache`: [v1.26.0](service/elasticache/CHANGELOG.md#v1260-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/elasticbeanstalk`: [v1.15.0](service/elasticbeanstalk/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/elasticinference`: [v1.12.0](service/elasticinference/CHANGELOG.md#v1120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/elasticloadbalancing`: [v1.15.0](service/elasticloadbalancing/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2`: [v1.19.0](service/elasticloadbalancingv2/CHANGELOG.md#v1190-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/elasticsearchservice`: [v1.18.0](service/elasticsearchservice/CHANGELOG.md#v1180-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/elastictranscoder`: [v1.14.0](service/elastictranscoder/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/emr`: [v1.22.0](service/emr/CHANGELOG.md#v1220-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/emrcontainers`: [v1.16.0](service/emrcontainers/CHANGELOG.md#v1160-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/emrserverless`: [v1.5.0](service/emrserverless/CHANGELOG.md#v150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). - * **Feature**: Adds support for customized images. You can now provide runtime images when creating or updating EMR Serverless Applications. -* `github.com/aws/aws-sdk-go-v2/service/eventbridge`: [v1.17.0](service/eventbridge/CHANGELOG.md#v1170-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/evidently`: [v1.10.0](service/evidently/CHANGELOG.md#v1100-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/finspace`: [v1.9.0](service/finspace/CHANGELOG.md#v190-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/finspacedata`: [v1.14.0](service/finspacedata/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/firehose`: [v1.16.0](service/firehose/CHANGELOG.md#v1160-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/fis`: [v1.14.0](service/fis/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/fms`: [v1.22.0](service/fms/CHANGELOG.md#v1220-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/forecast`: [v1.24.0](service/forecast/CHANGELOG.md#v1240-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/forecastquery`: [v1.13.0](service/forecastquery/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/frauddetector`: [v1.21.0](service/frauddetector/CHANGELOG.md#v1210-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/fsx`: [v1.28.0](service/fsx/CHANGELOG.md#v1280-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/gamelift`: [v1.17.0](service/gamelift/CHANGELOG.md#v1170-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/gamesparks`: [v1.2.0](service/gamesparks/CHANGELOG.md#v120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/glacier`: [v1.14.0](service/glacier/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/globalaccelerator`: [v1.16.0](service/globalaccelerator/CHANGELOG.md#v1160-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.39.0](service/glue/CHANGELOG.md#v1390-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/grafana`: [v1.11.0](service/grafana/CHANGELOG.md#v1110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/greengrass`: [v1.15.0](service/greengrass/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/greengrassv2`: [v1.21.0](service/greengrassv2/CHANGELOG.md#v1210-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/groundstation`: [v1.15.0](service/groundstation/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/guardduty`: [v1.17.0](service/guardduty/CHANGELOG.md#v1170-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/health`: [v1.16.0](service/health/CHANGELOG.md#v1160-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/healthlake`: [v1.15.0](service/healthlake/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/honeycode`: [v1.13.0](service/honeycode/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/iam`: [v1.19.0](service/iam/CHANGELOG.md#v1190-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/identitystore`: [v1.16.0](service/identitystore/CHANGELOG.md#v1160-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/imagebuilder`: [v1.21.0](service/imagebuilder/CHANGELOG.md#v1210-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/inspector`: [v1.13.0](service/inspector/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/inspector2`: [v1.11.0](service/inspector2/CHANGELOG.md#v1110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.33.0](service/iot/CHANGELOG.md#v1330-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/iot1clickdevicesservice`: [v1.11.0](service/iot1clickdevicesservice/CHANGELOG.md#v1110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/iot1clickprojects`: [v1.12.0](service/iot1clickprojects/CHANGELOG.md#v1120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/iotanalytics`: [v1.14.0](service/iotanalytics/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/iotdataplane`: [v1.14.0](service/iotdataplane/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/iotdeviceadvisor`: [v1.17.0](service/iotdeviceadvisor/CHANGELOG.md#v1170-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/iotevents`: [v1.15.0](service/iotevents/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/ioteventsdata`: [v1.13.0](service/ioteventsdata/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/iotfleethub`: [v1.13.0](service/iotfleethub/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/iotfleetwise`: [v1.3.0](service/iotfleetwise/CHANGELOG.md#v130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/iotjobsdataplane`: [v1.12.0](service/iotjobsdataplane/CHANGELOG.md#v1120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/iotroborunner`: [v1.1.0](service/iotroborunner/CHANGELOG.md#v110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/iotsecuretunneling`: [v1.15.0](service/iotsecuretunneling/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/iotsitewise`: [v1.27.0](service/iotsitewise/CHANGELOG.md#v1270-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/iotthingsgraph`: [v1.14.0](service/iotthingsgraph/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/iottwinmaker`: [v1.10.0](service/iottwinmaker/CHANGELOG.md#v1100-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/iotwireless`: [v1.24.0](service/iotwireless/CHANGELOG.md#v1240-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/ivs`: [v1.19.0](service/ivs/CHANGELOG.md#v1190-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/ivschat`: [v1.3.0](service/ivschat/CHANGELOG.md#v130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/kafka`: [v1.19.0](service/kafka/CHANGELOG.md#v1190-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/kafkaconnect`: [v1.9.0](service/kafkaconnect/CHANGELOG.md#v190-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.37.0](service/kendra/CHANGELOG.md#v1370-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/keyspaces`: [v1.1.0](service/keyspaces/CHANGELOG.md#v110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/kinesis`: [v1.17.0](service/kinesis/CHANGELOG.md#v1170-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/kinesisanalytics`: [v1.14.0](service/kinesisanalytics/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/kinesisanalyticsv2`: [v1.16.0](service/kinesisanalyticsv2/CHANGELOG.md#v1160-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/kinesisvideo`: [v1.15.0](service/kinesisvideo/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/kinesisvideoarchivedmedia`: [v1.14.0](service/kinesisvideoarchivedmedia/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/kinesisvideomedia`: [v1.11.0](service/kinesisvideomedia/CHANGELOG.md#v1110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/kinesisvideosignaling`: [v1.11.0](service/kinesisvideosignaling/CHANGELOG.md#v1110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/kinesisvideowebrtcstorage`: [v1.2.0](service/kinesisvideowebrtcstorage/CHANGELOG.md#v120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/kms`: [v1.20.0](service/kms/CHANGELOG.md#v1200-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/lakeformation`: [v1.19.0](service/lakeformation/CHANGELOG.md#v1190-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.27.0](service/lambda/CHANGELOG.md#v1270-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/lexmodelbuildingservice`: [v1.17.0](service/lexmodelbuildingservice/CHANGELOG.md#v1170-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/lexmodelsv2`: [v1.27.0](service/lexmodelsv2/CHANGELOG.md#v1270-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/lexruntimeservice`: [v1.13.0](service/lexruntimeservice/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/lexruntimev2`: [v1.16.0](service/lexruntimev2/CHANGELOG.md#v1160-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/licensemanager`: [v1.17.0](service/licensemanager/CHANGELOG.md#v1170-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/licensemanagerlinuxsubscriptions`: [v1.1.0](service/licensemanagerlinuxsubscriptions/CHANGELOG.md#v110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/licensemanagerusersubscriptions`: [v1.2.0](service/licensemanagerusersubscriptions/CHANGELOG.md#v120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/lightsail`: [v1.25.0](service/lightsail/CHANGELOG.md#v1250-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). - * **Documentation**: Documentation updates for Amazon Lightsail. -* `github.com/aws/aws-sdk-go-v2/service/location`: [v1.20.0](service/location/CHANGELOG.md#v1200-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/lookoutequipment`: [v1.17.0](service/lookoutequipment/CHANGELOG.md#v1170-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/lookoutmetrics`: [v1.19.0](service/lookoutmetrics/CHANGELOG.md#v1190-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/lookoutvision`: [v1.15.0](service/lookoutvision/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/m2`: [v1.3.0](service/m2/CHANGELOG.md#v130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/machinelearning`: [v1.15.0](service/machinelearning/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/macie`: [v1.15.0](service/macie/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/macie2`: [v1.26.0](service/macie2/CHANGELOG.md#v1260-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/managedblockchain`: [v1.14.0](service/managedblockchain/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/marketplacecatalog`: [v1.15.0](service/marketplacecatalog/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/marketplacecommerceanalytics`: [v1.12.0](service/marketplacecommerceanalytics/CHANGELOG.md#v1120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/marketplaceentitlementservice`: [v1.12.0](service/marketplaceentitlementservice/CHANGELOG.md#v1120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/marketplacemetering`: [v1.14.0](service/marketplacemetering/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/mediaconnect`: [v1.18.0](service/mediaconnect/CHANGELOG.md#v1180-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.29.0](service/mediaconvert/CHANGELOG.md#v1290-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/medialive`: [v1.28.0](service/medialive/CHANGELOG.md#v1280-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/mediapackage`: [v1.20.0](service/mediapackage/CHANGELOG.md#v1200-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/mediapackagevod`: [v1.21.0](service/mediapackagevod/CHANGELOG.md#v1210-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/mediastore`: [v1.13.0](service/mediastore/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/mediastoredata`: [v1.13.0](service/mediastoredata/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/mediatailor`: [v1.20.0](service/mediatailor/CHANGELOG.md#v1200-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/memorydb`: [v1.12.0](service/memorydb/CHANGELOG.md#v1120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/mgn`: [v1.17.0](service/mgn/CHANGELOG.md#v1170-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/migrationhub`: [v1.13.0](service/migrationhub/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/migrationhubconfig`: [v1.13.0](service/migrationhubconfig/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/migrationhuborchestrator`: [v1.1.0](service/migrationhuborchestrator/CHANGELOG.md#v110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/migrationhubrefactorspaces`: [v1.8.0](service/migrationhubrefactorspaces/CHANGELOG.md#v180-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/migrationhubstrategy`: [v1.7.0](service/migrationhubstrategy/CHANGELOG.md#v170-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/mobile`: [v1.12.0](service/mobile/CHANGELOG.md#v1120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/mq`: [v1.14.0](service/mq/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/mturk`: [v1.14.0](service/mturk/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/mwaa`: [v1.14.0](service/mwaa/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). - * **Documentation**: MWAA supports Apache Airflow version 2.4.3. -* `github.com/aws/aws-sdk-go-v2/service/neptune`: [v1.19.0](service/neptune/CHANGELOG.md#v1190-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/networkfirewall`: [v1.22.0](service/networkfirewall/CHANGELOG.md#v1220-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/networkmanager`: [v1.17.0](service/networkmanager/CHANGELOG.md#v1170-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/nimble`: [v1.16.0](service/nimble/CHANGELOG.md#v1160-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/oam`: [v1.1.0](service/oam/CHANGELOG.md#v110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/omics`: [v1.1.0](service/omics/CHANGELOG.md#v110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/opensearch`: [v1.12.0](service/opensearch/CHANGELOG.md#v1120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/opensearchserverless`: [v1.1.0](service/opensearchserverless/CHANGELOG.md#v110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/opsworks`: [v1.14.0](service/opsworks/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/opsworkscm`: [v1.15.0](service/opsworkscm/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/organizations`: [v1.18.0](service/organizations/CHANGELOG.md#v1180-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/outposts`: [v1.24.0](service/outposts/CHANGELOG.md#v1240-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/panorama`: [v1.10.0](service/panorama/CHANGELOG.md#v1100-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/personalize`: [v1.23.0](service/personalize/CHANGELOG.md#v1230-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/personalizeevents`: [v1.13.0](service/personalizeevents/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/personalizeruntime`: [v1.13.0](service/personalizeruntime/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/pi`: [v1.16.0](service/pi/CHANGELOG.md#v1160-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/pinpoint`: [v1.18.0](service/pinpoint/CHANGELOG.md#v1180-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/pinpointemail`: [v1.12.0](service/pinpointemail/CHANGELOG.md#v1120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/pinpointsmsvoice`: [v1.11.0](service/pinpointsmsvoice/CHANGELOG.md#v1110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/pinpointsmsvoicev2`: [v1.1.0](service/pinpointsmsvoicev2/CHANGELOG.md#v110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/pipes`: [v1.1.0](service/pipes/CHANGELOG.md#v110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/polly`: [v1.22.0](service/polly/CHANGELOG.md#v1220-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/pricing`: [v1.18.0](service/pricing/CHANGELOG.md#v1180-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/privatenetworks`: [v1.1.0](service/privatenetworks/CHANGELOG.md#v110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/proton`: [v1.19.0](service/proton/CHANGELOG.md#v1190-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/qldb`: [v1.15.0](service/qldb/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/qldbsession`: [v1.14.0](service/qldbsession/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.29.0](service/quicksight/CHANGELOG.md#v1290-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/ram`: [v1.17.0](service/ram/CHANGELOG.md#v1170-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/rbin`: [v1.8.0](service/rbin/CHANGELOG.md#v180-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.39.0](service/rds/CHANGELOG.md#v1390-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). - * **Feature**: This release adds support for specifying which certificate authority (CA) to use for a DB instance's server certificate during DB instance creation, as well as other CA enhancements. -* `github.com/aws/aws-sdk-go-v2/service/rdsdata`: [v1.13.0](service/rdsdata/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/redshift`: [v1.27.0](service/redshift/CHANGELOG.md#v1270-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/redshiftdata`: [v1.18.0](service/redshiftdata/CHANGELOG.md#v1180-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/redshiftserverless`: [v1.4.0](service/redshiftserverless/CHANGELOG.md#v140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/rekognition`: [v1.23.0](service/rekognition/CHANGELOG.md#v1230-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/resiliencehub`: [v1.8.0](service/resiliencehub/CHANGELOG.md#v180-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/resourceexplorer2`: [v1.2.0](service/resourceexplorer2/CHANGELOG.md#v120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/resourcegroups`: [v1.13.0](service/resourcegroups/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi`: [v1.14.0](service/resourcegroupstaggingapi/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/robomaker`: [v1.18.0](service/robomaker/CHANGELOG.md#v1180-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/rolesanywhere`: [v1.1.0](service/rolesanywhere/CHANGELOG.md#v110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/route53`: [v1.26.0](service/route53/CHANGELOG.md#v1260-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/route53domains`: [v1.14.0](service/route53domains/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/route53recoverycluster`: [v1.11.0](service/route53recoverycluster/CHANGELOG.md#v1110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/route53recoverycontrolconfig`: [v1.11.0](service/route53recoverycontrolconfig/CHANGELOG.md#v1110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/route53recoveryreadiness`: [v1.9.0](service/route53recoveryreadiness/CHANGELOG.md#v190-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/route53resolver`: [v1.16.0](service/route53resolver/CHANGELOG.md#v1160-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/rum`: [v1.9.0](service/rum/CHANGELOG.md#v190-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.30.0](service/s3/CHANGELOG.md#v1300-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/s3control`: [v1.29.0](service/s3control/CHANGELOG.md#v1290-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/s3outposts`: [v1.14.0](service/s3outposts/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.62.0](service/sagemaker/CHANGELOG.md#v1620-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/sagemakera2iruntime`: [v1.15.0](service/sagemakera2iruntime/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/sagemakeredge`: [v1.13.0](service/sagemakeredge/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/sagemakerfeaturestoreruntime`: [v1.13.0](service/sagemakerfeaturestoreruntime/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/sagemakergeospatial`: [v1.1.0](service/sagemakergeospatial/CHANGELOG.md#v110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/sagemakerruntime`: [v1.17.0](service/sagemakerruntime/CHANGELOG.md#v1170-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/savingsplans`: [v1.12.0](service/savingsplans/CHANGELOG.md#v1120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/scheduler`: [v1.1.0](service/scheduler/CHANGELOG.md#v110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/schemas`: [v1.15.0](service/schemas/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/secretsmanager`: [v1.18.0](service/secretsmanager/CHANGELOG.md#v1180-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.27.0](service/securityhub/CHANGELOG.md#v1270-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/securitylake`: [v1.2.0](service/securitylake/CHANGELOG.md#v120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/serverlessapplicationrepository`: [v1.12.0](service/serverlessapplicationrepository/CHANGELOG.md#v1120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/servicecatalog`: [v1.16.0](service/servicecatalog/CHANGELOG.md#v1160-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/servicecatalogappregistry`: [v1.16.0](service/servicecatalogappregistry/CHANGELOG.md#v1160-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/servicediscovery`: [v1.19.0](service/servicediscovery/CHANGELOG.md#v1190-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/servicequotas`: [v1.14.0](service/servicequotas/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/ses`: [v1.15.0](service/ses/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/sesv2`: [v1.16.0](service/sesv2/CHANGELOG.md#v1160-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/sfn`: [v1.17.0](service/sfn/CHANGELOG.md#v1170-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/shield`: [v1.18.0](service/shield/CHANGELOG.md#v1180-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/signer`: [v1.14.0](service/signer/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/simspaceweaver`: [v1.1.0](service/simspaceweaver/CHANGELOG.md#v110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/sms`: [v1.13.0](service/sms/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/snowball`: [v1.17.0](service/snowball/CHANGELOG.md#v1170-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/snowdevicemanagement`: [v1.9.0](service/snowdevicemanagement/CHANGELOG.md#v190-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/sns`: [v1.19.0](service/sns/CHANGELOG.md#v1190-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/sqs`: [v1.20.0](service/sqs/CHANGELOG.md#v1200-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.35.0](service/ssm/CHANGELOG.md#v1350-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/ssmcontacts`: [v1.14.0](service/ssmcontacts/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/ssmincidents`: [v1.20.0](service/ssmincidents/CHANGELOG.md#v1200-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/ssmsap`: [v1.1.0](service/ssmsap/CHANGELOG.md#v110-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/sso`: [v1.12.0](service/sso/CHANGELOG.md#v1120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/ssoadmin`: [v1.16.0](service/ssoadmin/CHANGELOG.md#v1160-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/ssooidc`: [v1.14.0](service/ssooidc/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/storagegateway`: [v1.18.0](service/storagegateway/CHANGELOG.md#v1180-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/sts`: [v1.18.0](service/sts/CHANGELOG.md#v1180-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/support`: [v1.14.0](service/support/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/supportapp`: [v1.2.0](service/supportapp/CHANGELOG.md#v120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/swf`: [v1.14.0](service/swf/CHANGELOG.md#v1140-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/synthetics`: [v1.17.0](service/synthetics/CHANGELOG.md#v1170-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/textract`: [v1.20.0](service/textract/CHANGELOG.md#v1200-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/timestreamquery`: [v1.15.0](service/timestreamquery/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/timestreamwrite`: [v1.15.0](service/timestreamwrite/CHANGELOG.md#v1150-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/transcribe`: [v1.25.0](service/transcribe/CHANGELOG.md#v1250-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/transcribestreaming`: [v1.9.0](service/transcribestreaming/CHANGELOG.md#v190-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.28.0](service/transfer/CHANGELOG.md#v1280-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/translate`: [v1.17.0](service/translate/CHANGELOG.md#v1170-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/voiceid`: [v1.12.0](service/voiceid/CHANGELOG.md#v1120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/waf`: [v1.12.0](service/waf/CHANGELOG.md#v1120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/wafregional`: [v1.13.0](service/wafregional/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.24.0](service/wafv2/CHANGELOG.md#v1240-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/wellarchitected`: [v1.18.0](service/wellarchitected/CHANGELOG.md#v1180-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/wisdom`: [v1.12.0](service/wisdom/CHANGELOG.md#v1120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/workdocs`: [v1.13.0](service/workdocs/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/worklink`: [v1.13.0](service/worklink/CHANGELOG.md#v1130-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/workmail`: [v1.18.0](service/workmail/CHANGELOG.md#v1180-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/workmailmessageflow`: [v1.12.0](service/workmailmessageflow/CHANGELOG.md#v1120-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/workspaces`: [v1.28.0](service/workspaces/CHANGELOG.md#v1280-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/workspacesweb`: [v1.8.0](service/workspacesweb/CHANGELOG.md#v180-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). -* `github.com/aws/aws-sdk-go-v2/service/xray`: [v1.16.0](service/xray/CHANGELOG.md#v1160-2023-01-05) - * **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). - -# Release (2023-01-04) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/applicationautoscaling`: [v1.16.0](service/applicationautoscaling/CHANGELOG.md#v1160-2023-01-04) - * **Feature**: Customers can now use the existing DescribeScalingActivities API to also see the detailed and machine-readable reasons for Application Auto Scaling not scaling their resources and, if needed, take the necessary corrective actions. -* `github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs`: [v1.17.4](service/cloudwatchlogs/CHANGELOG.md#v1174-2023-01-04) - * **Documentation**: Update to remove sequenceToken as a required field in PutLogEvents calls. -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.34.0](service/ssm/CHANGELOG.md#v1340-2023-01-04) - * **Feature**: Adding support for QuickSetup Document Type in Systems Manager - -# Release (2023-01-03) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/securitylake`: [v1.1.0](service/securitylake/CHANGELOG.md#v110-2023-01-03) - * **Feature**: Allow CreateSubscriber API to take string input that allows setting more descriptive SubscriberDescription field. Make souceTypes field required in model level for UpdateSubscriberRequest as it is required for every API call on the backend. Allow ListSubscribers take any String as nextToken param. - -# Release (2022-12-30) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudfront`: [v1.23.0](service/cloudfront/CHANGELOG.md#v1230-2022-12-30) - * **Feature**: Extend response headers policy to support removing headers from viewer responses -* `github.com/aws/aws-sdk-go-v2/service/iotfleetwise`: [v1.2.1](service/iotfleetwise/CHANGELOG.md#v121-2022-12-30) - * **Documentation**: Update documentation - correct the epoch constant value of default value for expiryTime field in CreateCampaign request. - -# Release (2022-12-29) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/apigateway`: [v1.15.28](service/apigateway/CHANGELOG.md#v11528-2022-12-29) - * **Documentation**: Documentation updates for Amazon API Gateway -* `github.com/aws/aws-sdk-go-v2/service/emr`: [v1.21.0](service/emr/CHANGELOG.md#v1210-2022-12-29) - * **Feature**: Added GetClusterSessionCredentials API to allow Amazon SageMaker Studio to connect to EMR on EC2 clusters with runtime roles and AWS Lake Formation-based access control for Apache Spark, Apache Hive, and Presto queries. -* `github.com/aws/aws-sdk-go-v2/service/secretsmanager`: [v1.17.0](service/secretsmanager/CHANGELOG.md#v1170-2022-12-29) - * **Feature**: Added owning service filter, include planned deletion flag, and next rotation date response parameter in ListSecrets. -* `github.com/aws/aws-sdk-go-v2/service/wisdom`: [v1.11.0](service/wisdom/CHANGELOG.md#v1110-2022-12-29) - * **Feature**: This release extends Wisdom CreateContent and StartContentUpload APIs to support PDF and MicrosoftWord docx document uploading. - -# Release (2022-12-28) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/elasticache`: [v1.25.0](service/elasticache/CHANGELOG.md#v1250-2022-12-28) - * **Feature**: This release allows you to modify the encryption in transit setting, for existing Redis clusters. You can now change the TLS configuration of your Redis clusters without the need to re-build or re-provision the clusters or impact application availability. -* `github.com/aws/aws-sdk-go-v2/service/networkfirewall`: [v1.21.0](service/networkfirewall/CHANGELOG.md#v1210-2022-12-28) - * **Feature**: AWS Network Firewall now provides status messages for firewalls to help you troubleshoot when your endpoint fails. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.38.0](service/rds/CHANGELOG.md#v1380-2022-12-28) - * **Feature**: This release adds support for Custom Engine Version (CEV) on RDS Custom SQL Server. -* `github.com/aws/aws-sdk-go-v2/service/route53recoverycontrolconfig`: [v1.10.0](service/route53recoverycontrolconfig/CHANGELOG.md#v1100-2022-12-28) - * **Feature**: Added support for Python paginators in the route53-recovery-control-config List* APIs. - -# Release (2022-12-27) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/memorydb`: [v1.11.0](service/memorydb/CHANGELOG.md#v1110-2022-12-27) - * **Feature**: This release adds support for MemoryDB Reserved nodes which provides a significant discount compared to on-demand node pricing. Reserved nodes are not physical nodes, but rather a billing discount applied to the use of on-demand nodes in your account. -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.27.0](service/transfer/CHANGELOG.md#v1270-2022-12-27) - * **Feature**: Add additional operations to throw ThrottlingExceptions - -# Release (2022-12-23) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.42.0](service/connect/CHANGELOG.md#v1420-2022-12-23) - * **Feature**: Support for Routing Profile filter, SortCriteria, and grouping by Routing Profiles for GetCurrentMetricData API. Support for RoutingProfiles, UserHierarchyGroups, and Agents as filters, NextStatus and AgentStatusName for GetCurrentUserData. Adds ApproximateTotalCount to both APIs. -* `github.com/aws/aws-sdk-go-v2/service/connectparticipant`: [v1.13.0](service/connectparticipant/CHANGELOG.md#v1130-2022-12-23) - * **Feature**: Amazon Connect Chat introduces the Message Receipts feature. This feature allows agents and customers to receive message delivered and read receipts after they send a chat message. -* `github.com/aws/aws-sdk-go-v2/service/detective`: [v1.17.0](service/detective/CHANGELOG.md#v1170-2022-12-23) - * **Feature**: This release adds a missed AccessDeniedException type to several endpoints. -* `github.com/aws/aws-sdk-go-v2/service/fsx`: [v1.27.0](service/fsx/CHANGELOG.md#v1270-2022-12-23) - * **Feature**: Fix a bug where a recent release might break certain existing SDKs. -* `github.com/aws/aws-sdk-go-v2/service/inspector2`: [v1.10.0](service/inspector2/CHANGELOG.md#v1100-2022-12-23) - * **Feature**: Amazon Inspector adds support for scanning NodeJS 18.x and Go 1.x AWS Lambda function runtimes. - -# Release (2022-12-22) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/computeoptimizer`: [v1.19.0](service/computeoptimizer/CHANGELOG.md#v1190-2022-12-22) - * **Feature**: This release enables AWS Compute Optimizer to analyze and generate optimization recommendations for ecs services running on Fargate. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.41.0](service/connect/CHANGELOG.md#v1410-2022-12-22) - * **Feature**: Amazon Connect Chat introduces the Idle Participant/Autodisconnect feature, which allows users to set timeouts relating to the activity of chat participants, using the new UpdateParticipantRoleConfig API. -* `github.com/aws/aws-sdk-go-v2/service/iotdeviceadvisor`: [v1.16.0](service/iotdeviceadvisor/CHANGELOG.md#v1160-2022-12-22) - * **Feature**: This release adds the following new features: 1) Documentation updates for IoT Device Advisor APIs. 2) Updated required request parameters for IoT Device Advisor APIs. 3) Added new service feature: ability to provide the test endpoint when customer executing the StartSuiteRun API. -* `github.com/aws/aws-sdk-go-v2/service/kinesisvideowebrtcstorage`: [v1.1.0](service/kinesisvideowebrtcstorage/CHANGELOG.md#v110-2022-12-22) - * **Feature**: Amazon Kinesis Video Streams offers capabilities to stream video and audio in real-time via WebRTC to the cloud for storage, playback, and analytical processing. Customers can use our enhanced WebRTC SDK and cloud APIs to enable real-time streaming, as well as media ingestion to the cloud. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.37.0](service/rds/CHANGELOG.md#v1370-2022-12-22) - * **Feature**: Add support for managing master user password in AWS Secrets Manager for the DBInstance and DBCluster. -* `github.com/aws/aws-sdk-go-v2/service/secretsmanager`: [v1.16.11](service/secretsmanager/CHANGELOG.md#v11611-2022-12-22) - * **Documentation**: Documentation updates for Secrets Manager - -# Release (2022-12-21) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/licensemanagerlinuxsubscriptions`: [v1.0.0](service/licensemanagerlinuxsubscriptions/CHANGELOG.md#v100-2022-12-21) - * **Release**: New AWS service client module - * **Feature**: AWS License Manager now offers cross-region, cross-account tracking of commercial Linux subscriptions on AWS. This includes subscriptions purchased as part of EC2 subscription-included AMIs, on the AWS Marketplace, or brought to AWS via Red Hat Cloud Access Program. -* `github.com/aws/aws-sdk-go-v2/service/macie2`: [v1.25.0](service/macie2/CHANGELOG.md#v1250-2022-12-21) - * **Feature**: This release adds support for analyzing Amazon S3 objects that use the S3 Glacier Instant Retrieval (Glacier_IR) storage class. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.61.0](service/sagemaker/CHANGELOG.md#v1610-2022-12-21) - * **Feature**: This release enables adding RStudio Workbench support to an existing Amazon SageMaker Studio domain. It allows setting your RStudio on SageMaker environment configuration parameters and also updating the RStudioConnectUrl and RStudioPackageManagerUrl parameters for existing domains -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.33.4](service/ssm/CHANGELOG.md#v1334-2022-12-21) - * **Documentation**: Doc-only updates for December 2022. -* `github.com/aws/aws-sdk-go-v2/service/support`: [v1.13.22](service/support/CHANGELOG.md#v11322-2022-12-21) - * **Documentation**: Documentation updates for the AWS Support API -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.26.0](service/transfer/CHANGELOG.md#v1260-2022-12-21) - * **Feature**: This release adds support for Decrypt as a workflow step type. - -# Release (2022-12-20) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/batch`: [v1.20.0](service/batch/CHANGELOG.md#v1200-2022-12-20) - * **Feature**: Adds isCancelled and isTerminated to DescribeJobs response. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.77.0](service/ec2/CHANGELOG.md#v1770-2022-12-20) - * **Feature**: Adds support for pagination in the EC2 DescribeImages API. -* `github.com/aws/aws-sdk-go-v2/service/lookoutequipment`: [v1.16.0](service/lookoutequipment/CHANGELOG.md#v1160-2022-12-20) - * **Feature**: This release adds support for listing inference schedulers by status. -* `github.com/aws/aws-sdk-go-v2/service/medialive`: [v1.27.0](service/medialive/CHANGELOG.md#v1270-2022-12-20) - * **Feature**: This release adds support for two new features to AWS Elemental MediaLive. First, you can now burn-in timecodes to your MediaLive outputs. Second, we now now support the ability to decode Dolby E audio when it comes in on an input. -* `github.com/aws/aws-sdk-go-v2/service/nimble`: [v1.15.0](service/nimble/CHANGELOG.md#v1150-2022-12-20) - * **Feature**: Amazon Nimble Studio now supports configuring session storage volumes and persistence, as well as backup and restore sessions through launch profiles. -* `github.com/aws/aws-sdk-go-v2/service/resourceexplorer2`: [v1.1.0](service/resourceexplorer2/CHANGELOG.md#v110-2022-12-20) - * **Feature**: Documentation updates for AWS Resource Explorer. -* `github.com/aws/aws-sdk-go-v2/service/route53domains`: [v1.13.0](service/route53domains/CHANGELOG.md#v1130-2022-12-20) - * **Feature**: Use Route 53 domain APIs to change owner, create/delete DS record, modify IPS tag, resend authorization. New: AssociateDelegationSignerToDomain, DisassociateDelegationSignerFromDomain, PushDomain, ResendOperationAuthorization. Updated: UpdateDomainContact, ListOperations, CheckDomainTransferability. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.60.0](service/sagemaker/CHANGELOG.md#v1600-2022-12-20) - * **Feature**: Amazon SageMaker Autopilot adds support for new objective metrics in CreateAutoMLJob API. -* `github.com/aws/aws-sdk-go-v2/service/transcribe`: [v1.24.0](service/transcribe/CHANGELOG.md#v1240-2022-12-20) - * **Feature**: Enable our batch transcription jobs for Swedish and Vietnamese. - -# Release (2022-12-19) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/athena`: [v1.21.0](service/athena/CHANGELOG.md#v1210-2022-12-19) - * **Feature**: Add missed InvalidRequestException in GetCalculationExecutionCode,StopCalculationExecution APIs. Correct required parameters (Payload and Type) in UpdateNotebook API. Change Notebook size from 15 Mb to 10 Mb. -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.22.0](service/ecs/CHANGELOG.md#v1220-2022-12-19) - * **Feature**: This release adds support for alarm-based rollbacks in ECS, a new feature that allows customers to add automated safeguards for Amazon ECS service rolling updates. -* `github.com/aws/aws-sdk-go-v2/service/kinesisvideo`: [v1.14.0](service/kinesisvideo/CHANGELOG.md#v1140-2022-12-19) - * **Feature**: Amazon Kinesis Video Streams offers capabilities to stream video and audio in real-time via WebRTC to the cloud for storage, playback, and analytical processing. Customers can use our enhanced WebRTC SDK and cloud APIs to enable real-time streaming, as well as media ingestion to the cloud. -* `github.com/aws/aws-sdk-go-v2/service/kinesisvideowebrtcstorage`: [v1.0.0](service/kinesisvideowebrtcstorage/CHANGELOG.md#v100-2022-12-19) - * **Release**: New AWS service client module - * **Feature**: Amazon Kinesis Video Streams offers capabilities to stream video and audio in real-time via WebRTC to the cloud for storage, playback, and analytical processing. Customers can use our enhanced WebRTC SDK and cloud APIs to enable real-time streaming, as well as media ingestion to the cloud. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.36.0](service/rds/CHANGELOG.md#v1360-2022-12-19) - * **Feature**: Add support for --enable-customer-owned-ip to RDS create-db-instance-read-replica API for RDS on Outposts. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.59.0](service/sagemaker/CHANGELOG.md#v1590-2022-12-19) - * **Feature**: AWS Sagemaker - Sagemaker Images now supports Aliases as secondary identifiers for ImageVersions. SageMaker Images now supports additional metadata for ImageVersions for better images management. - -# Release (2022-12-16) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/appflow`: [v1.22.0](service/appflow/CHANGELOG.md#v1220-2022-12-16) - * **Feature**: This release updates the ListConnectorEntities API action so that it returns paginated responses that customers can retrieve with next tokens. -* `github.com/aws/aws-sdk-go-v2/service/cloudfront`: [v1.22.2](service/cloudfront/CHANGELOG.md#v1222-2022-12-16) - * **Documentation**: Updated documentation for CloudFront -* `github.com/aws/aws-sdk-go-v2/service/datasync`: [v1.20.0](service/datasync/CHANGELOG.md#v1200-2022-12-16) - * **Feature**: AWS DataSync now supports the use of tags with task executions. With this new feature, you can apply tags each time you execute a task, giving you greater control and management over your task executions. -* `github.com/aws/aws-sdk-go-v2/service/efs`: [v1.18.3](service/efs/CHANGELOG.md#v1183-2022-12-16) - * **Documentation**: General documentation updates for EFS. -* `github.com/aws/aws-sdk-go-v2/service/guardduty`: [v1.16.6](service/guardduty/CHANGELOG.md#v1166-2022-12-16) - * **Documentation**: This release provides the valid characters for the Description and Name field. -* `github.com/aws/aws-sdk-go-v2/service/iotfleetwise`: [v1.2.0](service/iotfleetwise/CHANGELOG.md#v120-2022-12-16) - * **Feature**: Updated error handling for empty resource names in "UpdateSignalCatalog" and "GetModelManifest" operations. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.58.0](service/sagemaker/CHANGELOG.md#v1580-2022-12-16) - * **Feature**: AWS sagemaker - Features: This release adds support for random seed, it's an integer value used to initialize a pseudo-random number generator. Setting a random seed will allow the hyperparameter tuning search strategies to produce more consistent configurations for the same tuning job. - -# Release (2022-12-15) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2`: v1.17.3 - * **Bug Fix**: Unify logic between shared config and in finding home directory -* `github.com/aws/aws-sdk-go-v2/config`: [v1.18.5](config/CHANGELOG.md#v1185-2022-12-15) - * **Bug Fix**: Unify logic between shared config and in finding home directory -* `github.com/aws/aws-sdk-go-v2/credentials`: [v1.13.5](credentials/CHANGELOG.md#v1135-2022-12-15) - * **Bug Fix**: Unify logic between shared config and in finding home directory -* `github.com/aws/aws-sdk-go-v2/service/backupgateway`: [v1.8.0](service/backupgateway/CHANGELOG.md#v180-2022-12-15) - * **Feature**: This release adds support for VMware vSphere tags, enabling customer to protect VMware virtual machines using tag-based policies for AWS tags mapped from vSphere tags. This release also adds support for customer-accessible gateway-hypervisor interaction log and upload bandwidth rate limit schedule. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.40.0](service/connect/CHANGELOG.md#v1400-2022-12-15) - * **Feature**: Added support for "English - New Zealand" and "English - South African" to be used with Amazon Connect Custom Vocabulary APIs. -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.21.0](service/ecs/CHANGELOG.md#v1210-2022-12-15) - * **Feature**: This release adds support for container port ranges in ECS, a new capability that allows customers to provide container port ranges to simplify use cases where multiple ports are in use in a container. This release updates TaskDefinition mutation APIs and the Task description APIs. -* `github.com/aws/aws-sdk-go-v2/service/eks`: [v1.26.0](service/eks/CHANGELOG.md#v1260-2022-12-15) - * **Feature**: Add support for Windows managed nodes groups. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.38.0](service/glue/CHANGELOG.md#v1380-2022-12-15) - * **Feature**: This release adds support for AWS Glue Crawler with native DeltaLake tables, allowing Crawlers to classify Delta Lake format tables and catalog them for query engines to query against. -* `github.com/aws/aws-sdk-go-v2/service/kinesis`: [v1.16.0](service/kinesis/CHANGELOG.md#v1160-2022-12-15) - * **Feature**: Added StreamARN parameter for Kinesis Data Streams APIs. Added a new opaque pagination token for ListStreams. SDKs will auto-generate Account Endpoint when accessing Kinesis Data Streams. -* `github.com/aws/aws-sdk-go-v2/service/location`: [v1.19.5](service/location/CHANGELOG.md#v1195-2022-12-15) - * **Documentation**: This release adds support for a new style, "VectorOpenDataStandardLight" which can be used with the new data source, "Open Data Maps (Preview)". -* `github.com/aws/aws-sdk-go-v2/service/m2`: [v1.2.0](service/m2/CHANGELOG.md#v120-2022-12-15) - * **Feature**: Adds an optional create-only `KmsKeyId` property to Environment and Application resources. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.57.0](service/sagemaker/CHANGELOG.md#v1570-2022-12-15) - * **Feature**: SageMaker Inference Recommender now allows customers to load tests their models on various instance types using private VPC. -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.26.0](service/securityhub/CHANGELOG.md#v1260-2022-12-15) - * **Feature**: Added new resource details objects to ASFF, including resources for AwsEc2LaunchTemplate, AwsSageMakerNotebookInstance, AwsWafv2WebAcl and AwsWafv2RuleGroup. -* `github.com/aws/aws-sdk-go-v2/service/translate`: [v1.16.0](service/translate/CHANGELOG.md#v1160-2022-12-15) - * **Feature**: Raised the input byte size limit of the Text field in the TranslateText API to 10000 bytes. - -# Release (2022-12-14) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudwatch`: [v1.23.0](service/cloudwatch/CHANGELOG.md#v1230-2022-12-14) - * **Feature**: Adding support for Metrics Insights Alarms -* `github.com/aws/aws-sdk-go-v2/service/costexplorer`: [v1.24.0](service/costexplorer/CHANGELOG.md#v1240-2022-12-14) - * **Feature**: This release supports percentage-based thresholds on Cost Anomaly Detection alert subscriptions. -* `github.com/aws/aws-sdk-go-v2/service/networkmanager`: [v1.16.0](service/networkmanager/CHANGELOG.md#v1160-2022-12-14) - * **Feature**: Appliance Mode support for AWS Cloud WAN. -* `github.com/aws/aws-sdk-go-v2/service/redshiftdata`: [v1.17.0](service/redshiftdata/CHANGELOG.md#v1170-2022-12-14) - * **Feature**: This release adds a new --client-token field to ExecuteStatement and BatchExecuteStatement operations. Customers can now run queries with the additional client token parameter to ensures idempotency. -* `github.com/aws/aws-sdk-go-v2/service/sagemakermetrics`: [v1.0.1](service/sagemakermetrics/CHANGELOG.md#v101-2022-12-14) - * **Documentation**: Update SageMaker Metrics documentation. - -# Release (2022-12-13) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudtrail`: [v1.21.0](service/cloudtrail/CHANGELOG.md#v1210-2022-12-13) - * **Feature**: Merging mainline branch for service model into mainline release branch. There are no new APIs. -* `github.com/aws/aws-sdk-go-v2/service/marketplaceentitlementservice`: [v1.11.21](service/marketplaceentitlementservice/CHANGELOG.md#v11121-2022-12-13) - * **Bug Fix**: Fixing a shape type in the marketplaceentitlementservice client -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.35.0](service/rds/CHANGELOG.md#v1350-2022-12-13) - * **Feature**: This deployment adds ClientPasswordAuthType field to the Auth structure of the DBProxy. - -# Release (2022-12-12) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/customerprofiles`: [v1.21.0](service/customerprofiles/CHANGELOG.md#v1210-2022-12-12) - * **Feature**: This release allows custom strings in PartyType and Gender through 2 new attributes in the CreateProfile and UpdateProfile APIs: PartyTypeString and GenderString. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.76.0](service/ec2/CHANGELOG.md#v1760-2022-12-12) - * **Feature**: This release updates DescribeFpgaImages to show supported instance types of AFIs in its response. -* `github.com/aws/aws-sdk-go-v2/service/kinesisvideo`: [v1.13.0](service/kinesisvideo/CHANGELOG.md#v1130-2022-12-12) - * **Feature**: This release adds support for public preview of Kinesis Video Stream at Edge enabling customers to provide configuration for the Kinesis Video Stream EdgeAgent running on an on-premise IoT device. Customers can now locally record from cameras and stream videos to the cloud on configured schedule. -* `github.com/aws/aws-sdk-go-v2/service/lookoutvision`: [v1.14.13](service/lookoutvision/CHANGELOG.md#v11413-2022-12-12) - * **Documentation**: This documentation update adds kms:GenerateDataKey as a required permission to StartModelPackagingJob. -* `github.com/aws/aws-sdk-go-v2/service/migrationhubrefactorspaces`: [v1.7.0](service/migrationhubrefactorspaces/CHANGELOG.md#v170-2022-12-12) - * **Feature**: This release adds support for Lambda alias service endpoints. Lambda alias ARNs can now be passed into CreateService. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.34.0](service/rds/CHANGELOG.md#v1340-2022-12-12) - * **Feature**: Update the RDS API model to support copying option groups during the CopyDBSnapshot operation -* `github.com/aws/aws-sdk-go-v2/service/rekognition`: [v1.22.0](service/rekognition/CHANGELOG.md#v1220-2022-12-12) - * **Feature**: Adds support for "aliases" and "categories", inclusion and exclusion filters for labels and label categories, and aggregating labels by video segment timestamps for Stored Video Label Detection APIs. -* `github.com/aws/aws-sdk-go-v2/service/sagemakermetrics`: [v1.0.0](service/sagemakermetrics/CHANGELOG.md#v100-2022-12-12) - * **Release**: New AWS service client module - * **Feature**: This release introduces support SageMaker Metrics APIs. -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.23.3](service/wafv2/CHANGELOG.md#v1233-2022-12-12) - * **Documentation**: Documents the naming requirement for logging destinations that you use with web ACLs. - -# Release (2022-12-09) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs`: [v1.17.2](service/cloudwatchlogs/CHANGELOG.md#v1172-2022-12-09) - * **Documentation**: Doc-only update for CloudWatch Logs, for Tagging Permissions clarifications -* `github.com/aws/aws-sdk-go-v2/service/iotfleetwise`: [v1.1.0](service/iotfleetwise/CHANGELOG.md#v110-2022-12-09) - * **Feature**: Deprecated assignedValue property for actuators and attributes. Added a message to invalid nodes and invalid decoder manifest exceptions. -* `github.com/aws/aws-sdk-go-v2/service/medialive`: [v1.26.0](service/medialive/CHANGELOG.md#v1260-2022-12-09) - * **Feature**: Link devices now support buffer size (latency) configuration. A higher latency value means a longer delay in transmitting from the device to MediaLive, but improved resiliency. A lower latency value means a shorter delay, but less resiliency. -* `github.com/aws/aws-sdk-go-v2/service/mediapackagevod`: [v1.20.0](service/mediapackagevod/CHANGELOG.md#v1200-2022-12-09) - * **Feature**: This release provides the approximate number of assets in a packaging group. - -# Release (2022-12-08) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/autoscaling`: [v1.25.0](service/autoscaling/CHANGELOG.md#v1250-2022-12-08) - * **Feature**: Adds support for metric math for target tracking scaling policies, saving you the cost and effort of publishing a custom metric to CloudWatch. Also adds support for VPC Lattice by adding the Attach/Detach/DescribeTrafficSources APIs and a new health check type to the CreateAutoScalingGroup API. -* `github.com/aws/aws-sdk-go-v2/service/iottwinmaker`: [v1.9.0](service/iottwinmaker/CHANGELOG.md#v190-2022-12-08) - * **Feature**: This release adds the following new features: 1) New APIs for managing a continuous sync of assets and asset models from AWS IoT SiteWise. 2) Support user friendly names for component types (ComponentTypeName) and properties (DisplayName). -* `github.com/aws/aws-sdk-go-v2/service/migrationhubstrategy`: [v1.6.0](service/migrationhubstrategy/CHANGELOG.md#v160-2022-12-08) - * **Feature**: This release adds known application filtering, server selection for assessments, support for potential recommendations, and indications for configuration and assessment status. For more information, see the AWS Migration Hub documentation at https://docs.aws.amazon.com/migrationhub/index.html - -# Release (2022-12-07) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudfront`: [v1.22.0](service/cloudfront/CHANGELOG.md#v1220-2022-12-07) - * **Feature**: Introducing UpdateDistributionWithStagingConfig that can be used to promote the staging configuration to the production. -* `github.com/aws/aws-sdk-go-v2/service/costexplorer`: [v1.23.0](service/costexplorer/CHANGELOG.md#v1230-2022-12-07) - * **Feature**: This release adds the LinkedAccountName field to the GetAnomalies API response under RootCause -* `github.com/aws/aws-sdk-go-v2/service/eks`: [v1.25.0](service/eks/CHANGELOG.md#v1250-2022-12-07) - * **Feature**: Adds support for EKS add-ons configurationValues fields and DescribeAddonConfiguration function -* `github.com/aws/aws-sdk-go-v2/service/kms`: [v1.19.2](service/kms/CHANGELOG.md#v1192-2022-12-07) - * **Documentation**: Updated examples and exceptions for External Key Store (XKS). - -# Release (2022-12-06) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/billingconductor`: [v1.3.0](service/billingconductor/CHANGELOG.md#v130-2022-12-06) - * **Feature**: This release adds the Tiering Pricing Rule feature. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.39.0](service/connect/CHANGELOG.md#v1390-2022-12-06) - * **Feature**: This release provides APIs that enable you to programmatically manage rules for Contact Lens conversational analytics and third party applications. For more information, see https://docs.aws.amazon.com/connect/latest/APIReference/rules-api.html -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.33.0](service/rds/CHANGELOG.md#v1330-2022-12-06) - * **Feature**: This release adds the BlueGreenDeploymentNotFoundFault to the AddTagsToResource, ListTagsForResource, and RemoveTagsFromResource operations. -* `github.com/aws/aws-sdk-go-v2/service/sagemakerfeaturestoreruntime`: [v1.12.0](service/sagemakerfeaturestoreruntime/CHANGELOG.md#v1120-2022-12-06) - * **Feature**: For online + offline Feature Groups, added ability to target PutRecord and DeleteRecord actions to only online store, or only offline store. If target store parameter is not specified, actions will apply to both stores. - -# Release (2022-12-05) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/costexplorer`: [v1.22.0](service/costexplorer/CHANGELOG.md#v1220-2022-12-05) - * **Feature**: This release introduces two new APIs that offer a 1-click experience to refresh Savings Plans recommendations. The two APIs are StartSavingsPlansPurchaseRecommendationGeneration and ListSavingsPlansPurchaseRecommendationGeneration. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.75.0](service/ec2/CHANGELOG.md#v1750-2022-12-05) - * **Feature**: Documentation updates for EC2. -* `github.com/aws/aws-sdk-go-v2/service/ivschat`: [v1.2.0](service/ivschat/CHANGELOG.md#v120-2022-12-05) - * **Feature**: Adds PendingVerification error type to messaging APIs to block the resource usage for accounts identified as being fraudulent. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.32.0](service/rds/CHANGELOG.md#v1320-2022-12-05) - * **Feature**: This release adds the InvalidDBInstanceStateFault to the RestoreDBClusterFromSnapshot operation. -* `github.com/aws/aws-sdk-go-v2/service/transcribe`: [v1.23.0](service/transcribe/CHANGELOG.md#v1230-2022-12-05) - * **Feature**: Amazon Transcribe now supports creating custom language models in the following languages: Japanese (ja-JP) and German (de-DE). - -# Release (2022-12-02) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/appsync`: [v1.17.0](service/appsync/CHANGELOG.md#v1170-2022-12-02) - * **Feature**: Fixes the URI for the evaluatecode endpoint to include the /v1 prefix (ie. "/v1/dataplane-evaluatecode"). -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.20.1](service/ecs/CHANGELOG.md#v1201-2022-12-02) - * **Documentation**: Documentation updates for Amazon ECS -* `github.com/aws/aws-sdk-go-v2/service/fms`: [v1.21.0](service/fms/CHANGELOG.md#v1210-2022-12-02) - * **Feature**: AWS Firewall Manager now supports Fortigate Cloud Native Firewall as a Service as a third-party policy type. -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.28.0](service/mediaconvert/CHANGELOG.md#v1280-2022-12-02) - * **Feature**: The AWS Elemental MediaConvert SDK has added support for configurable ID3 eMSG box attributes and the ability to signal them with InbandEventStream tags in DASH and CMAF outputs. -* `github.com/aws/aws-sdk-go-v2/service/medialive`: [v1.25.0](service/medialive/CHANGELOG.md#v1250-2022-12-02) - * **Feature**: Updates to Event Signaling and Management (ESAM) API and documentation. -* `github.com/aws/aws-sdk-go-v2/service/polly`: [v1.21.0](service/polly/CHANGELOG.md#v1210-2022-12-02) - * **Feature**: Add language code for Finnish (fi-FI) -* `github.com/aws/aws-sdk-go-v2/service/proton`: [v1.18.0](service/proton/CHANGELOG.md#v1180-2022-12-02) - * **Feature**: CreateEnvironmentAccountConnection RoleArn input is now optional -* `github.com/aws/aws-sdk-go-v2/service/redshiftserverless`: [v1.3.0](service/redshiftserverless/CHANGELOG.md#v130-2022-12-02) - * **Feature**: Add Table Level Restore operations for Amazon Redshift Serverless. Add multi-port support for Amazon Redshift Serverless endpoints. Add Tagging support to Snapshots and Recovery Points in Amazon Redshift Serverless. -* `github.com/aws/aws-sdk-go-v2/service/sns`: [v1.18.7](service/sns/CHANGELOG.md#v1187-2022-12-02) - * **Documentation**: This release adds the message payload-filtering feature to the SNS Subscribe, SetSubscriptionAttributes, and GetSubscriptionAttributes API actions - -# Release (2022-12-01) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/codecatalyst`: [v1.0.0](service/codecatalyst/CHANGELOG.md#v100-2022-12-01) - * **Release**: New AWS service client module - * **Feature**: This release adds operations that support customers using the AWS Toolkits and Amazon CodeCatalyst, a unified software development service that helps developers develop, deploy, and maintain applications in the cloud. For more information, see the documentation. -* `github.com/aws/aws-sdk-go-v2/service/comprehend`: [v1.20.0](service/comprehend/CHANGELOG.md#v1200-2022-12-01) - * **Feature**: Comprehend now supports semi-structured documents (such as PDF files or image files) as inputs for custom analysis using the synchronous APIs (ClassifyDocument and DetectEntities). -* `github.com/aws/aws-sdk-go-v2/service/gamelift`: [v1.16.0](service/gamelift/CHANGELOG.md#v1160-2022-12-01) - * **Feature**: GameLift introduces a new feature, GameLift Anywhere. GameLift Anywhere allows you to integrate your own compute resources with GameLift. You can also use GameLift Anywhere to iteratively test your game servers without uploading the build to GameLift for every iteration. -* `github.com/aws/aws-sdk-go-v2/service/pipes`: [v1.0.0](service/pipes/CHANGELOG.md#v100-2022-12-01) - * **Release**: New AWS service client module - * **Feature**: AWS introduces new Amazon EventBridge Pipes which allow you to connect sources (SQS, Kinesis, DDB, Kafka, MQ) to Targets (14+ EventBridge Targets) without any code, with filtering, batching, input transformation, and an optional Enrichment stage (Lambda, StepFunctions, ApiGateway, ApiDestinations) -* `github.com/aws/aws-sdk-go-v2/service/sfn`: [v1.16.0](service/sfn/CHANGELOG.md#v1160-2022-12-01) - * **Feature**: This release adds support for the AWS Step Functions Map state in Distributed mode. The changes include a new MapRun resource and several new and modified APIs. - -# Release (2022-11-30) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/accessanalyzer`: [v1.18.0](service/accessanalyzer/CHANGELOG.md#v1180-2022-11-30) - * **Feature**: This release adds support for S3 cross account access points. IAM Access Analyzer will now produce public or cross account findings when it detects bucket delegation to external account access points. -* `github.com/aws/aws-sdk-go-v2/service/athena`: [v1.20.0](service/athena/CHANGELOG.md#v1200-2022-11-30) - * **Feature**: This release includes support for using Apache Spark in Amazon Athena. -* `github.com/aws/aws-sdk-go-v2/service/dataexchange`: [v1.17.0](service/dataexchange/CHANGELOG.md#v1170-2022-11-30) - * **Feature**: This release enables data providers to license direct access to data in their Amazon S3 buckets or AWS Lake Formation data lakes through AWS Data Exchange. Subscribers get read-only access to the data and can use it in downstream AWS services, like Amazon Athena, without creating or managing copies. -* `github.com/aws/aws-sdk-go-v2/service/docdbelastic`: [v1.0.0](service/docdbelastic/CHANGELOG.md#v100-2022-11-30) - * **Release**: New AWS service client module - * **Feature**: Launched Amazon DocumentDB Elastic Clusters. You can now use the SDK to create, list, update and delete Amazon DocumentDB Elastic Cluster resources -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.37.0](service/glue/CHANGELOG.md#v1370-2022-11-30) - * **Feature**: This release adds support for AWS Glue Data Quality, which helps you evaluate and monitor the quality of your data and includes the API for creating, deleting, or updating data quality rulesets, runs and evaluations. -* `github.com/aws/aws-sdk-go-v2/service/s3control`: [v1.28.0](service/s3control/CHANGELOG.md#v1280-2022-11-30) - * **Feature**: Amazon S3 now supports cross-account access points. S3 bucket owners can now allow trusted AWS accounts to create access points associated with their bucket. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.56.0](service/sagemaker/CHANGELOG.md#v1560-2022-11-30) - * **Feature**: Added Models as part of the Search API. Added Model shadow deployments in realtime inference, and shadow testing in managed inference. Added support for shared spaces, geospatial APIs, Model Cards, AutoMLJobStep in pipelines, Git repositories on user profiles and domains, Model sharing in Jumpstart. -* `github.com/aws/aws-sdk-go-v2/service/sagemakergeospatial`: [v1.0.0](service/sagemakergeospatial/CHANGELOG.md#v100-2022-11-30) - * **Release**: New AWS service client module - * **Feature**: This release provides Amazon SageMaker geospatial APIs to build, train, deploy and visualize geospatial models. - -# Release (2022-11-29.2) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.74.0](service/ec2/CHANGELOG.md#v1740-2022-11-292) - * **Feature**: This release adds support for AWS Verified Access and the Hpc6id Amazon EC2 compute optimized instance type, which features 3rd generation Intel Xeon Scalable processors. -* `github.com/aws/aws-sdk-go-v2/service/firehose`: [v1.15.0](service/firehose/CHANGELOG.md#v1150-2022-11-292) - * **Feature**: Allow support for the Serverless offering for Amazon OpenSearch Service as a Kinesis Data Firehose delivery destination. -* `github.com/aws/aws-sdk-go-v2/service/kms`: [v1.19.0](service/kms/CHANGELOG.md#v1190-2022-11-292) - * **Feature**: AWS KMS introduces the External Key Store (XKS), a new feature for customers who want to protect their data with encryption keys stored in an external key management system under their control. -* `github.com/aws/aws-sdk-go-v2/service/omics`: [v1.0.0](service/omics/CHANGELOG.md#v100-2022-11-292) - * **Release**: New AWS service client module - * **Feature**: Amazon Omics is a new, purpose-built service that can be used by healthcare and life science organizations to store, query, and analyze omics data. The insights from that data can be used to accelerate scientific discoveries and improve healthcare. -* `github.com/aws/aws-sdk-go-v2/service/opensearchserverless`: [v1.0.0](service/opensearchserverless/CHANGELOG.md#v100-2022-11-292) - * **Release**: New AWS service client module - * **Feature**: Publish SDK for Amazon OpenSearch Serverless -* `github.com/aws/aws-sdk-go-v2/service/securitylake`: [v1.0.0](service/securitylake/CHANGELOG.md#v100-2022-11-292) - * **Release**: New AWS service client module - * **Feature**: Amazon Security Lake automatically centralizes security data from cloud, on-premises, and custom sources into a purpose-built data lake stored in your account. Security Lake makes it easier to analyze security data, so you can improve the protection of your workloads, applications, and data -* `github.com/aws/aws-sdk-go-v2/service/simspaceweaver`: [v1.0.0](service/simspaceweaver/CHANGELOG.md#v100-2022-11-292) - * **Release**: New AWS service client module - * **Feature**: AWS SimSpace Weaver is a new service that helps customers build spatial simulations at new levels of scale - resulting in virtual worlds with millions of dynamic entities. See the AWS SimSpace Weaver developer guide for more details on how to get started. https://docs.aws.amazon.com/simspaceweaver - -# Release (2022-11-29) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/arczonalshift`: [v1.0.0](service/arczonalshift/CHANGELOG.md#v100-2022-11-29) - * **Release**: New AWS service client module - * **Feature**: Amazon Route 53 Application Recovery Controller Zonal Shift is a new service that makes it easy to shift traffic away from an Availability Zone in a Region. See the developer guide for more information: https://docs.aws.amazon.com/r53recovery/latest/dg/what-is-route53-recovery.html -* `github.com/aws/aws-sdk-go-v2/service/computeoptimizer`: [v1.18.0](service/computeoptimizer/CHANGELOG.md#v1180-2022-11-29) - * **Feature**: Adds support for a new recommendation preference that makes it possible for customers to optimize their EC2 recommendations by utilizing an external metrics ingestion service to provide metrics. -* `github.com/aws/aws-sdk-go-v2/service/configservice`: [v1.28.0](service/configservice/CHANGELOG.md#v1280-2022-11-29) - * **Feature**: With this release, you can use AWS Config to evaluate your resources for compliance with Config rules before they are created or updated. Using Config rules in proactive mode enables you to test and build compliant resource templates or check resource configurations at the time they are provisioned. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.73.0](service/ec2/CHANGELOG.md#v1730-2022-11-29) - * **Feature**: Introduces ENA Express, which uses AWS SRD and dynamic routing to increase throughput and minimize latency, adds support for trust relationships between Reachability Analyzer and AWS Organizations to enable cross-account analysis, and adds support for Infrastructure Performance metric subscriptions. -* `github.com/aws/aws-sdk-go-v2/service/eks`: [v1.24.0](service/eks/CHANGELOG.md#v1240-2022-11-29) - * **Feature**: Adds support for additional EKS add-ons metadata and filtering fields -* `github.com/aws/aws-sdk-go-v2/service/fsx`: [v1.26.0](service/fsx/CHANGELOG.md#v1260-2022-11-29) - * **Feature**: This release adds support for 4GB/s / 160K PIOPS FSx for ONTAP file systems and 10GB/s / 350K PIOPS FSx for OpenZFS file systems (Single_AZ_2). For FSx for ONTAP, this also adds support for DP volumes, snapshot policy, copy tags to backups, and Multi-AZ route table updates. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.36.0](service/glue/CHANGELOG.md#v1360-2022-11-29) - * **Feature**: This release allows the creation of Custom Visual Transforms (Dynamic Transforms) to be created via AWS Glue CLI/SDK. -* `github.com/aws/aws-sdk-go-v2/service/inspector2`: [v1.9.0](service/inspector2/CHANGELOG.md#v190-2022-11-29) - * **Feature**: This release adds support for Inspector to scan AWS Lambda. -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.26.0](service/lambda/CHANGELOG.md#v1260-2022-11-29) - * **Feature**: Adds support for Lambda SnapStart, which helps improve the startup performance of functions. Customers can now manage SnapStart based functions via CreateFunction and UpdateFunctionConfiguration APIs -* `github.com/aws/aws-sdk-go-v2/service/licensemanagerusersubscriptions`: [v1.1.0](service/licensemanagerusersubscriptions/CHANGELOG.md#v110-2022-11-29) - * **Feature**: AWS now offers fully-compliant, Amazon-provided licenses for Microsoft Office Professional Plus 2021 Amazon Machine Images (AMIs) on Amazon EC2. These AMIs are now available on the Amazon EC2 console and on AWS Marketplace to launch instances on-demand without any long-term licensing commitments. -* `github.com/aws/aws-sdk-go-v2/service/macie2`: [v1.24.0](service/macie2/CHANGELOG.md#v1240-2022-11-29) - * **Feature**: Added support for configuring Macie to continually sample objects from S3 buckets and inspect them for sensitive data. Results appear in statistics, findings, and other data that Macie provides. -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.28.0](service/quicksight/CHANGELOG.md#v1280-2022-11-29) - * **Feature**: This release adds new Describe APIs and updates Create and Update APIs to support the data model for Dashboards, Analyses, and Templates. -* `github.com/aws/aws-sdk-go-v2/service/s3control`: [v1.27.0](service/s3control/CHANGELOG.md#v1270-2022-11-29) - * **Feature**: Added two new APIs to support Amazon S3 Multi-Region Access Point failover controls: GetMultiRegionAccessPointRoutes and SubmitMultiRegionAccessPointRoutes. The failover control APIs are supported in the following Regions: us-east-1, us-west-2, eu-west-1, ap-southeast-2, and ap-northeast-1. -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.25.0](service/securityhub/CHANGELOG.md#v1250-2022-11-29) - * **Feature**: Adding StandardsManagedBy field to DescribeStandards API response - -# Release (2022-11-28) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/backup`: [v1.18.0](service/backup/CHANGELOG.md#v1180-2022-11-28) - * **Feature**: AWS Backup introduces support for legal hold and application stack backups. AWS Backup Audit Manager introduces support for cross-Region, cross-account reports. -* `github.com/aws/aws-sdk-go-v2/service/cloudwatch`: [v1.22.0](service/cloudwatch/CHANGELOG.md#v1220-2022-11-28) - * **Feature**: Adds cross-account support to the GetMetricData API. Adds cross-account support to the ListMetrics API through the usage of the IncludeLinkedAccounts flag and the new OwningAccounts field. -* `github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs`: [v1.17.0](service/cloudwatchlogs/CHANGELOG.md#v1170-2022-11-28) - * **Feature**: Updates to support CloudWatch Logs data protection and CloudWatch cross-account observability -* `github.com/aws/aws-sdk-go-v2/service/drs`: [v1.9.0](service/drs/CHANGELOG.md#v190-2022-11-28) - * **Feature**: Non breaking changes to existing APIs, and additional APIs added to support in-AWS failing back using AWS Elastic Disaster Recovery. -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.20.0](service/ecs/CHANGELOG.md#v1200-2022-11-28) - * **Feature**: This release adds support for ECS Service Connect, a new capability that simplifies writing and operating resilient distributed applications. This release updates the TaskDefinition, Cluster, Service mutation APIs with Service connect constructs and also adds a new ListServicesByNamespace API. -* `github.com/aws/aws-sdk-go-v2/service/efs`: [v1.18.0](service/efs/CHANGELOG.md#v1180-2022-11-28) - * **Feature**: This release adds elastic as a new ThroughputMode value for EFS file systems and adds AFTER_1_DAY as a value for TransitionToIARules. -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.32.0](service/iot/CHANGELOG.md#v1320-2022-11-28) - * **Feature**: Job scheduling enables the scheduled rollout of a Job with start and end times and a customizable end behavior when end time is reached. This is available for continuous and snapshot jobs. Added support for MQTT5 properties to AWS IoT TopicRule Republish Action. -* `github.com/aws/aws-sdk-go-v2/service/iotdataplane`: [v1.13.0](service/iotdataplane/CHANGELOG.md#v1130-2022-11-28) - * **Feature**: This release adds support for MQTT5 properties to AWS IoT HTTP Publish API. -* `github.com/aws/aws-sdk-go-v2/service/iotwireless`: [v1.23.0](service/iotwireless/CHANGELOG.md#v1230-2022-11-28) - * **Feature**: This release includes a new feature for customers to calculate the position of their devices by adding three new APIs: UpdateResourcePosition, GetResourcePosition, and GetPositionEstimate. -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.36.0](service/kendra/CHANGELOG.md#v1360-2022-11-28) - * **Feature**: Amazon Kendra now supports preview of table information from HTML tables in the search results. The most relevant cells with their corresponding rows, columns are displayed as a preview in the search result. The most relevant table cell or cells are also highlighted in table preview. -* `github.com/aws/aws-sdk-go-v2/service/mgn`: [v1.16.0](service/mgn/CHANGELOG.md#v1160-2022-11-28) - * **Feature**: This release adds support for Application and Wave management. We also now support custom post-launch actions. -* `github.com/aws/aws-sdk-go-v2/service/oam`: [v1.0.0](service/oam/CHANGELOG.md#v100-2022-11-28) - * **Release**: New AWS service client module - * **Feature**: Amazon CloudWatch Observability Access Manager is a new service that allows configuration of the CloudWatch cross-account observability feature. -* `github.com/aws/aws-sdk-go-v2/service/organizations`: [v1.17.0](service/organizations/CHANGELOG.md#v1170-2022-11-28) - * **Feature**: This release introduces delegated administrator for AWS Organizations, a new feature to help you delegate the management of your Organizations policies, enabling you to govern your AWS organization in a decentralized way. You can now allow member accounts to manage Organizations policies. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.31.0](service/rds/CHANGELOG.md#v1310-2022-11-28) - * **Feature**: This release enables new Aurora and RDS feature called Blue/Green Deployments that makes updates to databases safer, simpler and faster. -* `github.com/aws/aws-sdk-go-v2/service/textract`: [v1.19.0](service/textract/CHANGELOG.md#v1190-2022-11-28) - * **Feature**: This release adds support for classifying and splitting lending documents by type, and extracting information by using the Analyze Lending APIs. This release also includes support for summarized information of the processed lending document package, in addition to per document results. -* `github.com/aws/aws-sdk-go-v2/service/transcribe`: [v1.22.0](service/transcribe/CHANGELOG.md#v1220-2022-11-28) - * **Feature**: This release adds support for 'inputType' for post-call and real-time (streaming) Call Analytics within Amazon Transcribe. -* `github.com/aws/aws-sdk-go-v2/service/transcribestreaming`: [v1.8.0](service/transcribestreaming/CHANGELOG.md#v180-2022-11-28) - * **Feature**: This release adds support for real-time (streaming) and post-call Call Analytics within Amazon Transcribe. - -# Release (2022-11-23) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/grafana`: [v1.10.0](service/grafana/CHANGELOG.md#v1100-2022-11-23) - * **Feature**: This release includes support for configuring a Grafana workspace to connect to a datasource within a VPC as well as new APIs for configuring Grafana settings. -* `github.com/aws/aws-sdk-go-v2/service/rbin`: [v1.7.0](service/rbin/CHANGELOG.md#v170-2022-11-23) - * **Feature**: This release adds support for Rule Lock for Recycle Bin, which allows you to lock retention rules so that they can no longer be modified or deleted. - -# Release (2022-11-22) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/appflow`: [v1.21.0](service/appflow/CHANGELOG.md#v1210-2022-11-22) - * **Feature**: Adding support for Amazon AppFlow to transfer the data to Amazon Redshift databases through Amazon Redshift Data API service. This feature will support the Redshift destination connector on both public and private accessible Amazon Redshift Clusters and Amazon Redshift Serverless. -* `github.com/aws/aws-sdk-go-v2/service/kinesisanalyticsv2`: [v1.15.0](service/kinesisanalyticsv2/CHANGELOG.md#v1150-2022-11-22) - * **Feature**: Support for Apache Flink 1.15 in Kinesis Data Analytics. - -# Release (2022-11-21) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/route53`: [v1.25.0](service/route53/CHANGELOG.md#v1250-2022-11-21) - * **Feature**: Amazon Route 53 now supports the Asia Pacific (Hyderabad) Region (ap-south-2) for latency records, geoproximity records, and private DNS for Amazon VPCs in that region. - -# Release (2022-11-18.2) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/ssmsap`: [v1.0.1](service/ssmsap/CHANGELOG.md#v101-2022-11-182) - * **Bug Fix**: Removes old model file for ssm sap and uses the new model file to regenerate client - -# Release (2022-11-18) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/appflow`: [v1.20.0](service/appflow/CHANGELOG.md#v1200-2022-11-18) - * **Feature**: AppFlow provides a new API called UpdateConnectorRegistration to update a custom connector that customers have previously registered. With this API, customers no longer need to unregister and then register a connector to make an update. -* `github.com/aws/aws-sdk-go-v2/service/auditmanager`: [v1.21.0](service/auditmanager/CHANGELOG.md#v1210-2022-11-18) - * **Feature**: This release introduces a new feature for Audit Manager: Evidence finder. You can now use evidence finder to quickly query your evidence, and add the matching evidence results to an assessment report. -* `github.com/aws/aws-sdk-go-v2/service/chimesdkvoice`: [v1.0.0](service/chimesdkvoice/CHANGELOG.md#v100-2022-11-18) - * **Release**: New AWS service client module - * **Feature**: Amazon Chime Voice Connector, Voice Connector Group and PSTN Audio Service APIs are now available in the Amazon Chime SDK Voice namespace. See https://docs.aws.amazon.com/chime-sdk/latest/dg/sdk-available-regions.html for more details. -* `github.com/aws/aws-sdk-go-v2/service/cloudfront`: [v1.21.0](service/cloudfront/CHANGELOG.md#v1210-2022-11-18) - * **Feature**: CloudFront API support for staging distributions and associated traffic management policies. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.38.0](service/connect/CHANGELOG.md#v1380-2022-11-18) - * **Feature**: Added AllowedAccessControlTags and TagRestrictedResource for Tag Based Access Control on Amazon Connect Webpage -* `github.com/aws/aws-sdk-go-v2/service/dynamodb`: [v1.17.6](service/dynamodb/CHANGELOG.md#v1176-2022-11-18) - * **Documentation**: Updated minor fixes for DynamoDB documentation. -* `github.com/aws/aws-sdk-go-v2/service/dynamodbstreams`: [v1.13.25](service/dynamodbstreams/CHANGELOG.md#v11325-2022-11-18) - * **Documentation**: Updated minor fixes for DynamoDB documentation. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.72.0](service/ec2/CHANGELOG.md#v1720-2022-11-18) - * **Feature**: This release adds support for copying an Amazon Machine Image's tags when copying an AMI. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.35.0](service/glue/CHANGELOG.md#v1350-2022-11-18) - * **Feature**: AWSGlue Crawler - Adding support for Table and Column level Comments with database level datatypes for JDBC based crawler. -* `github.com/aws/aws-sdk-go-v2/service/iotroborunner`: [v1.0.0](service/iotroborunner/CHANGELOG.md#v100-2022-11-18) - * **Release**: New AWS service client module - * **Feature**: AWS IoT RoboRunner is a new service that makes it easy to build applications that help multi-vendor robots work together seamlessly. See the IoT RoboRunner developer guide for more details on getting started. https://docs.aws.amazon.com/iotroborunner/latest/dev/iotroborunner-welcome.html -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.27.0](service/quicksight/CHANGELOG.md#v1270-2022-11-18) - * **Feature**: This release adds the following: 1) Asset management for centralized assets governance 2) QuickSight Q now supports public embedding 3) New Termination protection flag to mitigate accidental deletes 4) Athena data sources now accept a custom IAM role 5) QuickSight supports connectivity to Databricks -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.55.0](service/sagemaker/CHANGELOG.md#v1550-2022-11-18) - * **Feature**: Added DisableProfiler flag as a new field in ProfilerConfig -* `github.com/aws/aws-sdk-go-v2/service/servicecatalog`: [v1.15.0](service/servicecatalog/CHANGELOG.md#v1150-2022-11-18) - * **Feature**: This release 1. adds support for Principal Name Sharing with Service Catalog portfolio sharing. 2. Introduces repo sourced products which are created and managed with existing SC APIs. These products are synced to external repos and auto create new product versions based on changes in the repo. -* `github.com/aws/aws-sdk-go-v2/service/sfn`: [v1.15.0](service/sfn/CHANGELOG.md#v1150-2022-11-18) - * **Feature**: This release adds support for using Step Functions service integrations to invoke any cross-account AWS resource, even if that service doesn't support resource-based policies or cross-account calls. See https://docs.aws.amazon.com/step-functions/latest/dg/concepts-access-cross-acct-resources.html -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.25.0](service/transfer/CHANGELOG.md#v1250-2022-11-18) - * **Feature**: Adds a NONE encryption algorithm type to AS2 connectors, providing support for skipping encryption of the AS2 message body when a HTTPS URL is also specified. - -# Release (2022-11-17) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/amplify`: [v1.12.0](service/amplify/CHANGELOG.md#v1120-2022-11-17) - * **Feature**: Adds a new value (WEB_COMPUTE) to the Platform enum that allows customers to create Amplify Apps with Server-Side Rendering support. -* `github.com/aws/aws-sdk-go-v2/service/appflow`: [v1.19.0](service/appflow/CHANGELOG.md#v1190-2022-11-17) - * **Feature**: AppFlow simplifies the preparation and cataloging of SaaS data into the AWS Glue Data Catalog where your data can be discovered and accessed by AWS analytics and ML services. AppFlow now also supports data field partitioning and file size optimization to improve query performance and reduce cost. -* `github.com/aws/aws-sdk-go-v2/service/appsync`: [v1.16.0](service/appsync/CHANGELOG.md#v1160-2022-11-17) - * **Feature**: This release introduces the APPSYNC_JS runtime, and adds support for JavaScript in AppSync functions and AppSync pipeline resolvers. -* `github.com/aws/aws-sdk-go-v2/service/databasemigrationservice`: [v1.22.0](service/databasemigrationservice/CHANGELOG.md#v1220-2022-11-17) - * **Feature**: Adds support for Internet Protocol Version 6 (IPv6) on DMS Replication Instances -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.71.0](service/ec2/CHANGELOG.md#v1710-2022-11-17) - * **Feature**: This release adds a new optional parameter "privateIpAddress" for the CreateNatGateway API. PrivateIPAddress will allow customers to select a custom Private IPv4 address instead of having it be auto-assigned. -* `github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2`: [v1.18.25](service/elasticloadbalancingv2/CHANGELOG.md#v11825-2022-11-17) - * **Documentation**: Provides new target group attributes to turn on/off cross zone load balancing and configure target group health for Network Load Balancers and Application Load Balancers. Provides improvements to health check configuration for Network Load Balancers. -* `github.com/aws/aws-sdk-go-v2/service/emrserverless`: [v1.4.0](service/emrserverless/CHANGELOG.md#v140-2022-11-17) - * **Feature**: Adds support for AWS Graviton2 based applications. You can now select CPU architecture when creating new applications or updating existing ones. -* `github.com/aws/aws-sdk-go-v2/service/ivschat`: [v1.1.0](service/ivschat/CHANGELOG.md#v110-2022-11-17) - * **Feature**: Adds LoggingConfiguration APIs for IVS Chat - a feature that allows customers to store and record sent messages in a chat room to S3 buckets, CloudWatch logs, or Kinesis firehose. -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.25.0](service/lambda/CHANGELOG.md#v1250-2022-11-17) - * **Feature**: Add Node 18 (nodejs18.x) support to AWS Lambda. -* `github.com/aws/aws-sdk-go-v2/service/personalize`: [v1.22.0](service/personalize/CHANGELOG.md#v1220-2022-11-17) - * **Feature**: This release provides support for creation and use of metric attributions in AWS Personalize -* `github.com/aws/aws-sdk-go-v2/service/polly`: [v1.20.0](service/polly/CHANGELOG.md#v1200-2022-11-17) - * **Feature**: Add two new neural voices - Ola (pl-PL) and Hala (ar-AE). -* `github.com/aws/aws-sdk-go-v2/service/rum`: [v1.8.0](service/rum/CHANGELOG.md#v180-2022-11-17) - * **Feature**: CloudWatch RUM now supports custom events. To use custom events, create an app monitor or update an app monitor with CustomEvent Status as ENABLED. -* `github.com/aws/aws-sdk-go-v2/service/s3control`: [v1.26.0](service/s3control/CHANGELOG.md#v1260-2022-11-17) - * **Feature**: Added 34 new S3 Storage Lens metrics to support additional customer use cases. -* `github.com/aws/aws-sdk-go-v2/service/secretsmanager`: [v1.16.7](service/secretsmanager/CHANGELOG.md#v1167-2022-11-17) - * **Documentation**: Documentation updates for Secrets Manager. -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.24.0](service/securityhub/CHANGELOG.md#v1240-2022-11-17) - * **Feature**: Added SourceLayerArn and SourceLayerHash field for security findings. Updated AwsLambdaFunction Resource detail -* `github.com/aws/aws-sdk-go-v2/service/servicecatalogappregistry`: [v1.15.0](service/servicecatalogappregistry/CHANGELOG.md#v1150-2022-11-17) - * **Feature**: This release adds support for tagged resource associations, which allows you to associate a group of resources with a defined resource tag key and value to the application. -* `github.com/aws/aws-sdk-go-v2/service/sts`: [v1.17.4](service/sts/CHANGELOG.md#v1174-2022-11-17) - * **Documentation**: Documentation updates for AWS Security Token Service. -* `github.com/aws/aws-sdk-go-v2/service/textract`: [v1.18.0](service/textract/CHANGELOG.md#v1180-2022-11-17) - * **Feature**: This release adds support for specifying and extracting information from documents using the Signatures feature within Analyze Document API -* `github.com/aws/aws-sdk-go-v2/service/workspaces`: [v1.27.0](service/workspaces/CHANGELOG.md#v1270-2022-11-17) - * **Feature**: The release introduces CreateStandbyWorkspaces, an API that allows you to create standby WorkSpaces associated with a primary WorkSpace in another Region. DescribeWorkspaces now includes related WorkSpaces properties. DescribeWorkspaceBundles and CreateWorkspaceBundle now return more bundle details. - -# Release (2022-11-16) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/batch`: [v1.19.1](service/batch/CHANGELOG.md#v1191-2022-11-16) - * **Documentation**: Documentation updates related to Batch on EKS -* `github.com/aws/aws-sdk-go-v2/service/billingconductor`: [v1.2.0](service/billingconductor/CHANGELOG.md#v120-2022-11-16) - * **Feature**: This release adds a new feature BillingEntity pricing rule. -* `github.com/aws/aws-sdk-go-v2/service/cloudformation`: [v1.24.0](service/cloudformation/CHANGELOG.md#v1240-2022-11-16) - * **Feature**: Added UnsupportedTarget HandlerErrorCode for use with CFN Resource Hooks -* `github.com/aws/aws-sdk-go-v2/service/comprehendmedical`: [v1.14.0](service/comprehendmedical/CHANGELOG.md#v1140-2022-11-16) - * **Feature**: This release supports new set of entities and traits. It also adds new category (BEHAVIORAL_ENVIRONMENTAL_SOCIAL). -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.37.0](service/connect/CHANGELOG.md#v1370-2022-11-16) - * **Feature**: This release adds a new MonitorContact API for initiating monitoring of ongoing Voice and Chat contacts. -* `github.com/aws/aws-sdk-go-v2/service/eks`: [v1.23.0](service/eks/CHANGELOG.md#v1230-2022-11-16) - * **Feature**: Adds support for customer-provided placement groups for Kubernetes control plane instances when creating local EKS clusters on Outposts -* `github.com/aws/aws-sdk-go-v2/service/elasticache`: [v1.24.0](service/elasticache/CHANGELOG.md#v1240-2022-11-16) - * **Feature**: for Redis now supports AWS Identity and Access Management authentication access to Redis clusters starting with redis-engine version 7.0 -* `github.com/aws/aws-sdk-go-v2/service/iottwinmaker`: [v1.8.0](service/iottwinmaker/CHANGELOG.md#v180-2022-11-16) - * **Feature**: This release adds the following: 1) ExecuteQuery API allows users to query their AWS IoT TwinMaker Knowledge Graph 2) Pricing plan APIs allow users to configure and manage their pricing mode 3) Support for property groups and tabular property values in existing AWS IoT TwinMaker APIs. -* `github.com/aws/aws-sdk-go-v2/service/personalizeevents`: [v1.12.0](service/personalizeevents/CHANGELOG.md#v1120-2022-11-16) - * **Feature**: This release provides support for creation and use of metric attributions in AWS Personalize -* `github.com/aws/aws-sdk-go-v2/service/proton`: [v1.17.0](service/proton/CHANGELOG.md#v1170-2022-11-16) - * **Feature**: Add support for sorting and filtering in ListServiceInstances -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.30.0](service/rds/CHANGELOG.md#v1300-2022-11-16) - * **Feature**: This release adds support for container databases (CDBs) to Amazon RDS Custom for Oracle. A CDB contains one PDB at creation. You can add more PDBs using Oracle SQL. You can also customize your database installation by setting the Oracle base, Oracle home, and the OS user name and group. -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.33.0](service/ssm/CHANGELOG.md#v1330-2022-11-16) - * **Feature**: This release adds support for cross account access in CreateOpsItem, UpdateOpsItem and GetOpsItem. It introduces new APIs to setup resource policies for SSM resources: PutResourcePolicy, GetResourcePolicies and DeleteResourcePolicy. -* `github.com/aws/aws-sdk-go-v2/service/ssmincidents`: [v1.19.0](service/ssmincidents/CHANGELOG.md#v1190-2022-11-16) - * **Feature**: Add support for PagerDuty integrations on ResponsePlan, IncidentRecord, and RelatedItem APIs -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.24.0](service/transfer/CHANGELOG.md#v1240-2022-11-16) - * **Feature**: Allow additional operations to throw ThrottlingException -* `github.com/aws/aws-sdk-go-v2/service/xray`: [v1.15.0](service/xray/CHANGELOG.md#v1150-2022-11-16) - * **Feature**: This release adds new APIs - PutResourcePolicy, DeleteResourcePolicy, ListResourcePolicies for supporting resource based policies for AWS X-Ray. - -# Release (2022-11-15) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.36.0](service/connect/CHANGELOG.md#v1360-2022-11-15) - * **Feature**: This release updates the APIs: UpdateInstanceAttribute, DescribeInstanceAttribute, and ListInstanceAttributes. You can use it to programmatically enable/disable enhanced contact monitoring using attribute type ENHANCED_CONTACT_MONITORING on the specified Amazon Connect instance. -* `github.com/aws/aws-sdk-go-v2/service/greengrassv2`: [v1.20.0](service/greengrassv2/CHANGELOG.md#v1200-2022-11-15) - * **Feature**: Adds new parent target ARN paramater to CreateDeployment, GetDeployment, and ListDeployments APIs for the new subdeployments feature. -* `github.com/aws/aws-sdk-go-v2/service/route53`: [v1.24.0](service/route53/CHANGELOG.md#v1240-2022-11-15) - * **Feature**: Amazon Route 53 now supports the Europe (Spain) Region (eu-south-2) for latency records, geoproximity records, and private DNS for Amazon VPCs in that region. -* `github.com/aws/aws-sdk-go-v2/service/ssmsap`: [v1.0.0](service/ssmsap/CHANGELOG.md#v100-2022-11-15) - * **Release**: New AWS service client module - * **Feature**: AWS Systems Manager for SAP provides simplified operations and management of SAP applications such as SAP HANA. With this release, SAP customers and partners can automate and simplify their SAP system administration tasks such as backup/restore of SAP HANA. -* `github.com/aws/aws-sdk-go-v2/service/workspaces`: [v1.26.0](service/workspaces/CHANGELOG.md#v1260-2022-11-15) - * **Feature**: This release introduces ModifyCertificateBasedAuthProperties, a new API that allows control of certificate-based auth properties associated with a WorkSpaces directory. The DescribeWorkspaceDirectories API will now additionally return certificate-based auth properties in its responses. - -# Release (2022-11-14) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/customerprofiles`: [v1.20.0](service/customerprofiles/CHANGELOG.md#v1200-2022-11-14) - * **Feature**: This release enhances the SearchProfiles API by providing functionality to search for profiles using multiple keys and logical operators. -* `github.com/aws/aws-sdk-go-v2/service/lakeformation`: [v1.18.0](service/lakeformation/CHANGELOG.md#v1180-2022-11-14) - * **Feature**: This release adds a new parameter "Parameters" in the DataLakeSettings. -* `github.com/aws/aws-sdk-go-v2/service/managedblockchain`: [v1.13.3](service/managedblockchain/CHANGELOG.md#v1133-2022-11-14) - * **Documentation**: Updating the API docs data type: NetworkEthereumAttributes, and the operations DeleteNode, and CreateNode to also include the supported Goerli network. -* `github.com/aws/aws-sdk-go-v2/service/proton`: [v1.16.0](service/proton/CHANGELOG.md#v1160-2022-11-14) - * **Feature**: Add support for CodeBuild Provisioning -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.29.0](service/rds/CHANGELOG.md#v1290-2022-11-14) - * **Feature**: This release adds support for restoring an RDS Multi-AZ DB cluster snapshot to a Single-AZ deployment or a Multi-AZ DB instance deployment. -* `github.com/aws/aws-sdk-go-v2/service/workdocs`: [v1.12.0](service/workdocs/CHANGELOG.md#v1120-2022-11-14) - * **Feature**: Added 2 new document related operations, DeleteDocumentVersion and RestoreDocumentVersions. -* `github.com/aws/aws-sdk-go-v2/service/xray`: [v1.14.0](service/xray/CHANGELOG.md#v1140-2022-11-14) - * **Feature**: This release enhances GetServiceGraph API to support new type of edge to represent links between SQS and Lambda in event-driven applications. - -# Release (2022-11-11) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/config`: [v1.18.0](config/CHANGELOG.md#v1180-2022-11-11) - * **Announcement**: When using the SSOTokenProvider, a previous implementation incorrectly compensated for invalid SSOTokenProvider configurations in the shared profile. This has been fixed via PR #1903 and tracked in issue #1846 - * **Feature**: Adds token refresh support (via SSOTokenProvider) when using the SSOCredentialProvider -* `github.com/aws/aws-sdk-go-v2/credentials`: [v1.13.0](credentials/CHANGELOG.md#v1130-2022-11-11) - * **Announcement**: When using the SSOTokenProvider, a previous implementation incorrectly compensated for invalid SSOTokenProvider configurations in the shared profile. This has been fixed via PR #1903 and tracked in issue #1846 - * **Feature**: Adds token refresh support (via SSOTokenProvider) when using the SSOCredentialProvider -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.34.1](service/glue/CHANGELOG.md#v1341-2022-11-11) - * **Documentation**: Added links related to enabling job bookmarks. -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.31.0](service/iot/CHANGELOG.md#v1310-2022-11-11) - * **Feature**: This release add new api listRelatedResourcesForAuditFinding and new member type IssuerCertificates for Iot device device defender Audit. -* `github.com/aws/aws-sdk-go-v2/service/licensemanager`: [v1.16.0](service/licensemanager/CHANGELOG.md#v1160-2022-11-11) - * **Feature**: AWS License Manager now supports onboarded Management Accounts or Delegated Admins to view granted licenses aggregated from all accounts in the organization. -* `github.com/aws/aws-sdk-go-v2/service/marketplacecatalog`: [v1.14.0](service/marketplacecatalog/CHANGELOG.md#v1140-2022-11-11) - * **Feature**: Added three new APIs to support tagging and tag-based authorization: TagResource, UntagResource, and ListTagsForResource. Added optional parameters to the StartChangeSet API to support tagging a resource while making a request to create it. -* `github.com/aws/aws-sdk-go-v2/service/rekognition`: [v1.21.0](service/rekognition/CHANGELOG.md#v1210-2022-11-11) - * **Feature**: Adding support for ImageProperties feature to detect dominant colors and image brightness, sharpness, and contrast, inclusion and exclusion filters for labels and label categories, new fields to the API response, "aliases" and "categories" -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.23.8](service/securityhub/CHANGELOG.md#v1238-2022-11-11) - * **Documentation**: Documentation updates for Security Hub -* `github.com/aws/aws-sdk-go-v2/service/ssmincidents`: [v1.18.0](service/ssmincidents/CHANGELOG.md#v1180-2022-11-11) - * **Feature**: RelatedItems now have an ID field which can be used for referencing them else where. Introducing event references in TimelineEvent API and increasing maximum length of "eventData" to 12K characters. - -# Release (2022-11-10) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/autoscaling`: [v1.24.1](service/autoscaling/CHANGELOG.md#v1241-2022-11-10) - * **Documentation**: This release adds a new price capacity optimized allocation strategy for Spot Instances to help customers optimize provisioning of Spot Instances via EC2 Auto Scaling, EC2 Fleet, and Spot Fleet. It allocates Spot Instances based on both spare capacity availability and Spot Instance price. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.70.0](service/ec2/CHANGELOG.md#v1700-2022-11-10) - * **Feature**: This release adds a new price capacity optimized allocation strategy for Spot Instances to help customers optimize provisioning of Spot Instances via EC2 Auto Scaling, EC2 Fleet, and Spot Fleet. It allocates Spot Instances based on both spare capacity availability and Spot Instance price. -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.19.0](service/ecs/CHANGELOG.md#v1190-2022-11-10) - * **Feature**: This release adds support for task scale-in protection with updateTaskProtection and getTaskProtection APIs. UpdateTaskProtection API can be used to protect a service managed task from being terminated by scale-in events and getTaskProtection API to get the scale-in protection status of a task. -* `github.com/aws/aws-sdk-go-v2/service/elasticsearchservice`: [v1.17.0](service/elasticsearchservice/CHANGELOG.md#v1170-2022-11-10) - * **Feature**: Amazon OpenSearch Service now offers managed VPC endpoints to connect to your Amazon OpenSearch Service VPC-enabled domain in a Virtual Private Cloud (VPC). This feature allows you to privately access OpenSearch Service domain without using public IPs or requiring traffic to traverse the Internet. -* `github.com/aws/aws-sdk-go-v2/service/resourceexplorer2`: [v1.0.1](service/resourceexplorer2/CHANGELOG.md#v101-2022-11-10) - * **Documentation**: Text only updates to some Resource Explorer descriptions. -* `github.com/aws/aws-sdk-go-v2/service/scheduler`: [v1.0.0](service/scheduler/CHANGELOG.md#v100-2022-11-10) - * **Release**: New AWS service client module - * **Feature**: AWS introduces the new Amazon EventBridge Scheduler. EventBridge Scheduler is a serverless scheduler that allows you to create, run, and manage tasks from one central, managed service. - -# Release (2022-11-09) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.35.0](service/connect/CHANGELOG.md#v1350-2022-11-09) - * **Feature**: This release adds new fields SignInUrl, UserArn, and UserId to GetFederationToken response payload. -* `github.com/aws/aws-sdk-go-v2/service/connectcases`: [v1.1.0](service/connectcases/CHANGELOG.md#v110-2022-11-09) - * **Feature**: This release adds the ability to disable templates through the UpdateTemplate API. Disabling templates prevents customers from creating cases using the template. For more information see https://docs.aws.amazon.com/cases/latest/APIReference/Welcome.html -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.69.0](service/ec2/CHANGELOG.md#v1690-2022-11-09) - * **Feature**: Amazon EC2 Trn1 instances, powered by AWS Trainium chips, are purpose built for high-performance deep learning training. u-24tb1.112xlarge and u-18tb1.112xlarge High Memory instances are purpose-built to run large in-memory databases. -* `github.com/aws/aws-sdk-go-v2/service/groundstation`: [v1.14.0](service/groundstation/CHANGELOG.md#v1140-2022-11-09) - * **Feature**: This release adds the preview of customer-provided ephemeris support for AWS Ground Station, allowing space vehicle owners to provide their own position and trajectory information for a satellite. -* `github.com/aws/aws-sdk-go-v2/service/mediapackagevod`: [v1.19.0](service/mediapackagevod/CHANGELOG.md#v1190-2022-11-09) - * **Feature**: This release adds "IncludeIframeOnlyStream" for Dash endpoints. -* `github.com/aws/aws-sdk-go-v2/service/transcribestreaming`: [v1.7.0](service/transcribestreaming/CHANGELOG.md#v170-2022-11-09) - * **Feature**: This will release hi-IN and th-TH - -# Release (2022-11-08) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/acm`: [v1.16.0](service/acm/CHANGELOG.md#v1160-2022-11-08) - * **Feature**: Support added for requesting elliptic curve certificate key algorithm types P-256 (EC_prime256v1) and P-384 (EC_secp384r1). -* `github.com/aws/aws-sdk-go-v2/service/billingconductor`: [v1.1.0](service/billingconductor/CHANGELOG.md#v110-2022-11-08) - * **Feature**: This release adds the Recurring Custom Line Item feature along with a new API ListCustomLineItemVersions. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.68.0](service/ec2/CHANGELOG.md#v1680-2022-11-08) - * **Feature**: This release enables sharing of EC2 Placement Groups across accounts and within AWS Organizations using Resource Access Manager -* `github.com/aws/aws-sdk-go-v2/service/fms`: [v1.20.0](service/fms/CHANGELOG.md#v1200-2022-11-08) - * **Feature**: AWS Firewall Manager now supports importing existing AWS Network Firewall firewalls into Firewall Manager policies. -* `github.com/aws/aws-sdk-go-v2/service/lightsail`: [v1.24.0](service/lightsail/CHANGELOG.md#v1240-2022-11-08) - * **Feature**: This release adds support for Amazon Lightsail to automate the delegation of domains registered through Amazon Route 53 to Lightsail DNS management and to automate record creation for DNS validation of Lightsail SSL/TLS certificates. -* `github.com/aws/aws-sdk-go-v2/service/opensearch`: [v1.11.0](service/opensearch/CHANGELOG.md#v1110-2022-11-08) - * **Feature**: Amazon OpenSearch Service now offers managed VPC endpoints to connect to your Amazon OpenSearch Service VPC-enabled domain in a Virtual Private Cloud (VPC). This feature allows you to privately access OpenSearch Service domain without using public IPs or requiring traffic to traverse the Internet. -* `github.com/aws/aws-sdk-go-v2/service/polly`: [v1.19.0](service/polly/CHANGELOG.md#v1190-2022-11-08) - * **Feature**: Amazon Polly adds new voices: Elin (sv-SE), Ida (nb-NO), Laura (nl-NL) and Suvi (fi-FI). They are available as neural voices only. -* `github.com/aws/aws-sdk-go-v2/service/resourceexplorer2`: [v1.0.0](service/resourceexplorer2/CHANGELOG.md#v100-2022-11-08) - * **Release**: New AWS service client module - * **Feature**: This is the initial SDK release for AWS Resource Explorer. AWS Resource Explorer lets your users search for and discover your AWS resources across the AWS Regions in your account. -* `github.com/aws/aws-sdk-go-v2/service/route53`: [v1.23.0](service/route53/CHANGELOG.md#v1230-2022-11-08) - * **Feature**: Amazon Route 53 now supports the Europe (Zurich) Region (eu-central-2) for latency records, geoproximity records, and private DNS for Amazon VPCs in that region. - -# Release (2022-11-07) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/athena`: [v1.19.0](service/athena/CHANGELOG.md#v1190-2022-11-07) - * **Feature**: Adds support for using Query Result Reuse -* `github.com/aws/aws-sdk-go-v2/service/autoscaling`: [v1.24.0](service/autoscaling/CHANGELOG.md#v1240-2022-11-07) - * **Feature**: This release adds support for two new attributes for attribute-based instance type selection - NetworkBandwidthGbps and AllowedInstanceTypes. -* `github.com/aws/aws-sdk-go-v2/service/cloudtrail`: [v1.20.0](service/cloudtrail/CHANGELOG.md#v1200-2022-11-07) - * **Feature**: This release includes support for configuring a delegated administrator to manage an AWS Organizations organization CloudTrail trails and event data stores, and AWS Key Management Service encryption of CloudTrail Lake event data stores. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.67.0](service/ec2/CHANGELOG.md#v1670-2022-11-07) - * **Feature**: This release adds support for two new attributes for attribute-based instance type selection - NetworkBandwidthGbps and AllowedInstanceTypes. -* `github.com/aws/aws-sdk-go-v2/service/elasticache`: [v1.23.0](service/elasticache/CHANGELOG.md#v1230-2022-11-07) - * **Feature**: Added support for IPv6 and dual stack for Memcached and Redis clusters. Customers can now launch new Redis and Memcached clusters with IPv6 and dual stack networking support. -* `github.com/aws/aws-sdk-go-v2/service/lexmodelsv2`: [v1.26.0](service/lexmodelsv2/CHANGELOG.md#v1260-2022-11-07) - * **Feature**: Amazon Lex now supports new APIs for viewing and editing Custom Vocabulary in bots. -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.27.0](service/mediaconvert/CHANGELOG.md#v1270-2022-11-07) - * **Feature**: The AWS Elemental MediaConvert SDK has added support for setting the SDR reference white point for HDR conversions and conversion of HDR10 to DolbyVision without mastering metadata. -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.32.0](service/ssm/CHANGELOG.md#v1320-2022-11-07) - * **Feature**: This release includes support for applying a CloudWatch alarm to multi account multi region Systems Manager Automation -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.23.1](service/wafv2/CHANGELOG.md#v1231-2022-11-07) - * **Documentation**: The geo match statement now adds labels for country and region. You can match requests at the region level by combining a geo match statement with label match statements. -* `github.com/aws/aws-sdk-go-v2/service/wellarchitected`: [v1.17.0](service/wellarchitected/CHANGELOG.md#v1170-2022-11-07) - * **Feature**: This release adds support for integrations with AWS Trusted Advisor and AWS Service Catalog AppRegistry to improve workload discovery and speed up your workload reviews. -* `github.com/aws/aws-sdk-go-v2/service/workspaces`: [v1.25.0](service/workspaces/CHANGELOG.md#v1250-2022-11-07) - * **Feature**: This release adds protocols attribute to workspaces properties data type. This enables customers to migrate workspaces from PC over IP (PCoIP) to WorkSpaces Streaming Protocol (WSP) using create and modify workspaces public APIs. - -# Release (2022-11-04) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs`: [v1.16.1](service/cloudwatchlogs/CHANGELOG.md#v1161-2022-11-04) - * **Documentation**: Doc-only update for bug fixes and support of export to buckets encrypted with SSE-KMS -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.66.0](service/ec2/CHANGELOG.md#v1660-2022-11-04) - * **Feature**: This release adds API support for the recipient of an AMI account share to remove shared AMI launch permissions. -* `github.com/aws/aws-sdk-go-v2/service/emrcontainers`: [v1.15.0](service/emrcontainers/CHANGELOG.md#v1150-2022-11-04) - * **Feature**: Adding support for Job templates. Job templates allow you to create and store templates to configure Spark applications parameters. This helps you ensure consistent settings across applications by reusing and enforcing configuration overrides in data pipelines. -* `github.com/aws/aws-sdk-go-v2/service/internal/eventstreamtesting`: [v1.0.37](service/internal/eventstreamtesting/CHANGELOG.md#v1037-2022-11-04) - * **Dependency Update**: update golang.org/x/net dependency to 0.1.0 - -# Release (2022-11-03) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/memorydb`: [v1.10.0](service/memorydb/CHANGELOG.md#v1100-2022-11-03) - * **Feature**: Adding support for r6gd instances for MemoryDB Redis with data tiering. In a cluster with data tiering enabled, when available memory capacity is exhausted, the least recently used data is automatically tiered to solid state drives for cost-effective capacity scaling with minimal performance impact. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.54.0](service/sagemaker/CHANGELOG.md#v1540-2022-11-03) - * **Feature**: Amazon SageMaker now supports running training jobs on ml.trn1 instance types. - -# Release (2022-11-02) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/iotsitewise`: [v1.26.0](service/iotsitewise/CHANGELOG.md#v1260-2022-11-02) - * **Feature**: This release adds the ListAssetModelProperties and ListAssetProperties APIs. You can list all properties that belong to a single asset model or asset using these two new APIs. -* `github.com/aws/aws-sdk-go-v2/service/s3control`: [v1.25.0](service/s3control/CHANGELOG.md#v1250-2022-11-02) - * **Feature**: S3 on Outposts launches support for Lifecycle configuration for Outposts buckets. With S3 Lifecycle configuration, you can mange objects so they are stored cost effectively. You can manage objects using size-based rules and specify how many noncurrent versions bucket will retain. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.53.0](service/sagemaker/CHANGELOG.md#v1530-2022-11-02) - * **Feature**: This release updates Framework model regex for ModelPackage to support new Framework version xgboost, sklearn. -* `github.com/aws/aws-sdk-go-v2/service/ssmincidents`: [v1.17.0](service/ssmincidents/CHANGELOG.md#v1170-2022-11-02) - * **Feature**: Adds support for tagging replication-set on creation. - -# Release (2022-11-01) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.28.0](service/rds/CHANGELOG.md#v1280-2022-11-01) - * **Feature**: Relational Database Service - This release adds support for configuring Storage Throughput on RDS database instances. -* `github.com/aws/aws-sdk-go-v2/service/textract`: [v1.17.0](service/textract/CHANGELOG.md#v1170-2022-11-01) - * **Feature**: Add ocr results in AnalyzeIDResponse as blocks - -# Release (2022-10-31) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/apprunner`: [v1.15.0](service/apprunner/CHANGELOG.md#v1150-2022-10-31) - * **Feature**: This release adds support for private App Runner services. Services may now be configured to be made private and only accessible from a VPC. The changes include a new VpcIngressConnection resource and several new and modified APIs. -* `github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs`: [v1.16.0](service/cloudwatchlogs/CHANGELOG.md#v1160-2022-10-31) - * **Feature**: SDK release to support tagging for destinations and log groups with TagResource. Also supports tag on create with PutDestination. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.34.0](service/connect/CHANGELOG.md#v1340-2022-10-31) - * **Feature**: Amazon connect now support a new API DismissUserContact to dismiss or remove terminated contacts in Agent CCP -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.65.0](service/ec2/CHANGELOG.md#v1650-2022-10-31) - * **Feature**: Elastic IP transfer is a new Amazon VPC feature that allows you to transfer your Elastic IP addresses from one AWS Account to another. -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.30.0](service/iot/CHANGELOG.md#v1300-2022-10-31) - * **Feature**: This release adds the Amazon Location action to IoT Rules Engine. -* `github.com/aws/aws-sdk-go-v2/service/sesv2`: [v1.15.0](service/sesv2/CHANGELOG.md#v1150-2022-10-31) - * **Feature**: This release includes support for interacting with the Virtual Deliverability Manager, allowing you to opt in/out of the feature and to retrieve recommendations and metric data. -* `github.com/aws/aws-sdk-go-v2/service/textract`: [v1.16.0](service/textract/CHANGELOG.md#v1160-2022-10-31) - * **Feature**: This release introduces additional support for 30+ normalized fields such as vendor address and currency. It also includes OCR output in the response and accuracy improvements for the already supported fields in previous version - -# Release (2022-10-28) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/apprunner`: [v1.14.0](service/apprunner/CHANGELOG.md#v1140-2022-10-28) - * **Feature**: AWS App Runner adds .NET 6, Go 1, PHP 8.1 and Ruby 3.1 runtimes. -* `github.com/aws/aws-sdk-go-v2/service/appstream`: [v1.18.0](service/appstream/CHANGELOG.md#v1180-2022-10-28) - * **Feature**: This release includes CertificateBasedAuthProperties in CreateDirectoryConfig and UpdateDirectoryConfig. -* `github.com/aws/aws-sdk-go-v2/service/cloud9`: [v1.16.20](service/cloud9/CHANGELOG.md#v11620-2022-10-28) - * **Documentation**: Update to the documentation section of the Cloud9 API Reference guide. -* `github.com/aws/aws-sdk-go-v2/service/cloudformation`: [v1.23.0](service/cloudformation/CHANGELOG.md#v1230-2022-10-28) - * **Feature**: This release adds more fields to improves visibility of AWS CloudFormation StackSets information in following APIs: ListStackInstances, DescribeStackInstance, ListStackSetOperationResults, ListStackSetOperations, DescribeStackSetOperation. -* `github.com/aws/aws-sdk-go-v2/service/mediatailor`: [v1.19.0](service/mediatailor/CHANGELOG.md#v1190-2022-10-28) - * **Feature**: This release introduces support for SCTE-35 segmentation descriptor messages which can be sent within time signal messages. - -# Release (2022-10-27) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.64.0](service/ec2/CHANGELOG.md#v1640-2022-10-27) - * **Feature**: Feature supports the replacement of instance root volume using an updated AMI without requiring customers to stop their instance. -* `github.com/aws/aws-sdk-go-v2/service/fms`: [v1.19.0](service/fms/CHANGELOG.md#v1190-2022-10-27) - * **Feature**: Add support NetworkFirewall Managed Rule Group Override flag in GetViolationDetails API -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.34.0](service/glue/CHANGELOG.md#v1340-2022-10-27) - * **Feature**: Added support for custom datatypes when using custom csv classifier. -* `github.com/aws/aws-sdk-go-v2/service/redshift`: [v1.26.13](service/redshift/CHANGELOG.md#v12613-2022-10-27) - * **Documentation**: This release clarifies use for the ElasticIp parameter of the CreateCluster and RestoreFromClusterSnapshot APIs. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.52.0](service/sagemaker/CHANGELOG.md#v1520-2022-10-27) - * **Feature**: This change allows customers to provide a custom entrypoint script for the docker container to be run while executing training jobs, and provide custom arguments to the entrypoint script. -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.23.0](service/wafv2/CHANGELOG.md#v1230-2022-10-27) - * **Feature**: This release adds the following: Challenge rule action, to silently verify client browsers; rule group rule action override to any valid rule action, not just Count; token sharing between protected applications for challenge/CAPTCHA token; targeted rules option for Bot Control managed rule group. - -# Release (2022-10-26) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/iam`: [v1.18.23](service/iam/CHANGELOG.md#v11823-2022-10-26) - * **Documentation**: Doc only update that corrects instances of CLI not using an entity. -* `github.com/aws/aws-sdk-go-v2/service/kafka`: [v1.18.0](service/kafka/CHANGELOG.md#v1180-2022-10-26) - * **Feature**: This release adds support for Tiered Storage. UpdateStorage allows you to control the Storage Mode for supported storage tiers. -* `github.com/aws/aws-sdk-go-v2/service/neptune`: [v1.18.0](service/neptune/CHANGELOG.md#v1180-2022-10-26) - * **Feature**: Added a new cluster-level attribute to set the capacity range for Neptune Serverless instances. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.51.0](service/sagemaker/CHANGELOG.md#v1510-2022-10-26) - * **Feature**: Amazon SageMaker Automatic Model Tuning now supports specifying Grid Search strategy for tuning jobs, which evaluates all hyperparameter combinations exhaustively based on the categorical hyperparameters provided. - -# Release (2022-10-25) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/accessanalyzer`: [v1.17.0](service/accessanalyzer/CHANGELOG.md#v1170-2022-10-25) - * **Feature**: This release adds support for six new resource types in IAM Access Analyzer to help you easily identify public and cross-account access to your AWS resources. Updated service API, documentation, and paginators. -* `github.com/aws/aws-sdk-go-v2/service/location`: [v1.19.3](service/location/CHANGELOG.md#v1193-2022-10-25) - * **Documentation**: Added new map styles with satellite imagery for map resources using HERE as a data provider. -* `github.com/aws/aws-sdk-go-v2/service/mediatailor`: [v1.18.0](service/mediatailor/CHANGELOG.md#v1180-2022-10-25) - * **Feature**: This release is a documentation update -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.27.0](service/rds/CHANGELOG.md#v1270-2022-10-25) - * **Feature**: Relational Database Service - This release adds support for exporting DB cluster data to Amazon S3. -* `github.com/aws/aws-sdk-go-v2/service/workspaces`: [v1.24.0](service/workspaces/CHANGELOG.md#v1240-2022-10-25) - * **Feature**: This release adds new enums for supporting Workspaces Core features, including creating Manual running mode workspaces, importing regular Workspaces Core images and importing g4dn Workspaces Core images. - -# Release (2022-10-24) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/feature/ec2/imds`: [v1.12.19](feature/ec2/imds/CHANGELOG.md#v11219-2022-10-24) - * **Bug Fix**: Fixes an issue that prevented logging of the API request or responses when the respective log modes were enabled. -* `github.com/aws/aws-sdk-go-v2/service/acmpca`: [v1.19.0](service/acmpca/CHANGELOG.md#v1190-2022-10-24) - * **Feature**: AWS Private Certificate Authority (AWS Private CA) now offers usage modes which are combination of features to address specific use cases. -* `github.com/aws/aws-sdk-go-v2/service/batch`: [v1.19.0](service/batch/CHANGELOG.md#v1190-2022-10-24) - * **Feature**: This release adds support for AWS Batch on Amazon EKS. -* `github.com/aws/aws-sdk-go-v2/service/datasync`: [v1.19.0](service/datasync/CHANGELOG.md#v1190-2022-10-24) - * **Feature**: Added support for self-signed certificates when using object storage locations; added BytesCompressed to the TaskExecution response. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.50.0](service/sagemaker/CHANGELOG.md#v1500-2022-10-24) - * **Feature**: SageMaker Inference Recommender now supports a new API ListInferenceRecommendationJobSteps to return the details of all the benchmark we create for an inference recommendation job. - -# Release (2022-10-21) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2`: v1.17.0 - * **Feature**: Adds `aws.IsCredentialsProvider` for inspecting `CredentialProvider` types when needing to determine if the underlying implementation type matches a target type. This resolves an issue where `CredentialsCache` could mask `AnonymousCredentials` providers, breaking downstream detection logic. -* `github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider`: [v1.21.0](service/cognitoidentityprovider/CHANGELOG.md#v1210-2022-10-21) - * **Feature**: This release adds a new "DeletionProtection" field to the UserPool in Cognito. Application admins can configure this value with either ACTIVE or INACTIVE value. Setting this field to ACTIVE will prevent a user pool from accidental deletion. -* `github.com/aws/aws-sdk-go-v2/service/eventbridge`: [v1.16.16](service/eventbridge/CHANGELOG.md#v11616-2022-10-21) - * **Bug Fix**: The SDK client has been updated to utilize the `aws.IsCredentialsProvider` function for determining if `aws.AnonymousCredentials` has been configured for the `CredentialProvider`. -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.29.0](service/s3/CHANGELOG.md#v1290-2022-10-21) - * **Feature**: S3 on Outposts launches support for automatic bucket-style alias. You can use the automatic access point alias instead of an access point ARN for any object-level operation in an Outposts bucket. - * **Bug Fix**: The SDK client has been updated to utilize the `aws.IsCredentialsProvider` function for determining if `aws.AnonymousCredentials` has been configured for the `CredentialProvider`. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.49.0](service/sagemaker/CHANGELOG.md#v1490-2022-10-21) - * **Feature**: CreateInferenceRecommenderjob API now supports passing endpoint details directly, that will help customers to identify the max invocation and max latency they can achieve for their model and the associated endpoint along with getting recommendations on other instances. -* `github.com/aws/aws-sdk-go-v2/service/sts`: [v1.17.0](service/sts/CHANGELOG.md#v1170-2022-10-21) - * **Feature**: Add presign functionality for sts:AssumeRole operation - -# Release (2022-10-20) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/devopsguru`: [v1.20.0](service/devopsguru/CHANGELOG.md#v1200-2022-10-20) - * **Feature**: This release adds information about the resources DevOps Guru is analyzing. -* `github.com/aws/aws-sdk-go-v2/service/globalaccelerator`: [v1.15.0](service/globalaccelerator/CHANGELOG.md#v1150-2022-10-20) - * **Feature**: Global Accelerator now supports AddEndpoints and RemoveEndpoints operations for standard endpoint groups. -* `github.com/aws/aws-sdk-go-v2/service/resiliencehub`: [v1.7.0](service/resiliencehub/CHANGELOG.md#v170-2022-10-20) - * **Feature**: In this release, we are introducing support for regional optimization for AWS Resilience Hub applications. It also includes a few documentation updates to improve clarity. -* `github.com/aws/aws-sdk-go-v2/service/rum`: [v1.7.0](service/rum/CHANGELOG.md#v170-2022-10-20) - * **Feature**: CloudWatch RUM now supports Extended CloudWatch Metrics with Additional Dimensions - -# Release (2022-10-19) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmessaging`: [v1.11.6](service/chimesdkmessaging/CHANGELOG.md#v1116-2022-10-19) - * **Documentation**: Documentation updates for Chime Messaging SDK -* `github.com/aws/aws-sdk-go-v2/service/cloudtrail`: [v1.19.0](service/cloudtrail/CHANGELOG.md#v1190-2022-10-19) - * **Feature**: This release includes support for exporting CloudTrail Lake query results to an Amazon S3 bucket. -* `github.com/aws/aws-sdk-go-v2/service/configservice`: [v1.27.0](service/configservice/CHANGELOG.md#v1270-2022-10-19) - * **Feature**: This release adds resourceType enums for AppConfig, AppSync, DataSync, EC2, EKS, Glue, GuardDuty, SageMaker, ServiceDiscovery, SES, Route53 types. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.33.0](service/connect/CHANGELOG.md#v1330-2022-10-19) - * **Feature**: This release adds API support for managing phone numbers that can be used across multiple AWS regions through telephony traffic distribution. -* `github.com/aws/aws-sdk-go-v2/service/managedblockchain`: [v1.13.0](service/managedblockchain/CHANGELOG.md#v1130-2022-10-19) - * **Feature**: Adding new Accessor APIs for Amazon Managed Blockchain -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.28.0](service/s3/CHANGELOG.md#v1280-2022-10-19) - * **Feature**: Updates internal logic for constructing API endpoints. We have added rule-based endpoints and internal model parameters. -* `github.com/aws/aws-sdk-go-v2/service/supportapp`: [v1.1.0](service/supportapp/CHANGELOG.md#v110-2022-10-19) - * **Feature**: This release adds the RegisterSlackWorkspaceForOrganization API. You can use the API to register a Slack workspace for an AWS account that is part of an organization. -* `github.com/aws/aws-sdk-go-v2/service/workspacesweb`: [v1.7.0](service/workspacesweb/CHANGELOG.md#v170-2022-10-19) - * **Feature**: WorkSpaces Web now supports user access logging for recording session start, stop, and URL navigation. - -# Release (2022-10-18) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/frauddetector`: [v1.20.10](service/frauddetector/CHANGELOG.md#v12010-2022-10-18) - * **Documentation**: Documentation Updates for Amazon Fraud Detector -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.48.0](service/sagemaker/CHANGELOG.md#v1480-2022-10-18) - * **Feature**: This change allows customers to enable data capturing while running a batch transform job, and configure monitoring schedule to monitoring the captured data. -* `github.com/aws/aws-sdk-go-v2/service/servicediscovery`: [v1.18.0](service/servicediscovery/CHANGELOG.md#v1180-2022-10-18) - * **Feature**: Updated the ListNamespaces API to support the NAME and HTTP_NAME filters, and the BEGINS_WITH filter condition. -* `github.com/aws/aws-sdk-go-v2/service/sesv2`: [v1.14.0](service/sesv2/CHANGELOG.md#v1140-2022-10-18) - * **Feature**: This release allows subscribers to enable Dedicated IPs (managed) to send email via a fully managed dedicated IP experience. It also adds identities' VerificationStatus in the response of GetEmailIdentity and ListEmailIdentities APIs, and ImportJobs counts in the response of ListImportJobs API. - -# Release (2022-10-17) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/greengrass`: [v1.14.0](service/greengrass/CHANGELOG.md#v1140-2022-10-17) - * **Feature**: This change allows customers to specify FunctionRuntimeOverride in FunctionDefinitionVersion. This configuration can be used if the runtime on the device is different from the AWS Lambda runtime specified for that function. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.47.0](service/sagemaker/CHANGELOG.md#v1470-2022-10-17) - * **Feature**: This release adds support for C7g, C6g, C6gd, C6gn, M6g, M6gd, R6g, and R6gn Graviton instance types in Amazon SageMaker Inference. - -# Release (2022-10-14) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.26.0](service/mediaconvert/CHANGELOG.md#v1260-2022-10-14) - * **Feature**: MediaConvert now supports specifying the minimum percentage of the HRD buffer available at the end of each encoded video segment. - -# Release (2022-10-13) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/amplifyuibuilder`: [v1.8.0](service/amplifyuibuilder/CHANGELOG.md#v180-2022-10-13) - * **Feature**: We are releasing the ability for fields to be configured as arrays. -* `github.com/aws/aws-sdk-go-v2/service/appflow`: [v1.18.0](service/appflow/CHANGELOG.md#v1180-2022-10-13) - * **Feature**: With this update, you can choose which Salesforce API is used by Amazon AppFlow to transfer data to or from your Salesforce account. You can choose the Salesforce REST API or Bulk API 2.0. You can also choose for Amazon AppFlow to pick the API automatically. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.32.0](service/connect/CHANGELOG.md#v1320-2022-10-13) - * **Feature**: This release adds support for a secondary email and a mobile number for Amazon Connect instance users. -* `github.com/aws/aws-sdk-go-v2/service/directoryservice`: [v1.15.0](service/directoryservice/CHANGELOG.md#v1150-2022-10-13) - * **Feature**: This release adds support for describing and updating AWS Managed Microsoft AD set up. -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.18.24](service/ecs/CHANGELOG.md#v11824-2022-10-13) - * **Documentation**: Documentation update to address tickets. -* `github.com/aws/aws-sdk-go-v2/service/guardduty`: [v1.16.0](service/guardduty/CHANGELOG.md#v1160-2022-10-13) - * **Feature**: Add UnprocessedDataSources to CreateDetectorResponse which specifies the data sources that couldn't be enabled during the CreateDetector request. In addition, update documentations. -* `github.com/aws/aws-sdk-go-v2/service/iam`: [v1.18.20](service/iam/CHANGELOG.md#v11820-2022-10-13) - * **Documentation**: Documentation updates for the AWS Identity and Access Management API Reference. -* `github.com/aws/aws-sdk-go-v2/service/iotfleetwise`: [v1.0.1](service/iotfleetwise/CHANGELOG.md#v101-2022-10-13) - * **Documentation**: Documentation update for AWS IoT FleetWise -* `github.com/aws/aws-sdk-go-v2/service/medialive`: [v1.24.0](service/medialive/CHANGELOG.md#v1240-2022-10-13) - * **Feature**: AWS Elemental MediaLive now supports forwarding SCTE-35 messages through the Event Signaling and Management (ESAM) API, and can read those SCTE-35 messages from an inactive source. -* `github.com/aws/aws-sdk-go-v2/service/mediapackagevod`: [v1.18.0](service/mediapackagevod/CHANGELOG.md#v1180-2022-10-13) - * **Feature**: This release adds SPEKE v2 support for MediaPackage VOD. Speke v2 is an upgrade to the existing SPEKE API to support multiple encryption keys, based on an encryption contract selected by the customer. -* `github.com/aws/aws-sdk-go-v2/service/panorama`: [v1.9.0](service/panorama/CHANGELOG.md#v190-2022-10-13) - * **Feature**: Pause and resume camera stream processing with SignalApplicationInstanceNodeInstances. Reboot an appliance with CreateJobForDevices. More application state information in DescribeApplicationInstance response. -* `github.com/aws/aws-sdk-go-v2/service/rdsdata`: [v1.12.16](service/rdsdata/CHANGELOG.md#v11216-2022-10-13) - * **Documentation**: Doc update to reflect no support for schema parameter on BatchExecuteStatement API -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.31.0](service/ssm/CHANGELOG.md#v1310-2022-10-13) - * **Feature**: Support of AmazonLinux2022 by Patch Manager -* `github.com/aws/aws-sdk-go-v2/service/ssmincidents`: [v1.16.0](service/ssmincidents/CHANGELOG.md#v1160-2022-10-13) - * **Feature**: Update RelatedItem enum to support Tasks -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.23.0](service/transfer/CHANGELOG.md#v1230-2022-10-13) - * **Feature**: This release adds an option for customers to configure workflows that are triggered when files are only partially received from a client due to premature session disconnect. -* `github.com/aws/aws-sdk-go-v2/service/translate`: [v1.15.1](service/translate/CHANGELOG.md#v1151-2022-10-13) - * **Documentation**: This release enables customers to specify multiple target languages in asynchronous batch translation requests. -* `github.com/aws/aws-sdk-go-v2/service/wisdom`: [v1.10.0](service/wisdom/CHANGELOG.md#v1100-2022-10-13) - * **Feature**: This release updates the GetRecommendations API to include a trigger event list for classifying and grouping recommendations. - -# Release (2022-10-07) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/codegurureviewer`: [v1.16.15](service/codegurureviewer/CHANGELOG.md#v11615-2022-10-07) - * **Documentation**: Documentation update to replace broken link. -* `github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2`: [v1.18.20](service/elasticloadbalancingv2/CHANGELOG.md#v11820-2022-10-07) - * **Documentation**: Gateway Load Balancer adds a new feature (target_failover) for customers to rebalance existing flows to a healthy target after marked unhealthy or deregistered. This allows graceful patching/upgrades of target appliances during maintenance windows, and helps reduce unhealthy target failover time. -* `github.com/aws/aws-sdk-go-v2/service/greengrassv2`: [v1.19.0](service/greengrassv2/CHANGELOG.md#v1190-2022-10-07) - * **Feature**: This release adds error status details for deployments and components that failed on a device and adds features to improve visibility into component installation. -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.26.0](service/quicksight/CHANGELOG.md#v1260-2022-10-07) - * **Feature**: Amazon QuickSight now supports SecretsManager Secret ARN in place of CredentialPair for DataSource creation and update. This release also has some minor documentation updates and removes CountryCode as a required parameter in GeoSpatialColumnGroup - -# Release (2022-10-06) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/resiliencehub`: [v1.6.15](service/resiliencehub/CHANGELOG.md#v1615-2022-10-06) - * **Documentation**: Documentation change for AWS Resilience Hub. Doc-only update to fix Documentation layout - -# Release (2022-10-05) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.33.0](service/glue/CHANGELOG.md#v1330-2022-10-05) - * **Feature**: This SDK release adds support to sync glue jobs with source control provider. Additionally, a new parameter called SourceControlDetails will be added to Job model. -* `github.com/aws/aws-sdk-go-v2/service/networkfirewall`: [v1.20.0](service/networkfirewall/CHANGELOG.md#v1200-2022-10-05) - * **Feature**: StreamExceptionPolicy configures how AWS Network Firewall processes traffic when a network connection breaks midstream -* `github.com/aws/aws-sdk-go-v2/service/outposts`: [v1.23.0](service/outposts/CHANGELOG.md#v1230-2022-10-05) - * **Feature**: This release adds the Asset state information to the ListAssets response. The ListAssets request supports filtering on Asset state. - -# Release (2022-10-04) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.31.0](service/connect/CHANGELOG.md#v1310-2022-10-04) - * **Feature**: Updated the CreateIntegrationAssociation API to support the CASES_DOMAIN IntegrationType. -* `github.com/aws/aws-sdk-go-v2/service/connectcases`: [v1.0.0](service/connectcases/CHANGELOG.md#v100-2022-10-04) - * **Release**: New AWS service client module - * **Feature**: This release adds APIs for Amazon Connect Cases. Cases allows your agents to quickly track and manage customer issues that require multiple interactions, follow-up tasks, and teams in your contact center. For more information, see https://docs.aws.amazon.com/cases/latest/APIReference/Welcome.html -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.63.0](service/ec2/CHANGELOG.md#v1630-2022-10-04) - * **Feature**: Added EnableNetworkAddressUsageMetrics flag for ModifyVpcAttribute, DescribeVpcAttribute APIs. -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.18.23](service/ecs/CHANGELOG.md#v11823-2022-10-04) - * **Documentation**: Documentation updates to address various Amazon ECS tickets. -* `github.com/aws/aws-sdk-go-v2/service/s3control`: [v1.24.0](service/s3control/CHANGELOG.md#v1240-2022-10-04) - * **Feature**: S3 Object Lambda adds support to allow customers to intercept HeadObject and ListObjects requests and introduce their own compute. These requests were previously proxied to S3. -* `github.com/aws/aws-sdk-go-v2/service/workmail`: [v1.17.0](service/workmail/CHANGELOG.md#v1170-2022-10-04) - * **Feature**: This release adds support for impersonation roles in Amazon WorkMail. - -# Release (2022-10-03) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/accessanalyzer`: [v1.16.0](service/accessanalyzer/CHANGELOG.md#v1160-2022-10-03) - * **Feature**: AWS IAM Access Analyzer policy validation introduces new checks for role trust policies. As customers author a policy, IAM Access Analyzer policy validation evaluates the policy for any issues to make it easier for customers to author secure policies. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.62.0](service/ec2/CHANGELOG.md#v1620-2022-10-03) - * **Feature**: Adding an imdsSupport attribute to EC2 AMIs -* `github.com/aws/aws-sdk-go-v2/service/snowball`: [v1.16.0](service/snowball/CHANGELOG.md#v1160-2022-10-03) - * **Feature**: Adds support for V3_5C. This is a refreshed AWS Snowball Edge Compute Optimized device type with 28TB SSD, 104 vCPU and 416GB memory (customer usable). - -# Release (2022-09-30) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/codedeploy`: [v1.15.0](service/codedeploy/CHANGELOG.md#v1150-2022-09-30) - * **Feature**: This release allows you to override the alarm configurations when creating a deployment. -* `github.com/aws/aws-sdk-go-v2/service/devopsguru`: [v1.19.0](service/devopsguru/CHANGELOG.md#v1190-2022-09-30) - * **Feature**: This release adds filter feature on AddNotificationChannel API, enable customer to configure the SNS notification messages by Severity or MessageTypes -* `github.com/aws/aws-sdk-go-v2/service/dlm`: [v1.13.0](service/dlm/CHANGELOG.md#v1130-2022-09-30) - * **Feature**: This release adds support for archival of single-volume snapshots created by Amazon Data Lifecycle Manager policies -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.46.0](service/sagemaker/CHANGELOG.md#v1460-2022-09-30) - * **Feature**: A new parameter called ExplainerConfig is added to CreateEndpointConfig API to enable SageMaker Clarify online explainability feature. -* `github.com/aws/aws-sdk-go-v2/service/sagemakerruntime`: [v1.16.0](service/sagemakerruntime/CHANGELOG.md#v1160-2022-09-30) - * **Feature**: A new parameter called EnableExplanations is added to InvokeEndpoint API to enable on-demand SageMaker Clarify online explainability requests. -* `github.com/aws/aws-sdk-go-v2/service/ssooidc`: [v1.13.6](service/ssooidc/CHANGELOG.md#v1136-2022-09-30) - * **Documentation**: Documentation updates for the IAM Identity Center OIDC CLI Reference. - -# Release (2022-09-29) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/acm`: [v1.15.0](service/acm/CHANGELOG.md#v1150-2022-09-29) - * **Feature**: This update returns additional certificate details such as certificate SANs and allows sorting in the ListCertificates API. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.61.0](service/ec2/CHANGELOG.md#v1610-2022-09-29) - * **Feature**: u-3tb1 instances are powered by Intel Xeon Platinum 8176M (Skylake) processors and are purpose-built to run large in-memory databases. -* `github.com/aws/aws-sdk-go-v2/service/emrserverless`: [v1.3.0](service/emrserverless/CHANGELOG.md#v130-2022-09-29) - * **Feature**: This release adds API support to debug Amazon EMR Serverless jobs in real-time with live application UIs -* `github.com/aws/aws-sdk-go-v2/service/fsx`: [v1.25.0](service/fsx/CHANGELOG.md#v1250-2022-09-29) - * **Feature**: This release adds support for Amazon File Cache. -* `github.com/aws/aws-sdk-go-v2/service/migrationhuborchestrator`: [v1.0.0](service/migrationhuborchestrator/CHANGELOG.md#v100-2022-09-29) - * **Release**: New AWS service client module - * **Feature**: Introducing AWS MigrationHubOrchestrator. This is the first public release of AWS MigrationHubOrchestrator. -* `github.com/aws/aws-sdk-go-v2/service/polly`: [v1.18.0](service/polly/CHANGELOG.md#v1180-2022-09-29) - * **Feature**: Added support for the new Cantonese voice - Hiujin. Hiujin is available as a Neural voice only. -* `github.com/aws/aws-sdk-go-v2/service/proton`: [v1.15.0](service/proton/CHANGELOG.md#v1150-2022-09-29) - * **Feature**: This release adds an option to delete pipeline provisioning repositories using the UpdateAccountSettings API -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.45.0](service/sagemaker/CHANGELOG.md#v1450-2022-09-29) - * **Feature**: SageMaker Training Managed Warm Pools let you retain provisioned infrastructure to reduce latency for repetitive training workloads. -* `github.com/aws/aws-sdk-go-v2/service/secretsmanager`: [v1.16.2](service/secretsmanager/CHANGELOG.md#v1162-2022-09-29) - * **Documentation**: Documentation updates for Secrets Manager -* `github.com/aws/aws-sdk-go-v2/service/translate`: [v1.15.0](service/translate/CHANGELOG.md#v1150-2022-09-29) - * **Feature**: This release enables customers to access control rights on Translate resources like Parallel Data and Custom Terminology using Tag Based Authorization. -* `github.com/aws/aws-sdk-go-v2/service/workspaces`: [v1.23.0](service/workspaces/CHANGELOG.md#v1230-2022-09-29) - * **Feature**: This release includes diagnostic log uploading feature. If it is enabled, the log files of WorkSpaces Windows client will be sent to Amazon WorkSpaces automatically for troubleshooting. You can use modifyClientProperty api to enable/disable this feature. - -# Release (2022-09-27) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/costexplorer`: [v1.21.0](service/costexplorer/CHANGELOG.md#v1210-2022-09-27) - * **Feature**: This release is to support retroactive Cost Categories. The new field will enable you to retroactively apply new and existing cost category rules to previous months. -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.35.0](service/kendra/CHANGELOG.md#v1350-2022-09-27) - * **Feature**: My AWS Service (placeholder) - Amazon Kendra now provides a data source connector for DropBox. For more information, see https://docs.aws.amazon.com/kendra/latest/dg/data-source-dropbox.html -* `github.com/aws/aws-sdk-go-v2/service/location`: [v1.19.0](service/location/CHANGELOG.md#v1190-2022-09-27) - * **Feature**: This release adds place IDs, which are unique identifiers of places, along with a new GetPlace operation, which can be used with place IDs to find a place again later. UnitNumber and UnitType are also added as new properties of places. - -# Release (2022-09-26) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue`: [v1.10.0](feature/dynamodb/attributevalue/CHANGELOG.md#v1100-2022-09-26) - * **Feature**: Adds a String method to UnixTime, so that when structs with this field get logged it prints a human readable time. -* `github.com/aws/aws-sdk-go-v2/feature/dynamodbstreams/attributevalue`: [v1.10.0](feature/dynamodbstreams/attributevalue/CHANGELOG.md#v1100-2022-09-26) - * **Feature**: Adds a String method to UnixTime, so that when structs with this field get logged it prints a human readable time. -* `github.com/aws/aws-sdk-go-v2/service/costandusagereportservice`: [v1.14.0](service/costandusagereportservice/CHANGELOG.md#v1140-2022-09-26) - * **Feature**: This release adds two new support regions(me-central-1/eu-south-2) for OSG. -* `github.com/aws/aws-sdk-go-v2/service/iotfleetwise`: [v1.0.0](service/iotfleetwise/CHANGELOG.md#v100-2022-09-26) - * **Release**: New AWS service client module - * **Feature**: General availability (GA) for AWS IoT Fleetwise. It adds AWS IoT Fleetwise to AWS SDK. For more information, see https://docs.aws.amazon.com/iot-fleetwise/latest/APIReference/Welcome.html. -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.30.0](service/ssm/CHANGELOG.md#v1300-2022-09-26) - * **Feature**: This release includes support for applying a CloudWatch alarm to Systems Manager capabilities like Automation, Run Command, State Manager, and Maintenance Windows. - -# Release (2022-09-23) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/apprunner`: [v1.13.0](service/apprunner/CHANGELOG.md#v1130-2022-09-23) - * **Feature**: AWS App Runner adds a Node.js 16 runtime. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.60.0](service/ec2/CHANGELOG.md#v1600-2022-09-23) - * **Feature**: Letting external AWS customers provide ImageId as a Launch Template override in FleetLaunchTemplateOverridesRequest -* `github.com/aws/aws-sdk-go-v2/service/lexmodelsv2`: [v1.25.0](service/lexmodelsv2/CHANGELOG.md#v1250-2022-09-23) - * **Feature**: This release introduces additional optional parameters promptAttemptsSpecification to PromptSpecification, which enables the users to configure interrupt setting and Audio, DTMF and Text input configuration for the initial and retry prompt played by the Bot -* `github.com/aws/aws-sdk-go-v2/service/lightsail`: [v1.23.0](service/lightsail/CHANGELOG.md#v1230-2022-09-23) - * **Feature**: This release adds Instance Metadata Service (IMDS) support for Lightsail instances. -* `github.com/aws/aws-sdk-go-v2/service/nimble`: [v1.14.0](service/nimble/CHANGELOG.md#v1140-2022-09-23) - * **Feature**: Amazon Nimble Studio adds support for on-demand Amazon Elastic Compute Cloud (EC2) G3 and G5 instances, allowing customers to utilize additional GPU instance types for their creative projects. -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.29.0](service/ssm/CHANGELOG.md#v1290-2022-09-23) - * **Feature**: This release adds new SSM document types ConformancePackTemplate and CloudFormation -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.22.9](service/wafv2/CHANGELOG.md#v1229-2022-09-23) - * **Documentation**: Add the default specification for ResourceType in ListResourcesForWebACL. - -# Release (2022-09-22) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/backupgateway`: [v1.7.0](service/backupgateway/CHANGELOG.md#v170-2022-09-22) - * **Feature**: Changes include: new GetVirtualMachineApi to fetch a single user's VM, improving ListVirtualMachines to fetch filtered VMs as well as all VMs, and improving GetGatewayApi to now also return the gateway's MaintenanceStartTime. -* `github.com/aws/aws-sdk-go-v2/service/devicefarm`: [v1.14.0](service/devicefarm/CHANGELOG.md#v1140-2022-09-22) - * **Feature**: This release adds the support for VPC-ENI based connectivity for private devices on AWS Device Farm. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.59.0](service/ec2/CHANGELOG.md#v1590-2022-09-22) - * **Feature**: Documentation updates for Amazon EC2. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.32.0](service/glue/CHANGELOG.md#v1320-2022-09-22) - * **Feature**: Added support for S3 Event Notifications for Catalog Target Crawlers. -* `github.com/aws/aws-sdk-go-v2/service/identitystore`: [v1.15.5](service/identitystore/CHANGELOG.md#v1155-2022-09-22) - * **Documentation**: Documentation updates for the Identity Store CLI Reference. - -# Release (2022-09-21) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/comprehend`: [v1.19.0](service/comprehend/CHANGELOG.md#v1190-2022-09-21) - * **Feature**: Amazon Comprehend now supports synchronous mode for targeted sentiment API operations. -* `github.com/aws/aws-sdk-go-v2/service/route53`: [v1.22.2](service/route53/CHANGELOG.md#v1222-2022-09-21) - * **Bug Fix**: Updated GetChange to sanitize /change/ prefix of the changeId returned from the service. -* `github.com/aws/aws-sdk-go-v2/service/s3control`: [v1.23.0](service/s3control/CHANGELOG.md#v1230-2022-09-21) - * **Feature**: S3 on Outposts launches support for object versioning for Outposts buckets. With S3 Versioning, you can preserve, retrieve, and restore every version of every object stored in your buckets. You can recover from both unintended user actions and application failures. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.44.0](service/sagemaker/CHANGELOG.md#v1440-2022-09-21) - * **Feature**: SageMaker now allows customization on Canvas Application settings, including enabling/disabling time-series forecasting and specifying an Amazon Forecast execution role at both the Domain and UserProfile levels. - -# Release (2022-09-20) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2`: v1.16.16 - * **Documentation**: added clafirfication on the Credential object to show usage of loadDefaultConfig to load credentials -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.58.0](service/ec2/CHANGELOG.md#v1580-2022-09-20) - * **Feature**: This release adds support for blocked paths to Amazon VPC Reachability Analyzer. - -# Release (2022-09-19) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudtrail`: [v1.18.0](service/cloudtrail/CHANGELOG.md#v1180-2022-09-19) - * **Feature**: This release includes support for importing existing trails into CloudTrail Lake. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.57.0](service/ec2/CHANGELOG.md#v1570-2022-09-19) - * **Feature**: This release adds CapacityAllocations field to DescribeCapacityReservations -* `github.com/aws/aws-sdk-go-v2/service/mediaconnect`: [v1.17.0](service/mediaconnect/CHANGELOG.md#v1170-2022-09-19) - * **Feature**: This change allows the customer to use the SRT Caller protocol as part of their flows -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.26.0](service/rds/CHANGELOG.md#v1260-2022-09-19) - * **Feature**: This release adds support for Amazon RDS Proxy with SQL Server compatibility. - -# Release (2022-09-16) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/codestarnotifications`: [v1.13.0](service/codestarnotifications/CHANGELOG.md#v1130-2022-09-16) - * **Feature**: This release adds tag based access control for the UntagResource API. -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.18.21](service/ecs/CHANGELOG.md#v11821-2022-09-16) - * **Documentation**: This release supports new task definition sizes. - -# Release (2022-09-15) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/dynamodb`: [v1.17.0](service/dynamodb/CHANGELOG.md#v1170-2022-09-15) - * **Feature**: Increased DynamoDB transaction limit from 25 to 100. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.56.0](service/ec2/CHANGELOG.md#v1560-2022-09-15) - * **Feature**: This feature allows customers to create tags for vpc-endpoint-connections and vpc-endpoint-service-permissions. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.43.0](service/sagemaker/CHANGELOG.md#v1430-2022-09-15) - * **Feature**: Amazon SageMaker Automatic Model Tuning now supports specifying Hyperband strategy for tuning jobs, which uses a multi-fidelity based tuning strategy to stop underperforming hyperparameter configurations early. - -# Release (2022-09-14) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/feature/rds/auth`: [v1.2.0](feature/rds/auth/CHANGELOG.md#v120-2022-09-14) - * **Feature**: Updated `BuildAuthToken` to validate the provided endpoint contains a port. -* `github.com/aws/aws-sdk-go-v2/internal/v4a`: [v1.0.13](internal/v4a/CHANGELOG.md#v1013-2022-09-14) - * **Bug Fix**: Fixes an issues where an error from an underlying SigV4 credential provider would not be surfaced from the SigV4a credential provider. Contribution by [sakthipriyan-aqfer](https://github.com/sakthipriyan-aqfer). -* `github.com/aws/aws-sdk-go-v2/service/acmpca`: [v1.18.0](service/acmpca/CHANGELOG.md#v1180-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/amplifyuibuilder`: [v1.7.0](service/amplifyuibuilder/CHANGELOG.md#v170-2022-09-14) - * **Feature**: Amplify Studio UIBuilder is introducing forms functionality. Forms can be configured from Data Store models, JSON, or from scratch. These forms can then be generated in your project and used like any other React components. -* `github.com/aws/aws-sdk-go-v2/service/appconfig`: [v1.14.0](service/appconfig/CHANGELOG.md#v1140-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/appflow`: [v1.17.0](service/appflow/CHANGELOG.md#v1170-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/appmesh`: [v1.16.0](service/appmesh/CHANGELOG.md#v1160-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/cloudtrail`: [v1.17.0](service/cloudtrail/CHANGELOG.md#v1170-2022-09-14) - * **Feature**: This release adds CloudTrail getChannel and listChannels APIs to allow customer to view the ServiceLinkedChannel configurations. -* `github.com/aws/aws-sdk-go-v2/service/codestar`: [v1.12.0](service/codestar/CHANGELOG.md#v1120-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/codestarnotifications`: [v1.12.0](service/codestarnotifications/CHANGELOG.md#v1120-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/cognitoidentity`: [v1.14.0](service/cognitoidentity/CHANGELOG.md#v1140-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider`: [v1.20.0](service/cognitoidentityprovider/CHANGELOG.md#v1200-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/configservice`: [v1.26.0](service/configservice/CHANGELOG.md#v1260-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.30.0](service/connect/CHANGELOG.md#v1300-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/connectparticipant`: [v1.12.0](service/connectparticipant/CHANGELOG.md#v1120-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/costexplorer`: [v1.20.0](service/costexplorer/CHANGELOG.md#v1200-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/customerprofiles`: [v1.19.0](service/customerprofiles/CHANGELOG.md#v1190-2022-09-14) - * **Feature**: Added isUnstructured in response for Customer Profiles Integration APIs - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/dataexchange`: [v1.16.0](service/dataexchange/CHANGELOG.md#v1160-2022-09-14) - * **Feature**: Documentation updates for AWS Data Exchange. -* `github.com/aws/aws-sdk-go-v2/service/drs`: [v1.8.0](service/drs/CHANGELOG.md#v180-2022-09-14) - * **Feature**: Fixed the data type of lagDuration that is returned in Describe Source Server API -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.55.0](service/ec2/CHANGELOG.md#v1550-2022-09-14) - * **Feature**: Documentation updates for Amazon EC2. - * **Feature**: This release adds support to send VPC Flow Logs to kinesis-data-firehose as new destination type - * **Feature**: This update introduces API operations to manage and create local gateway route tables, CoIP pools, and VIF group associations. - * **Feature**: Two new features for local gateway route tables: support for static routes targeting Elastic Network Interfaces and direct VPC routing. -* `github.com/aws/aws-sdk-go-v2/service/eks`: [v1.22.0](service/eks/CHANGELOG.md#v1220-2022-09-14) - * **Feature**: Adding support for local Amazon EKS clusters on Outposts - * **Feature**: Adds support for EKS Addons ResolveConflicts "preserve" flag. Also adds new update failed status for EKS Addons. -* `github.com/aws/aws-sdk-go-v2/service/emrcontainers`: [v1.14.0](service/emrcontainers/CHANGELOG.md#v1140-2022-09-14) - * **Feature**: EMR on EKS now allows running Spark SQL using the newly introduced Spark SQL Job Driver in the Start Job Run API -* `github.com/aws/aws-sdk-go-v2/service/emrserverless`: [v1.2.0](service/emrserverless/CHANGELOG.md#v120-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/evidently`: [v1.9.0](service/evidently/CHANGELOG.md#v190-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. - * **Feature**: This release adds support for the client-side evaluation - powered by AWS AppConfig feature. -* `github.com/aws/aws-sdk-go-v2/service/finspacedata`: [v1.13.0](service/finspacedata/CHANGELOG.md#v1130-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/fis`: [v1.13.0](service/fis/CHANGELOG.md#v1130-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/fsx`: [v1.24.12](service/fsx/CHANGELOG.md#v12412-2022-09-14) - * **Documentation**: Documentation update for Amazon FSx. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.31.0](service/glue/CHANGELOG.md#v1310-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/greengrassv2`: [v1.18.0](service/greengrassv2/CHANGELOG.md#v1180-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/identitystore`: [v1.15.3](service/identitystore/CHANGELOG.md#v1153-2022-09-14) - * **Documentation**: Documentation updates for the Identity Store CLI Reference. -* `github.com/aws/aws-sdk-go-v2/service/imagebuilder`: [v1.20.0](service/imagebuilder/CHANGELOG.md#v1200-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/inspector2`: [v1.8.0](service/inspector2/CHANGELOG.md#v180-2022-09-14) - * **Feature**: This release adds new fields like fixAvailable, fixedInVersion and remediation to the finding model. The requirement to have vulnerablePackages in the finding model has also been removed. The documentation has been updated to reflect these changes. -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.29.0](service/iot/CHANGELOG.md#v1290-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/iotanalytics`: [v1.13.0](service/iotanalytics/CHANGELOG.md#v1130-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/iotsecuretunneling`: [v1.14.0](service/iotsecuretunneling/CHANGELOG.md#v1140-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/iotsitewise`: [v1.25.0](service/iotsitewise/CHANGELOG.md#v1250-2022-09-14) - * **Feature**: Allow specifying units in Asset Properties -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.34.0](service/kendra/CHANGELOG.md#v1340-2022-09-14) - * **Feature**: This release enables our customer to choose the option of Sharepoint 2019 for the on-premise Sharepoint connector. -* `github.com/aws/aws-sdk-go-v2/service/lexmodelsv2`: [v1.24.0](service/lexmodelsv2/CHANGELOG.md#v1240-2022-09-14) - * **Feature**: This release is for supporting Composite Slot Type feature in AWS Lex V2. Composite Slot Type will help developer to logically group coherent slots and maintain their inter-relationships in runtime conversation. -* `github.com/aws/aws-sdk-go-v2/service/lexruntimev2`: [v1.15.0](service/lexruntimev2/CHANGELOG.md#v1150-2022-09-14) - * **Feature**: This release is for supporting Composite Slot Type feature in AWS Lex V2. Composite Slot Type will help developer to logically group coherent slots and maintain their inter-relationships in runtime conversation. -* `github.com/aws/aws-sdk-go-v2/service/lookoutmetrics`: [v1.18.0](service/lookoutmetrics/CHANGELOG.md#v1180-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. - * **Feature**: Release dimension value filtering feature to allow customers to define dimension filters for including only a subset of their dataset to be used by LookoutMetrics. -* `github.com/aws/aws-sdk-go-v2/service/m2`: [v1.1.0](service/m2/CHANGELOG.md#v110-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/medialive`: [v1.23.0](service/medialive/CHANGELOG.md#v1230-2022-09-14) - * **Feature**: This change exposes API settings which allow Dolby Atmos and Dolby Vision to be used when running a channel using Elemental Media Live -* `github.com/aws/aws-sdk-go-v2/service/networkfirewall`: [v1.19.0](service/networkfirewall/CHANGELOG.md#v1190-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/pi`: [v1.15.0](service/pi/CHANGELOG.md#v1150-2022-09-14) - * **Feature**: Increases the maximum values of two RDS Performance Insights APIs. The maximum value of the Limit parameter of DimensionGroup is 25. The MaxResult maximum is now 25 for the following APIs: DescribeDimensionKeys, GetResourceMetrics, ListAvailableResourceDimensions, and ListAvailableResourceMetrics. -* `github.com/aws/aws-sdk-go-v2/service/pricing`: [v1.17.0](service/pricing/CHANGELOG.md#v1170-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.25.0](service/quicksight/CHANGELOG.md#v1250-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/redshift`: [v1.26.9](service/redshift/CHANGELOG.md#v1269-2022-09-14) - * **Documentation**: This release updates documentation for AQUA features and other description updates. -* `github.com/aws/aws-sdk-go-v2/service/route53`: [v1.22.0](service/route53/CHANGELOG.md#v1220-2022-09-14) - * **Feature**: Amazon Route 53 now supports the Middle East (UAE) Region (me-central-1) for latency records, geoproximity records, and private DNS for Amazon VPCs in that region. -* `github.com/aws/aws-sdk-go-v2/service/route53recoverycluster`: [v1.10.0](service/route53recoverycluster/CHANGELOG.md#v1100-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/s3control`: [v1.22.0](service/s3control/CHANGELOG.md#v1220-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.42.0](service/sagemaker/CHANGELOG.md#v1420-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. - * **Feature**: SageMaker Hosting now allows customization on ML instance storage volume size, model data download timeout and inference container startup ping health check timeout for each ProductionVariant in CreateEndpointConfig API. - * **Feature**: This release adds HyperParameterTuningJob type in Search API. - * **Feature**: This release adds Mode to AutoMLJobConfig. -* `github.com/aws/aws-sdk-go-v2/service/sagemakera2iruntime`: [v1.14.0](service/sagemakera2iruntime/CHANGELOG.md#v1140-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/secretsmanager`: [v1.16.0](service/secretsmanager/CHANGELOG.md#v1160-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/servicecatalogappregistry`: [v1.14.0](service/servicecatalogappregistry/CHANGELOG.md#v1140-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/sfn`: [v1.14.0](service/sfn/CHANGELOG.md#v1140-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/sns`: [v1.18.0](service/sns/CHANGELOG.md#v1180-2022-09-14) - * **Feature**: Amazon SNS introduces the Data Protection Policy APIs, which enable customers to attach a data protection policy to an SNS topic. This allows topic owners to enable the new message data protection feature to audit and block sensitive data that is exchanged through their topics. -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.28.0](service/ssm/CHANGELOG.md#v1280-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. - * **Feature**: This release adds support for Systems Manager State Manager Association tagging. -* `github.com/aws/aws-sdk-go-v2/service/timestreamwrite`: [v1.14.0](service/timestreamwrite/CHANGELOG.md#v1140-2022-09-14) - * **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.22.0](service/transfer/CHANGELOG.md#v1220-2022-09-14) - * **Feature**: This release introduces the ability to have multiple server host keys for any of your Transfer Family servers that use the SFTP protocol. - -# Release (2022-09-02.2) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/identitystore`: [v1.15.2](service/identitystore/CHANGELOG.md#v1152-2022-09-022) - * **Bug Fix**: Reverts a change to the identitystore module so that MaxResults members of ListGroupMemberShips, ListGroupMembershipsForMembers, ListGroups, and ListUsers are correctly generated as pointer types instead of value types - -# Release (2022-09-02) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider`: [v1.19.0](service/cognitoidentityprovider/CHANGELOG.md#v1190-2022-09-02) - * **Feature**: This release adds a new "AuthSessionValidity" field to the UserPoolClient in Cognito. Application admins can configure this value for their users' authentication duration, which is currently fixed at 3 minutes, up to 15 minutes. Setting this field will also apply to the SMS MFA authentication flow. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.29.0](service/connect/CHANGELOG.md#v1290-2022-09-02) - * **Feature**: This release adds search APIs for Routing Profiles and Queues, which can be used to search for those resources within a Connect Instance. -* `github.com/aws/aws-sdk-go-v2/service/mediapackage`: [v1.19.0](service/mediapackage/CHANGELOG.md#v1190-2022-09-02) - * **Feature**: Added support for AES_CTR encryption to CMAF origin endpoints -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.41.0](service/sagemaker/CHANGELOG.md#v1410-2022-09-02) - * **Feature**: This release enables administrators to attribute user activity and API calls from Studio notebooks, Data Wrangler and Canvas to specific users even when users share the same execution IAM role. ExecutionRoleIdentityConfig at Sagemaker domain level enables this feature. - -# Release (2022-09-01) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/codegurureviewer`: [v1.16.11](service/codegurureviewer/CHANGELOG.md#v11611-2022-09-01) - * **Documentation**: Documentation updates to fix formatting issues in CLI and SDK documentation. -* `github.com/aws/aws-sdk-go-v2/service/controltower`: [v1.0.0](service/controltower/CHANGELOG.md#v100-2022-09-01) - * **Release**: New AWS service client module - * **Feature**: This release contains the first SDK for AWS Control Tower. It introduces a new set of APIs: EnableControl, DisableControl, GetControlOperation, and ListEnabledControls. -* `github.com/aws/aws-sdk-go-v2/service/route53`: [v1.21.10](service/route53/CHANGELOG.md#v12110-2022-09-01) - * **Documentation**: Documentation updates for Amazon Route 53. - -# Release (2022-08-31) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudfront`: [v1.20.2](service/cloudfront/CHANGELOG.md#v1202-2022-08-31) - * **Documentation**: Update API documentation for CloudFront origin access control (OAC) -* `github.com/aws/aws-sdk-go-v2/service/identitystore`: [v1.15.0](service/identitystore/CHANGELOG.md#v1150-2022-08-31) - * **Feature**: Expand IdentityStore API to support Create, Read, Update, Delete and Get operations for User, Group and GroupMembership resources. -* `github.com/aws/aws-sdk-go-v2/service/iotthingsgraph`: [v1.13.0](service/iotthingsgraph/CHANGELOG.md#v1130-2022-08-31) - * **Feature**: This release deprecates all APIs of the ThingsGraph service -* `github.com/aws/aws-sdk-go-v2/service/ivs`: [v1.18.0](service/ivs/CHANGELOG.md#v1180-2022-08-31) - * **Feature**: IVS Merge Fragmented Streams. This release adds support for recordingReconnectWindow field in IVS recordingConfigurations. For more information see https://docs.aws.amazon.com/ivs/latest/APIReference/Welcome.html -* `github.com/aws/aws-sdk-go-v2/service/rdsdata`: [v1.12.12](service/rdsdata/CHANGELOG.md#v11212-2022-08-31) - * **Documentation**: Documentation updates for RDS Data API -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.40.0](service/sagemaker/CHANGELOG.md#v1400-2022-08-31) - * **Feature**: SageMaker Inference Recommender now accepts Inference Recommender fields: Domain, Task, Framework, SamplePayloadUrl, SupportedContentTypes, SupportedInstanceTypes, directly in our CreateInferenceRecommendationsJob API through ContainerConfig - -# Release (2022-08-30) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/greengrassv2`: [v1.17.0](service/greengrassv2/CHANGELOG.md#v1170-2022-08-30) - * **Feature**: Adds topologyFilter to ListInstalledComponentsRequest which allows filtration of components by ROOT or ALL (including root and dependency components). Adds lastStatusChangeTimestamp to ListInstalledComponents response to show the last time a component changed state on a device. -* `github.com/aws/aws-sdk-go-v2/service/identitystore`: [v1.14.15](service/identitystore/CHANGELOG.md#v11415-2022-08-30) - * **Documentation**: Documentation updates for the Identity Store CLI Reference. -* `github.com/aws/aws-sdk-go-v2/service/lookoutequipment`: [v1.15.0](service/lookoutequipment/CHANGELOG.md#v1150-2022-08-30) - * **Feature**: This release adds new apis for providing labels. -* `github.com/aws/aws-sdk-go-v2/service/macie2`: [v1.23.0](service/macie2/CHANGELOG.md#v1230-2022-08-30) - * **Feature**: This release of the Amazon Macie API adds support for using allow lists to define specific text and text patterns to ignore when inspecting data sources for sensitive data. -* `github.com/aws/aws-sdk-go-v2/service/sso`: [v1.11.19](service/sso/CHANGELOG.md#v11119-2022-08-30) - * **Documentation**: Documentation updates for the AWS IAM Identity Center Portal CLI Reference. -* `github.com/aws/aws-sdk-go-v2/service/ssoadmin`: [v1.15.7](service/ssoadmin/CHANGELOG.md#v1157-2022-08-30) - * **Documentation**: Documentation updates for the AWS IAM Identity Center CLI Reference. - -# Release (2022-08-29) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/fsx`: [v1.24.9](service/fsx/CHANGELOG.md#v1249-2022-08-29) - * **Documentation**: Documentation updates for Amazon FSx for NetApp ONTAP. -* `github.com/aws/aws-sdk-go-v2/service/voiceid`: [v1.11.0](service/voiceid/CHANGELOG.md#v1110-2022-08-29) - * **Feature**: Amazon Connect Voice ID now detects voice spoofing. When a prospective fraudster tries to spoof caller audio using audio playback or synthesized speech, Voice ID will return a risk score and outcome to indicate the how likely it is that the voice is spoofed. - -# Release (2022-08-26) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/mediapackage`: [v1.18.0](service/mediapackage/CHANGELOG.md#v1180-2022-08-26) - * **Feature**: This release adds Ads AdTriggers and AdsOnDeliveryRestrictions to describe calls for CMAF endpoints on MediaPackage. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.25.1](service/rds/CHANGELOG.md#v1251-2022-08-26) - * **Documentation**: Removes support for RDS Custom from DBInstanceClass in ModifyDBInstance - -# Release (2022-08-25) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2`: [v1.18.13](service/elasticloadbalancingv2/CHANGELOG.md#v11813-2022-08-25) - * **Documentation**: Documentation updates for ELBv2. Gateway Load Balancer now supports Configurable Flow Stickiness, enabling you to configure the hashing used to maintain stickiness of flows to a specific target appliance. -* `github.com/aws/aws-sdk-go-v2/service/gamelift`: [v1.15.0](service/gamelift/CHANGELOG.md#v1150-2022-08-25) - * **Feature**: This release adds support for eight EC2 local zones as fleet locations; Atlanta, Chicago, Dallas, Denver, Houston, Kansas City (us-east-1-mci-1a), Los Angeles, and Phoenix. It also adds support for C5d, C6a, C6i, and R5d EC2 instance families. -* `github.com/aws/aws-sdk-go-v2/service/iotwireless`: [v1.22.0](service/iotwireless/CHANGELOG.md#v1220-2022-08-25) - * **Feature**: This release includes a new feature for the customers to enable the LoRa gateways to send out beacons for Class B devices and an option to select one or more gateways for Class C devices when sending the LoRaWAN downlink messages. -* `github.com/aws/aws-sdk-go-v2/service/ivschat`: [v1.0.13](service/ivschat/CHANGELOG.md#v1013-2022-08-25) - * **Documentation**: Documentation change for IVS Chat API Reference. Doc-only update to add a paragraph on ARNs to the Welcome section. -* `github.com/aws/aws-sdk-go-v2/service/panorama`: [v1.8.0](service/panorama/CHANGELOG.md#v180-2022-08-25) - * **Feature**: Support sorting and filtering in ListDevices API, and add more fields to device listings and single device detail -* `github.com/aws/aws-sdk-go-v2/service/ssooidc`: [v1.13.0](service/ssooidc/CHANGELOG.md#v1130-2022-08-25) - * **Feature**: Updated required request parameters on IAM Identity Center's OIDC CreateToken action. - -# Release (2022-08-24) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudfront`: [v1.20.0](service/cloudfront/CHANGELOG.md#v1200-2022-08-24) - * **Feature**: Adds support for CloudFront origin access control (OAC), making it possible to restrict public access to S3 bucket origins in all AWS Regions, those with SSE-KMS, and more. -* `github.com/aws/aws-sdk-go-v2/service/configservice`: [v1.25.0](service/configservice/CHANGELOG.md#v1250-2022-08-24) - * **Feature**: AWS Config now supports ConformancePackTemplate documents in SSM Docs for the deployment and update of conformance packs. -* `github.com/aws/aws-sdk-go-v2/service/iam`: [v1.18.14](service/iam/CHANGELOG.md#v11814-2022-08-24) - * **Documentation**: Documentation updates for AWS Identity and Access Management (IAM). -* `github.com/aws/aws-sdk-go-v2/service/ivs`: [v1.17.1](service/ivs/CHANGELOG.md#v1171-2022-08-24) - * **Documentation**: Documentation Change for IVS API Reference - Doc-only update to type field description for CreateChannel and UpdateChannel actions and for Channel data type. Also added Amazon Resource Names (ARNs) paragraph to Welcome section. -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.24.0](service/quicksight/CHANGELOG.md#v1240-2022-08-24) - * **Feature**: Added a new optional property DashboardVisual under ExperienceConfiguration parameter of GenerateEmbedUrlForAnonymousUser and GenerateEmbedUrlForRegisteredUser API operations. This supports embedding of specific visuals in QuickSight dashboards. -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.21.5](service/transfer/CHANGELOG.md#v1215-2022-08-24) - * **Documentation**: Documentation updates for AWS Transfer Family - -# Release (2022-08-23) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.25.0](service/rds/CHANGELOG.md#v1250-2022-08-23) - * **Feature**: RDS for Oracle supports Oracle Data Guard switchover and read replica backups. -* `github.com/aws/aws-sdk-go-v2/service/ssoadmin`: [v1.15.5](service/ssoadmin/CHANGELOG.md#v1155-2022-08-23) - * **Documentation**: Documentation updates to reflect service rename - AWS IAM Identity Center (successor to AWS Single Sign-On) - -# Release (2022-08-22) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/docdb`: [v1.19.5](service/docdb/CHANGELOG.md#v1195-2022-08-22) - * **Documentation**: Update document for volume clone -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.54.0](service/ec2/CHANGELOG.md#v1540-2022-08-22) - * **Feature**: R6a instances are powered by 3rd generation AMD EPYC (Milan) processors delivering all-core turbo frequency of 3.6 GHz. C6id, M6id, and R6id instances are powered by 3rd generation Intel Xeon Scalable processor (Ice Lake) delivering all-core turbo frequency of 3.5 GHz. -* `github.com/aws/aws-sdk-go-v2/service/forecast`: [v1.23.0](service/forecast/CHANGELOG.md#v1230-2022-08-22) - * **Feature**: releasing What-If Analysis APIs and update ARN regex pattern to be more strict in accordance with security recommendation -* `github.com/aws/aws-sdk-go-v2/service/forecastquery`: [v1.12.0](service/forecastquery/CHANGELOG.md#v1120-2022-08-22) - * **Feature**: releasing What-If Analysis APIs -* `github.com/aws/aws-sdk-go-v2/service/iotsitewise`: [v1.24.0](service/iotsitewise/CHANGELOG.md#v1240-2022-08-22) - * **Feature**: Enable non-unique asset names under different hierarchies -* `github.com/aws/aws-sdk-go-v2/service/lexmodelsv2`: [v1.23.0](service/lexmodelsv2/CHANGELOG.md#v1230-2022-08-22) - * **Feature**: This release introduces a new feature to stop a running BotRecommendation Job for Automated Chatbot Designer. -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.23.0](service/securityhub/CHANGELOG.md#v1230-2022-08-22) - * **Feature**: Added new resource details objects to ASFF, including resources for AwsBackupBackupVault, AwsBackupBackupPlan and AwsBackupRecoveryPoint. Added FixAvailable, FixedInVersion and Remediation to Vulnerability. -* `github.com/aws/aws-sdk-go-v2/service/supportapp`: [v1.0.0](service/supportapp/CHANGELOG.md#v100-2022-08-22) - * **Release**: New AWS service client module - * **Feature**: This is the initial SDK release for the AWS Support App in Slack. - -# Release (2022-08-19) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.28.0](service/connect/CHANGELOG.md#v1280-2022-08-19) - * **Feature**: This release adds SearchSecurityProfiles API which can be used to search for Security Profile resources within a Connect Instance. -* `github.com/aws/aws-sdk-go-v2/service/ivschat`: [v1.0.12](service/ivschat/CHANGELOG.md#v1012-2022-08-19) - * **Documentation**: Documentation Change for IVS Chat API Reference - Doc-only update to change text/description for tags field. -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.33.0](service/kendra/CHANGELOG.md#v1330-2022-08-19) - * **Feature**: This release adds support for a new authentication type - Personal Access Token (PAT) for confluence server. -* `github.com/aws/aws-sdk-go-v2/service/lookoutmetrics`: [v1.17.0](service/lookoutmetrics/CHANGELOG.md#v1170-2022-08-19) - * **Feature**: This release is to make GetDataQualityMetrics API publicly available. - -# Release (2022-08-18) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmediapipelines`: [v1.1.0](service/chimesdkmediapipelines/CHANGELOG.md#v110-2022-08-18) - * **Feature**: The Amazon Chime SDK now supports live streaming of real-time video from the Amazon Chime SDK sessions to streaming platforms such as Amazon IVS and Amazon Elemental MediaLive. We have also added support for concatenation to create a single media capture file. -* `github.com/aws/aws-sdk-go-v2/service/cloudwatch`: [v1.21.0](service/cloudwatch/CHANGELOG.md#v1210-2022-08-18) - * **Feature**: Add support for managed Contributor Insights Rules -* `github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider`: [v1.18.4](service/cognitoidentityprovider/CHANGELOG.md#v1184-2022-08-18) - * **Documentation**: This change is being made simply to fix the public documentation based on the models. We have included the PasswordChange and ResendCode events, along with the Pass, Fail and InProgress status. We have removed the Success and Failure status which are never returned by our APIs. -* `github.com/aws/aws-sdk-go-v2/service/dynamodb`: [v1.16.0](service/dynamodb/CHANGELOG.md#v1160-2022-08-18) - * **Feature**: This release adds support for importing data from S3 into a new DynamoDB table -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.53.0](service/ec2/CHANGELOG.md#v1530-2022-08-18) - * **Feature**: This release adds support for VPN log options , a new feature allowing S2S VPN connections to send IKE activity logs to CloudWatch Logs -* `github.com/aws/aws-sdk-go-v2/service/networkmanager`: [v1.15.0](service/networkmanager/CHANGELOG.md#v1150-2022-08-18) - * **Feature**: Add TransitGatewayPeeringAttachmentId property to TransitGatewayPeering Model - -# Release (2022-08-17) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/appmesh`: [v1.15.0](service/appmesh/CHANGELOG.md#v1150-2022-08-17) - * **Feature**: AWS App Mesh release to support Multiple Listener and Access Log Format feature -* `github.com/aws/aws-sdk-go-v2/service/connectcampaigns`: [v1.1.0](service/connectcampaigns/CHANGELOG.md#v110-2022-08-17) - * **Feature**: Updated exceptions for Amazon Connect Outbound Campaign api's. -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.32.0](service/kendra/CHANGELOG.md#v1320-2022-08-17) - * **Feature**: This release adds Zendesk connector (which allows you to specify Zendesk SAAS platform as data source), Proxy Support for Sharepoint and Confluence Server (which allows you to specify the proxy configuration if proxy is required to connect to your Sharepoint/Confluence Server as data source). -* `github.com/aws/aws-sdk-go-v2/service/lakeformation`: [v1.17.0](service/lakeformation/CHANGELOG.md#v1170-2022-08-17) - * **Feature**: This release adds a new API support "AssumeDecoratedRoleWithSAML" and also release updates the corresponding documentation. -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.24.0](service/lambda/CHANGELOG.md#v1240-2022-08-17) - * **Feature**: Added support for customization of Consumer Group ID for MSK and Kafka Event Source Mappings. -* `github.com/aws/aws-sdk-go-v2/service/lexmodelsv2`: [v1.22.0](service/lexmodelsv2/CHANGELOG.md#v1220-2022-08-17) - * **Feature**: This release introduces support for enhanced conversation design with the ability to define custom conversation flows with conditional branching and new bot responses. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.24.0](service/rds/CHANGELOG.md#v1240-2022-08-17) - * **Feature**: Adds support for Internet Protocol Version 6 (IPv6) for RDS Aurora database clusters. -* `github.com/aws/aws-sdk-go-v2/service/secretsmanager`: [v1.15.18](service/secretsmanager/CHANGELOG.md#v11518-2022-08-17) - * **Documentation**: Documentation updates for Secrets Manager. - -# Release (2022-08-16) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/rekognition`: [v1.20.0](service/rekognition/CHANGELOG.md#v1200-2022-08-16) - * **Feature**: This release adds APIs which support copying an Amazon Rekognition Custom Labels model and managing project policies across AWS account. -* `github.com/aws/aws-sdk-go-v2/service/servicecatalog`: [v1.14.12](service/servicecatalog/CHANGELOG.md#v11412-2022-08-16) - * **Documentation**: Documentation updates for Service Catalog - -# Release (2022-08-15) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudfront`: [v1.19.0](service/cloudfront/CHANGELOG.md#v1190-2022-08-15) - * **Feature**: Adds Http 3 support to distributions -* `github.com/aws/aws-sdk-go-v2/service/identitystore`: [v1.14.13](service/identitystore/CHANGELOG.md#v11413-2022-08-15) - * **Documentation**: Documentation updates to reflect service rename - AWS IAM Identity Center (successor to AWS Single Sign-On) -* `github.com/aws/aws-sdk-go-v2/service/sso`: [v1.11.17](service/sso/CHANGELOG.md#v11117-2022-08-15) - * **Documentation**: Documentation updates to reflect service rename - AWS IAM Identity Center (successor to AWS Single Sign-On) -* `github.com/aws/aws-sdk-go-v2/service/wisdom`: [v1.9.0](service/wisdom/CHANGELOG.md#v190-2022-08-15) - * **Feature**: This release introduces a new API PutFeedback that allows submitting feedback to Wisdom on content relevance. - -# Release (2022-08-14) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/config`: [v1.17.0](config/CHANGELOG.md#v1170-2022-08-14) - * **Feature**: Add alternative mechanism for determning the users `$HOME` or `%USERPROFILE%` location when the environment variables are not present. -* `github.com/aws/aws-sdk-go-v2/service/amp`: [v1.15.0](service/amp/CHANGELOG.md#v1150-2022-08-14) - * **Feature**: This release adds log APIs that allow customers to manage logging for their Amazon Managed Service for Prometheus workspaces. -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmessaging`: [v1.11.0](service/chimesdkmessaging/CHANGELOG.md#v1110-2022-08-14) - * **Feature**: The Amazon Chime SDK now supports channels with up to one million participants with elastic channels. -* `github.com/aws/aws-sdk-go-v2/service/ivs`: [v1.17.0](service/ivs/CHANGELOG.md#v1170-2022-08-14) - * **Feature**: Updates various list api MaxResults ranges -* `github.com/aws/aws-sdk-go-v2/service/personalizeruntime`: [v1.12.0](service/personalizeruntime/CHANGELOG.md#v1120-2022-08-14) - * **Feature**: This release provides support for promotions in AWS Personalize runtime. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.23.6](service/rds/CHANGELOG.md#v1236-2022-08-14) - * **Documentation**: Adds support for RDS Custom to DBInstanceClass in ModifyDBInstance - -# Release (2022-08-11) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/backupstorage`: [v1.0.0](service/backupstorage/CHANGELOG.md#v100-2022-08-11) - * **Release**: New AWS service client module - * **Feature**: This is the first public release of AWS Backup Storage. We are exposing some previously-internal APIs for use by external services. These APIs are not meant to be used directly by customers. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.30.0](service/glue/CHANGELOG.md#v1300-2022-08-11) - * **Feature**: Add support for Python 3.9 AWS Glue Python Shell jobs -* `github.com/aws/aws-sdk-go-v2/service/privatenetworks`: [v1.0.0](service/privatenetworks/CHANGELOG.md#v100-2022-08-11) - * **Release**: New AWS service client module - * **Feature**: This is the initial SDK release for AWS Private 5G. AWS Private 5G is a managed service that makes it easy to deploy, operate, and scale your own private mobile network at your on-premises location. - -# Release (2022-08-10) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/config`: [v1.16.0](config/CHANGELOG.md#v1160-2022-08-10) - * **Feature**: Adds support for the following settings in the `~/.aws/credentials` file: `sso_account_id`, `sso_region`, `sso_role_name`, `sso_start_url`, and `ca_bundle`. -* `github.com/aws/aws-sdk-go-v2/service/dlm`: [v1.12.0](service/dlm/CHANGELOG.md#v1120-2022-08-10) - * **Feature**: This release adds support for excluding specific data (non-boot) volumes from multi-volume snapshot sets created by snapshot lifecycle policies -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.52.0](service/ec2/CHANGELOG.md#v1520-2022-08-10) - * **Feature**: This release adds support for excluding specific data (non-root) volumes from multi-volume snapshot sets created from instances. - -# Release (2022-08-09) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudwatch`: [v1.20.0](service/cloudwatch/CHANGELOG.md#v1200-2022-08-09) - * **Feature**: Various quota increases related to dimensions and custom metrics -* `github.com/aws/aws-sdk-go-v2/service/location`: [v1.18.0](service/location/CHANGELOG.md#v1180-2022-08-09) - * **Feature**: Amazon Location Service now allows circular geofences in BatchPutGeofence, PutGeofence, and GetGeofence APIs. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.39.0](service/sagemaker/CHANGELOG.md#v1390-2022-08-09) - * **Feature**: Amazon SageMaker Automatic Model Tuning now supports specifying multiple alternate EC2 instance types to make tuning jobs more robust when the preferred instance type is not available due to insufficient capacity. -* `github.com/aws/aws-sdk-go-v2/service/sagemakera2iruntime`: [v1.13.0](service/sagemakera2iruntime/CHANGELOG.md#v1130-2022-08-09) - * **Feature**: Fix bug with parsing ISO-8601 CreationTime in Java SDK in DescribeHumanLoop - -# Release (2022-08-08) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2`: v1.16.9 - * **Bug Fix**: aws/signer/v4: Fixes a panic in SDK's handling of endpoint URLs with ports by correcting how URL path is parsed from opaque URLs. Fixes [#1294](https://github.com/aws/aws-sdk-go-v2/issues/1294). -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.29.0](service/glue/CHANGELOG.md#v1290-2022-08-08) - * **Feature**: Add an option to run non-urgent or non-time sensitive Glue Jobs on spare capacity -* `github.com/aws/aws-sdk-go-v2/service/identitystore`: [v1.14.10](service/identitystore/CHANGELOG.md#v11410-2022-08-08) - * **Documentation**: Documentation updates to reflect service rename - AWS IAM Identity Center (successor to AWS Single Sign-On) -* `github.com/aws/aws-sdk-go-v2/service/iotwireless`: [v1.21.0](service/iotwireless/CHANGELOG.md#v1210-2022-08-08) - * **Feature**: AWS IoT Wireless release support for sidewalk data reliability. -* `github.com/aws/aws-sdk-go-v2/service/pinpoint`: [v1.17.0](service/pinpoint/CHANGELOG.md#v1170-2022-08-08) - * **Feature**: Adds support for Advance Quiet Time in Journeys. Adds RefreshOnSegmentUpdate and WaitForQuietTime to JourneyResponse. -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.23.2](service/quicksight/CHANGELOG.md#v1232-2022-08-08) - * **Documentation**: A series of documentation updates to the QuickSight API reference. -* `github.com/aws/aws-sdk-go-v2/service/sso`: [v1.11.14](service/sso/CHANGELOG.md#v11114-2022-08-08) - * **Documentation**: Documentation updates to reflect service rename - AWS IAM Identity Center (successor to AWS Single Sign-On) -* `github.com/aws/aws-sdk-go-v2/service/ssoadmin`: [v1.15.2](service/ssoadmin/CHANGELOG.md#v1152-2022-08-08) - * **Documentation**: Documentation updates to reflect service rename - AWS IAM Identity Center (successor to AWS Single Sign-On) -* `github.com/aws/aws-sdk-go-v2/service/ssooidc`: [v1.12.12](service/ssooidc/CHANGELOG.md#v11212-2022-08-08) - * **Documentation**: Documentation updates to reflect service rename - AWS IAM Identity Center (successor to AWS Single Sign-On) - -# Release (2022-08-04) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmeetings`: [v1.13.0](service/chimesdkmeetings/CHANGELOG.md#v1130-2022-08-04) - * **Feature**: Adds support for Tags on Amazon Chime SDK WebRTC sessions -* `github.com/aws/aws-sdk-go-v2/service/configservice`: [v1.24.0](service/configservice/CHANGELOG.md#v1240-2022-08-04) - * **Feature**: Add resourceType enums for Athena, GlobalAccelerator, Detective and EC2 types -* `github.com/aws/aws-sdk-go-v2/service/databasemigrationservice`: [v1.21.3](service/databasemigrationservice/CHANGELOG.md#v1213-2022-08-04) - * **Documentation**: Documentation updates for Database Migration Service (DMS). -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.28.0](service/iot/CHANGELOG.md#v1280-2022-08-04) - * **Feature**: The release is to support attach a provisioning template to CACert for JITP function, Customer now doesn't have to hardcode a roleArn and templateBody during register a CACert to enable JITP. - -# Release (2022-08-03) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider`: [v1.18.0](service/cognitoidentityprovider/CHANGELOG.md#v1180-2022-08-03) - * **Feature**: Add a new exception type, ForbiddenException, that is returned when request is not allowed -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.22.0](service/wafv2/CHANGELOG.md#v1220-2022-08-03) - * **Feature**: You can now associate an AWS WAF web ACL with an Amazon Cognito user pool. - -# Release (2022-08-02) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/licensemanagerusersubscriptions`: [v1.0.0](service/licensemanagerusersubscriptions/CHANGELOG.md#v100-2022-08-02) - * **Release**: New AWS service client module - * **Feature**: This release supports user based subscription for Microsoft Visual Studio Professional and Enterprise on EC2. -* `github.com/aws/aws-sdk-go-v2/service/personalize`: [v1.21.0](service/personalize/CHANGELOG.md#v1210-2022-08-02) - * **Feature**: This release adds support for incremental bulk ingestion for the Personalize CreateDatasetImportJob API. - -# Release (2022-08-01) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/configservice`: [v1.23.1](service/configservice/CHANGELOG.md#v1231-2022-08-01) - * **Documentation**: Documentation update for PutConfigRule and PutOrganizationConfigRule -* `github.com/aws/aws-sdk-go-v2/service/workspaces`: [v1.22.0](service/workspaces/CHANGELOG.md#v1220-2022-08-01) - * **Feature**: This release introduces ModifySamlProperties, a new API that allows control of SAML properties associated with a WorkSpaces directory. The DescribeWorkspaceDirectories API will now additionally return SAML properties in its responses. - -# Release (2022-07-29) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.51.0](service/ec2/CHANGELOG.md#v1510-2022-07-29) - * **Feature**: Documentation updates for Amazon EC2. -* `github.com/aws/aws-sdk-go-v2/service/fsx`: [v1.24.4](service/fsx/CHANGELOG.md#v1244-2022-07-29) - * **Documentation**: Documentation updates for Amazon FSx -* `github.com/aws/aws-sdk-go-v2/service/shield`: [v1.17.0](service/shield/CHANGELOG.md#v1170-2022-07-29) - * **Feature**: AWS Shield Advanced now supports filtering for ListProtections and ListProtectionGroups. - -# Release (2022-07-28) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.50.1](service/ec2/CHANGELOG.md#v1501-2022-07-28) - * **Documentation**: Documentation updates for VM Import/Export. -* `github.com/aws/aws-sdk-go-v2/service/elasticsearchservice`: [v1.16.0](service/elasticsearchservice/CHANGELOG.md#v1160-2022-07-28) - * **Feature**: This release adds support for gp3 EBS (Elastic Block Store) storage. -* `github.com/aws/aws-sdk-go-v2/service/lookoutvision`: [v1.14.0](service/lookoutvision/CHANGELOG.md#v1140-2022-07-28) - * **Feature**: This release introduces support for image segmentation models and updates CPU accelerator options for models hosted on edge devices. -* `github.com/aws/aws-sdk-go-v2/service/opensearch`: [v1.10.0](service/opensearch/CHANGELOG.md#v1100-2022-07-28) - * **Feature**: This release adds support for gp3 EBS (Elastic Block Store) storage. - -# Release (2022-07-27) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/auditmanager`: [v1.20.0](service/auditmanager/CHANGELOG.md#v1200-2022-07-27) - * **Feature**: This release adds an exceeded quota exception to several APIs. We added a ServiceQuotaExceededException for the following operations: CreateAssessment, CreateControl, CreateAssessmentFramework, and UpdateAssessmentStatus. -* `github.com/aws/aws-sdk-go-v2/service/chime`: [v1.21.0](service/chime/CHANGELOG.md#v1210-2022-07-27) - * **Feature**: Chime VoiceConnector will now support ValidateE911Address which will allow customers to prevalidate their addresses included in their SIP invites for emergency calling -* `github.com/aws/aws-sdk-go-v2/service/configservice`: [v1.23.0](service/configservice/CHANGELOG.md#v1230-2022-07-27) - * **Feature**: This release adds ListConformancePackComplianceScores API to support the new compliance score feature, which provides a percentage of the number of compliant rule-resource combinations in a conformance pack compared to the number of total possible rule-resource combinations in the conformance pack. -* `github.com/aws/aws-sdk-go-v2/service/globalaccelerator`: [v1.14.0](service/globalaccelerator/CHANGELOG.md#v1140-2022-07-27) - * **Feature**: Global Accelerator now supports dual-stack accelerators, enabling support for IPv4 and IPv6 traffic. -* `github.com/aws/aws-sdk-go-v2/service/marketplacecatalog`: [v1.13.0](service/marketplacecatalog/CHANGELOG.md#v1130-2022-07-27) - * **Feature**: The SDK for the StartChangeSet API will now automatically set and use an idempotency token in the ClientRequestToken request parameter if the customer does not provide it. -* `github.com/aws/aws-sdk-go-v2/service/polly`: [v1.17.0](service/polly/CHANGELOG.md#v1170-2022-07-27) - * **Feature**: Amazon Polly adds new English and Hindi voice - Kajal. Kajal is available as Neural voice only. -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.27.5](service/ssm/CHANGELOG.md#v1275-2022-07-27) - * **Documentation**: Adding doc updates for OpsCenter support in Service Setting actions. -* `github.com/aws/aws-sdk-go-v2/service/workspaces`: [v1.21.0](service/workspaces/CHANGELOG.md#v1210-2022-07-27) - * **Feature**: Added CreateWorkspaceImage API to create a new WorkSpace image from an existing WorkSpace. - -# Release (2022-07-26) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/appsync`: [v1.15.0](service/appsync/CHANGELOG.md#v1150-2022-07-26) - * **Feature**: Adds support for a new API to evaluate mapping templates with mock data, allowing you to remotely unit test your AppSync resolvers and functions. -* `github.com/aws/aws-sdk-go-v2/service/detective`: [v1.16.0](service/detective/CHANGELOG.md#v1160-2022-07-26) - * **Feature**: Added the ability to get data source package information for the behavior graph. Graph administrators can now start (or stop) optional datasources on the behavior graph. -* `github.com/aws/aws-sdk-go-v2/service/guardduty`: [v1.15.0](service/guardduty/CHANGELOG.md#v1150-2022-07-26) - * **Feature**: Amazon GuardDuty introduces a new Malware Protection feature that triggers malware scan on selected EC2 instance resources, after the service detects a potentially malicious activity. -* `github.com/aws/aws-sdk-go-v2/service/lookoutvision`: [v1.13.0](service/lookoutvision/CHANGELOG.md#v1130-2022-07-26) - * **Feature**: This release introduces support for the automatic scaling of inference units used by Amazon Lookout for Vision models. -* `github.com/aws/aws-sdk-go-v2/service/macie2`: [v1.22.0](service/macie2/CHANGELOG.md#v1220-2022-07-26) - * **Feature**: This release adds support for retrieving (revealing) sample occurrences of sensitive data that Amazon Macie detects and reports in findings. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.23.1](service/rds/CHANGELOG.md#v1231-2022-07-26) - * **Documentation**: Adds support for using RDS Proxies with RDS for MariaDB databases. -* `github.com/aws/aws-sdk-go-v2/service/rekognition`: [v1.19.0](service/rekognition/CHANGELOG.md#v1190-2022-07-26) - * **Feature**: This release introduces support for the automatic scaling of inference units used by Amazon Rekognition Custom Labels models. -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.22.3](service/securityhub/CHANGELOG.md#v1223-2022-07-26) - * **Documentation**: Documentation updates for AWS Security Hub -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.21.0](service/transfer/CHANGELOG.md#v1210-2022-07-26) - * **Feature**: AWS Transfer Family now supports Applicability Statement 2 (AS2), a network protocol used for the secure and reliable transfer of critical Business-to-Business (B2B) data over the public internet using HTTP/HTTPS as the transport mechanism. - -# Release (2022-07-25) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/autoscaling`: [v1.23.6](service/autoscaling/CHANGELOG.md#v1236-2022-07-25) - * **Documentation**: Documentation update for Amazon EC2 Auto Scaling. - -# Release (2022-07-22) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/account`: [v1.7.0](service/account/CHANGELOG.md#v170-2022-07-22) - * **Feature**: This release enables customers to manage the primary contact information for their AWS accounts. For more information, see https://docs.aws.amazon.com/accounts/latest/reference/API_Operations.html -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.50.0](service/ec2/CHANGELOG.md#v1500-2022-07-22) - * **Feature**: Added support for EC2 M1 Mac instances. For more information, please visit aws.amazon.com/mac. -* `github.com/aws/aws-sdk-go-v2/service/iotdeviceadvisor`: [v1.15.0](service/iotdeviceadvisor/CHANGELOG.md#v1150-2022-07-22) - * **Feature**: Added new service feature (Early access only) - Long Duration Test, where customers can test the IoT device to observe how it behaves when the device is in operation for longer period. -* `github.com/aws/aws-sdk-go-v2/service/medialive`: [v1.22.0](service/medialive/CHANGELOG.md#v1220-2022-07-22) - * **Feature**: Link devices now support remote rebooting. Link devices now support maintenance windows. Maintenance windows allow a Link device to install software updates without stopping the MediaLive channel. The channel will experience a brief loss of input from the device while updates are installed. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.23.0](service/rds/CHANGELOG.md#v1230-2022-07-22) - * **Feature**: This release adds the "ModifyActivityStream" API with support for audit policy state locking and unlocking. -* `github.com/aws/aws-sdk-go-v2/service/transcribe`: [v1.21.0](service/transcribe/CHANGELOG.md#v1210-2022-07-22) - * **Feature**: Remove unsupported language codes for StartTranscriptionJob and update VocabularyFileUri for UpdateMedicalVocabulary - -# Release (2022-07-21) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/athena`: [v1.18.0](service/athena/CHANGELOG.md#v1180-2022-07-21) - * **Feature**: This feature allows customers to retrieve runtime statistics for completed queries -* `github.com/aws/aws-sdk-go-v2/service/cloudwatch`: [v1.19.0](service/cloudwatch/CHANGELOG.md#v1190-2022-07-21) - * **Feature**: Adding support for the suppression of Composite Alarm actions -* `github.com/aws/aws-sdk-go-v2/service/databasemigrationservice`: [v1.21.1](service/databasemigrationservice/CHANGELOG.md#v1211-2022-07-21) - * **Documentation**: Documentation updates for Database Migration Service (DMS). -* `github.com/aws/aws-sdk-go-v2/service/docdb`: [v1.19.0](service/docdb/CHANGELOG.md#v1190-2022-07-21) - * **Feature**: Enable copy-on-write restore type -* `github.com/aws/aws-sdk-go-v2/service/ec2instanceconnect`: [v1.14.0](service/ec2instanceconnect/CHANGELOG.md#v1140-2022-07-21) - * **Feature**: This release includes a new exception type "EC2InstanceUnavailableException" for SendSSHPublicKey and SendSerialConsoleSSHPublicKey APIs. -* `github.com/aws/aws-sdk-go-v2/service/frauddetector`: [v1.20.0](service/frauddetector/CHANGELOG.md#v1200-2022-07-21) - * **Feature**: The release introduces Account Takeover Insights (ATI) model. The ATI model detects fraud relating to account takeover. This release also adds support for new variable types: ARE_CREDENTIALS_VALID and SESSION_ID and adds new structures to Model Version APIs. -* `github.com/aws/aws-sdk-go-v2/service/iotsitewise`: [v1.23.0](service/iotsitewise/CHANGELOG.md#v1230-2022-07-21) - * **Feature**: Added asynchronous API to ingest bulk historical and current data into IoT SiteWise. -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.31.0](service/kendra/CHANGELOG.md#v1310-2022-07-21) - * **Feature**: Amazon Kendra now provides Oauth2 support for SharePoint Online. For more information, see https://docs.aws.amazon.com/kendra/latest/dg/data-source-sharepoint.html -* `github.com/aws/aws-sdk-go-v2/service/networkfirewall`: [v1.18.0](service/networkfirewall/CHANGELOG.md#v1180-2022-07-21) - * **Feature**: Network Firewall now supports referencing dynamic IP sets from stateful rule groups, for IP sets stored in Amazon VPC prefix lists. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.22.1](service/rds/CHANGELOG.md#v1221-2022-07-21) - * **Documentation**: Adds support for creating an RDS Proxy for an RDS for MariaDB database. - -# Release (2022-07-20) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/acmpca`: [v1.17.11](service/acmpca/CHANGELOG.md#v11711-2022-07-20) - * **Documentation**: AWS Certificate Manager (ACM) Private Certificate Authority (PCA) documentation updates -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.27.0](service/iot/CHANGELOG.md#v1270-2022-07-20) - * **Feature**: GA release the ability to enable/disable IoT Fleet Indexing for Device Defender and Named Shadow information, and search them through IoT Fleet Indexing APIs. This includes Named Shadow Selection as a part of the UpdateIndexingConfiguration API. - -# Release (2022-07-19) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/devopsguru`: [v1.18.0](service/devopsguru/CHANGELOG.md#v1180-2022-07-19) - * **Feature**: Added new APIs for log anomaly detection feature. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.28.1](service/glue/CHANGELOG.md#v1281-2022-07-19) - * **Documentation**: Documentation updates for AWS Glue Job Timeout and Autoscaling -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.38.0](service/sagemaker/CHANGELOG.md#v1380-2022-07-19) - * **Feature**: Fixed an issue with cross account QueryLineage -* `github.com/aws/aws-sdk-go-v2/service/sagemakeredge`: [v1.12.0](service/sagemakeredge/CHANGELOG.md#v1120-2022-07-19) - * **Feature**: Amazon SageMaker Edge Manager provides lightweight model deployment feature to deploy machine learning models on requested devices. -* `github.com/aws/aws-sdk-go-v2/service/workspaces`: [v1.20.0](service/workspaces/CHANGELOG.md#v1200-2022-07-19) - * **Feature**: Increased the character limit of the login message from 850 to 2000 characters. - -# Release (2022-07-18) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/applicationdiscoveryservice`: [v1.14.0](service/applicationdiscoveryservice/CHANGELOG.md#v1140-2022-07-18) - * **Feature**: Add AWS Agentless Collector details to the GetDiscoverySummary API response -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.49.1](service/ec2/CHANGELOG.md#v1491-2022-07-18) - * **Documentation**: Documentation updates for Amazon EC2. -* `github.com/aws/aws-sdk-go-v2/service/elasticache`: [v1.22.0](service/elasticache/CHANGELOG.md#v1220-2022-07-18) - * **Feature**: Adding AutoMinorVersionUpgrade in the DescribeReplicationGroups API -* `github.com/aws/aws-sdk-go-v2/service/kms`: [v1.18.0](service/kms/CHANGELOG.md#v1180-2022-07-18) - * **Feature**: Added support for the SM2 KeySpec in China Partition Regions -* `github.com/aws/aws-sdk-go-v2/service/mediapackage`: [v1.17.0](service/mediapackage/CHANGELOG.md#v1170-2022-07-18) - * **Feature**: This release adds "IncludeIframeOnlyStream" for Dash endpoints and increases the number of supported video and audio encryption presets for Speke v2 -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.37.0](service/sagemaker/CHANGELOG.md#v1370-2022-07-18) - * **Feature**: Amazon SageMaker Edge Manager provides lightweight model deployment feature to deploy machine learning models on requested devices. -* `github.com/aws/aws-sdk-go-v2/service/ssoadmin`: [v1.15.0](service/ssoadmin/CHANGELOG.md#v1150-2022-07-18) - * **Feature**: AWS SSO now supports attaching customer managed policies and a permissions boundary to your permission sets. This release adds new API operations to manage and view the customer managed policies and the permissions boundary for a given permission set. - -# Release (2022-07-15) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/datasync`: [v1.18.3](service/datasync/CHANGELOG.md#v1183-2022-07-15) - * **Documentation**: Documentation updates for AWS DataSync regarding configuring Amazon FSx for ONTAP location security groups and SMB user permissions. -* `github.com/aws/aws-sdk-go-v2/service/drs`: [v1.7.0](service/drs/CHANGELOG.md#v170-2022-07-15) - * **Feature**: Changed existing APIs to allow choosing a dynamic volume type for replicating volumes, to reduce costs for customers. -* `github.com/aws/aws-sdk-go-v2/service/evidently`: [v1.8.0](service/evidently/CHANGELOG.md#v180-2022-07-15) - * **Feature**: This release adds support for the new segmentation feature. -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.21.0](service/wafv2/CHANGELOG.md#v1210-2022-07-15) - * **Feature**: This SDK release provide customers ability to add sensitivity level for WAF SQLI Match Statements. - -# Release (2022-07-14) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/athena`: [v1.17.0](service/athena/CHANGELOG.md#v1170-2022-07-14) - * **Feature**: This release updates data types that contain either QueryExecutionId, NamedQueryId or ExpectedBucketOwner. Ids must be between 1 and 128 characters and contain only non-whitespace characters. ExpectedBucketOwner must be 12-digit string. -* `github.com/aws/aws-sdk-go-v2/service/codeartifact`: [v1.13.0](service/codeartifact/CHANGELOG.md#v1130-2022-07-14) - * **Feature**: This release introduces Package Origin Controls, a mechanism used to counteract Dependency Confusion attacks. Adds two new APIs, PutPackageOriginConfiguration and DescribePackage, and updates the ListPackage, DescribePackageVersion and ListPackageVersion APIs in support of the feature. -* `github.com/aws/aws-sdk-go-v2/service/configservice`: [v1.22.0](service/configservice/CHANGELOG.md#v1220-2022-07-14) - * **Feature**: Update ResourceType enum with values for Route53Resolver, Batch, DMS, Workspaces, Stepfunctions, SageMaker, ElasticLoadBalancingV2, MSK types -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.49.0](service/ec2/CHANGELOG.md#v1490-2022-07-14) - * **Feature**: This release adds flow logs for Transit Gateway to allow customers to gain deeper visibility and insights into network traffic through their Transit Gateways. -* `github.com/aws/aws-sdk-go-v2/service/fms`: [v1.18.0](service/fms/CHANGELOG.md#v1180-2022-07-14) - * **Feature**: Adds support for strict ordering in stateful rule groups in Network Firewall policies. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.28.0](service/glue/CHANGELOG.md#v1280-2022-07-14) - * **Feature**: This release adds an additional worker type for Glue Streaming jobs. -* `github.com/aws/aws-sdk-go-v2/service/inspector2`: [v1.7.0](service/inspector2/CHANGELOG.md#v170-2022-07-14) - * **Feature**: This release adds support for Inspector V2 scan configurations through the get and update configuration APIs. Currently this allows configuring ECR automated re-scan duration to lifetime or 180 days or 30 days. -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.30.0](service/kendra/CHANGELOG.md#v1300-2022-07-14) - * **Feature**: This release adds AccessControlConfigurations which allow you to redefine your document level access control without the need for content re-indexing. -* `github.com/aws/aws-sdk-go-v2/service/nimble`: [v1.13.0](service/nimble/CHANGELOG.md#v1130-2022-07-14) - * **Feature**: Amazon Nimble Studio adds support for IAM-based access to AWS resources for Nimble Studio components and custom studio components. Studio Component scripts use these roles on Nimble Studio workstation to mount filesystems, access S3 buckets, or other configured resources in the Studio's AWS account -* `github.com/aws/aws-sdk-go-v2/service/outposts`: [v1.22.0](service/outposts/CHANGELOG.md#v1220-2022-07-14) - * **Feature**: This release adds the ShipmentInformation and AssetInformationList fields to the GetOrder API response. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.36.0](service/sagemaker/CHANGELOG.md#v1360-2022-07-14) - * **Feature**: This release adds support for G5, P4d, and C6i instance types in Amazon SageMaker Inference and increases the number of hyperparameters that can be searched from 20 to 30 in Amazon SageMaker Automatic Model Tuning - -# Release (2022-07-13) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/appconfig`: [v1.13.0](service/appconfig/CHANGELOG.md#v1130-2022-07-13) - * **Feature**: Adding Create, Get, Update, Delete, and List APIs for new two new resources: Extensions and ExtensionAssociations. - -# Release (2022-07-12) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/networkmanager`: [v1.14.0](service/networkmanager/CHANGELOG.md#v1140-2022-07-12) - * **Feature**: This release adds general availability API support for AWS Cloud WAN. - -# Release (2022-07-11) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.48.0](service/ec2/CHANGELOG.md#v1480-2022-07-11) - * **Feature**: Build, manage, and monitor a unified global network that connects resources running across your cloud and on-premises environments using the AWS Cloud WAN APIs. -* `github.com/aws/aws-sdk-go-v2/service/redshift`: [v1.26.0](service/redshift/CHANGELOG.md#v1260-2022-07-11) - * **Feature**: This release adds a new --snapshot-arn field for describe-cluster-snapshots, describe-node-configuration-options, restore-from-cluster-snapshot, authorize-snapshot-acsess, and revoke-snapshot-acsess APIs. It allows customers to give a Redshift snapshot ARN or a Redshift Serverless ARN as input. -* `github.com/aws/aws-sdk-go-v2/service/redshiftserverless`: [v1.2.2](service/redshiftserverless/CHANGELOG.md#v122-2022-07-11) - * **Documentation**: Removed prerelease language for GA launch. - -# Release (2022-07-08) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/backup`: [v1.17.0](service/backup/CHANGELOG.md#v1170-2022-07-08) - * **Feature**: This release adds support for authentication using IAM user identity instead of passed IAM role, identified by excluding the IamRoleArn field in the StartRestoreJob API. This feature applies to only resource clients with a destructive restore nature (e.g. SAP HANA). - -# Release (2022-07-07) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmeetings`: [v1.12.0](service/chimesdkmeetings/CHANGELOG.md#v1120-2022-07-07) - * **Feature**: Adds support for AppKeys and TenantIds in Amazon Chime SDK WebRTC sessions -* `github.com/aws/aws-sdk-go-v2/service/databasemigrationservice`: [v1.21.0](service/databasemigrationservice/CHANGELOG.md#v1210-2022-07-07) - * **Feature**: New api to migrate event subscriptions to event bridge rules -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.26.0](service/iot/CHANGELOG.md#v1260-2022-07-07) - * **Feature**: This release adds support to register a CA certificate without having to provide a verification certificate. This also allows multiple AWS accounts to register the same CA in the same region. -* `github.com/aws/aws-sdk-go-v2/service/iotwireless`: [v1.20.0](service/iotwireless/CHANGELOG.md#v1200-2022-07-07) - * **Feature**: Adds 5 APIs: PutPositionConfiguration, GetPositionConfiguration, ListPositionConfigurations, UpdatePosition, GetPosition for the new Positioning Service feature which enables customers to configure solvers to calculate position of LoRaWAN devices, or specify position of LoRaWAN devices & gateways. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.35.0](service/sagemaker/CHANGELOG.md#v1350-2022-07-07) - * **Feature**: Heterogeneous clusters: the ability to launch training jobs with multiple instance types. This enables running component of the training job on the instance type that is most suitable for it. e.g. doing data processing and augmentation on CPU instances and neural network training on GPU instances - -# Release (2022-07-06) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudformation`: [v1.22.0](service/cloudformation/CHANGELOG.md#v1220-2022-07-06) - * **Feature**: My AWS Service (placeholder) - Add a new feature Account-level Targeting for StackSet operation -* `github.com/aws/aws-sdk-go-v2/service/synthetics`: [v1.16.0](service/synthetics/CHANGELOG.md#v1160-2022-07-06) - * **Feature**: This release introduces Group feature, which enables users to group cross-region canaries. - -# Release (2022-07-05) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/configservice`: [v1.21.5](service/configservice/CHANGELOG.md#v1215-2022-07-05) - * **Documentation**: Updating documentation service limits -* `github.com/aws/aws-sdk-go-v2/service/lexmodelsv2`: [v1.21.0](service/lexmodelsv2/CHANGELOG.md#v1210-2022-07-05) - * **Feature**: This release introduces additional optional parameters "messageSelectionStrategy" to PromptSpecification, which enables the users to configure the bot to play messages in orderly manner. -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.23.0](service/quicksight/CHANGELOG.md#v1230-2022-07-05) - * **Feature**: This release allows customers to programmatically create QuickSight accounts with Enterprise and Enterprise + Q editions. It also releases allowlisting domains for embedding QuickSight dashboards at runtime through the embedding APIs. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.22.0](service/rds/CHANGELOG.md#v1220-2022-07-05) - * **Feature**: Adds waiters support for DBCluster. -* `github.com/aws/aws-sdk-go-v2/service/rolesanywhere`: [v1.0.0](service/rolesanywhere/CHANGELOG.md#v100-2022-07-05) - * **Release**: New AWS service client module - * **Feature**: IAM Roles Anywhere allows your workloads such as servers, containers, and applications to obtain temporary AWS credentials and use the same IAM roles and policies that you have configured for your AWS workloads to access AWS resources. -* `github.com/aws/aws-sdk-go-v2/service/sqs`: [v1.19.0](service/sqs/CHANGELOG.md#v1190-2022-07-05) - * **Feature**: Adds support for the SQS client to automatically validate message checksums for SendMessage, SendMessageBatch, and ReceiveMessage. A DisableMessageChecksumValidation parameter has been added to the Options struct for SQS package. Setting this to true will disable the checksum validation. This can be set when creating a client, or per operation call. -* `github.com/aws/aws-sdk-go-v2/service/ssmincidents`: [v1.15.0](service/ssmincidents/CHANGELOG.md#v1150-2022-07-05) - * **Feature**: Adds support for tagging incident-record on creation by providing incident tags in the template within a response-plan. - -# Release (2022-07-01) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/databasemigrationservice`: [v1.20.0](service/databasemigrationservice/CHANGELOG.md#v1200-2022-07-01) - * **Feature**: Added new features for AWS DMS version 3.4.7 that includes new endpoint settings for S3, OpenSearch, Postgres, SQLServer and Oracle. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.21.5](service/rds/CHANGELOG.md#v1215-2022-07-01) - * **Documentation**: Adds support for additional retention periods to Performance Insights. -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.27.0](service/s3/CHANGELOG.md#v1270-2022-07-01) - * **Feature**: Add presign support for HeadBucket, DeleteObject, and DeleteBucket. Fixes [#1076](https://github.com/aws/aws-sdk-go-v2/issues/1076). - -# Release (2022-06-30) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/athena`: [v1.16.0](service/athena/CHANGELOG.md#v1160-2022-06-30) - * **Feature**: This feature introduces the API support for Athena's parameterized query and BatchGetPreparedStatement API. -* `github.com/aws/aws-sdk-go-v2/service/customerprofiles`: [v1.18.0](service/customerprofiles/CHANGELOG.md#v1180-2022-06-30) - * **Feature**: This release adds the optional MinAllowedConfidenceScoreForMerging parameter to the CreateDomain, UpdateDomain, and GetAutoMergingPreview APIs in Customer Profiles. This parameter is used as a threshold to influence the profile auto-merging step of the Identity Resolution process. -* `github.com/aws/aws-sdk-go-v2/service/emr`: [v1.20.0](service/emr/CHANGELOG.md#v1200-2022-06-30) - * **Feature**: This release adds support for the ExecutionRoleArn parameter in the AddJobFlowSteps and DescribeStep APIs. Customers can use ExecutionRoleArn to specify the IAM role used for each job they submit using the AddJobFlowSteps API. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.27.0](service/glue/CHANGELOG.md#v1270-2022-06-30) - * **Feature**: This release adds tag as an input of CreateDatabase -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.29.0](service/kendra/CHANGELOG.md#v1290-2022-06-30) - * **Feature**: Amazon Kendra now provides a data source connector for alfresco -* `github.com/aws/aws-sdk-go-v2/service/mwaa`: [v1.13.0](service/mwaa/CHANGELOG.md#v1130-2022-06-30) - * **Feature**: Documentation updates for Amazon Managed Workflows for Apache Airflow. -* `github.com/aws/aws-sdk-go-v2/service/pricing`: [v1.16.0](service/pricing/CHANGELOG.md#v1160-2022-06-30) - * **Feature**: Documentation update for GetProducts Response. -* `github.com/aws/aws-sdk-go-v2/service/wellarchitected`: [v1.16.0](service/wellarchitected/CHANGELOG.md#v1160-2022-06-30) - * **Feature**: Added support for UpdateGlobalSettings API. Added status filter to ListWorkloadShares and ListLensShares. -* `github.com/aws/aws-sdk-go-v2/service/workmail`: [v1.16.0](service/workmail/CHANGELOG.md#v1160-2022-06-30) - * **Feature**: This release adds support for managing user availability configurations in Amazon WorkMail. - -# Release (2022-06-29) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2`: v1.16.6 - * **Bug Fix**: Fix aws/signer/v4 to not double sign Content-Length header. Fixes [#1728](https://github.com/aws/aws-sdk-go-v2/issues/1728). Thanks to @matelang for creating the issue and PR. -* `github.com/aws/aws-sdk-go-v2/service/appstream`: [v1.17.0](service/appstream/CHANGELOG.md#v1170-2022-06-29) - * **Feature**: Includes support for StreamingExperienceSettings in CreateStack and UpdateStack APIs -* `github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2`: [v1.18.7](service/elasticloadbalancingv2/CHANGELOG.md#v1187-2022-06-29) - * **Documentation**: This release adds two attributes for ALB. One, helps to preserve the host header and the other helps to modify, preserve, or remove the X-Forwarded-For header in the HTTP request. -* `github.com/aws/aws-sdk-go-v2/service/emr`: [v1.19.0](service/emr/CHANGELOG.md#v1190-2022-06-29) - * **Feature**: This release introduces additional optional parameter "Throughput" to VolumeSpecification to enable user to configure throughput for gp3 ebs volumes. -* `github.com/aws/aws-sdk-go-v2/service/medialive`: [v1.21.0](service/medialive/CHANGELOG.md#v1210-2022-06-29) - * **Feature**: This release adds support for automatic renewal of MediaLive reservations at the end of each reservation term. Automatic renewal is optional. This release also adds support for labelling accessibility-focused audio and caption tracks in HLS outputs. -* `github.com/aws/aws-sdk-go-v2/service/redshiftserverless`: [v1.2.0](service/redshiftserverless/CHANGELOG.md#v120-2022-06-29) - * **Feature**: Add new API operations for Amazon Redshift Serverless, a new way of using Amazon Redshift without needing to manually manage provisioned clusters. The new operations let you interact with Redshift Serverless resources, such as create snapshots, list VPC endpoints, delete resource policies, and more. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.34.0](service/sagemaker/CHANGELOG.md#v1340-2022-06-29) - * **Feature**: This release adds: UpdateFeatureGroup, UpdateFeatureMetadata, DescribeFeatureMetadata APIs; FeatureMetadata type in Search API; LastModifiedTime, LastUpdateStatus, OnlineStoreTotalSizeBytes in DescribeFeatureGroup API. -* `github.com/aws/aws-sdk-go-v2/service/translate`: [v1.14.0](service/translate/CHANGELOG.md#v1140-2022-06-29) - * **Feature**: Added ListLanguages API which can be used to list the languages supported by Translate. - -# Release (2022-06-28) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/datasync`: [v1.18.0](service/datasync/CHANGELOG.md#v1180-2022-06-28) - * **Feature**: AWS DataSync now supports Amazon FSx for NetApp ONTAP locations. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.47.0](service/ec2/CHANGELOG.md#v1470-2022-06-28) - * **Feature**: This release adds a new spread placement group to EC2 Placement Groups: host level spread, which spread instances between physical hosts, available to Outpost customers only. CreatePlacementGroup and DescribePlacementGroups APIs were updated with a new parameter: SpreadLevel to support this feature. -* `github.com/aws/aws-sdk-go-v2/service/finspacedata`: [v1.12.0](service/finspacedata/CHANGELOG.md#v1120-2022-06-28) - * **Feature**: Release new API GetExternalDataViewAccessDetails -* `github.com/aws/aws-sdk-go-v2/service/polly`: [v1.16.0](service/polly/CHANGELOG.md#v1160-2022-06-28) - * **Feature**: Add 4 new neural voices - Pedro (es-US), Liam (fr-CA), Daniel (de-DE) and Arthur (en-GB). - -# Release (2022-06-24.2) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/emrcontainers`: [v1.13.7](service/emrcontainers/CHANGELOG.md#v1137-2022-06-242) - * **Bug Fix**: Fixes bug with incorrect modeled timestamp format - -# Release (2022-06-23) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/lookoutequipment`: [v1.14.0](service/lookoutequipment/CHANGELOG.md#v1140-2022-06-23) - * **Feature**: This release adds visualizations to the scheduled inference results. Users will be able to see interference results, including diagnostic results from their running inference schedulers. -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.25.1](service/mediaconvert/CHANGELOG.md#v1251-2022-06-23) - * **Documentation**: AWS Elemental MediaConvert SDK has released support for automatic DolbyVision metadata generation when converting HDR10 to DolbyVision. -* `github.com/aws/aws-sdk-go-v2/service/mgn`: [v1.15.0](service/mgn/CHANGELOG.md#v1150-2022-06-23) - * **Feature**: New and modified APIs for the Post-Migration Framework -* `github.com/aws/aws-sdk-go-v2/service/migrationhubrefactorspaces`: [v1.6.0](service/migrationhubrefactorspaces/CHANGELOG.md#v160-2022-06-23) - * **Feature**: This release adds the new API UpdateRoute that allows route to be updated to ACTIVE/INACTIVE state. In addition, CreateRoute API will now allow users to create route in ACTIVE/INACTIVE state. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.33.0](service/sagemaker/CHANGELOG.md#v1330-2022-06-23) - * **Feature**: SageMaker Ground Truth now supports Virtual Private Cloud. Customers can launch labeling jobs and access to their private workforce in VPC mode. - -# Release (2022-06-22) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/apigateway`: [v1.15.8](service/apigateway/CHANGELOG.md#v1158-2022-06-22) - * **Documentation**: Documentation updates for Amazon API Gateway -* `github.com/aws/aws-sdk-go-v2/service/pricing`: [v1.15.0](service/pricing/CHANGELOG.md#v1150-2022-06-22) - * **Feature**: This release introduces 1 update to the GetProducts API. The serviceCode attribute is now required when you use the GetProductsRequest. -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.20.0](service/transfer/CHANGELOG.md#v1200-2022-06-22) - * **Feature**: Until today, the service supported only RSA host keys and user keys. Now with this launch, Transfer Family has expanded the support for ECDSA and ED25519 host keys and user keys, enabling customers to support a broader set of clients by choosing RSA, ECDSA, and ED25519 host and user keys. - -# Release (2022-06-21) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.46.0](service/ec2/CHANGELOG.md#v1460-2022-06-21) - * **Feature**: This release adds support for Private IP VPNs, a new feature allowing S2S VPN connections to use private ip addresses as the tunnel outside ip address over Direct Connect as transport. -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.18.9](service/ecs/CHANGELOG.md#v1189-2022-06-21) - * **Documentation**: Amazon ECS UpdateService now supports the following parameters: PlacementStrategies, PlacementConstraints and CapacityProviderStrategy. -* `github.com/aws/aws-sdk-go-v2/service/wellarchitected`: [v1.15.0](service/wellarchitected/CHANGELOG.md#v1150-2022-06-21) - * **Feature**: Adds support for lens tagging, Adds support for multiple helpful-resource urls and multiple improvement-plan urls. - -# Release (2022-06-20) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/directoryservice`: [v1.14.0](service/directoryservice/CHANGELOG.md#v1140-2022-06-20) - * **Feature**: This release adds support for describing and updating AWS Managed Microsoft AD settings -* `github.com/aws/aws-sdk-go-v2/service/kafka`: [v1.17.7](service/kafka/CHANGELOG.md#v1177-2022-06-20) - * **Documentation**: Documentation updates to use Az Id during cluster creation. -* `github.com/aws/aws-sdk-go-v2/service/outposts`: [v1.21.0](service/outposts/CHANGELOG.md#v1210-2022-06-20) - * **Feature**: This release adds the AssetLocation structure to the ListAssets response. AssetLocation includes the RackElevation for an Asset. - -# Release (2022-06-17) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.27.0](service/connect/CHANGELOG.md#v1270-2022-06-17) - * **Feature**: This release updates these APIs: UpdateInstanceAttribute, DescribeInstanceAttribute and ListInstanceAttributes. You can use it to programmatically enable/disable High volume outbound communications using attribute type HIGH_VOLUME_OUTBOUND on the specified Amazon Connect instance. -* `github.com/aws/aws-sdk-go-v2/service/connectcampaigns`: [v1.0.0](service/connectcampaigns/CHANGELOG.md#v100-2022-06-17) - * **Release**: New AWS service client module - * **Feature**: Added Amazon Connect high volume outbound communications SDK. -* `github.com/aws/aws-sdk-go-v2/service/dynamodb`: [v1.15.7](service/dynamodb/CHANGELOG.md#v1157-2022-06-17) - * **Documentation**: Doc only update for DynamoDB service -* `github.com/aws/aws-sdk-go-v2/service/dynamodbstreams`: [v1.13.7](service/dynamodbstreams/CHANGELOG.md#v1137-2022-06-17) - * **Documentation**: Doc only update for DynamoDB service - -# Release (2022-06-16) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/redshiftdata`: [v1.16.0](service/redshiftdata/CHANGELOG.md#v1160-2022-06-16) - * **Feature**: This release adds a new --workgroup-name field to operations that connect to an endpoint. Customers can now execute queries against their serverless workgroups. -* `github.com/aws/aws-sdk-go-v2/service/redshiftserverless`: [v1.1.0](service/redshiftserverless/CHANGELOG.md#v110-2022-06-16) - * **Feature**: Add new API operations for Amazon Redshift Serverless, a new way of using Amazon Redshift without needing to manually manage provisioned clusters. The new operations let you interact with Redshift Serverless resources, such as create snapshots, list VPC endpoints, delete resource policies, and more. -* `github.com/aws/aws-sdk-go-v2/service/secretsmanager`: [v1.15.11](service/secretsmanager/CHANGELOG.md#v11511-2022-06-16) - * **Documentation**: Documentation updates for Secrets Manager -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.22.0](service/securityhub/CHANGELOG.md#v1220-2022-06-16) - * **Feature**: Added Threats field for security findings. Added new resource details for ECS Container, ECS Task, RDS SecurityGroup, Kinesis Stream, EC2 TransitGateway, EFS AccessPoint, CloudFormation Stack, CloudWatch Alarm, VPC Peering Connection and WAF Rules - -# Release (2022-06-15) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/finspacedata`: [v1.11.0](service/finspacedata/CHANGELOG.md#v1110-2022-06-15) - * **Feature**: This release adds a new set of APIs, GetPermissionGroup, DisassociateUserFromPermissionGroup, AssociateUserToPermissionGroup, ListPermissionGroupsByUser, ListUsersByPermissionGroup. -* `github.com/aws/aws-sdk-go-v2/service/guardduty`: [v1.14.0](service/guardduty/CHANGELOG.md#v1140-2022-06-15) - * **Feature**: Adds finding fields available from GuardDuty Console. Adds FreeTrial related operations. Deprecates the use of various APIs related to Master Accounts and Replace them with Administrator Accounts. -* `github.com/aws/aws-sdk-go-v2/service/servicecatalogappregistry`: [v1.13.0](service/servicecatalogappregistry/CHANGELOG.md#v1130-2022-06-15) - * **Feature**: This release adds a new API ListAttributeGroupsForApplication that returns associated attribute groups of an application. In addition, the UpdateApplication and UpdateAttributeGroup APIs will not allow users to update the 'Name' attribute. -* `github.com/aws/aws-sdk-go-v2/service/workspaces`: [v1.19.0](service/workspaces/CHANGELOG.md#v1190-2022-06-15) - * **Feature**: Added new field "reason" to OperationNotSupportedException. Receiving this exception in the DeregisterWorkspaceDirectory API will now return a reason giving more context on the failure. - -# Release (2022-06-14) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/budgets`: [v1.13.0](service/budgets/CHANGELOG.md#v1130-2022-06-14) - * **Feature**: Add a budgets ThrottlingException. Update the CostFilters value pattern. -* `github.com/aws/aws-sdk-go-v2/service/lookoutmetrics`: [v1.16.0](service/lookoutmetrics/CHANGELOG.md#v1160-2022-06-14) - * **Feature**: Adding filters to Alert and adding new UpdateAlert API. -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.25.0](service/mediaconvert/CHANGELOG.md#v1250-2022-06-14) - * **Feature**: AWS Elemental MediaConvert SDK has added support for rules that constrain Automatic-ABR rendition selection when generating ABR package ladders. - -# Release (2022-06-13) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/outposts`: [v1.20.0](service/outposts/CHANGELOG.md#v1200-2022-06-13) - * **Feature**: This release adds API operations AWS uses to install Outpost servers. - -# Release (2022-06-10) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/frauddetector`: [v1.19.7](service/frauddetector/CHANGELOG.md#v1197-2022-06-10) - * **Documentation**: Documentation updates for Amazon Fraud Detector (AWSHawksNest) - -# Release (2022-06-09) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmeetings`: [v1.11.0](service/chimesdkmeetings/CHANGELOG.md#v1110-2022-06-09) - * **Feature**: Adds support for live transcription in AWS GovCloud (US) Regions. - -# Release (2022-06-08) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/databasemigrationservice`: [v1.19.0](service/databasemigrationservice/CHANGELOG.md#v1190-2022-06-08) - * **Feature**: This release adds DMS Fleet Advisor APIs and exposes functionality for DMS Fleet Advisor. It adds functionality to create and modify fleet advisor instances, and to collect and analyze information about the local data infrastructure. -* `github.com/aws/aws-sdk-go-v2/service/iam`: [v1.18.7](service/iam/CHANGELOG.md#v1187-2022-06-08) - * **Documentation**: Documentation updates for AWS Identity and Access Management (IAM). -* `github.com/aws/aws-sdk-go-v2/service/m2`: [v1.0.0](service/m2/CHANGELOG.md#v100-2022-06-08) - * **Release**: New AWS service client module - * **Feature**: AWS Mainframe Modernization service is a managed mainframe service and set of tools for planning, migrating, modernizing, and running mainframe workloads on AWS -* `github.com/aws/aws-sdk-go-v2/service/neptune`: [v1.17.0](service/neptune/CHANGELOG.md#v1170-2022-06-08) - * **Feature**: This release adds support for Neptune to be configured as a global database, with a primary DB cluster in one region, and up to five secondary DB clusters in other regions. -* `github.com/aws/aws-sdk-go-v2/service/redshift`: [v1.25.0](service/redshift/CHANGELOG.md#v1250-2022-06-08) - * **Feature**: Adds new API GetClusterCredentialsWithIAM to return temporary credentials. -* `github.com/aws/aws-sdk-go-v2/service/redshiftserverless`: [v1.0.0](service/redshiftserverless/CHANGELOG.md#v100-2022-06-08) - * **Release**: New AWS service client module - * **Feature**: Add new API operations for Amazon Redshift Serverless, a new way of using Amazon Redshift without needing to manually manage provisioned clusters. The new operations let you interact with Redshift Serverless resources, such as create snapshots, list VPC endpoints, delete resource policies, and more. - -# Release (2022-06-07) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/auditmanager`: [v1.19.0](service/auditmanager/CHANGELOG.md#v1190-2022-06-07) - * **Feature**: This release introduces 2 updates to the Audit Manager API. The roleType and roleArn attributes are now required when you use the CreateAssessment or UpdateAssessment operation. We also added a throttling exception to the RegisterAccount API operation. -* `github.com/aws/aws-sdk-go-v2/service/costexplorer`: [v1.19.0](service/costexplorer/CHANGELOG.md#v1190-2022-06-07) - * **Feature**: Added two new APIs to support cost allocation tags operations: ListCostAllocationTags, UpdateCostAllocationTagsStatus. - -# Release (2022-06-06) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmessaging`: [v1.10.0](service/chimesdkmessaging/CHANGELOG.md#v1100-2022-06-06) - * **Feature**: This release adds support for searching channels by members via the SearchChannels API, removes required restrictions for Name and Mode in UpdateChannel API and enhances CreateChannel API by exposing member and moderator list as well as channel id as optional parameters. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.26.0](service/connect/CHANGELOG.md#v1260-2022-06-06) - * **Feature**: This release adds a new API, GetCurrentUserData, which returns real-time details about users' current activity. - -# Release (2022-06-02) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/applicationinsights`: [v1.16.0](service/applicationinsights/CHANGELOG.md#v1160-2022-06-02) - * **Feature**: Provide Account Level onboarding support through CFN/CLI -* `github.com/aws/aws-sdk-go-v2/service/codeartifact`: [v1.12.6](service/codeartifact/CHANGELOG.md#v1126-2022-06-02) - * **Documentation**: Documentation updates for CodeArtifact -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.25.0](service/connect/CHANGELOG.md#v1250-2022-06-02) - * **Feature**: This release adds the following features: 1) New APIs to manage (create, list, update) task template resources, 2) Updates to startTaskContact API to support task templates, and 3) new TransferContact API to programmatically transfer in-progress tasks via a contact flow. -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.28.0](service/kendra/CHANGELOG.md#v1280-2022-06-02) - * **Feature**: Amazon Kendra now provides a data source connector for GitHub. For more information, see https://docs.aws.amazon.com/kendra/latest/dg/data-source-github.html -* `github.com/aws/aws-sdk-go-v2/service/proton`: [v1.14.0](service/proton/CHANGELOG.md#v1140-2022-06-02) - * **Feature**: Add new "Components" API to enable users to Create, Delete and Update AWS Proton components. -* `github.com/aws/aws-sdk-go-v2/service/voiceid`: [v1.10.0](service/voiceid/CHANGELOG.md#v1100-2022-06-02) - * **Feature**: Added a new attribute ServerSideEncryptionUpdateDetails to Domain and DomainSummary. - -# Release (2022-06-01) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/backupgateway`: [v1.6.0](service/backupgateway/CHANGELOG.md#v160-2022-06-01) - * **Feature**: Adds GetGateway and UpdateGatewaySoftwareNow API and adds hypervisor name to UpdateHypervisor API -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmeetings`: [v1.10.0](service/chimesdkmeetings/CHANGELOG.md#v1100-2022-06-01) - * **Feature**: Adds support for centrally controlling each participant's ability to send and receive audio, video and screen share within a WebRTC session. Attendee capabilities can be specified when the attendee is created and updated during the session with the new BatchUpdateAttendeeCapabilitiesExcept API. -* `github.com/aws/aws-sdk-go-v2/service/forecast`: [v1.22.0](service/forecast/CHANGELOG.md#v1220-2022-06-01) - * **Feature**: Added Format field to Import and Export APIs in Amazon Forecast. Added TimeSeriesSelector to Create Forecast API. -* `github.com/aws/aws-sdk-go-v2/service/route53`: [v1.21.0](service/route53/CHANGELOG.md#v1210-2022-06-01) - * **Feature**: Add new APIs to support Route 53 IP Based Routing - -# Release (2022-05-31) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider`: [v1.17.0](service/cognitoidentityprovider/CHANGELOG.md#v1170-2022-05-31) - * **Feature**: Amazon Cognito now supports IP Address propagation for all unauthenticated APIs (e.g. SignUp, ForgotPassword). -* `github.com/aws/aws-sdk-go-v2/service/drs`: [v1.6.0](service/drs/CHANGELOG.md#v160-2022-05-31) - * **Feature**: Changed existing APIs and added new APIs to accommodate using multiple AWS accounts with AWS Elastic Disaster Recovery. -* `github.com/aws/aws-sdk-go-v2/service/iotsitewise`: [v1.22.0](service/iotsitewise/CHANGELOG.md#v1220-2022-05-31) - * **Feature**: This release adds the following new optional field to the IoT SiteWise asset resource: assetDescription. -* `github.com/aws/aws-sdk-go-v2/service/lookoutmetrics`: [v1.15.0](service/lookoutmetrics/CHANGELOG.md#v1150-2022-05-31) - * **Feature**: Adding backtest mode to detectors using the Cloudwatch data source. -* `github.com/aws/aws-sdk-go-v2/service/transcribe`: [v1.20.0](service/transcribe/CHANGELOG.md#v1200-2022-05-31) - * **Feature**: Amazon Transcribe now supports automatic language identification for multi-lingual audio in batch mode. - -# Release (2022-05-27) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/appflow`: [v1.16.0](service/appflow/CHANGELOG.md#v1160-2022-05-27) - * **Feature**: Adding the following features/changes: Parquet output that preserves typing from the source connector, Failed executions threshold before deactivation for scheduled flows, increasing max size of access and refresh token from 2048 to 4096 -* `github.com/aws/aws-sdk-go-v2/service/datasync`: [v1.17.0](service/datasync/CHANGELOG.md#v1170-2022-05-27) - * **Feature**: AWS DataSync now supports TLS encryption in transit, file system policies and access points for EFS locations. -* `github.com/aws/aws-sdk-go-v2/service/emrserverless`: [v1.1.0](service/emrserverless/CHANGELOG.md#v110-2022-05-27) - * **Feature**: This release adds support for Amazon EMR Serverless, a serverless runtime environment that simplifies running analytics applications using the latest open source frameworks such as Apache Spark and Apache Hive. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.32.0](service/sagemaker/CHANGELOG.md#v1320-2022-05-27) - * **Feature**: Amazon SageMaker Notebook Instances now allows configuration of Instance Metadata Service version and Amazon SageMaker Studio now supports G5 instance types. - -# Release (2022-05-26) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.45.0](service/ec2/CHANGELOG.md#v1450-2022-05-26) - * **Feature**: C7g instances, powered by the latest generation AWS Graviton3 processors, provide the best price performance in Amazon EC2 for compute-intensive workloads. -* `github.com/aws/aws-sdk-go-v2/service/emrserverless`: [v1.0.0](service/emrserverless/CHANGELOG.md#v100-2022-05-26) - * **Release**: New AWS service client module - * **Feature**: This release adds support for Amazon EMR Serverless, a serverless runtime environment that simplifies running analytics applications using the latest open source frameworks such as Apache Spark and Apache Hive. -* `github.com/aws/aws-sdk-go-v2/service/forecast`: [v1.21.0](service/forecast/CHANGELOG.md#v1210-2022-05-26) - * **Feature**: Introduced a new field in Auto Predictor as Time Alignment Boundary. It helps in aligning the timestamps generated during Forecast exports -* `github.com/aws/aws-sdk-go-v2/service/lightsail`: [v1.22.0](service/lightsail/CHANGELOG.md#v1220-2022-05-26) - * **Feature**: Amazon Lightsail now supports the ability to configure a Lightsail Container Service to pull images from Amazon ECR private repositories in your account. - -# Release (2022-05-25) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/apigateway`: [v1.15.6](service/apigateway/CHANGELOG.md#v1156-2022-05-25) - * **Documentation**: Documentation updates for Amazon API Gateway -* `github.com/aws/aws-sdk-go-v2/service/apprunner`: [v1.12.3](service/apprunner/CHANGELOG.md#v1123-2022-05-25) - * **Documentation**: Documentation-only update added for CodeConfiguration. -* `github.com/aws/aws-sdk-go-v2/service/cloudformation`: [v1.21.0](service/cloudformation/CHANGELOG.md#v1210-2022-05-25) - * **Feature**: Add a new parameter statusReason to DescribeStackSetOperation output for additional details -* `github.com/aws/aws-sdk-go-v2/service/fsx`: [v1.24.0](service/fsx/CHANGELOG.md#v1240-2022-05-25) - * **Feature**: This release adds root squash support to FSx for Lustre to restrict root level access from clients by mapping root users to a less-privileged user/group with limited permissions. -* `github.com/aws/aws-sdk-go-v2/service/lookoutmetrics`: [v1.14.0](service/lookoutmetrics/CHANGELOG.md#v1140-2022-05-25) - * **Feature**: Adding AthenaSourceConfig for MetricSet APIs to support Athena as a data source. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.31.0](service/sagemaker/CHANGELOG.md#v1310-2022-05-25) - * **Feature**: Amazon SageMaker Autopilot adds support for manually selecting features from the input dataset using the CreateAutoMLJob API. -* `github.com/aws/aws-sdk-go-v2/service/secretsmanager`: [v1.15.9](service/secretsmanager/CHANGELOG.md#v1159-2022-05-25) - * **Documentation**: Documentation updates for Secrets Manager -* `github.com/aws/aws-sdk-go-v2/service/voiceid`: [v1.9.0](service/voiceid/CHANGELOG.md#v190-2022-05-25) - * **Feature**: VoiceID will now automatically expire Speakers if they haven't been accessed for Enrollment, Re-enrollment or Successful Auth for three years. The Speaker APIs now return a "LastAccessedAt" time for Speakers, and the EvaluateSession API returns "SPEAKER_EXPIRED" Auth Decision for EXPIRED Speakers. - -# Release (2022-05-24) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider`: [v1.16.0](service/cognitoidentityprovider/CHANGELOG.md#v1160-2022-05-24) - * **Feature**: Amazon Cognito now supports requiring attribute verification (ex. email and phone number) before update. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.44.0](service/ec2/CHANGELOG.md#v1440-2022-05-24) - * **Feature**: Stop Protection feature enables customers to protect their instances from accidental stop actions. -* `github.com/aws/aws-sdk-go-v2/service/ivschat`: [v1.0.4](service/ivschat/CHANGELOG.md#v104-2022-05-24) - * **Documentation**: Doc-only update. For MessageReviewHandler structure, added timeout period in the description of the fallbackResult field -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.24.0](service/mediaconvert/CHANGELOG.md#v1240-2022-05-24) - * **Feature**: AWS Elemental MediaConvert SDK has added support for rules that constrain Automatic-ABR rendition selection when generating ABR package ladders. -* `github.com/aws/aws-sdk-go-v2/service/networkmanager`: [v1.13.0](service/networkmanager/CHANGELOG.md#v1130-2022-05-24) - * **Feature**: This release adds Multi Account API support for a TGW Global Network, to enable and disable AWSServiceAccess with AwsOrganizations for Network Manager service and dependency CloudFormation StackSets service. - -# Release (2022-05-23) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/elasticache`: [v1.21.0](service/elasticache/CHANGELOG.md#v1210-2022-05-23) - * **Feature**: Added support for encryption in transit for Memcached clusters. Customers can now launch Memcached cluster with encryption in transit enabled when using Memcached version 1.6.12 or later. -* `github.com/aws/aws-sdk-go-v2/service/forecast`: [v1.20.0](service/forecast/CHANGELOG.md#v1200-2022-05-23) - * **Feature**: New APIs for Monitor that help you understand how your predictors perform over time. -* `github.com/aws/aws-sdk-go-v2/service/personalize`: [v1.20.0](service/personalize/CHANGELOG.md#v1200-2022-05-23) - * **Feature**: Adding modelMetrics as part of DescribeRecommender API response for Personalize. - -# Release (2022-05-20) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs`: [v1.15.7](service/cloudwatchlogs/CHANGELOG.md#v1157-2022-05-20) - * **Documentation**: Doc-only update to publish the new valid values for log retention -* `github.com/aws/aws-sdk-go-v2/service/comprehend`: [v1.18.0](service/comprehend/CHANGELOG.md#v1180-2022-05-20) - * **Feature**: Comprehend releases 14 new entity types for DetectPiiEntities and ContainsPiiEntities APIs. - -# Release (2022-05-19) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/gamesparks`: [v1.1.0](service/gamesparks/CHANGELOG.md#v110-2022-05-19) - * **Feature**: This release adds an optional DeploymentResult field in the responses of GetStageDeploymentIntegrationTests and ListStageDeploymentIntegrationTests APIs. -* `github.com/aws/aws-sdk-go-v2/service/lookoutmetrics`: [v1.13.0](service/lookoutmetrics/CHANGELOG.md#v1130-2022-05-19) - * **Feature**: In this release we added SnsFormat to SNSConfiguration to support human readable alert. - -# Release (2022-05-18) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/appmesh`: [v1.14.0](service/appmesh/CHANGELOG.md#v1140-2022-05-18) - * **Feature**: This release updates the existing Create and Update APIs for meshes and virtual nodes by adding a new IP preference field. This new IP preference field can be used to control the IP versions being used with the mesh and allows for IPv6 support within App Mesh. -* `github.com/aws/aws-sdk-go-v2/service/batch`: [v1.18.3](service/batch/CHANGELOG.md#v1183-2022-05-18) - * **Documentation**: Documentation updates for AWS Batch. -* `github.com/aws/aws-sdk-go-v2/service/greengrassv2`: [v1.16.0](service/greengrassv2/CHANGELOG.md#v1160-2022-05-18) - * **Feature**: This release adds the new DeleteDeployment API operation that you can use to delete deployment resources. This release also adds support for discontinued AWS-provided components, so AWS can communicate when a component has any issues that you should consider before you deploy it. -* `github.com/aws/aws-sdk-go-v2/service/ioteventsdata`: [v1.12.0](service/ioteventsdata/CHANGELOG.md#v1120-2022-05-18) - * **Feature**: Introducing new API for deleting detectors: BatchDeleteDetector. -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.22.0](service/quicksight/CHANGELOG.md#v1220-2022-05-18) - * **Feature**: API UpdatePublicSharingSettings enables IAM admins to enable/disable account level setting for public access of dashboards. When enabled, owners/co-owners for dashboards can enable public access on their dashboards. These dashboards can only be accessed through share link or embedding. -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.19.0](service/transfer/CHANGELOG.md#v1190-2022-05-18) - * **Feature**: AWS Transfer Family now supports SetStat server configuration option, which provides the ability to ignore SetStat command issued by file transfer clients, enabling customers to upload files without any errors. - -# Release (2022-05-17) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/internal/ini`: [v1.3.12](internal/ini/CHANGELOG.md#v1312-2022-05-17) - * **Bug Fix**: Removes the fuzz testing files from the module, as they are invalid and not used. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.25.0](service/glue/CHANGELOG.md#v1250-2022-05-17) - * **Feature**: This release adds a new optional parameter called codeGenNodeConfiguration to CRUD job APIs that allows users to manage visual jobs via APIs. The updated CreateJob and UpdateJob will create jobs that can be viewed in Glue Studio as a visual graph. GetJob can be used to get codeGenNodeConfiguration. -* `github.com/aws/aws-sdk-go-v2/service/iotsecuretunneling`: [v1.13.1](service/iotsecuretunneling/CHANGELOG.md#v1131-2022-05-17) - * **Bug Fix**: Fixes iotsecuretunneling and mobile API clients to use the correct name for signing requests, Fixes [#1686](https://github.com/aws/aws-sdk-go-v2/issues/1686). -* `github.com/aws/aws-sdk-go-v2/service/kms`: [v1.17.2](service/kms/CHANGELOG.md#v1172-2022-05-17) - * **Documentation**: Add HMAC best practice tip, annual rotation of AWS managed keys. -* `github.com/aws/aws-sdk-go-v2/service/mobile`: [v1.11.5](service/mobile/CHANGELOG.md#v1115-2022-05-17) - * **Bug Fix**: Fixes iotsecuretunneling and mobile API clients to use the correct name for signing requests, Fixes [#1686](https://github.com/aws/aws-sdk-go-v2/issues/1686). - -# Release (2022-05-16) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/applicationdiscoveryservice`: [v1.13.0](service/applicationdiscoveryservice/CHANGELOG.md#v1130-2022-05-16) - * **Feature**: Add Migration Evaluator Collector details to the GetDiscoverySummary API response -* `github.com/aws/aws-sdk-go-v2/service/cloudfront`: [v1.18.0](service/cloudfront/CHANGELOG.md#v1180-2022-05-16) - * **Feature**: Introduced a new error (TooLongCSPInResponseHeadersPolicy) that is returned when the value of the Content-Security-Policy header in a response headers policy exceeds the maximum allowed length. -* `github.com/aws/aws-sdk-go-v2/service/rekognition`: [v1.18.1](service/rekognition/CHANGELOG.md#v1181-2022-05-16) - * **Documentation**: Documentation updates for Amazon Rekognition. -* `github.com/aws/aws-sdk-go-v2/service/resiliencehub`: [v1.6.0](service/resiliencehub/CHANGELOG.md#v160-2022-05-16) - * **Feature**: In this release, we are introducing support for Amazon Elastic Container Service, Amazon Route 53, AWS Elastic Disaster Recovery, AWS Backup in addition to the existing supported Services. This release also supports Terraform file input from S3 and scheduling daily assessments -* `github.com/aws/aws-sdk-go-v2/service/servicecatalog`: [v1.14.2](service/servicecatalog/CHANGELOG.md#v1142-2022-05-16) - * **Documentation**: Updated the descriptions for the ListAcceptedPortfolioShares API description and the PortfolioShareType parameters. -* `github.com/aws/aws-sdk-go-v2/service/sts`: [v1.16.5](service/sts/CHANGELOG.md#v1165-2022-05-16) - * **Documentation**: Documentation updates for AWS Security Token Service. -* `github.com/aws/aws-sdk-go-v2/service/workspacesweb`: [v1.6.0](service/workspacesweb/CHANGELOG.md#v160-2022-05-16) - * **Feature**: Amazon WorkSpaces Web now supports Administrator timeout control - -# Release (2022-05-13) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/grafana`: [v1.9.0](service/grafana/CHANGELOG.md#v190-2022-05-13) - * **Feature**: This release adds APIs for creating and deleting API keys in an Amazon Managed Grafana workspace. - -# Release (2022-05-12) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.43.0](service/ec2/CHANGELOG.md#v1430-2022-05-12) - * **Feature**: This release introduces a target type Gateway Load Balancer Endpoint for mirrored traffic. Customers can now specify GatewayLoadBalancerEndpoint option during the creation of a traffic mirror target. -* `github.com/aws/aws-sdk-go-v2/service/finspacedata`: [v1.10.5](service/finspacedata/CHANGELOG.md#v1105-2022-05-12) - * **Documentation**: We've now deprecated CreateSnapshot permission for creating a data view, instead use CreateDataView permission. -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.25.1](service/iot/CHANGELOG.md#v1251-2022-05-12) - * **Documentation**: Documentation update for China region ListMetricValues for IoT -* `github.com/aws/aws-sdk-go-v2/service/ivschat`: [v1.0.2](service/ivschat/CHANGELOG.md#v102-2022-05-12) - * **Documentation**: Documentation-only updates for IVS Chat API Reference. -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.27.0](service/kendra/CHANGELOG.md#v1270-2022-05-12) - * **Feature**: Amazon Kendra now provides a data source connector for Jira. For more information, see https://docs.aws.amazon.com/kendra/latest/dg/data-source-jira.html -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.23.0](service/lambda/CHANGELOG.md#v1230-2022-05-12) - * **Feature**: Lambda releases NodeJs 16 managed runtime to be available in all commercial regions. -* `github.com/aws/aws-sdk-go-v2/service/lightsail`: [v1.21.0](service/lightsail/CHANGELOG.md#v1210-2022-05-12) - * **Feature**: This release adds support to include inactive database bundles in the response of the GetRelationalDatabaseBundles request. -* `github.com/aws/aws-sdk-go-v2/service/outposts`: [v1.19.1](service/outposts/CHANGELOG.md#v1191-2022-05-12) - * **Documentation**: Documentation updates for AWS Outposts. -* `github.com/aws/aws-sdk-go-v2/service/ssmincidents`: [v1.14.0](service/ssmincidents/CHANGELOG.md#v1140-2022-05-12) - * **Feature**: Adding support for dynamic SSM Runbook parameter values. Updating validation pattern for engagements. Adding ConflictException to UpdateReplicationSet API contract. -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.18.6](service/transfer/CHANGELOG.md#v1186-2022-05-12) - * **Documentation**: AWS Transfer Family now accepts ECDSA keys for server host keys - -# Release (2022-05-11) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.42.0](service/ec2/CHANGELOG.md#v1420-2022-05-11) - * **Feature**: This release updates AWS PrivateLink APIs to support IPv6 for PrivateLink Services and Endpoints of type 'Interface'. -* `github.com/aws/aws-sdk-go-v2/service/secretsmanager`: [v1.15.7](service/secretsmanager/CHANGELOG.md#v1157-2022-05-11) - * **Documentation**: Doc only update for Secrets Manager that fixes several customer-reported issues. - -# Release (2022-05-10) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/computeoptimizer`: [v1.17.5](service/computeoptimizer/CHANGELOG.md#v1175-2022-05-10) - * **Documentation**: Documentation updates for Compute Optimizer -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.41.0](service/ec2/CHANGELOG.md#v1410-2022-05-10) - * **Feature**: Added support for using NitroTPM and UEFI Secure Boot on EC2 instances. -* `github.com/aws/aws-sdk-go-v2/service/eks`: [v1.21.0](service/eks/CHANGELOG.md#v1210-2022-05-10) - * **Feature**: Adds BOTTLEROCKET_ARM_64_NVIDIA and BOTTLEROCKET_x86_64_NVIDIA AMI types to EKS managed nodegroups -* `github.com/aws/aws-sdk-go-v2/service/emr`: [v1.18.0](service/emr/CHANGELOG.md#v1180-2022-05-10) - * **Feature**: This release updates the Amazon EMR ModifyInstanceGroups API to support "MERGE" type cluster reconfiguration. Also, added the ability to specify a particular Amazon Linux release for all nodes in a cluster launch request. -* `github.com/aws/aws-sdk-go-v2/service/migrationhubrefactorspaces`: [v1.5.5](service/migrationhubrefactorspaces/CHANGELOG.md#v155-2022-05-10) - * **Documentation**: AWS Migration Hub Refactor Spaces documentation only update to fix a formatting issue. - -# Release (2022-05-09) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/config`: [v1.15.5](config/CHANGELOG.md#v1155-2022-05-09) - * **Bug Fix**: Fixes a bug in LoadDefaultConfig to correctly assign ConfigSources so all config resolvers have access to the config sources. This fixes the feature/ec2/imds client not having configuration applied via config.LoadOptions such as EC2IMDSClientEnableState. PR [#1682](https://github.com/aws/aws-sdk-go-v2/pull/1682) -* `github.com/aws/aws-sdk-go-v2/service/cloudcontrol`: [v1.10.0](service/cloudcontrol/CHANGELOG.md#v1100-2022-05-09) - * **Feature**: SDK release for Cloud Control API to include paginators for Python SDK. -* `github.com/aws/aws-sdk-go-v2/service/evidently`: [v1.7.0](service/evidently/CHANGELOG.md#v170-2022-05-09) - * **Feature**: Add detail message inside GetExperimentResults API response to indicate experiment result availability -* `github.com/aws/aws-sdk-go-v2/service/ssmcontacts`: [v1.13.5](service/ssmcontacts/CHANGELOG.md#v1135-2022-05-09) - * **Documentation**: Fixed an error in the DescribeEngagement example for AWS Incident Manager. - -# Release (2022-05-06) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.40.0](service/ec2/CHANGELOG.md#v1400-2022-05-06) - * **Feature**: Add new state values for IPAMs, IPAM Scopes, and IPAM Pools. -* `github.com/aws/aws-sdk-go-v2/service/location`: [v1.17.0](service/location/CHANGELOG.md#v1170-2022-05-06) - * **Feature**: Amazon Location Service now includes a MaxResults parameter for ListGeofences requests. -* `github.com/aws/aws-sdk-go-v2/service/mediapackage`: [v1.16.0](service/mediapackage/CHANGELOG.md#v1160-2022-05-06) - * **Feature**: This release adds Dvb Dash 2014 as an available profile option for Dash Origin Endpoints. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.21.1](service/rds/CHANGELOG.md#v1211-2022-05-06) - * **Documentation**: Various documentation improvements. -* `github.com/aws/aws-sdk-go-v2/service/redshift`: [v1.24.0](service/redshift/CHANGELOG.md#v1240-2022-05-06) - * **Feature**: Introduces new field 'LoadSampleData' in CreateCluster operation. Customers can now specify 'LoadSampleData' option during creation of a cluster, which results in loading of sample data in the cluster that is created. -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.21.1](service/securityhub/CHANGELOG.md#v1211-2022-05-06) - * **Documentation**: Documentation updates for Security Hub API reference - -# Release (2022-05-05) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/datasync`: [v1.16.0](service/datasync/CHANGELOG.md#v1160-2022-05-05) - * **Feature**: AWS DataSync now supports a new ObjectTags Task API option that can be used to control whether Object Tags are transferred. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.39.0](service/ec2/CHANGELOG.md#v1390-2022-05-05) - * **Feature**: Amazon EC2 I4i instances are powered by 3rd generation Intel Xeon Scalable processors and feature up to 30 TB of local AWS Nitro SSD storage -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.25.0](service/iot/CHANGELOG.md#v1250-2022-05-05) - * **Feature**: AWS IoT Jobs now allows you to create up to 100,000 active continuous and snapshot jobs by using concurrency control. -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.26.0](service/kendra/CHANGELOG.md#v1260-2022-05-05) - * **Feature**: AWS Kendra now supports hierarchical facets for a query. For more information, see https://docs.aws.amazon.com/kendra/latest/dg/filtering.html - -# Release (2022-05-04) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/backup`: [v1.16.0](service/backup/CHANGELOG.md#v1160-2022-05-04) - * **Feature**: Adds support to 2 new filters about job complete time for 3 list jobs APIs in AWS Backup -* `github.com/aws/aws-sdk-go-v2/service/iotsecuretunneling`: [v1.13.0](service/iotsecuretunneling/CHANGELOG.md#v1130-2022-05-04) - * **Feature**: This release introduces a new API RotateTunnelAccessToken that allow revoking the existing tokens and generate new tokens -* `github.com/aws/aws-sdk-go-v2/service/lightsail`: [v1.20.1](service/lightsail/CHANGELOG.md#v1201-2022-05-04) - * **Documentation**: Documentation updates for Lightsail -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.27.0](service/ssm/CHANGELOG.md#v1270-2022-05-04) - * **Feature**: This release adds the TargetMaps parameter in SSM State Manager API. - -# Release (2022-05-03) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.38.0](service/ec2/CHANGELOG.md#v1380-2022-05-03) - * **Feature**: Adds support for allocating Dedicated Hosts on AWS Outposts. The AllocateHosts API now accepts an OutpostArn request parameter, and the DescribeHosts API now includes an OutpostArn response parameter. -* `github.com/aws/aws-sdk-go-v2/service/kinesisvideo`: [v1.12.0](service/kinesisvideo/CHANGELOG.md#v1120-2022-05-03) - * **Feature**: Add support for multiple image feature related APIs for configuring image generation and notification of a video stream. Add "GET_IMAGES" to the list of supported API names for the GetDataEndpoint API. -* `github.com/aws/aws-sdk-go-v2/service/kinesisvideoarchivedmedia`: [v1.13.0](service/kinesisvideoarchivedmedia/CHANGELOG.md#v1130-2022-05-03) - * **Feature**: Add support for GetImages API for retrieving images from a video stream -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.26.8](service/s3/CHANGELOG.md#v1268-2022-05-03) - * **Documentation**: Documentation only update for doc bug fixes for the S3 API docs. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.30.0](service/sagemaker/CHANGELOG.md#v1300-2022-05-03) - * **Feature**: SageMaker Autopilot adds new metrics for all candidate models generated by Autopilot experiments; RStudio on SageMaker now allows users to bring your own development environment in a custom image. - -# Release (2022-05-02) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/organizations`: [v1.16.0](service/organizations/CHANGELOG.md#v1160-2022-05-02) - * **Feature**: This release adds the INVALID_PAYMENT_INSTRUMENT as a fail reason and an error message. -* `github.com/aws/aws-sdk-go-v2/service/outposts`: [v1.19.0](service/outposts/CHANGELOG.md#v1190-2022-05-02) - * **Feature**: This release adds a new API called ListAssets to the Outposts SDK, which lists the hardware assets in an Outpost. -* `github.com/aws/aws-sdk-go-v2/service/synthetics`: [v1.15.0](service/synthetics/CHANGELOG.md#v1150-2022-05-02) - * **Feature**: CloudWatch Synthetics has introduced a new feature to provide customers with an option to delete the underlying resources that Synthetics canary creates when the user chooses to delete the canary. - -# Release (2022-04-29) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/codegurureviewer`: [v1.16.0](service/codegurureviewer/CHANGELOG.md#v1160-2022-04-29) - * **Feature**: Amazon CodeGuru Reviewer now supports suppressing recommendations from being generated on specific files and directories. -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.23.0](service/mediaconvert/CHANGELOG.md#v1230-2022-04-29) - * **Feature**: AWS Elemental MediaConvert SDK nows supports creation of Dolby Vision profile 8.1, the ability to generate black frames of video, and introduces audio-only DASH and CMAF support. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.21.0](service/rds/CHANGELOG.md#v1210-2022-04-29) - * **Feature**: Feature - Adds support for Internet Protocol Version 6 (IPv6) on RDS database instances. -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.26.0](service/ssm/CHANGELOG.md#v1260-2022-04-29) - * **Feature**: Update the StartChangeRequestExecution, adding TargetMaps to the Runbook parameter -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.20.0](service/wafv2/CHANGELOG.md#v1200-2022-04-29) - * **Feature**: You can now inspect all request headers and all cookies. You can now specify how to handle oversize body contents in your rules that inspect the body. - -# Release (2022-04-28) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/auditmanager`: [v1.18.5](service/auditmanager/CHANGELOG.md#v1185-2022-04-28) - * **Documentation**: This release adds documentation updates for Audit Manager. We provided examples of how to use the Custom_ prefix for the keywordValue attribute. We also provided more details about the DeleteAssessmentReport operation. -* `github.com/aws/aws-sdk-go-v2/service/braket`: [v1.16.0](service/braket/CHANGELOG.md#v1160-2022-04-28) - * **Feature**: This release enables Braket Hybrid Jobs with Embedded Simulators to have multiple instances. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.24.0](service/connect/CHANGELOG.md#v1240-2022-04-28) - * **Feature**: This release introduces an API for changing the current agent status of a user in Connect. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.37.0](service/ec2/CHANGELOG.md#v1370-2022-04-28) - * **Feature**: This release adds support to query the public key and creation date of EC2 Key Pairs. Additionally, the format (pem or ppk) of a key pair can be specified when creating a new key pair. -* `github.com/aws/aws-sdk-go-v2/service/guardduty`: [v1.13.5](service/guardduty/CHANGELOG.md#v1135-2022-04-28) - * **Documentation**: Documentation update for API description. -* `github.com/aws/aws-sdk-go-v2/service/networkfirewall`: [v1.17.0](service/networkfirewall/CHANGELOG.md#v1170-2022-04-28) - * **Feature**: AWS Network Firewall adds support for stateful threat signature AWS managed rule groups. - -# Release (2022-04-27) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/amplify`: [v1.11.5](service/amplify/CHANGELOG.md#v1115-2022-04-27) - * **Documentation**: Documentation only update to support the Amplify GitHub App feature launch -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmediapipelines`: [v1.0.0](service/chimesdkmediapipelines/CHANGELOG.md#v100-2022-04-27) - * **Release**: New AWS service client module - * **Feature**: For Amazon Chime SDK meetings, the Amazon Chime Media Pipelines SDK allows builders to capture audio, video, and content share streams. You can also capture meeting events, live transcripts, and data messages. The pipelines save the artifacts to an Amazon S3 bucket that you designate. -* `github.com/aws/aws-sdk-go-v2/service/cloudtrail`: [v1.16.0](service/cloudtrail/CHANGELOG.md#v1160-2022-04-27) - * **Feature**: Increases the retention period maximum to 2557 days. Deprecates unused fields of the ListEventDataStores API response. Updates documentation. -* `github.com/aws/aws-sdk-go-v2/service/internal/checksum`: [v1.1.5](service/internal/checksum/CHANGELOG.md#v115-2022-04-27) - * **Bug Fix**: Fixes a bug that could cause the SigV4 payload hash to be incorrectly encoded, leading to signing errors. -* `github.com/aws/aws-sdk-go-v2/service/iotwireless`: [v1.19.0](service/iotwireless/CHANGELOG.md#v1190-2022-04-27) - * **Feature**: Add list support for event configurations, allow to get and update event configurations by resource type, support LoRaWAN events; Make NetworkAnalyzerConfiguration as a resource, add List, Create, Delete API support; Add FCntStart attribute support for ABP WirelessDevice. -* `github.com/aws/aws-sdk-go-v2/service/lookoutequipment`: [v1.13.0](service/lookoutequipment/CHANGELOG.md#v1130-2022-04-27) - * **Feature**: This release adds the following new features: 1) Introduces an option for automatic schema creation 2) Now allows for Ingestion of data containing most common errors and allows automatic data cleaning 3) Introduces new API ListSensorStatistics that gives further information about the ingested data -* `github.com/aws/aws-sdk-go-v2/service/rekognition`: [v1.18.0](service/rekognition/CHANGELOG.md#v1180-2022-04-27) - * **Feature**: This release adds support to configure stream-processor resources for label detections on streaming-videos. UpateStreamProcessor API is also launched with this release, which could be used to update an existing stream-processor. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.29.0](service/sagemaker/CHANGELOG.md#v1290-2022-04-27) - * **Feature**: Amazon SageMaker Autopilot adds support for custom validation dataset and validation ratio through the CreateAutoMLJob and DescribeAutoMLJob APIs. - -# Release (2022-04-26) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudfront`: [v1.17.0](service/cloudfront/CHANGELOG.md#v1170-2022-04-26) - * **Feature**: CloudFront now supports the Server-Timing header in HTTP responses sent from CloudFront. You can use this header to view metrics that help you gain insights about the behavior and performance of CloudFront. To use this header, enable it in a response headers policy. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.24.2](service/glue/CHANGELOG.md#v1242-2022-04-26) - * **Documentation**: This release adds documentation for the APIs to create, read, delete, list, and batch read of AWS Glue custom patterns, and for Lake Formation configuration settings in the AWS Glue crawler. -* `github.com/aws/aws-sdk-go-v2/service/ivschat`: [v1.0.0](service/ivschat/CHANGELOG.md#v100-2022-04-26) - * **Release**: New AWS service client module - * **Feature**: Adds new APIs for IVS Chat, a feature for building interactive chat experiences alongside an IVS broadcast. -* `github.com/aws/aws-sdk-go-v2/service/lightsail`: [v1.20.0](service/lightsail/CHANGELOG.md#v1200-2022-04-26) - * **Feature**: This release adds support for Lightsail load balancer HTTP to HTTPS redirect and TLS policy configuration. -* `github.com/aws/aws-sdk-go-v2/service/networkfirewall`: [v1.16.0](service/networkfirewall/CHANGELOG.md#v1160-2022-04-26) - * **Feature**: AWS Network Firewall now enables customers to use a customer managed AWS KMS key for the encryption of their firewall resources. -* `github.com/aws/aws-sdk-go-v2/service/pricing`: [v1.14.5](service/pricing/CHANGELOG.md#v1145-2022-04-26) - * **Documentation**: Documentation updates for Price List API -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.28.0](service/sagemaker/CHANGELOG.md#v1280-2022-04-26) - * **Feature**: SageMaker Inference Recommender now accepts customer KMS key ID for encryption of endpoints and compilation outputs created during inference recommendation. - -# Release (2022-04-25) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2`: v1.16.3 - * **Dependency Update**: Update SDK's internal copy of golang.org/x/sync/singleflight to address issue with test failing due to timeing issues -* `github.com/aws/aws-sdk-go-v2/credentials`: [v1.12.0](credentials/CHANGELOG.md#v1120-2022-04-25) - * **Feature**: Adds Duration and Policy options that can be used when creating stscreds.WebIdentityRoleProvider credentials provider. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.23.0](service/connect/CHANGELOG.md#v1230-2022-04-25) - * **Feature**: This release adds SearchUsers API which can be used to search for users with a Connect Instance -* `github.com/aws/aws-sdk-go-v2/service/gamelift`: [v1.14.4](service/gamelift/CHANGELOG.md#v1144-2022-04-25) - * **Documentation**: Documentation updates for Amazon GameLift. -* `github.com/aws/aws-sdk-go-v2/service/mq`: [v1.13.0](service/mq/CHANGELOG.md#v1130-2022-04-25) - * **Feature**: This release adds the CRITICAL_ACTION_REQUIRED broker state and the ActionRequired API property. CRITICAL_ACTION_REQUIRED informs you when your broker is degraded. ActionRequired provides you with a code which you can use to find instructions in the Developer Guide on how to resolve the issue. -* `github.com/aws/aws-sdk-go-v2/service/rdsdata`: [v1.12.0](service/rdsdata/CHANGELOG.md#v1120-2022-04-25) - * **Feature**: Support to receive SQL query results in the form of a simplified JSON string. This enables developers using the new JSON string format to more easily convert it to an object using popular JSON string parsing libraries. -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.21.0](service/securityhub/CHANGELOG.md#v1210-2022-04-25) - * **Feature**: Security Hub now lets you opt-out of auto-enabling the defaults standards (CIS and FSBP) in accounts that are auto-enabled with Security Hub via Security Hub's integration with AWS Organizations. - -# Release (2022-04-22) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmeetings`: [v1.9.0](service/chimesdkmeetings/CHANGELOG.md#v190-2022-04-22) - * **Feature**: Include additional exceptions types. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.36.0](service/ec2/CHANGELOG.md#v1360-2022-04-22) - * **Feature**: Adds support for waiters that automatically poll for a deleted NAT Gateway until it reaches the deleted state. - -# Release (2022-04-21) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/elasticache`: [v1.20.5](service/elasticache/CHANGELOG.md#v1205-2022-04-21) - * **Documentation**: Doc only update for ElastiCache -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.24.0](service/glue/CHANGELOG.md#v1240-2022-04-21) - * **Feature**: This release adds APIs to create, read, delete, list, and batch read of Glue custom entity types -* `github.com/aws/aws-sdk-go-v2/service/iotsitewise`: [v1.21.0](service/iotsitewise/CHANGELOG.md#v1210-2022-04-21) - * **Feature**: This release adds 3 new batch data query APIs : BatchGetAssetPropertyValue, BatchGetAssetPropertyValueHistory and BatchGetAssetPropertyAggregates -* `github.com/aws/aws-sdk-go-v2/service/iottwinmaker`: [v1.7.0](service/iottwinmaker/CHANGELOG.md#v170-2022-04-21) - * **Feature**: General availability (GA) for AWS IoT TwinMaker. For more information, see https://docs.aws.amazon.com/iot-twinmaker/latest/apireference/Welcome.html -* `github.com/aws/aws-sdk-go-v2/service/lookoutmetrics`: [v1.12.0](service/lookoutmetrics/CHANGELOG.md#v1120-2022-04-21) - * **Feature**: Added DetectMetricSetConfig API for detecting configuration required for creating metric set from provided S3 data source. -* `github.com/aws/aws-sdk-go-v2/service/mediatailor`: [v1.17.0](service/mediatailor/CHANGELOG.md#v1170-2022-04-21) - * **Feature**: This release introduces tiered channels and adds support for live sources. Customers using a STANDARD channel can now create programs using live sources. -* `github.com/aws/aws-sdk-go-v2/service/secretsmanager`: [v1.15.5](service/secretsmanager/CHANGELOG.md#v1155-2022-04-21) - * **Documentation**: Documentation updates for Secrets Manager -* `github.com/aws/aws-sdk-go-v2/service/storagegateway`: [v1.17.0](service/storagegateway/CHANGELOG.md#v1170-2022-04-21) - * **Feature**: This release adds support for minimum of 5 character length virtual tape barcodes. -* `github.com/aws/aws-sdk-go-v2/service/wisdom`: [v1.8.0](service/wisdom/CHANGELOG.md#v180-2022-04-21) - * **Feature**: This release updates the GetRecommendations API to include a trigger event list for classifying and grouping recommendations. - -# Release (2022-04-20) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.22.0](service/connect/CHANGELOG.md#v1220-2022-04-20) - * **Feature**: This release adds APIs to search, claim, release, list, update, and describe phone numbers. You can also use them to associate and disassociate contact flows to phone numbers. -* `github.com/aws/aws-sdk-go-v2/service/macie2`: [v1.21.0](service/macie2/CHANGELOG.md#v1210-2022-04-20) - * **Feature**: Sensitive data findings in Amazon Macie now indicate how Macie found the sensitive data that produced a finding (originType). -* `github.com/aws/aws-sdk-go-v2/service/mgn`: [v1.14.0](service/mgn/CHANGELOG.md#v1140-2022-04-20) - * **Feature**: Removed required annotation from input fields in Describe operations requests. Added quotaValue to ServiceQuotaExceededException -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.20.0](service/rds/CHANGELOG.md#v1200-2022-04-20) - * **Feature**: Added a new cluster-level attribute to set the capacity range for Aurora Serverless v2 instances. - -# Release (2022-04-19) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/autoscaling`: [v1.23.0](service/autoscaling/CHANGELOG.md#v1230-2022-04-19) - * **Feature**: EC2 Auto Scaling now adds default instance warm-up times for all scaling activities, health check replacements, and other replacement events in the Auto Scaling instance lifecycle. -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.25.0](service/kendra/CHANGELOG.md#v1250-2022-04-19) - * **Feature**: Amazon Kendra now provides a data source connector for Quip. For more information, see https://docs.aws.amazon.com/kendra/latest/dg/data-source-quip.html -* `github.com/aws/aws-sdk-go-v2/service/kms`: [v1.17.0](service/kms/CHANGELOG.md#v1170-2022-04-19) - * **Feature**: Adds support for KMS keys and APIs that generate and verify HMAC codes -* `github.com/aws/aws-sdk-go-v2/service/personalize`: [v1.19.0](service/personalize/CHANGELOG.md#v1190-2022-04-19) - * **Feature**: Adding StartRecommender and StopRecommender APIs for Personalize. -* `github.com/aws/aws-sdk-go-v2/service/polly`: [v1.15.0](service/polly/CHANGELOG.md#v1150-2022-04-19) - * **Feature**: Amazon Polly adds new Austrian German voice - Hannah. Hannah is available as Neural voice only. -* `github.com/aws/aws-sdk-go-v2/service/redshift`: [v1.23.0](service/redshift/CHANGELOG.md#v1230-2022-04-19) - * **Feature**: Introduces new fields for LogDestinationType and LogExports on EnableLogging requests and Enable/Disable/DescribeLogging responses. Customers can now select CloudWatch Logs as a destination for their Audit Logs. -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.25.0](service/ssm/CHANGELOG.md#v1250-2022-04-19) - * **Feature**: Added offset support for specifying the number of days to wait after the date and time specified by a CRON expression when creating SSM association. -* `github.com/aws/aws-sdk-go-v2/service/textract`: [v1.15.0](service/textract/CHANGELOG.md#v1150-2022-04-19) - * **Feature**: This release adds support for specifying and extracting information from documents using the Queries feature within Analyze Document API -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.18.4](service/transfer/CHANGELOG.md#v1184-2022-04-19) - * **Documentation**: This release contains corrected HomeDirectoryMappings examples for several API functions: CreateAccess, UpdateAccess, CreateUser, and UpdateUser,. -* `github.com/aws/aws-sdk-go-v2/service/worklink`: [v1.12.0](service/worklink/CHANGELOG.md#v1120-2022-04-19) - * **Feature**: Amazon WorkLink is no longer supported. This will be removed in a future version of the SDK. - -# Release (2022-04-15) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue`: [v1.9.0](feature/dynamodb/attributevalue/CHANGELOG.md#v190-2022-04-15) - * **Feature**: Support has been added for specifying a custom time format when encoding and decoding DynamoDB AttributeValues. Use `EncoderOptions.EncodeTime` to specify a custom time encoding function, and use `DecoderOptions.DecodeTime` for specifying how to handle the corresponding AttributeValues using the format. Thank you [Pablo Lopez](https://github.com/plopezlpz) for this contribution. -* `github.com/aws/aws-sdk-go-v2/feature/dynamodbstreams/attributevalue`: [v1.9.0](feature/dynamodbstreams/attributevalue/CHANGELOG.md#v190-2022-04-15) - * **Feature**: Support has been added for specifying a custom time format when encoding and decoding DynamoDB AttributeValues. Use `EncoderOptions.EncodeTime` to specify a custom time encoding function, and use `DecoderOptions.DecodeTime` for specifying how to handle the corresponding AttributeValues using the format. Thank you [Pablo Lopez](https://github.com/plopezlpz) for this contribution. -* `github.com/aws/aws-sdk-go-v2/service/athena`: [v1.15.0](service/athena/CHANGELOG.md#v1150-2022-04-15) - * **Feature**: This release adds subfields, ErrorMessage, Retryable, to the AthenaError response object in the GetQueryExecution API when a query fails. -* `github.com/aws/aws-sdk-go-v2/service/lightsail`: [v1.19.0](service/lightsail/CHANGELOG.md#v1190-2022-04-15) - * **Feature**: This release adds support to describe the synchronization status of the account-level block public access feature for your Amazon Lightsail buckets. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.19.0](service/rds/CHANGELOG.md#v1190-2022-04-15) - * **Feature**: Removes Amazon RDS on VMware with the deletion of APIs related to Custom Availability Zones and Media installation - -# Release (2022-04-14) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/appflow`: [v1.15.0](service/appflow/CHANGELOG.md#v1150-2022-04-14) - * **Feature**: Enables users to pass custom token URL parameters for Oauth2 authentication during create connector profile -* `github.com/aws/aws-sdk-go-v2/service/appstream`: [v1.16.0](service/appstream/CHANGELOG.md#v1160-2022-04-14) - * **Feature**: Includes updates for create and update fleet APIs to manage the session scripts locations for Elastic fleets. -* `github.com/aws/aws-sdk-go-v2/service/batch`: [v1.18.0](service/batch/CHANGELOG.md#v1180-2022-04-14) - * **Feature**: Enables configuration updates for compute environments with BEST_FIT_PROGRESSIVE and SPOT_CAPACITY_OPTIMIZED allocation strategies. -* `github.com/aws/aws-sdk-go-v2/service/cloudwatch`: [v1.18.1](service/cloudwatch/CHANGELOG.md#v1181-2022-04-14) - * **Documentation**: Updates documentation for additional statistics in CloudWatch Metric Streams. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.35.1](service/ec2/CHANGELOG.md#v1351-2022-04-14) - * **Documentation**: Documentation updates for Amazon EC2. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.23.0](service/glue/CHANGELOG.md#v1230-2022-04-14) - * **Feature**: Auto Scaling for Glue version 3.0 and later jobs to dynamically scale compute resources. This SDK change provides customers with the auto-scaled DPU usage - -# Release (2022-04-13) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudwatch`: [v1.18.0](service/cloudwatch/CHANGELOG.md#v1180-2022-04-13) - * **Feature**: Adds support for additional statistics in CloudWatch Metric Streams. -* `github.com/aws/aws-sdk-go-v2/service/fsx`: [v1.23.0](service/fsx/CHANGELOG.md#v1230-2022-04-13) - * **Feature**: This release adds support for deploying FSx for ONTAP file systems in a single Availability Zone. - -# Release (2022-04-12) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/devopsguru`: [v1.17.0](service/devopsguru/CHANGELOG.md#v1170-2022-04-12) - * **Feature**: This release adds new APIs DeleteInsight to deletes the insight along with the associated anomalies, events and recommendations. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.35.0](service/ec2/CHANGELOG.md#v1350-2022-04-12) - * **Feature**: X2idn and X2iedn instances are powered by 3rd generation Intel Xeon Scalable processors with an all-core turbo frequency up to 3.5 GHzAmazon EC2. C6a instances are powered by 3rd generation AMD EPYC processors. -* `github.com/aws/aws-sdk-go-v2/service/efs`: [v1.17.0](service/efs/CHANGELOG.md#v1170-2022-04-12) - * **Feature**: Amazon EFS adds support for a ThrottlingException when using the CreateAccessPoint API if the account is nearing the AccessPoint limit(120). -* `github.com/aws/aws-sdk-go-v2/service/iottwinmaker`: [v1.6.0](service/iottwinmaker/CHANGELOG.md#v160-2022-04-12) - * **Feature**: This release adds the following new features: 1) ListEntities API now supports search using ExternalId. 2) BatchPutPropertyValue and GetPropertyValueHistory API now allows users to represent time in sub-second level precisions. -* `github.com/aws/aws-sdk-go-v2/service/kinesis`: [v1.15.4](service/kinesis/CHANGELOG.md#v1154-2022-04-12) - * **Bug Fix**: Fixes an issue that caused the unexported constructor function names for EventStream types to be swapped for the event reader and writer respectivly. -* `github.com/aws/aws-sdk-go-v2/service/lexruntimev2`: [v1.14.4](service/lexruntimev2/CHANGELOG.md#v1144-2022-04-12) - * **Bug Fix**: Fixes an issue that caused the unexported constructor function names for EventStream types to be swapped for the event reader and writer respectivly. -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.26.5](service/s3/CHANGELOG.md#v1265-2022-04-12) - * **Bug Fix**: Fixes an issue that caused the unexported constructor function names for EventStream types to be swapped for the event reader and writer respectivly. -* `github.com/aws/aws-sdk-go-v2/service/transcribestreaming`: [v1.6.4](service/transcribestreaming/CHANGELOG.md#v164-2022-04-12) - * **Bug Fix**: Fixes an issue that caused the unexported constructor function names for EventStream types to be swapped for the event reader and writer respectivly. - -# Release (2022-04-11) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/amplifyuibuilder`: [v1.6.0](service/amplifyuibuilder/CHANGELOG.md#v160-2022-04-11) - * **Feature**: In this release, we have added the ability to bind events to component level actions. -* `github.com/aws/aws-sdk-go-v2/service/apprunner`: [v1.12.0](service/apprunner/CHANGELOG.md#v1120-2022-04-11) - * **Feature**: This release adds tracing for App Runner services with X-Ray using AWS Distro for OpenTelemetry. New APIs: CreateObservabilityConfiguration, DescribeObservabilityConfiguration, ListObservabilityConfigurations, and DeleteObservabilityConfiguration. Updated APIs: CreateService and UpdateService. -* `github.com/aws/aws-sdk-go-v2/service/workspaces`: [v1.18.0](service/workspaces/CHANGELOG.md#v1180-2022-04-11) - * **Feature**: Added API support that allows customers to create GPU-enabled WorkSpaces using EC2 G4dn instances. - -# Release (2022-04-08) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.22.0](service/mediaconvert/CHANGELOG.md#v1220-2022-04-08) - * **Feature**: AWS Elemental MediaConvert SDK has added support for the pass-through of WebVTT styling to WebVTT outputs, pass-through of KLV metadata to supported formats, and improved filter support for processing 444/RGB content. -* `github.com/aws/aws-sdk-go-v2/service/mediapackagevod`: [v1.17.0](service/mediapackagevod/CHANGELOG.md#v1170-2022-04-08) - * **Feature**: This release adds ScteMarkersSource as an available field for Dash Packaging Configurations. When set to MANIFEST, MediaPackage will source the SCTE-35 markers from the manifest. When set to SEGMENTS, MediaPackage will source the SCTE-35 markers from the segments. -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.19.0](service/wafv2/CHANGELOG.md#v1190-2022-04-08) - * **Feature**: Add a new CurrentDefaultVersion field to ListAvailableManagedRuleGroupVersions API response; add a new VersioningSupported boolean to each ManagedRuleGroup returned from ListAvailableManagedRuleGroups API response. - -# Release (2022-04-07) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/internal/v4a`: [v1.0.0](internal/v4a/CHANGELOG.md#v100-2022-04-07) - * **Release**: New internal v4a signing module location. -* `github.com/aws/aws-sdk-go-v2/service/docdb`: [v1.18.0](service/docdb/CHANGELOG.md#v1180-2022-04-07) - * **Feature**: Added support to enable/disable performance insights when creating or modifying db instances -* `github.com/aws/aws-sdk-go-v2/service/eventbridge`: [v1.16.0](service/eventbridge/CHANGELOG.md#v1160-2022-04-07) - * **Feature**: Adds new EventBridge Endpoint resources for disaster recovery, multi-region failover, and cross-region replication capabilities to help you build resilient event-driven applications. -* `github.com/aws/aws-sdk-go-v2/service/personalize`: [v1.18.0](service/personalize/CHANGELOG.md#v1180-2022-04-07) - * **Feature**: This release provides tagging support in AWS Personalize. -* `github.com/aws/aws-sdk-go-v2/service/pi`: [v1.14.4](service/pi/CHANGELOG.md#v1144-2022-04-07) - * **Documentation**: Adds support for DocumentDB to the Performance Insights API. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.27.0](service/sagemaker/CHANGELOG.md#v1270-2022-04-07) - * **Feature**: Amazon Sagemaker Notebook Instances now supports G5 instance types - -# Release (2022-04-06) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/configservice`: [v1.21.0](service/configservice/CHANGELOG.md#v1210-2022-04-06) - * **Feature**: Add resourceType enums for AWS::EMR::SecurityConfiguration and AWS::SageMaker::CodeRepository -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.24.0](service/kendra/CHANGELOG.md#v1240-2022-04-06) - * **Feature**: Amazon Kendra now provides a data source connector for Box. For more information, see https://docs.aws.amazon.com/kendra/latest/dg/data-source-box.html -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.22.0](service/lambda/CHANGELOG.md#v1220-2022-04-06) - * **Feature**: This release adds new APIs for creating and managing Lambda Function URLs and adds a new FunctionUrlAuthType parameter to the AddPermission API. Customers can use Function URLs to create built-in HTTPS endpoints on their functions. -* `github.com/aws/aws-sdk-go-v2/service/panorama`: [v1.7.0](service/panorama/CHANGELOG.md#v170-2022-04-06) - * **Feature**: Added Brand field to device listings. - -# Release (2022-04-05) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/datasync`: [v1.15.0](service/datasync/CHANGELOG.md#v1150-2022-04-05) - * **Feature**: AWS DataSync now supports Amazon FSx for OpenZFS locations. -* `github.com/aws/aws-sdk-go-v2/service/fsx`: [v1.22.0](service/fsx/CHANGELOG.md#v1220-2022-04-05) - * **Feature**: Provide customers more visibility into file system status by adding new "Misconfigured Unavailable" status for Amazon FSx for Windows File Server. -* `github.com/aws/aws-sdk-go-v2/service/s3control`: [v1.21.4](service/s3control/CHANGELOG.md#v1214-2022-04-05) - * **Documentation**: Documentation-only update for doc bug fixes for the S3 Control API docs. -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.20.0](service/securityhub/CHANGELOG.md#v1200-2022-04-05) - * **Feature**: Added additional ASFF details for RdsSecurityGroup AutoScalingGroup, ElbLoadBalancer, CodeBuildProject and RedshiftCluster. - -# Release (2022-04-04) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.24.0](service/iot/CHANGELOG.md#v1240-2022-04-04) - * **Feature**: AWS IoT - AWS IoT Device Defender adds support to list metric datapoints collected for IoT devices through the ListMetricValues API -* `github.com/aws/aws-sdk-go-v2/service/proton`: [v1.13.0](service/proton/CHANGELOG.md#v1130-2022-04-04) - * **Feature**: SDK release to support tagging for AWS Proton Repository resource -* `github.com/aws/aws-sdk-go-v2/service/servicecatalog`: [v1.14.0](service/servicecatalog/CHANGELOG.md#v1140-2022-04-04) - * **Feature**: This release adds ProvisioningArtifictOutputKeys to DescribeProvisioningParameters to reference the outputs of a Provisioned Product and deprecates ProvisioningArtifactOutputs. -* `github.com/aws/aws-sdk-go-v2/service/sms`: [v1.12.4](service/sms/CHANGELOG.md#v1124-2022-04-04) - * **Documentation**: Revised product update notice for SMS console deprecation. - -# Release (2022-04-01) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.21.0](service/connect/CHANGELOG.md#v1210-2022-04-01) - * **Feature**: This release updates these APIs: UpdateInstanceAttribute, DescribeInstanceAttribute and ListInstanceAttributes. You can use it to programmatically enable/disable multi-party conferencing using attribute type MULTI_PARTY_CONFERENCING on the specified Amazon Connect instance. - -# Release (2022-03-31) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue`: [v1.8.4](feature/dynamodb/attributevalue/CHANGELOG.md#v184-2022-03-31) - * **Documentation**: Fixes documentation typos in Number type's helper methods -* `github.com/aws/aws-sdk-go-v2/feature/dynamodbstreams/attributevalue`: [v1.8.4](feature/dynamodbstreams/attributevalue/CHANGELOG.md#v184-2022-03-31) - * **Documentation**: Fixes documentation typos in Number type's helper methods -* `github.com/aws/aws-sdk-go-v2/service/auditmanager`: [v1.18.3](service/auditmanager/CHANGELOG.md#v1183-2022-03-31) - * **Documentation**: This release adds documentation updates for Audit Manager. The updates provide data deletion guidance when a customer deregisters Audit Manager or deregisters a delegated administrator. -* `github.com/aws/aws-sdk-go-v2/service/cloudcontrol`: [v1.9.0](service/cloudcontrol/CHANGELOG.md#v190-2022-03-31) - * **Feature**: SDK release for Cloud Control API in Amazon Web Services China (Beijing) Region, operated by Sinnet, and Amazon Web Services China (Ningxia) Region, operated by NWCD -* `github.com/aws/aws-sdk-go-v2/service/databrew`: [v1.20.0](service/databrew/CHANGELOG.md#v1200-2022-03-31) - * **Feature**: This AWS Glue Databrew release adds feature to support ORC as an input format. -* `github.com/aws/aws-sdk-go-v2/service/grafana`: [v1.8.0](service/grafana/CHANGELOG.md#v180-2022-03-31) - * **Feature**: This release adds tagging support to the Managed Grafana service. New APIs: TagResource, UntagResource and ListTagsForResource. Updates: add optional field tags to support tagging while calling CreateWorkspace. -* `github.com/aws/aws-sdk-go-v2/service/pinpointsmsvoicev2`: [v1.0.0](service/pinpointsmsvoicev2/CHANGELOG.md#v100-2022-03-31) - * **Release**: New AWS service client module - * **Feature**: Amazon Pinpoint now offers a version 2.0 suite of SMS and voice APIs, providing increased control over sending and configuration. This release is a new SDK for sending SMS and voice messages called PinpointSMSVoiceV2. -* `github.com/aws/aws-sdk-go-v2/service/route53recoverycluster`: [v1.9.0](service/route53recoverycluster/CHANGELOG.md#v190-2022-03-31) - * **Feature**: This release adds a new API "ListRoutingControls" to list routing control states using the highly reliable Route 53 ARC data plane endpoints. -* `github.com/aws/aws-sdk-go-v2/service/workspaces`: [v1.17.0](service/workspaces/CHANGELOG.md#v1170-2022-03-31) - * **Feature**: Added APIs that allow you to customize the logo, login message, and help links in the WorkSpaces client login page. To learn more, visit https://docs.aws.amazon.com/workspaces/latest/adminguide/customize-branding.html - -# Release (2022-03-30) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.34.0](service/ec2/CHANGELOG.md#v1340-2022-03-30) - * **Feature**: This release simplifies the auto-recovery configuration process enabling customers to set the recovery behavior to disabled or default -* `github.com/aws/aws-sdk-go-v2/service/fms`: [v1.17.0](service/fms/CHANGELOG.md#v1170-2022-03-30) - * **Feature**: AWS Firewall Manager now supports the configuration of third-party policies that can use either the centralized or distributed deployment models. -* `github.com/aws/aws-sdk-go-v2/service/fsx`: [v1.21.0](service/fsx/CHANGELOG.md#v1210-2022-03-30) - * **Feature**: This release adds support for modifying throughput capacity for FSx for ONTAP file systems. -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.23.3](service/iot/CHANGELOG.md#v1233-2022-03-30) - * **Documentation**: Doc only update for IoT that fixes customer-reported issues. -* `github.com/aws/aws-sdk-go-v2/service/iotdataplane`: [v1.12.0](service/iotdataplane/CHANGELOG.md#v1120-2022-03-30) - * **Feature**: Update the default AWS IoT Core Data Plane endpoint from VeriSign signed to ATS signed. If you have firewalls with strict egress rules, configure the rules to grant you access to data-ats.iot.[region].amazonaws.com or data-ats.iot.[region].amazonaws.com.cn. - -# Release (2022-03-29) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/organizations`: [v1.15.0](service/organizations/CHANGELOG.md#v1150-2022-03-29) - * **Feature**: This release provides the new CloseAccount API that enables principals in the management account to close any member account within an organization. - -# Release (2022-03-28) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/acmpca`: [v1.17.3](service/acmpca/CHANGELOG.md#v1173-2022-03-28) - * **Documentation**: Updating service name entities -* `github.com/aws/aws-sdk-go-v2/service/medialive`: [v1.20.0](service/medialive/CHANGELOG.md#v1200-2022-03-28) - * **Feature**: This release adds support for selecting a maintenance window. - -# Release (2022-03-25) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/batch`: [v1.17.0](service/batch/CHANGELOG.md#v1170-2022-03-25) - * **Feature**: Bug Fix: Fixed a bug where shapes were marked as unboxed and were not serialized and sent over the wire, causing an API error from the service. - * This is a breaking change, and has been accepted due to the API operation not being usable due to the members modeled as unboxed (aka value) types. The update changes the members to boxed (aka pointer) types so that the zero value of the members can be handled correctly by the SDK and service. Your application will fail to compile with the updated module. To workaround this you'll need to update your application to use pointer types for the members impacted. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.33.0](service/ec2/CHANGELOG.md#v1330-2022-03-25) - * **Feature**: This is release adds support for Amazon VPC Reachability Analyzer to analyze path through a Transit Gateway. -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.24.0](service/ssm/CHANGELOG.md#v1240-2022-03-25) - * **Feature**: This Patch Manager release supports creating, updating, and deleting Patch Baselines for Rocky Linux OS. - -# Release (2022-03-24) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/configservice`: [v1.20.0](service/configservice/CHANGELOG.md#v1200-2022-03-24) - * **Feature**: Added new APIs GetCustomRulePolicy and GetOrganizationCustomRulePolicy, and updated existing APIs PutConfigRule, DescribeConfigRule, DescribeConfigRuleEvaluationStatus, PutOrganizationConfigRule, DescribeConfigRule to support a new feature for building AWS Config rules with AWS CloudFormation Guard -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.21.0](service/lambda/CHANGELOG.md#v1210-2022-03-24) - * **Feature**: Adds support for increased ephemeral storage (/tmp) up to 10GB for Lambda functions. Customers can now provision up to 10 GB of ephemeral storage per function instance, a 20x increase over the previous limit of 512 MB. -* `github.com/aws/aws-sdk-go-v2/service/transcribe`: [v1.19.0](service/transcribe/CHANGELOG.md#v1190-2022-03-24) - * **Feature**: This release adds an additional parameter for subtitling with Amazon Transcribe batch jobs: outputStartIndex. - -# Release (2022-03-23) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2`: v1.16.0 - * **Feature**: Update CredentialsCache to make use of two new optional CredentialsProvider interfaces to give the cache, per provider, behavior how the cache handles credentials that fail to refresh, and adjusting expires time. See [aws.CredentialsCache](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/aws#CredentialsCache) for more details. - * **Feature**: Update `ec2rolecreds` package's `Provider` to implememnt support for CredentialsCache new optional caching strategy interfaces, HandleFailRefreshCredentialsCacheStrategy and AdjustExpiresByCredentialsCacheStrategy. -* `github.com/aws/aws-sdk-go-v2/credentials`: [v1.11.0](credentials/CHANGELOG.md#v1110-2022-03-23) - * **Feature**: Update `ec2rolecreds` package's `Provider` to implememnt support for CredentialsCache new optional caching strategy interfaces, HandleFailRefreshCredentialsCacheStrategy and AdjustExpiresByCredentialsCacheStrategy. -* `github.com/aws/aws-sdk-go-v2/service/auditmanager`: [v1.18.0](service/auditmanager/CHANGELOG.md#v1180-2022-03-23) - * **Feature**: This release updates 1 API parameter, the SnsArn attribute. The character length and regex pattern for the SnsArn attribute have been updated, which enables you to deselect an SNS topic when using the UpdateSettings operation. -* `github.com/aws/aws-sdk-go-v2/service/ebs`: [v1.15.0](service/ebs/CHANGELOG.md#v1150-2022-03-23) - * **Feature**: Increased the maximum supported value for the Timeout parameter of the StartSnapshot API from 60 minutes to 4320 minutes. Changed the HTTP error code for ConflictException from 503 to 409. -* `github.com/aws/aws-sdk-go-v2/service/elasticache`: [v1.20.2](service/elasticache/CHANGELOG.md#v1202-2022-03-23) - * **Documentation**: Doc only update for ElastiCache -* `github.com/aws/aws-sdk-go-v2/service/gamesparks`: [v1.0.0](service/gamesparks/CHANGELOG.md#v100-2022-03-23) - * **Release**: New AWS service client module - * **Feature**: Released the preview of Amazon GameSparks, a fully managed AWS service that provides a multi-service backend for game developers. -* `github.com/aws/aws-sdk-go-v2/service/redshift`: [v1.22.0](service/redshift/CHANGELOG.md#v1220-2022-03-23) - * **Feature**: This release adds a new [--encrypted | --no-encrypted] field in restore-from-cluster-snapshot API. Customers can now restore an unencrypted snapshot to a cluster encrypted with AWS Managed Key or their own KMS key. -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.23.0](service/ssm/CHANGELOG.md#v1230-2022-03-23) - * **Feature**: Update AddTagsToResource, ListTagsForResource, and RemoveTagsFromResource APIs to reflect the support for tagging Automation resources. Includes other minor documentation updates. -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.18.1](service/transfer/CHANGELOG.md#v1181-2022-03-23) - * **Documentation**: Documentation updates for AWS Transfer Family to describe how to remove an associated workflow from a server. - -# Release (2022-03-22) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/costexplorer`: [v1.18.0](service/costexplorer/CHANGELOG.md#v1180-2022-03-22) - * **Feature**: Added three new APIs to support tagging and resource-level authorization on Cost Explorer resources: TagResource, UntagResource, ListTagsForResource. Added optional parameters to CreateCostCategoryDefinition, CreateAnomalySubscription and CreateAnomalyMonitor APIs to support Tag On Create. -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.18.2](service/ecs/CHANGELOG.md#v1182-2022-03-22) - * **Documentation**: Documentation only update to address tickets -* `github.com/aws/aws-sdk-go-v2/service/lakeformation`: [v1.16.0](service/lakeformation/CHANGELOG.md#v1160-2022-03-22) - * **Feature**: The release fixes the incorrect permissions called out in the documentation - DESCRIBE_TAG, ASSOCIATE_TAG, DELETE_TAG, ALTER_TAG. This trebuchet release fixes the corresponding SDK and documentation. -* `github.com/aws/aws-sdk-go-v2/service/location`: [v1.16.0](service/location/CHANGELOG.md#v1160-2022-03-22) - * **Feature**: Amazon Location Service now includes a MaxResults parameter for GetDevicePositionHistory requests. -* `github.com/aws/aws-sdk-go-v2/service/polly`: [v1.14.0](service/polly/CHANGELOG.md#v1140-2022-03-22) - * **Feature**: Amazon Polly adds new Catalan voice - Arlet. Arlet is available as Neural voice only. - -# Release (2022-03-21) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmeetings`: [v1.8.0](service/chimesdkmeetings/CHANGELOG.md#v180-2022-03-21) - * **Feature**: Add support for media replication to link multiple WebRTC media sessions together to reach larger and global audiences. Participants connected to a replica session can be granted access to join the primary session and can switch sessions with their existing WebRTC connection -* `github.com/aws/aws-sdk-go-v2/service/ecr`: [v1.17.0](service/ecr/CHANGELOG.md#v1170-2022-03-21) - * **Feature**: This release includes a fix in the DescribeImageScanFindings paginated output. -* `github.com/aws/aws-sdk-go-v2/service/mediaconnect`: [v1.16.0](service/mediaconnect/CHANGELOG.md#v1160-2022-03-21) - * **Feature**: This release adds support for selecting a maintenance window. -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.21.0](service/quicksight/CHANGELOG.md#v1210-2022-03-21) - * **Feature**: AWS QuickSight Service Features - Expand public API support for group management. -* `github.com/aws/aws-sdk-go-v2/service/ram`: [v1.16.1](service/ram/CHANGELOG.md#v1161-2022-03-21) - * **Documentation**: Document improvements to the RAM API operations and parameter descriptions. - -# Release (2022-03-18) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.22.0](service/glue/CHANGELOG.md#v1220-2022-03-18) - * **Feature**: Added 9 new APIs for AWS Glue Interactive Sessions: ListSessions, StopSession, CreateSession, GetSession, DeleteSession, RunStatement, GetStatement, ListStatements, CancelStatement - -# Release (2022-03-16) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/acmpca`: [v1.17.0](service/acmpca/CHANGELOG.md#v1170-2022-03-16) - * **Feature**: AWS Certificate Manager (ACM) Private Certificate Authority (CA) now supports customizable certificate subject names and extensions. -* `github.com/aws/aws-sdk-go-v2/service/amplifybackend`: [v1.13.0](service/amplifybackend/CHANGELOG.md#v1130-2022-03-16) - * **Feature**: Adding the ability to customize Cognito verification messages for email and SMS in CreateBackendAuth and UpdateBackendAuth. Adding deprecation documentation for ForgotPassword in CreateBackendAuth and UpdateBackendAuth -* `github.com/aws/aws-sdk-go-v2/service/billingconductor`: [v1.0.0](service/billingconductor/CHANGELOG.md#v100-2022-03-16) - * **Release**: New AWS service client module - * **Feature**: This is the initial SDK release for AWS Billing Conductor. The AWS Billing Conductor is a customizable billing service, allowing you to customize your billing data to match your desired business structure. -* `github.com/aws/aws-sdk-go-v2/service/s3outposts`: [v1.13.0](service/s3outposts/CHANGELOG.md#v1130-2022-03-16) - * **Feature**: S3 on Outposts is releasing a new API, ListSharedEndpoints, that lists all endpoints associated with S3 on Outpost, that has been shared by Resource Access Manager (RAM). -* `github.com/aws/aws-sdk-go-v2/service/ssmincidents`: [v1.13.0](service/ssmincidents/CHANGELOG.md#v1130-2022-03-16) - * **Feature**: Removed incorrect validation pattern for IncidentRecordSource.invokedBy - -# Release (2022-03-15) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider`: [v1.15.0](service/cognitoidentityprovider/CHANGELOG.md#v1150-2022-03-15) - * **Feature**: Updated EmailConfigurationType and SmsConfigurationType to reflect that you can now choose Amazon SES and Amazon SNS resources in the same Region. -* `github.com/aws/aws-sdk-go-v2/service/dataexchange`: [v1.15.0](service/dataexchange/CHANGELOG.md#v1150-2022-03-15) - * **Feature**: This feature enables data providers to use the RevokeRevision operation to revoke subscriber access to a given revision. Subscribers are unable to interact with assets within a revoked revision. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.32.0](service/ec2/CHANGELOG.md#v1320-2022-03-15) - * **Feature**: Adds the Cascade parameter to the DeleteIpam API. Customers can use this parameter to automatically delete their IPAM, including non-default scopes, pools, cidrs, and allocations. There mustn't be any pools provisioned in the default public scope to use this parameter. -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.18.1](service/ecs/CHANGELOG.md#v1181-2022-03-15) - * **Documentation**: Documentation only update to address tickets -* `github.com/aws/aws-sdk-go-v2/service/keyspaces`: [v1.0.2](service/keyspaces/CHANGELOG.md#v102-2022-03-15) - * **Documentation**: Fixing formatting issues in CLI and SDK documentation -* `github.com/aws/aws-sdk-go-v2/service/location`: [v1.15.1](service/location/CHANGELOG.md#v1151-2022-03-15) - * **Documentation**: New HERE style "VectorHereExplore" and "VectorHereExploreTruck". -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.18.1](service/rds/CHANGELOG.md#v1181-2022-03-15) - * **Documentation**: Various documentation improvements -* `github.com/aws/aws-sdk-go-v2/service/robomaker`: [v1.17.0](service/robomaker/CHANGELOG.md#v1170-2022-03-15) - * **Feature**: This release deprecates ROS, Ubuntu and Gazbeo from RoboMaker Simulation Service Software Suites in favor of user-supplied containers and Relaxed Software Suites. - -# Release (2022-03-14) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/configservice`: [v1.19.0](service/configservice/CHANGELOG.md#v1190-2022-03-14) - * **Feature**: Add resourceType enums for AWS::ECR::PublicRepository and AWS::EC2::LaunchTemplate -* `github.com/aws/aws-sdk-go-v2/service/elasticache`: [v1.20.1](service/elasticache/CHANGELOG.md#v1201-2022-03-14) - * **Documentation**: Doc only update for ElastiCache -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.23.0](service/kendra/CHANGELOG.md#v1230-2022-03-14) - * **Feature**: Amazon Kendra now provides a data source connector for Slack. For more information, see https://docs.aws.amazon.com/kendra/latest/dg/data-source-slack.html -* `github.com/aws/aws-sdk-go-v2/service/timestreamquery`: [v1.14.0](service/timestreamquery/CHANGELOG.md#v1140-2022-03-14) - * **Feature**: Amazon Timestream Scheduled Queries now support Timestamp datatype in a multi-measure record. - -# Release (2022-03-11) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/chime`: [v1.20.0](service/chime/CHANGELOG.md#v1200-2022-03-11) - * **Feature**: Chime VoiceConnector Logging APIs will now support MediaMetricLogs. Also CreateMeetingDialOut now returns AccessDeniedException. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.20.0](service/connect/CHANGELOG.md#v1200-2022-03-11) - * **Feature**: This release adds support for enabling Rich Messaging when starting a new chat session via the StartChatContact API. Rich Messaging enables the following formatting options: bold, italics, hyperlinks, bulleted lists, and numbered lists. -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.20.0](service/lambda/CHANGELOG.md#v1200-2022-03-11) - * **Feature**: Adds PrincipalOrgID support to AddPermission API. Customers can use it to manage permissions to lambda functions at AWS Organizations level. -* `github.com/aws/aws-sdk-go-v2/service/outposts`: [v1.18.0](service/outposts/CHANGELOG.md#v1180-2022-03-11) - * **Feature**: This release adds address filters for listSites -* `github.com/aws/aws-sdk-go-v2/service/secretsmanager`: [v1.15.1](service/secretsmanager/CHANGELOG.md#v1151-2022-03-11) - * **Documentation**: Documentation updates for Secrets Manager. -* `github.com/aws/aws-sdk-go-v2/service/transcribestreaming`: [v1.6.0](service/transcribestreaming/CHANGELOG.md#v160-2022-03-11) - * **Feature**: Amazon Transcribe StartTranscription API now supports additional parameters for Language Identification feature: customVocabularies and customFilterVocabularies - -# Release (2022-03-10) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/lexmodelsv2`: [v1.20.0](service/lexmodelsv2/CHANGELOG.md#v1200-2022-03-10) - * **Feature**: This release makes slotTypeId an optional parameter in CreateSlot and UpdateSlot APIs in Amazon Lex V2 for model building. Customers can create and update slots without specifying a slot type id. -* `github.com/aws/aws-sdk-go-v2/service/transcribe`: [v1.18.0](service/transcribe/CHANGELOG.md#v1180-2022-03-10) - * **Feature**: Documentation fix for API `StartMedicalTranscriptionJobRequest`, now showing min sample rate as 16khz -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.18.0](service/transfer/CHANGELOG.md#v1180-2022-03-10) - * **Feature**: Adding more descriptive error types for managed workflows - -# Release (2022-03-09) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/comprehend`: [v1.17.0](service/comprehend/CHANGELOG.md#v1170-2022-03-09) - * **Feature**: Amazon Comprehend now supports extracting the sentiment associated with entities such as brands, products and services from text documents. - -# Release (2022-03-08.3) - -* No change notes available for this release. - -# Release (2022-03-08.2) - -* No change notes available for this release. - -# Release (2022-03-08) - -## General Highlights -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/amplify`: [v1.11.0](service/amplify/CHANGELOG.md#v1110-2022-03-08) - * **Feature**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/amplifyuibuilder`: [v1.5.0](service/amplifyuibuilder/CHANGELOG.md#v150-2022-03-08) - * **Feature**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/appflow`: [v1.14.0](service/appflow/CHANGELOG.md#v1140-2022-03-08) - * **Feature**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/apprunner`: [v1.11.0](service/apprunner/CHANGELOG.md#v1110-2022-03-08) - * **Feature**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/athena`: [v1.14.0](service/athena/CHANGELOG.md#v1140-2022-03-08) - * **Feature**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/braket`: [v1.15.0](service/braket/CHANGELOG.md#v1150-2022-03-08) - * **Feature**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmeetings`: [v1.7.0](service/chimesdkmeetings/CHANGELOG.md#v170-2022-03-08) - * **Feature**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/cloudtrail`: [v1.15.0](service/cloudtrail/CHANGELOG.md#v1150-2022-03-08) - * **Feature**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.19.0](service/connect/CHANGELOG.md#v1190-2022-03-08) - * **Feature**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/devopsguru`: [v1.16.0](service/devopsguru/CHANGELOG.md#v1160-2022-03-08) - * **Feature**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.31.0](service/ec2/CHANGELOG.md#v1310-2022-03-08) - * **Feature**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/ecr`: [v1.16.0](service/ecr/CHANGELOG.md#v1160-2022-03-08) - * **Feature**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.18.0](service/ecs/CHANGELOG.md#v1180-2022-03-08) - * **Feature**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/elasticache`: [v1.20.0](service/elasticache/CHANGELOG.md#v1200-2022-03-08) - * **Documentation**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/finspacedata`: [v1.10.0](service/finspacedata/CHANGELOG.md#v1100-2022-03-08) - * **Feature**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/fis`: [v1.12.0](service/fis/CHANGELOG.md#v1120-2022-03-08) - * **Feature**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/fsx`: [v1.20.0](service/fsx/CHANGELOG.md#v1200-2022-03-08) - * **Feature**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/gamelift`: [v1.14.0](service/gamelift/CHANGELOG.md#v1140-2022-03-08) - * **Documentation**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/greengrassv2`: [v1.15.0](service/greengrassv2/CHANGELOG.md#v1150-2022-03-08) - * **Documentation**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/internal/checksum`: [v1.1.0](service/internal/checksum/CHANGELOG.md#v110-2022-03-08) - * **Feature**: Updates the SDK's checksum validation logic to require opt-in to output response payload validation. The SDK was always preforming output response payload checksum validation, not respecting the output validation model option. Fixes [#1606](https://github.com/aws/aws-sdk-go-v2/issues/1606) -* `github.com/aws/aws-sdk-go-v2/service/kafkaconnect`: [v1.8.0](service/kafkaconnect/CHANGELOG.md#v180-2022-03-08) - * **Feature**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.22.0](service/kendra/CHANGELOG.md#v1220-2022-03-08) - * **Feature**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/keyspaces`: [v1.0.0](service/keyspaces/CHANGELOG.md#v100-2022-03-08) - * **Release**: New AWS service client module -* `github.com/aws/aws-sdk-go-v2/service/macie`: [v1.14.0](service/macie/CHANGELOG.md#v1140-2022-03-08) - * **Documentation**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/mediapackage`: [v1.15.0](service/mediapackage/CHANGELOG.md#v1150-2022-03-08) - * **Feature**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/mgn`: [v1.13.0](service/mgn/CHANGELOG.md#v1130-2022-03-08) - * **Feature**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/migrationhubrefactorspaces`: [v1.5.0](service/migrationhubrefactorspaces/CHANGELOG.md#v150-2022-03-08) - * **Documentation**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/mq`: [v1.12.0](service/mq/CHANGELOG.md#v1120-2022-03-08) - * **Feature**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/panorama`: [v1.6.0](service/panorama/CHANGELOG.md#v160-2022-03-08) - * **Feature**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.18.0](service/rds/CHANGELOG.md#v1180-2022-03-08) - * **Documentation**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/route53recoverycluster`: [v1.8.0](service/route53recoverycluster/CHANGELOG.md#v180-2022-03-08) - * **Feature**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/servicecatalogappregistry`: [v1.12.0](service/servicecatalogappregistry/CHANGELOG.md#v1120-2022-03-08) - * **Documentation**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/sqs`: [v1.18.0](service/sqs/CHANGELOG.md#v1180-2022-03-08) - * **Feature**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/sts`: [v1.16.0](service/sts/CHANGELOG.md#v1160-2022-03-08) - * **Documentation**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/synthetics`: [v1.14.0](service/synthetics/CHANGELOG.md#v1140-2022-03-08) - * **Documentation**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/timestreamquery`: [v1.13.0](service/timestreamquery/CHANGELOG.md#v1130-2022-03-08) - * **Documentation**: Updated service client model to latest release. -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.17.0](service/transfer/CHANGELOG.md#v1170-2022-03-08) - * **Feature**: Updated service client model to latest release. - -# Release (2022-02-24.2) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/autoscaling`: [v1.21.0](service/autoscaling/CHANGELOG.md#v1210-2022-02-242) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/databrew`: [v1.18.0](service/databrew/CHANGELOG.md#v1180-2022-02-242) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/fms`: [v1.15.0](service/fms/CHANGELOG.md#v1150-2022-02-242) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lightsail`: [v1.17.0](service/lightsail/CHANGELOG.md#v1170-2022-02-242) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/route53`: [v1.19.0](service/route53/CHANGELOG.md#v1190-2022-02-242) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/s3control`: [v1.20.0](service/s3control/CHANGELOG.md#v1200-2022-02-242) - * **Feature**: API client updated - -# Release (2022-02-24) - -## General Highlights -* **Feature**: Adds RetryMaxAttempts and RetryMod to API client Options. This allows the API clients' default Retryer to be configured from the shared configuration files or environment variables. Adding a new Retry mode of `Adaptive`. `Adaptive` retry mode is an experimental mode, adding client rate limiting when throttles reponses are received from an API. See [retry.AdaptiveMode](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/aws/retry#AdaptiveMode) for more details, and configuration options. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Bug Fix**: Fixes the AWS Sigv4 signer to trim header value's whitespace when computing the canonical headers block of the string to sign. -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2`: v1.14.0 - * **Feature**: Add new AdaptiveMode retryer to aws/retry package. This new retryer uses dynamic token bucketing with client ratelimiting when throttle responses are received. - * **Feature**: Adds new interface aws.RetryerV2, replacing aws.Retryer and deprecating the GetInitialToken method in favor of GetAttemptToken so Context can be provided. The SDK will use aws.RetryerV2 internally. Wrapping aws.Retryers as aws.RetryerV2 automatically. -* `github.com/aws/aws-sdk-go-v2/config`: [v1.14.0](config/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: Adds support for loading RetryMaxAttempts and RetryMod from the environment and shared configuration files. These parameters drive how the SDK's API client will initialize its default retryer, if custome retryer has not been specified. See [config](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/config) module and [aws.Config](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/aws#Config) for more information about and how to use these new options. - * **Feature**: Adds support for the `ca_bundle` parameter in shared config and credentials files. The usage of the file is the same as environment variable, `AWS_CA_BUNDLE`, but sourced from shared config. Fixes [#1589](https://github.com/aws/aws-sdk-go-v2/issues/1589) -* `github.com/aws/aws-sdk-go-v2/credentials`: [v1.9.0](credentials/CHANGELOG.md#v190-2022-02-24) - * **Feature**: Adds support for `SourceIdentity` to `stscreds.AssumeRoleProvider` [#1588](https://github.com/aws/aws-sdk-go-v2/pull/1588). Fixes [#1575](https://github.com/aws/aws-sdk-go-v2/issues/1575) -* `github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue`: [v1.7.0](feature/dynamodb/attributevalue/CHANGELOG.md#v170-2022-02-24) - * **Feature**: Fixes [#645](https://github.com/aws/aws-sdk-go-v2/issues/645), [#411](https://github.com/aws/aws-sdk-go-v2/issues/411) by adding support for (un)marshaling AttributeValue maps to Go maps key types of string, number, bool, and types implementing encoding.Text(un)Marshaler interface - * **Bug Fix**: Fixes [#1569](https://github.com/aws/aws-sdk-go-v2/issues/1569) inconsistent serialization of Go struct field names -* `github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression`: [v1.4.0](feature/dynamodb/expression/CHANGELOG.md#v140-2022-02-24) - * **Feature**: Add support for expression names with dots via new NameBuilder function NameNoDotSplit, related to [aws/aws-sdk-go#2570](https://github.com/aws/aws-sdk-go/issues/2570) -* `github.com/aws/aws-sdk-go-v2/feature/dynamodbstreams/attributevalue`: [v1.7.0](feature/dynamodbstreams/attributevalue/CHANGELOG.md#v170-2022-02-24) - * **Feature**: Fixes [#645](https://github.com/aws/aws-sdk-go-v2/issues/645), [#411](https://github.com/aws/aws-sdk-go-v2/issues/411) by adding support for (un)marshaling AttributeValue maps to Go maps key types of string, number, bool, and types implementing encoding.Text(un)Marshaler interface - * **Bug Fix**: Fixes [#1569](https://github.com/aws/aws-sdk-go-v2/issues/1569) inconsistent serialization of Go struct field names -* `github.com/aws/aws-sdk-go-v2/service/accessanalyzer`: [v1.14.0](service/accessanalyzer/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/account`: [v1.5.0](service/account/CHANGELOG.md#v150-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/acm`: [v1.13.0](service/acm/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/acmpca`: [v1.15.0](service/acmpca/CHANGELOG.md#v1150-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/alexaforbusiness`: [v1.13.0](service/alexaforbusiness/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/amp`: [v1.13.0](service/amp/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/amplify`: [v1.10.0](service/amplify/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/amplifybackend`: [v1.11.0](service/amplifybackend/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/amplifyuibuilder`: [v1.4.0](service/amplifyuibuilder/CHANGELOG.md#v140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/apigateway`: [v1.14.0](service/apigateway/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/apigatewaymanagementapi`: [v1.9.0](service/apigatewaymanagementapi/CHANGELOG.md#v190-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/apigatewayv2`: [v1.11.0](service/apigatewayv2/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/appconfig`: [v1.11.0](service/appconfig/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/appconfigdata`: [v1.3.0](service/appconfigdata/CHANGELOG.md#v130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/appflow`: [v1.13.0](service/appflow/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/appintegrations`: [v1.12.0](service/appintegrations/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/applicationautoscaling`: [v1.14.0](service/applicationautoscaling/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/applicationcostprofiler`: [v1.8.0](service/applicationcostprofiler/CHANGELOG.md#v180-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/applicationdiscoveryservice`: [v1.11.0](service/applicationdiscoveryservice/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/applicationinsights`: [v1.14.0](service/applicationinsights/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/appmesh`: [v1.12.0](service/appmesh/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/apprunner`: [v1.10.0](service/apprunner/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/appstream`: [v1.14.0](service/appstream/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/appsync`: [v1.13.0](service/appsync/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/athena`: [v1.13.0](service/athena/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/auditmanager`: [v1.16.0](service/auditmanager/CHANGELOG.md#v1160-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/autoscaling`: [v1.20.0](service/autoscaling/CHANGELOG.md#v1200-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/autoscalingplans`: [v1.11.0](service/autoscalingplans/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/backup`: [v1.14.0](service/backup/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/backupgateway`: [v1.4.0](service/backupgateway/CHANGELOG.md#v140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/batch`: [v1.15.0](service/batch/CHANGELOG.md#v1150-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/braket`: [v1.14.0](service/braket/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/budgets`: [v1.11.0](service/budgets/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/chime`: [v1.18.0](service/chime/CHANGELOG.md#v1180-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/chimesdkidentity`: [v1.8.0](service/chimesdkidentity/CHANGELOG.md#v180-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmeetings`: [v1.6.0](service/chimesdkmeetings/CHANGELOG.md#v160-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmessaging`: [v1.8.0](service/chimesdkmessaging/CHANGELOG.md#v180-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloud9`: [v1.15.0](service/cloud9/CHANGELOG.md#v1150-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudcontrol`: [v1.7.0](service/cloudcontrol/CHANGELOG.md#v170-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/clouddirectory`: [v1.11.0](service/clouddirectory/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudformation`: [v1.19.0](service/cloudformation/CHANGELOG.md#v1190-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudfront`: [v1.15.0](service/cloudfront/CHANGELOG.md#v1150-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudhsm`: [v1.11.0](service/cloudhsm/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudhsmv2`: [v1.12.0](service/cloudhsmv2/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudsearch`: [v1.12.0](service/cloudsearch/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudsearchdomain`: [v1.10.0](service/cloudsearchdomain/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudtrail`: [v1.14.0](service/cloudtrail/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudwatch`: [v1.16.0](service/cloudwatch/CHANGELOG.md#v1160-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudwatchevents`: [v1.13.0](service/cloudwatchevents/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs`: [v1.14.0](service/cloudwatchlogs/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/codeartifact`: [v1.11.0](service/codeartifact/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/codebuild`: [v1.18.0](service/codebuild/CHANGELOG.md#v1180-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/codecommit`: [v1.12.0](service/codecommit/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/codedeploy`: [v1.13.0](service/codedeploy/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/codeguruprofiler`: [v1.11.0](service/codeguruprofiler/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/codegurureviewer`: [v1.14.0](service/codegurureviewer/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/codepipeline`: [v1.12.0](service/codepipeline/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/codestar`: [v1.10.0](service/codestar/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/codestarconnections`: [v1.12.0](service/codestarconnections/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/codestarnotifications`: [v1.10.0](service/codestarnotifications/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cognitoidentity`: [v1.12.0](service/cognitoidentity/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider`: [v1.13.0](service/cognitoidentityprovider/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cognitosync`: [v1.10.0](service/cognitosync/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/comprehend`: [v1.15.0](service/comprehend/CHANGELOG.md#v1150-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/comprehendmedical`: [v1.12.0](service/comprehendmedical/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/computeoptimizer`: [v1.16.0](service/computeoptimizer/CHANGELOG.md#v1160-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/configservice`: [v1.17.0](service/configservice/CHANGELOG.md#v1170-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.18.0](service/connect/CHANGELOG.md#v1180-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/connectcontactlens`: [v1.11.0](service/connectcontactlens/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/connectparticipant`: [v1.10.0](service/connectparticipant/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/costandusagereportservice`: [v1.12.0](service/costandusagereportservice/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/costexplorer`: [v1.16.0](service/costexplorer/CHANGELOG.md#v1160-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/customerprofiles`: [v1.16.0](service/customerprofiles/CHANGELOG.md#v1160-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/databasemigrationservice`: [v1.17.0](service/databasemigrationservice/CHANGELOG.md#v1170-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/databrew`: [v1.17.0](service/databrew/CHANGELOG.md#v1170-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/dataexchange`: [v1.13.0](service/dataexchange/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/datapipeline`: [v1.12.0](service/datapipeline/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/datasync`: [v1.13.0](service/datasync/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/dax`: [v1.10.0](service/dax/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/detective`: [v1.14.0](service/detective/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/devicefarm`: [v1.12.0](service/devicefarm/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/devopsguru`: [v1.15.0](service/devopsguru/CHANGELOG.md#v1150-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/directconnect`: [v1.16.0](service/directconnect/CHANGELOG.md#v1160-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/directoryservice`: [v1.12.0](service/directoryservice/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/dlm`: [v1.10.0](service/dlm/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/docdb`: [v1.16.0](service/docdb/CHANGELOG.md#v1160-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/drs`: [v1.4.0](service/drs/CHANGELOG.md#v140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/dynamodb`: [v1.14.0](service/dynamodb/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/dynamodbstreams`: [v1.12.0](service/dynamodbstreams/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ebs`: [v1.13.0](service/ebs/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.30.0](service/ec2/CHANGELOG.md#v1300-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ec2instanceconnect`: [v1.12.0](service/ec2instanceconnect/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ecr`: [v1.15.0](service/ecr/CHANGELOG.md#v1150-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ecrpublic`: [v1.12.0](service/ecrpublic/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.17.0](service/ecs/CHANGELOG.md#v1170-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/efs`: [v1.15.0](service/efs/CHANGELOG.md#v1150-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/eks`: [v1.19.0](service/eks/CHANGELOG.md#v1190-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/elasticache`: [v1.19.0](service/elasticache/CHANGELOG.md#v1190-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/elasticbeanstalk`: [v1.13.0](service/elasticbeanstalk/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/elasticinference`: [v1.10.0](service/elasticinference/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/elasticloadbalancing`: [v1.13.0](service/elasticloadbalancing/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2`: [v1.17.0](service/elasticloadbalancingv2/CHANGELOG.md#v1170-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/elasticsearchservice`: [v1.14.0](service/elasticsearchservice/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/elastictranscoder`: [v1.12.0](service/elastictranscoder/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/emr`: [v1.16.0](service/emr/CHANGELOG.md#v1160-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/emrcontainers`: [v1.12.0](service/emrcontainers/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/eventbridge`: [v1.14.0](service/eventbridge/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/evidently`: [v1.5.0](service/evidently/CHANGELOG.md#v150-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/finspace`: [v1.7.0](service/finspace/CHANGELOG.md#v170-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/finspacedata`: [v1.9.0](service/finspacedata/CHANGELOG.md#v190-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/firehose`: [v1.13.0](service/firehose/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/fis`: [v1.11.0](service/fis/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/fms`: [v1.14.0](service/fms/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/forecast`: [v1.18.0](service/forecast/CHANGELOG.md#v1180-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/forecastquery`: [v1.10.0](service/forecastquery/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated - * **Bug Fix**: Fixed an issue that resulted in the wrong service endpoints being constructed. -* `github.com/aws/aws-sdk-go-v2/service/frauddetector`: [v1.18.0](service/frauddetector/CHANGELOG.md#v1180-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/fsx`: [v1.19.0](service/fsx/CHANGELOG.md#v1190-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/gamelift`: [v1.13.0](service/gamelift/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/glacier`: [v1.12.0](service/glacier/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/globalaccelerator`: [v1.12.0](service/globalaccelerator/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.20.0](service/glue/CHANGELOG.md#v1200-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/grafana`: [v1.6.0](service/grafana/CHANGELOG.md#v160-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/greengrass`: [v1.12.0](service/greengrass/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/greengrassv2`: [v1.14.0](service/greengrassv2/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/groundstation`: [v1.12.0](service/groundstation/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/guardduty`: [v1.12.0](service/guardduty/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/health`: [v1.14.0](service/health/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/healthlake`: [v1.13.0](service/healthlake/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/honeycode`: [v1.11.0](service/honeycode/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iam`: [v1.17.0](service/iam/CHANGELOG.md#v1170-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/identitystore`: [v1.13.0](service/identitystore/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/imagebuilder`: [v1.18.0](service/imagebuilder/CHANGELOG.md#v1180-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/inspector`: [v1.11.0](service/inspector/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/inspector2`: [v1.5.0](service/inspector2/CHANGELOG.md#v150-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/internal/checksum`: [v1.0.0](service/internal/checksum/CHANGELOG.md#v100-2022-02-24) - * **Release**: New module for computing checksums -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.22.0](service/iot/CHANGELOG.md#v1220-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iot1clickdevicesservice`: [v1.9.0](service/iot1clickdevicesservice/CHANGELOG.md#v190-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iot1clickprojects`: [v1.10.0](service/iot1clickprojects/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iotanalytics`: [v1.11.0](service/iotanalytics/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iotdataplane`: [v1.10.0](service/iotdataplane/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iotdeviceadvisor`: [v1.13.0](service/iotdeviceadvisor/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iotevents`: [v1.13.0](service/iotevents/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ioteventsdata`: [v1.10.0](service/ioteventsdata/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iotfleethub`: [v1.11.0](service/iotfleethub/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iotjobsdataplane`: [v1.10.0](service/iotjobsdataplane/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iotsecuretunneling`: [v1.11.0](service/iotsecuretunneling/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iotsitewise`: [v1.19.0](service/iotsitewise/CHANGELOG.md#v1190-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iotthingsgraph`: [v1.11.0](service/iotthingsgraph/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iottwinmaker`: [v1.4.0](service/iottwinmaker/CHANGELOG.md#v140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iotwireless`: [v1.17.0](service/iotwireless/CHANGELOG.md#v1170-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ivs`: [v1.15.0](service/ivs/CHANGELOG.md#v1150-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kafka`: [v1.16.0](service/kafka/CHANGELOG.md#v1160-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kafkaconnect`: [v1.7.0](service/kafkaconnect/CHANGELOG.md#v170-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.21.0](service/kendra/CHANGELOG.md#v1210-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kinesis`: [v1.14.0](service/kinesis/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kinesisanalytics`: [v1.12.0](service/kinesisanalytics/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kinesisanalyticsv2`: [v1.13.0](service/kinesisanalyticsv2/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kinesisvideo`: [v1.10.0](service/kinesisvideo/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kinesisvideoarchivedmedia`: [v1.11.0](service/kinesisvideoarchivedmedia/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kinesisvideomedia`: [v1.9.0](service/kinesisvideomedia/CHANGELOG.md#v190-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kinesisvideosignaling`: [v1.9.0](service/kinesisvideosignaling/CHANGELOG.md#v190-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kms`: [v1.15.0](service/kms/CHANGELOG.md#v1150-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lakeformation`: [v1.14.0](service/lakeformation/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.18.0](service/lambda/CHANGELOG.md#v1180-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lexmodelbuildingservice`: [v1.15.0](service/lexmodelbuildingservice/CHANGELOG.md#v1150-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lexmodelsv2`: [v1.18.0](service/lexmodelsv2/CHANGELOG.md#v1180-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lexruntimeservice`: [v1.11.0](service/lexruntimeservice/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lexruntimev2`: [v1.13.0](service/lexruntimev2/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/licensemanager`: [v1.14.0](service/licensemanager/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lightsail`: [v1.16.0](service/lightsail/CHANGELOG.md#v1160-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/location`: [v1.14.0](service/location/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lookoutequipment`: [v1.11.0](service/lookoutequipment/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lookoutmetrics`: [v1.10.0](service/lookoutmetrics/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lookoutvision`: [v1.11.0](service/lookoutvision/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/machinelearning`: [v1.13.0](service/machinelearning/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/macie`: [v1.13.0](service/macie/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/macie2`: [v1.19.0](service/macie2/CHANGELOG.md#v1190-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/managedblockchain`: [v1.11.0](service/managedblockchain/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/marketplacecatalog`: [v1.11.0](service/marketplacecatalog/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/marketplacecommerceanalytics`: [v1.10.0](service/marketplacecommerceanalytics/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/marketplaceentitlementservice`: [v1.10.0](service/marketplaceentitlementservice/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/marketplacemetering`: [v1.12.0](service/marketplacemetering/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mediaconnect`: [v1.14.0](service/mediaconnect/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.20.0](service/mediaconvert/CHANGELOG.md#v1200-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/medialive`: [v1.18.0](service/medialive/CHANGELOG.md#v1180-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mediapackage`: [v1.14.0](service/mediapackage/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mediapackagevod`: [v1.15.0](service/mediapackagevod/CHANGELOG.md#v1150-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mediastore`: [v1.11.0](service/mediastore/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mediastoredata`: [v1.11.0](service/mediastoredata/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mediatailor`: [v1.15.0](service/mediatailor/CHANGELOG.md#v1150-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/memorydb`: [v1.8.0](service/memorydb/CHANGELOG.md#v180-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mgn`: [v1.12.0](service/mgn/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/migrationhub`: [v1.11.0](service/migrationhub/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/migrationhubconfig`: [v1.11.0](service/migrationhubconfig/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/migrationhubrefactorspaces`: [v1.4.0](service/migrationhubrefactorspaces/CHANGELOG.md#v140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/migrationhubstrategy`: [v1.4.0](service/migrationhubstrategy/CHANGELOG.md#v140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mobile`: [v1.10.0](service/mobile/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mq`: [v1.11.0](service/mq/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mturk`: [v1.12.0](service/mturk/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mwaa`: [v1.11.0](service/mwaa/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/neptune`: [v1.15.0](service/neptune/CHANGELOG.md#v1150-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/networkfirewall`: [v1.14.0](service/networkfirewall/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/networkmanager`: [v1.11.0](service/networkmanager/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/nimble`: [v1.11.0](service/nimble/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/opensearch`: [v1.8.0](service/opensearch/CHANGELOG.md#v180-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/opsworks`: [v1.12.0](service/opsworks/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/opsworkscm`: [v1.13.0](service/opsworkscm/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/organizations`: [v1.13.0](service/organizations/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/outposts`: [v1.16.0](service/outposts/CHANGELOG.md#v1160-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/panorama`: [v1.5.0](service/panorama/CHANGELOG.md#v150-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/personalize`: [v1.16.0](service/personalize/CHANGELOG.md#v1160-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/personalizeevents`: [v1.10.0](service/personalizeevents/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/personalizeruntime`: [v1.10.0](service/personalizeruntime/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/pi`: [v1.13.0](service/pi/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/pinpoint`: [v1.15.0](service/pinpoint/CHANGELOG.md#v1150-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/pinpointemail`: [v1.10.0](service/pinpointemail/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/pinpointsmsvoice`: [v1.9.0](service/pinpointsmsvoice/CHANGELOG.md#v190-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/polly`: [v1.12.0](service/polly/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/pricing`: [v1.13.0](service/pricing/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/proton`: [v1.11.0](service/proton/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/qldb`: [v1.13.0](service/qldb/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/qldbsession`: [v1.12.0](service/qldbsession/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.19.0](service/quicksight/CHANGELOG.md#v1190-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ram`: [v1.15.0](service/ram/CHANGELOG.md#v1150-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/rbin`: [v1.5.0](service/rbin/CHANGELOG.md#v150-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.17.0](service/rds/CHANGELOG.md#v1170-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/rdsdata`: [v1.10.0](service/rdsdata/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/redshift`: [v1.20.0](service/redshift/CHANGELOG.md#v1200-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/redshiftdata`: [v1.14.0](service/redshiftdata/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/rekognition`: [v1.16.0](service/rekognition/CHANGELOG.md#v1160-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/resiliencehub`: [v1.4.0](service/resiliencehub/CHANGELOG.md#v140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/resourcegroups`: [v1.11.0](service/resourcegroups/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi`: [v1.12.0](service/resourcegroupstaggingapi/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/robomaker`: [v1.15.0](service/robomaker/CHANGELOG.md#v1150-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/route53`: [v1.18.0](service/route53/CHANGELOG.md#v1180-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/route53domains`: [v1.11.0](service/route53domains/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/route53recoverycluster`: [v1.7.0](service/route53recoverycluster/CHANGELOG.md#v170-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/route53recoverycontrolconfig`: [v1.8.0](service/route53recoverycontrolconfig/CHANGELOG.md#v180-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/route53recoveryreadiness`: [v1.7.0](service/route53recoveryreadiness/CHANGELOG.md#v170-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/route53resolver`: [v1.14.0](service/route53resolver/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/rum`: [v1.5.0](service/rum/CHANGELOG.md#v150-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.25.0](service/s3/CHANGELOG.md#v1250-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/s3control`: [v1.19.0](service/s3control/CHANGELOG.md#v1190-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/s3outposts`: [v1.11.0](service/s3outposts/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.25.0](service/sagemaker/CHANGELOG.md#v1250-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sagemakera2iruntime`: [v1.11.0](service/sagemakera2iruntime/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sagemakeredge`: [v1.10.0](service/sagemakeredge/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sagemakerfeaturestoreruntime`: [v1.10.0](service/sagemakerfeaturestoreruntime/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sagemakerruntime`: [v1.14.0](service/sagemakerruntime/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/savingsplans`: [v1.10.0](service/savingsplans/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/schemas`: [v1.13.0](service/schemas/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/secretsmanager`: [v1.14.0](service/secretsmanager/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.18.0](service/securityhub/CHANGELOG.md#v1180-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/serverlessapplicationrepository`: [v1.10.0](service/serverlessapplicationrepository/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/servicecatalog`: [v1.12.0](service/servicecatalog/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/servicecatalogappregistry`: [v1.11.0](service/servicecatalogappregistry/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/servicediscovery`: [v1.16.0](service/servicediscovery/CHANGELOG.md#v1160-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/servicequotas`: [v1.12.0](service/servicequotas/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ses`: [v1.13.0](service/ses/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sesv2`: [v1.12.0](service/sesv2/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sfn`: [v1.12.0](service/sfn/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/shield`: [v1.15.0](service/shield/CHANGELOG.md#v1150-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/signer`: [v1.12.0](service/signer/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sms`: [v1.11.0](service/sms/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/snowball`: [v1.14.0](service/snowball/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/snowdevicemanagement`: [v1.7.0](service/snowdevicemanagement/CHANGELOG.md#v170-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sns`: [v1.16.0](service/sns/CHANGELOG.md#v1160-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sqs`: [v1.17.0](service/sqs/CHANGELOG.md#v1170-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.21.0](service/ssm/CHANGELOG.md#v1210-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ssmcontacts`: [v1.12.0](service/ssmcontacts/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ssmincidents`: [v1.11.0](service/ssmincidents/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sso`: [v1.10.0](service/sso/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ssoadmin`: [v1.13.0](service/ssoadmin/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ssooidc`: [v1.11.0](service/ssooidc/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/storagegateway`: [v1.15.0](service/storagegateway/CHANGELOG.md#v1150-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sts`: [v1.15.0](service/sts/CHANGELOG.md#v1150-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/support`: [v1.12.0](service/support/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/swf`: [v1.12.0](service/swf/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/synthetics`: [v1.13.0](service/synthetics/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/textract`: [v1.13.0](service/textract/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/timestreamquery`: [v1.12.0](service/timestreamquery/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/timestreamwrite`: [v1.12.0](service/timestreamwrite/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/transcribe`: [v1.16.0](service/transcribe/CHANGELOG.md#v1160-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/transcribestreaming`: [v1.4.0](service/transcribestreaming/CHANGELOG.md#v140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.16.0](service/transfer/CHANGELOG.md#v1160-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/translate`: [v1.12.0](service/translate/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/voiceid`: [v1.7.0](service/voiceid/CHANGELOG.md#v170-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/waf`: [v1.10.0](service/waf/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/wafregional`: [v1.11.0](service/wafregional/CHANGELOG.md#v1110-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.17.0](service/wafv2/CHANGELOG.md#v1170-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/wellarchitected`: [v1.13.0](service/wellarchitected/CHANGELOG.md#v1130-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/wisdom`: [v1.6.0](service/wisdom/CHANGELOG.md#v160-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/workdocs`: [v1.10.0](service/workdocs/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/worklink`: [v1.10.0](service/worklink/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/workmail`: [v1.14.0](service/workmail/CHANGELOG.md#v1140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/workmailmessageflow`: [v1.10.0](service/workmailmessageflow/CHANGELOG.md#v1100-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/workspaces`: [v1.15.0](service/workspaces/CHANGELOG.md#v1150-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/workspacesweb`: [v1.4.0](service/workspacesweb/CHANGELOG.md#v140-2022-02-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/xray`: [v1.12.0](service/xray/CHANGELOG.md#v1120-2022-02-24) - * **Feature**: API client updated - -# Release (2022-01-28) - -## General Highlights -* **Bug Fix**: Fixes the SDK's handling of `duration_sections` in the shared credentials file or specified in multiple shared config and shared credentials files under the same profile. [#1568](https://github.com/aws/aws-sdk-go-v2/pull/1568). Thanks to [Amir Szekely](https://github.com/kichik) for help reproduce this bug. -* **Bug Fix**: Updates SDK API client deserialization to pre-allocate byte slice and string response payloads, [#1565](https://github.com/aws/aws-sdk-go-v2/pull/1565). Thanks to [Tyson Mote](https://github.com/tysonmote) for submitting this PR. -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/config`: [v1.13.1](config/CHANGELOG.md#v1131-2022-01-28) - * **Bug Fix**: Fixes LoadDefaultConfig handling of errors returned by passed in functional options. Previously errors returned from the LoadOptions passed into LoadDefaultConfig were incorrectly ignored. [#1562](https://github.com/aws/aws-sdk-go-v2/pull/1562). Thanks to [Pinglei Guo](https://github.com/pingleig) for submitting this PR. - * **Bug Fix**: Updates `config` module to use os.UserHomeDir instead of hard coded environment variable for OS. [#1563](https://github.com/aws/aws-sdk-go-v2/pull/1563) -* `github.com/aws/aws-sdk-go-v2/service/applicationinsights`: [v1.13.0](service/applicationinsights/CHANGELOG.md#v1130-2022-01-28) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/cloudtrail`: [v1.13.1](service/cloudtrail/CHANGELOG.md#v1131-2022-01-28) - * **Documentation**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/codegurureviewer`: [v1.13.1](service/codegurureviewer/CHANGELOG.md#v1131-2022-01-28) - * **Documentation**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/configservice`: [v1.16.0](service/configservice/CHANGELOG.md#v1160-2022-01-28) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.17.0](service/connect/CHANGELOG.md#v1170-2022-01-28) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/ebs`: [v1.12.1](service/ebs/CHANGELOG.md#v1121-2022-01-28) - * **Documentation**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.29.0](service/ec2/CHANGELOG.md#v1290-2022-01-28) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/ec2instanceconnect`: [v1.11.0](service/ec2instanceconnect/CHANGELOG.md#v1110-2022-01-28) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/efs`: [v1.14.0](service/efs/CHANGELOG.md#v1140-2022-01-28) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/fis`: [v1.10.0](service/fis/CHANGELOG.md#v1100-2022-01-28) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/frauddetector`: [v1.17.0](service/frauddetector/CHANGELOG.md#v1170-2022-01-28) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/fsx`: [v1.18.0](service/fsx/CHANGELOG.md#v1180-2022-01-28) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/greengrass`: [v1.11.0](service/greengrass/CHANGELOG.md#v1110-2022-01-28) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/greengrassv2`: [v1.13.0](service/greengrassv2/CHANGELOG.md#v1130-2022-01-28) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/guardduty`: [v1.11.0](service/guardduty/CHANGELOG.md#v1110-2022-01-28) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/honeycode`: [v1.10.0](service/honeycode/CHANGELOG.md#v1100-2022-01-28) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/ivs`: [v1.14.0](service/ivs/CHANGELOG.md#v1140-2022-01-28) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/kafka`: [v1.15.0](service/kafka/CHANGELOG.md#v1150-2022-01-28) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/location`: [v1.13.0](service/location/CHANGELOG.md#v1130-2022-01-28) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/lookoutmetrics`: [v1.9.0](service/lookoutmetrics/CHANGELOG.md#v190-2022-01-28) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/macie2`: [v1.18.0](service/macie2/CHANGELOG.md#v1180-2022-01-28) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.19.0](service/mediaconvert/CHANGELOG.md#v1190-2022-01-28) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/mediatailor`: [v1.14.0](service/mediatailor/CHANGELOG.md#v1140-2022-01-28) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/ram`: [v1.14.0](service/ram/CHANGELOG.md#v1140-2022-01-28) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/route53recoveryreadiness`: [v1.6.1](service/route53recoveryreadiness/CHANGELOG.md#v161-2022-01-28) - * **Documentation**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.24.0](service/sagemaker/CHANGELOG.md#v1240-2022-01-28) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.17.0](service/securityhub/CHANGELOG.md#v1170-2022-01-28) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/storagegateway`: [v1.14.0](service/storagegateway/CHANGELOG.md#v1140-2022-01-28) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/transcribe`: [v1.15.0](service/transcribe/CHANGELOG.md#v1150-2022-01-28) - * **Feature**: Updated to latest API model. - -# Release (2022-01-14) - -## General Highlights -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2`: v1.13.0 - * **Bug Fix**: Updates the Retry middleware to release the retry token, on subsequent attempts. This fixes #1413, and is based on PR #1424 -* `github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue`: [v1.6.0](feature/dynamodb/attributevalue/CHANGELOG.md#v160-2022-01-14) - * **Feature**: Adds new MarshalWithOptions and UnmarshalWithOptions helpers allowing Encoding and Decoding options to be specified when serializing AttributeValues. Addresses issue: https://github.com/aws/aws-sdk-go-v2/issues/1494 -* `github.com/aws/aws-sdk-go-v2/feature/dynamodbstreams/attributevalue`: [v1.6.0](feature/dynamodbstreams/attributevalue/CHANGELOG.md#v160-2022-01-14) - * **Feature**: Adds new MarshalWithOptions and UnmarshalWithOptions helpers allowing Encoding and Decoding options to be specified when serializing AttributeValues. Addresses issue: https://github.com/aws/aws-sdk-go-v2/issues/1494 -* `github.com/aws/aws-sdk-go-v2/service/appsync`: [v1.12.0](service/appsync/CHANGELOG.md#v1120-2022-01-14) - * **Feature**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/autoscalingplans`: [v1.10.0](service/autoscalingplans/CHANGELOG.md#v1100-2022-01-14) - * **Documentation**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/computeoptimizer`: [v1.15.0](service/computeoptimizer/CHANGELOG.md#v1150-2022-01-14) - * **Feature**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/costexplorer`: [v1.15.0](service/costexplorer/CHANGELOG.md#v1150-2022-01-14) - * **Documentation**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/databasemigrationservice`: [v1.16.0](service/databasemigrationservice/CHANGELOG.md#v1160-2022-01-14) - * **Documentation**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/databrew`: [v1.16.0](service/databrew/CHANGELOG.md#v1160-2022-01-14) - * **Feature**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.28.0](service/ec2/CHANGELOG.md#v1280-2022-01-14) - * **Feature**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/elasticache`: [v1.18.0](service/elasticache/CHANGELOG.md#v1180-2022-01-14) - * **Feature**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/elasticsearchservice`: [v1.13.0](service/elasticsearchservice/CHANGELOG.md#v1130-2022-01-14) - * **Feature**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/finspacedata`: [v1.8.0](service/finspacedata/CHANGELOG.md#v180-2022-01-14) - * **Documentation**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/fms`: [v1.13.0](service/fms/CHANGELOG.md#v1130-2022-01-14) - * **Documentation**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.19.0](service/glue/CHANGELOG.md#v1190-2022-01-14) - * **Feature**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/honeycode`: [v1.9.0](service/honeycode/CHANGELOG.md#v190-2022-01-14) - * **Feature**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/identitystore`: [v1.12.0](service/identitystore/CHANGELOG.md#v1120-2022-01-14) - * **Documentation**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/ioteventsdata`: [v1.9.0](service/ioteventsdata/CHANGELOG.md#v190-2022-01-14) - * **Documentation**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/iotwireless`: [v1.16.0](service/iotwireless/CHANGELOG.md#v1160-2022-01-14) - * **Feature**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.20.0](service/kendra/CHANGELOG.md#v1200-2022-01-14) - * **Feature**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/lexmodelsv2`: [v1.17.0](service/lexmodelsv2/CHANGELOG.md#v1170-2022-01-14) - * **Feature**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/lexruntimev2`: [v1.12.0](service/lexruntimev2/CHANGELOG.md#v1120-2022-01-14) - * **Feature**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/lookoutmetrics`: [v1.8.0](service/lookoutmetrics/CHANGELOG.md#v180-2022-01-14) - * **Feature**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/medialive`: [v1.17.0](service/medialive/CHANGELOG.md#v1170-2022-01-14) - * **Feature**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/mediatailor`: [v1.13.0](service/mediatailor/CHANGELOG.md#v1130-2022-01-14) - * **Feature**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/mwaa`: [v1.10.0](service/mwaa/CHANGELOG.md#v1100-2022-01-14) - * **Feature**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/nimble`: [v1.10.0](service/nimble/CHANGELOG.md#v1100-2022-01-14) - * **Feature**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/opensearch`: [v1.7.0](service/opensearch/CHANGELOG.md#v170-2022-01-14) - * **Feature**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/pi`: [v1.12.0](service/pi/CHANGELOG.md#v1120-2022-01-14) - * **Feature**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/pinpoint`: [v1.14.0](service/pinpoint/CHANGELOG.md#v1140-2022-01-14) - * **Feature**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.16.0](service/rds/CHANGELOG.md#v1160-2022-01-14) - * **Feature**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.20.0](service/ssm/CHANGELOG.md#v1200-2022-01-14) - * **Feature**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/sso`: [v1.9.0](service/sso/CHANGELOG.md#v190-2022-01-14) - * **Documentation**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/transcribe`: [v1.14.0](service/transcribe/CHANGELOG.md#v1140-2022-01-14) - * **Documentation**: Updated API models -* `github.com/aws/aws-sdk-go-v2/service/workspaces`: [v1.14.0](service/workspaces/CHANGELOG.md#v1140-2022-01-14) - * **Feature**: Updated API models - -# Release (2022-01-07) - -## General Highlights -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/config`: [v1.12.0](config/CHANGELOG.md#v1120-2022-01-07) - * **Feature**: Add load option for CredentialCache. Adds a new member to the LoadOptions struct, CredentialsCacheOptions. This member allows specifying a function that will be used to configure the CredentialsCache. The CredentialsCacheOptions will only be used if the configuration loader will wrap the underlying credential provider in the CredentialsCache. -* `github.com/aws/aws-sdk-go-v2/service/appstream`: [v1.12.0](service/appstream/CHANGELOG.md#v1120-2022-01-07) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudtrail`: [v1.12.0](service/cloudtrail/CHANGELOG.md#v1120-2022-01-07) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/detective`: [v1.12.0](service/detective/CHANGELOG.md#v1120-2022-01-07) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.27.0](service/ec2/CHANGELOG.md#v1270-2022-01-07) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.15.0](service/ecs/CHANGELOG.md#v1150-2022-01-07) - * **Documentation**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/eks`: [v1.17.0](service/eks/CHANGELOG.md#v1170-2022-01-07) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.18.0](service/glue/CHANGELOG.md#v1180-2022-01-07) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/greengrassv2`: [v1.11.0](service/greengrassv2/CHANGELOG.md#v1110-2022-01-07) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.20.0](service/iot/CHANGELOG.md#v1200-2022-01-07) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lakeformation`: [v1.12.0](service/lakeformation/CHANGELOG.md#v1120-2022-01-07) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.16.0](service/lambda/CHANGELOG.md#v1160-2022-01-07) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.17.0](service/mediaconvert/CHANGELOG.md#v1170-2022-01-07) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.17.0](service/quicksight/CHANGELOG.md#v1170-2022-01-07) - * **Documentation**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.15.0](service/rds/CHANGELOG.md#v1150-2022-01-07) - * **Documentation**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/rekognition`: [v1.14.0](service/rekognition/CHANGELOG.md#v1140-2022-01-07) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.23.0](service/s3/CHANGELOG.md#v1230-2022-01-07) - * **Documentation**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/s3control`: [v1.17.0](service/s3control/CHANGELOG.md#v1170-2022-01-07) - * **Documentation**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/s3outposts`: [v1.9.0](service/s3outposts/CHANGELOG.md#v190-2022-01-07) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.22.0](service/sagemaker/CHANGELOG.md#v1220-2022-01-07) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/secretsmanager`: [v1.12.0](service/secretsmanager/CHANGELOG.md#v1120-2022-01-07) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ssooidc`: [v1.9.0](service/ssooidc/CHANGELOG.md#v190-2022-01-07) - * **Feature**: API client updated - -# Release (2021-12-21) - -## General Highlights -* **Feature**: API Paginators now support specifying the initial starting token, and support stopping on empty string tokens. -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/accessanalyzer`: [v1.11.0](service/accessanalyzer/CHANGELOG.md#v1110-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/acm`: [v1.10.0](service/acm/CHANGELOG.md#v1100-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/apigateway`: [v1.11.0](service/apigateway/CHANGELOG.md#v1110-2021-12-21) - * **Documentation**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/applicationautoscaling`: [v1.11.0](service/applicationautoscaling/CHANGELOG.md#v1110-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/appsync`: [v1.10.0](service/appsync/CHANGELOG.md#v1100-2021-12-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/autoscaling`: [v1.17.0](service/autoscaling/CHANGELOG.md#v1170-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmeetings`: [v1.3.0](service/chimesdkmeetings/CHANGELOG.md#v130-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmessaging`: [v1.5.0](service/chimesdkmessaging/CHANGELOG.md#v150-2021-12-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudcontrol`: [v1.4.0](service/cloudcontrol/CHANGELOG.md#v140-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/cloudformation`: [v1.16.0](service/cloudformation/CHANGELOG.md#v1160-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/cloudwatch`: [v1.13.0](service/cloudwatch/CHANGELOG.md#v1130-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/cloudwatchevents`: [v1.10.0](service/cloudwatchevents/CHANGELOG.md#v1100-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs`: [v1.11.0](service/cloudwatchlogs/CHANGELOG.md#v1110-2021-12-21) - * **Feature**: API client updated - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/codedeploy`: [v1.10.0](service/codedeploy/CHANGELOG.md#v1100-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/comprehendmedical`: [v1.9.0](service/comprehendmedical/CHANGELOG.md#v190-2021-12-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/configservice`: [v1.13.0](service/configservice/CHANGELOG.md#v1130-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/customerprofiles`: [v1.13.0](service/customerprofiles/CHANGELOG.md#v1130-2021-12-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/databasemigrationservice`: [v1.14.0](service/databasemigrationservice/CHANGELOG.md#v1140-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/datasync`: [v1.10.0](service/datasync/CHANGELOG.md#v1100-2021-12-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/devopsguru`: [v1.12.0](service/devopsguru/CHANGELOG.md#v1120-2021-12-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/directconnect`: [v1.13.0](service/directconnect/CHANGELOG.md#v1130-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/docdb`: [v1.13.0](service/docdb/CHANGELOG.md#v1130-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/dynamodb`: [v1.11.0](service/dynamodb/CHANGELOG.md#v1110-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/dynamodbstreams`: [v1.9.0](service/dynamodbstreams/CHANGELOG.md#v190-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.26.0](service/ec2/CHANGELOG.md#v1260-2021-12-21) - * **Feature**: API client updated - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/ecr`: [v1.12.0](service/ecr/CHANGELOG.md#v1120-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.14.0](service/ecs/CHANGELOG.md#v1140-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/elasticache`: [v1.16.0](service/elasticache/CHANGELOG.md#v1160-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/elasticloadbalancing`: [v1.10.0](service/elasticloadbalancing/CHANGELOG.md#v1100-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2`: [v1.14.0](service/elasticloadbalancingv2/CHANGELOG.md#v1140-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/elasticsearchservice`: [v1.11.0](service/elasticsearchservice/CHANGELOG.md#v1110-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/emr`: [v1.13.0](service/emr/CHANGELOG.md#v1130-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/eventbridge`: [v1.11.0](service/eventbridge/CHANGELOG.md#v1110-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/finspacedata`: [v1.6.0](service/finspacedata/CHANGELOG.md#v160-2021-12-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/forecast`: [v1.15.0](service/forecast/CHANGELOG.md#v1150-2021-12-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/glacier`: [v1.9.0](service/glacier/CHANGELOG.md#v190-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/groundstation`: [v1.9.0](service/groundstation/CHANGELOG.md#v190-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/health`: [v1.11.0](service/health/CHANGELOG.md#v1110-2021-12-21) - * **Documentation**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/imagebuilder`: [v1.15.0](service/imagebuilder/CHANGELOG.md#v1150-2021-12-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.19.0](service/iot/CHANGELOG.md#v1190-2021-12-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kinesis`: [v1.11.0](service/kinesis/CHANGELOG.md#v1110-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/kinesisanalytics`: [v1.9.0](service/kinesisanalytics/CHANGELOG.md#v190-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/kinesisanalyticsv2`: [v1.10.0](service/kinesisanalyticsv2/CHANGELOG.md#v1100-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/kms`: [v1.12.0](service/kms/CHANGELOG.md#v1120-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.15.0](service/lambda/CHANGELOG.md#v1150-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/lexmodelsv2`: [v1.15.0](service/lexmodelsv2/CHANGELOG.md#v1150-2021-12-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/location`: [v1.10.0](service/location/CHANGELOG.md#v1100-2021-12-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lookoutmetrics`: [v1.6.0](service/lookoutmetrics/CHANGELOG.md#v160-2021-12-21) - * **Feature**: API client updated - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/lookoutvision`: [v1.8.0](service/lookoutvision/CHANGELOG.md#v180-2021-12-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/marketplacemetering`: [v1.9.0](service/marketplacemetering/CHANGELOG.md#v190-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/mediaconnect`: [v1.11.0](service/mediaconnect/CHANGELOG.md#v1110-2021-12-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/neptune`: [v1.12.0](service/neptune/CHANGELOG.md#v1120-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/networkfirewall`: [v1.11.0](service/networkfirewall/CHANGELOG.md#v1110-2021-12-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/nimble`: [v1.8.0](service/nimble/CHANGELOG.md#v180-2021-12-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/opensearch`: [v1.5.0](service/opensearch/CHANGELOG.md#v150-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/outposts`: [v1.13.0](service/outposts/CHANGELOG.md#v1130-2021-12-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/pi`: [v1.10.0](service/pi/CHANGELOG.md#v1100-2021-12-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/qldb`: [v1.10.0](service/qldb/CHANGELOG.md#v1100-2021-12-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.14.0](service/rds/CHANGELOG.md#v1140-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/redshift`: [v1.17.0](service/redshift/CHANGELOG.md#v1170-2021-12-21) - * **Feature**: API client updated - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/resourcegroups`: [v1.8.0](service/resourcegroups/CHANGELOG.md#v180-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi`: [v1.9.0](service/resourcegroupstaggingapi/CHANGELOG.md#v190-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/route53`: [v1.15.0](service/route53/CHANGELOG.md#v1150-2021-12-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/route53domains`: [v1.8.0](service/route53domains/CHANGELOG.md#v180-2021-12-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/route53recoverycontrolconfig`: [v1.5.0](service/route53recoverycontrolconfig/CHANGELOG.md#v150-2021-12-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.22.0](service/s3/CHANGELOG.md#v1220-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/s3control`: [v1.16.0](service/s3control/CHANGELOG.md#v1160-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.21.0](service/sagemaker/CHANGELOG.md#v1210-2021-12-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/savingsplans`: [v1.7.3](service/savingsplans/CHANGELOG.md#v173-2021-12-21) - * **Documentation**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/secretsmanager`: [v1.11.0](service/secretsmanager/CHANGELOG.md#v1110-2021-12-21) - * **Documentation**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.14.0](service/securityhub/CHANGELOG.md#v1140-2021-12-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sfn`: [v1.9.0](service/sfn/CHANGELOG.md#v190-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/sms`: [v1.8.0](service/sms/CHANGELOG.md#v180-2021-12-21) - * **Documentation**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sns`: [v1.13.0](service/sns/CHANGELOG.md#v1130-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/sqs`: [v1.14.0](service/sqs/CHANGELOG.md#v1140-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.18.0](service/ssm/CHANGELOG.md#v1180-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/sts`: [v1.12.0](service/sts/CHANGELOG.md#v1120-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/support`: [v1.9.0](service/support/CHANGELOG.md#v190-2021-12-21) - * **Documentation**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/swf`: [v1.9.0](service/swf/CHANGELOG.md#v190-2021-12-21) - * **Feature**: Updated to latest service endpoints -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.13.0](service/transfer/CHANGELOG.md#v1130-2021-12-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/workmail`: [v1.11.0](service/workmail/CHANGELOG.md#v1110-2021-12-21) - * **Feature**: API client updated - -# Release (2021-12-03) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/accessanalyzer`: [v1.10.1](service/accessanalyzer/CHANGELOG.md#v1101-2021-12-03) - * **Bug Fix**: Fixed an issue that prevent auto-filling of an API's idempotency parameters when not explictly provided by the caller. -* `github.com/aws/aws-sdk-go-v2/service/amp`: [v1.9.3](service/amp/CHANGELOG.md#v193-2021-12-03) - * **Bug Fix**: Fixed an issue that prevent auto-filling of an API's idempotency parameters when not explictly provided by the caller. -* `github.com/aws/aws-sdk-go-v2/service/amplifyuibuilder`: [v1.0.0](service/amplifyuibuilder/CHANGELOG.md#v100-2021-12-03) - * **Release**: New AWS service client module -* `github.com/aws/aws-sdk-go-v2/service/appmesh`: [v1.8.3](service/appmesh/CHANGELOG.md#v183-2021-12-03) - * **Bug Fix**: Fixed an issue that prevent auto-filling of an API's idempotency parameters when not explictly provided by the caller. -* `github.com/aws/aws-sdk-go-v2/service/braket`: [v1.10.2](service/braket/CHANGELOG.md#v1102-2021-12-03) - * **Bug Fix**: Fixed an issue that prevent auto-filling of an API's idempotency parameters when not explictly provided by the caller. -* `github.com/aws/aws-sdk-go-v2/service/codeguruprofiler`: [v1.7.3](service/codeguruprofiler/CHANGELOG.md#v173-2021-12-03) - * **Bug Fix**: Fixed an issue that prevent auto-filling of an API's idempotency parameters when not explictly provided by the caller. -* `github.com/aws/aws-sdk-go-v2/service/evidently`: [v1.1.1](service/evidently/CHANGELOG.md#v111-2021-12-03) - * **Bug Fix**: Fixed a bug that prevented the resolution of the correct endpoint for some API operations. -* `github.com/aws/aws-sdk-go-v2/service/grafana`: [v1.2.3](service/grafana/CHANGELOG.md#v123-2021-12-03) - * **Bug Fix**: Fixed an issue that prevent auto-filling of an API's idempotency parameters when not explictly provided by the caller. -* `github.com/aws/aws-sdk-go-v2/service/location`: [v1.9.2](service/location/CHANGELOG.md#v192-2021-12-03) - * **Bug Fix**: Fixed a bug that prevented the resolution of the correct endpoint for some API operations. - * **Bug Fix**: Fixed an issue that caused some operations to not be signed using sigv4, resulting in authentication failures. -* `github.com/aws/aws-sdk-go-v2/service/networkmanager`: [v1.7.0](service/networkmanager/CHANGELOG.md#v170-2021-12-03) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/nimble`: [v1.7.3](service/nimble/CHANGELOG.md#v173-2021-12-03) - * **Bug Fix**: Fixed an issue that prevent auto-filling of an API's idempotency parameters when not explictly provided by the caller. -* `github.com/aws/aws-sdk-go-v2/service/proton`: [v1.7.2](service/proton/CHANGELOG.md#v172-2021-12-03) - * **Bug Fix**: Fixed an issue that prevent auto-filling of an API's idempotency parameters when not explictly provided by the caller. -* `github.com/aws/aws-sdk-go-v2/service/ram`: [v1.10.0](service/ram/CHANGELOG.md#v1100-2021-12-03) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/rekognition`: [v1.12.0](service/rekognition/CHANGELOG.md#v1120-2021-12-03) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/snowdevicemanagement`: [v1.3.3](service/snowdevicemanagement/CHANGELOG.md#v133-2021-12-03) - * **Bug Fix**: Fixed an issue that prevent auto-filling of an API's idempotency parameters when not explictly provided by the caller. -* `github.com/aws/aws-sdk-go-v2/service/wisdom`: [v1.2.3](service/wisdom/CHANGELOG.md#v123-2021-12-03) - * **Bug Fix**: Fixed an issue that prevent auto-filling of an API's idempotency parameters when not explictly provided by the caller. - -# Release (2021-12-02) - -## General Highlights -* **Bug Fix**: Fixes a bug that prevented aws.EndpointResolverWithOptions from being used by the service client. ([#1514](https://github.com/aws/aws-sdk-go-v2/pull/1514)) -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/config`: [v1.11.0](config/CHANGELOG.md#v1110-2021-12-02) - * **Feature**: Add support for specifying `EndpointResolverWithOptions` on `LoadOptions`, and associated `WithEndpointResolverWithOptions`. -* `github.com/aws/aws-sdk-go-v2/service/accessanalyzer`: [v1.10.0](service/accessanalyzer/CHANGELOG.md#v1100-2021-12-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/applicationinsights`: [v1.9.0](service/applicationinsights/CHANGELOG.md#v190-2021-12-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/backupgateway`: [v1.0.0](service/backupgateway/CHANGELOG.md#v100-2021-12-02) - * **Release**: New AWS service client module -* `github.com/aws/aws-sdk-go-v2/service/cloudhsm`: [v1.8.0](service/cloudhsm/CHANGELOG.md#v180-2021-12-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/devopsguru`: [v1.11.0](service/devopsguru/CHANGELOG.md#v1110-2021-12-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/directconnect`: [v1.12.0](service/directconnect/CHANGELOG.md#v1120-2021-12-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/dynamodb`: [v1.10.0](service/dynamodb/CHANGELOG.md#v1100-2021-12-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.25.0](service/ec2/CHANGELOG.md#v1250-2021-12-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/evidently`: [v1.1.0](service/evidently/CHANGELOG.md#v110-2021-12-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/fsx`: [v1.14.0](service/fsx/CHANGELOG.md#v1140-2021-12-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.16.0](service/glue/CHANGELOG.md#v1160-2021-12-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/inspector2`: [v1.1.0](service/inspector2/CHANGELOG.md#v110-2021-12-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.18.0](service/iot/CHANGELOG.md#v1180-2021-12-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iottwinmaker`: [v1.0.0](service/iottwinmaker/CHANGELOG.md#v100-2021-12-02) - * **Release**: New AWS service client module -* `github.com/aws/aws-sdk-go-v2/service/kafka`: [v1.11.0](service/kafka/CHANGELOG.md#v1110-2021-12-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.17.0](service/kendra/CHANGELOG.md#v1170-2021-12-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kinesis`: [v1.10.0](service/kinesis/CHANGELOG.md#v1100-2021-12-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lakeformation`: [v1.10.0](service/lakeformation/CHANGELOG.md#v1100-2021-12-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lexmodelsv2`: [v1.14.0](service/lexmodelsv2/CHANGELOG.md#v1140-2021-12-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lexruntimev2`: [v1.10.0](service/lexruntimev2/CHANGELOG.md#v1100-2021-12-02) - * **Feature**: Support has been added for the `StartConversation` API. -* `github.com/aws/aws-sdk-go-v2/service/outposts`: [v1.12.0](service/outposts/CHANGELOG.md#v1120-2021-12-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/rbin`: [v1.1.0](service/rbin/CHANGELOG.md#v110-2021-12-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/redshiftdata`: [v1.10.0](service/redshiftdata/CHANGELOG.md#v1100-2021-12-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/rum`: [v1.1.0](service/rum/CHANGELOG.md#v110-2021-12-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.21.0](service/s3/CHANGELOG.md#v1210-2021-12-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.20.0](service/sagemaker/CHANGELOG.md#v1200-2021-12-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sagemakerruntime`: [v1.11.0](service/sagemakerruntime/CHANGELOG.md#v1110-2021-12-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/shield`: [v1.11.0](service/shield/CHANGELOG.md#v1110-2021-12-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/snowball`: [v1.10.0](service/snowball/CHANGELOG.md#v1100-2021-12-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/storagegateway`: [v1.10.0](service/storagegateway/CHANGELOG.md#v1100-2021-12-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/workspacesweb`: [v1.0.0](service/workspacesweb/CHANGELOG.md#v100-2021-12-02) - * **Release**: New AWS service client module - -# Release (2021-11-30) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/autoscaling`: [v1.16.0](service/autoscaling/CHANGELOG.md#v1160-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/backup`: [v1.10.0](service/backup/CHANGELOG.md#v1100-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/braket`: [v1.10.0](service/braket/CHANGELOG.md#v1100-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmeetings`: [v1.2.0](service/chimesdkmeetings/CHANGELOG.md#v120-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudformation`: [v1.15.0](service/cloudformation/CHANGELOG.md#v1150-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/computeoptimizer`: [v1.13.0](service/computeoptimizer/CHANGELOG.md#v1130-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.13.0](service/connect/CHANGELOG.md#v1130-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/customerprofiles`: [v1.12.0](service/customerprofiles/CHANGELOG.md#v1120-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/databasemigrationservice`: [v1.13.0](service/databasemigrationservice/CHANGELOG.md#v1130-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/dataexchange`: [v1.9.0](service/dataexchange/CHANGELOG.md#v190-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/dynamodb`: [v1.9.0](service/dynamodb/CHANGELOG.md#v190-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.24.0](service/ec2/CHANGELOG.md#v1240-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ecr`: [v1.11.0](service/ecr/CHANGELOG.md#v1110-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.13.0](service/ecs/CHANGELOG.md#v1130-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/eks`: [v1.15.0](service/eks/CHANGELOG.md#v1150-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/elasticache`: [v1.15.0](service/elasticache/CHANGELOG.md#v1150-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2`: [v1.13.0](service/elasticloadbalancingv2/CHANGELOG.md#v1130-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/elasticsearchservice`: [v1.10.0](service/elasticsearchservice/CHANGELOG.md#v1100-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/evidently`: [v1.0.0](service/evidently/CHANGELOG.md#v100-2021-11-30) - * **Release**: New AWS service client module -* `github.com/aws/aws-sdk-go-v2/service/finspacedata`: [v1.5.0](service/finspacedata/CHANGELOG.md#v150-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/imagebuilder`: [v1.14.0](service/imagebuilder/CHANGELOG.md#v1140-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/inspector2`: [v1.0.0](service/inspector2/CHANGELOG.md#v100-2021-11-30) - * **Release**: New AWS service client module -* `github.com/aws/aws-sdk-go-v2/service/internal/endpoint-discovery`: [v1.3.2](service/internal/endpoint-discovery/CHANGELOG.md#v132-2021-11-30) - * **Bug Fix**: Fixed a race condition that caused concurrent calls relying on endpoint discovery to share the same `url.URL` reference in their operation's http.Request. -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.17.0](service/iot/CHANGELOG.md#v1170-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iotdeviceadvisor`: [v1.9.0](service/iotdeviceadvisor/CHANGELOG.md#v190-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iotsitewise`: [v1.15.0](service/iotsitewise/CHANGELOG.md#v1150-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iotwireless`: [v1.13.0](service/iotwireless/CHANGELOG.md#v1130-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.14.0](service/lambda/CHANGELOG.md#v1140-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/macie2`: [v1.14.0](service/macie2/CHANGELOG.md#v1140-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mgn`: [v1.8.0](service/mgn/CHANGELOG.md#v180-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/migrationhubrefactorspaces`: [v1.0.0](service/migrationhubrefactorspaces/CHANGELOG.md#v100-2021-11-30) - * **Release**: New AWS service client module -* `github.com/aws/aws-sdk-go-v2/service/opensearch`: [v1.4.0](service/opensearch/CHANGELOG.md#v140-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/outposts`: [v1.11.0](service/outposts/CHANGELOG.md#v1110-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/personalize`: [v1.12.0](service/personalize/CHANGELOG.md#v1120-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/personalizeruntime`: [v1.7.0](service/personalizeruntime/CHANGELOG.md#v170-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/pinpoint`: [v1.12.0](service/pinpoint/CHANGELOG.md#v1120-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/proton`: [v1.7.0](service/proton/CHANGELOG.md#v170-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.15.0](service/quicksight/CHANGELOG.md#v1150-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/rbin`: [v1.0.0](service/rbin/CHANGELOG.md#v100-2021-11-30) - * **Release**: New AWS service client module -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.13.0](service/rds/CHANGELOG.md#v1130-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/redshift`: [v1.16.0](service/redshift/CHANGELOG.md#v1160-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/rum`: [v1.0.0](service/rum/CHANGELOG.md#v100-2021-11-30) - * **Release**: New AWS service client module -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.20.0](service/s3/CHANGELOG.md#v1200-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/s3control`: [v1.15.0](service/s3control/CHANGELOG.md#v1150-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sqs`: [v1.13.0](service/sqs/CHANGELOG.md#v1130-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.17.0](service/ssm/CHANGELOG.md#v1170-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sts`: [v1.11.0](service/sts/CHANGELOG.md#v1110-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/textract`: [v1.10.0](service/textract/CHANGELOG.md#v1100-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/timestreamquery`: [v1.8.0](service/timestreamquery/CHANGELOG.md#v180-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/timestreamwrite`: [v1.8.0](service/timestreamwrite/CHANGELOG.md#v180-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/transcribestreaming`: [v1.1.0](service/transcribestreaming/CHANGELOG.md#v110-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/translate`: [v1.8.0](service/translate/CHANGELOG.md#v180-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/wellarchitected`: [v1.9.0](service/wellarchitected/CHANGELOG.md#v190-2021-11-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/workspaces`: [v1.11.0](service/workspaces/CHANGELOG.md#v1110-2021-11-30) - * **Feature**: API client updated - -# Release (2021-11-19) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2`: v1.11.1 - * **Bug Fix**: Fixed a bug that prevented aws.EndpointResolverWithOptionsFunc from satisfying the aws.EndpointResolverWithOptions interface. -* `github.com/aws/aws-sdk-go-v2/service/amplifybackend`: [v1.8.0](service/amplifybackend/CHANGELOG.md#v180-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/apigateway`: [v1.10.0](service/apigateway/CHANGELOG.md#v1100-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/appconfig`: [v1.7.0](service/appconfig/CHANGELOG.md#v170-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/appconfigdata`: [v1.0.0](service/appconfigdata/CHANGELOG.md#v100-2021-11-19) - * **Release**: New AWS service client module -* `github.com/aws/aws-sdk-go-v2/service/applicationinsights`: [v1.8.0](service/applicationinsights/CHANGELOG.md#v180-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/appstream`: [v1.10.0](service/appstream/CHANGELOG.md#v1100-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/auditmanager`: [v1.12.0](service/auditmanager/CHANGELOG.md#v1120-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/batch`: [v1.11.0](service/batch/CHANGELOG.md#v1110-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/chime`: [v1.14.0](service/chime/CHANGELOG.md#v1140-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmeetings`: [v1.1.0](service/chimesdkmeetings/CHANGELOG.md#v110-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudformation`: [v1.14.0](service/cloudformation/CHANGELOG.md#v1140-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudtrail`: [v1.10.0](service/cloudtrail/CHANGELOG.md#v1100-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudwatch`: [v1.12.0](service/cloudwatch/CHANGELOG.md#v1120-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.12.0](service/connect/CHANGELOG.md#v1120-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/databasemigrationservice`: [v1.12.0](service/databasemigrationservice/CHANGELOG.md#v1120-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/databrew`: [v1.13.0](service/databrew/CHANGELOG.md#v1130-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/devopsguru`: [v1.10.0](service/devopsguru/CHANGELOG.md#v1100-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/drs`: [v1.0.0](service/drs/CHANGELOG.md#v100-2021-11-19) - * **Release**: New AWS service client module -* `github.com/aws/aws-sdk-go-v2/service/dynamodbstreams`: [v1.8.0](service/dynamodbstreams/CHANGELOG.md#v180-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.23.0](service/ec2/CHANGELOG.md#v1230-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/eks`: [v1.14.0](service/eks/CHANGELOG.md#v1140-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/forecast`: [v1.14.0](service/forecast/CHANGELOG.md#v1140-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ivs`: [v1.10.0](service/ivs/CHANGELOG.md#v1100-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kafka`: [v1.10.0](service/kafka/CHANGELOG.md#v1100-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.16.0](service/kendra/CHANGELOG.md#v1160-2021-11-19) - * **Announcement**: Fix API modeling bug incorrectly generating `DocumentAttributeValue` type as a union instead of a structure. This update corrects this bug by correcting the `DocumentAttributeValue` type to be a `struct` instead of an `interface`. This change also removes the `DocumentAttributeValueMember` types. To migrate to this change your application using service/kendra will need to be updated to use struct members in `DocumentAttributeValue` instead of `DocumentAttributeValueMember` types. - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kms`: [v1.11.0](service/kms/CHANGELOG.md#v1110-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.13.0](service/lambda/CHANGELOG.md#v1130-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lexmodelsv2`: [v1.13.0](service/lexmodelsv2/CHANGELOG.md#v1130-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lexruntimev2`: [v1.9.0](service/lexruntimev2/CHANGELOG.md#v190-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/location`: [v1.9.0](service/location/CHANGELOG.md#v190-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.15.0](service/mediaconvert/CHANGELOG.md#v1150-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/medialive`: [v1.14.0](service/medialive/CHANGELOG.md#v1140-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mgn`: [v1.7.0](service/mgn/CHANGELOG.md#v170-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/migrationhubstrategy`: [v1.0.0](service/migrationhubstrategy/CHANGELOG.md#v100-2021-11-19) - * **Release**: New AWS service client module -* `github.com/aws/aws-sdk-go-v2/service/qldb`: [v1.9.0](service/qldb/CHANGELOG.md#v190-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/qldbsession`: [v1.9.0](service/qldbsession/CHANGELOG.md#v190-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/redshift`: [v1.15.0](service/redshift/CHANGELOG.md#v1150-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sns`: [v1.12.0](service/sns/CHANGELOG.md#v1120-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.16.0](service/ssm/CHANGELOG.md#v1160-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.12.0](service/transfer/CHANGELOG.md#v1120-2021-11-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.14.0](service/wafv2/CHANGELOG.md#v1140-2021-11-19) - * **Feature**: API client updated - -# Release (2021-11-12) - -## General Highlights -* **Feature**: Service clients now support custom endpoints that have an initial URI path defined. -* **Feature**: Waiters now have a `WaitForOutput` method, which can be used to retrieve the output of the successful wait operation. Thank you to [Andrew Haines](https://github.com/haines) for contributing this feature. -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/backup`: [v1.9.0](service/backup/CHANGELOG.md#v190-2021-11-12) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/batch`: [v1.10.0](service/batch/CHANGELOG.md#v1100-2021-11-12) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmeetings`: [v1.0.0](service/chimesdkmeetings/CHANGELOG.md#v100-2021-11-12) - * **Release**: New AWS service client module -* `github.com/aws/aws-sdk-go-v2/service/computeoptimizer`: [v1.12.0](service/computeoptimizer/CHANGELOG.md#v1120-2021-11-12) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.11.0](service/connect/CHANGELOG.md#v1110-2021-11-12) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/docdb`: [v1.12.0](service/docdb/CHANGELOG.md#v1120-2021-11-12) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/dynamodb`: [v1.8.0](service/dynamodb/CHANGELOG.md#v180-2021-11-12) - * **Documentation**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.22.0](service/ec2/CHANGELOG.md#v1220-2021-11-12) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.12.0](service/ecs/CHANGELOG.md#v1120-2021-11-12) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/gamelift`: [v1.9.0](service/gamelift/CHANGELOG.md#v190-2021-11-12) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/greengrassv2`: [v1.9.0](service/greengrassv2/CHANGELOG.md#v190-2021-11-12) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/health`: [v1.10.0](service/health/CHANGELOG.md#v1100-2021-11-12) - * **Documentation**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/identitystore`: [v1.9.0](service/identitystore/CHANGELOG.md#v190-2021-11-12) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/iotwireless`: [v1.12.0](service/iotwireless/CHANGELOG.md#v1120-2021-11-12) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/neptune`: [v1.11.0](service/neptune/CHANGELOG.md#v1110-2021-11-12) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.12.0](service/rds/CHANGELOG.md#v1120-2021-11-12) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/resiliencehub`: [v1.0.0](service/resiliencehub/CHANGELOG.md#v100-2021-11-12) - * **Release**: New AWS service client module -* `github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi`: [v1.8.0](service/resourcegroupstaggingapi/CHANGELOG.md#v180-2021-11-12) - * **Documentation**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/s3control`: [v1.14.0](service/s3control/CHANGELOG.md#v1140-2021-11-12) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.19.0](service/sagemaker/CHANGELOG.md#v1190-2021-11-12) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/sagemakerruntime`: [v1.10.0](service/sagemakerruntime/CHANGELOG.md#v1100-2021-11-12) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/ssmincidents`: [v1.7.0](service/ssmincidents/CHANGELOG.md#v170-2021-11-12) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/transcribe`: [v1.11.0](service/transcribe/CHANGELOG.md#v1110-2021-11-12) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/translate`: [v1.7.0](service/translate/CHANGELOG.md#v170-2021-11-12) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.13.0](service/wafv2/CHANGELOG.md#v1130-2021-11-12) - * **Feature**: Updated service to latest API model. - -# Release (2021-11-06) - -## General Highlights -* **Feature**: The SDK now supports configuration of FIPS and DualStack endpoints using environment variables, shared configuration, or programmatically. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream`: [v1.0.0](aws/protocol/eventstream/CHANGELOG.md#v100-2021-11-06) - * **Announcement**: Support has been added for AWS EventStream APIs for Kinesis, S3, and Transcribe Streaming. Support for the Lex Runtime V2 EventStream API will be added in a future release. - * **Release**: Protocol support has been added for AWS event stream. -* `github.com/aws/aws-sdk-go-v2/internal/endpoints/v2`: [v2.0.0](internal/endpoints/v2/CHANGELOG.md#v200-2021-11-06) - * **Release**: Endpoint Variant Model Support -* `github.com/aws/aws-sdk-go-v2/service/applicationinsights`: [v1.6.0](service/applicationinsights/CHANGELOG.md#v160-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/appstream`: [v1.8.0](service/appstream/CHANGELOG.md#v180-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/auditmanager`: [v1.11.0](service/auditmanager/CHANGELOG.md#v1110-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/autoscaling`: [v1.14.0](service/autoscaling/CHANGELOG.md#v1140-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/chime`: [v1.13.0](service/chime/CHANGELOG.md#v1130-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/chimesdkidentity`: [v1.4.0](service/chimesdkidentity/CHANGELOG.md#v140-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmessaging`: [v1.4.0](service/chimesdkmessaging/CHANGELOG.md#v140-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/cloudfront`: [v1.10.0](service/cloudfront/CHANGELOG.md#v1100-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/codecommit`: [v1.7.0](service/codecommit/CHANGELOG.md#v170-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.10.0](service/connect/CHANGELOG.md#v1100-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/connectcontactlens`: [v1.7.0](service/connectcontactlens/CHANGELOG.md#v170-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/connectparticipant`: [v1.6.0](service/connectparticipant/CHANGELOG.md#v160-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/databasemigrationservice`: [v1.10.0](service/databasemigrationservice/CHANGELOG.md#v1100-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/datasync`: [v1.8.0](service/datasync/CHANGELOG.md#v180-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/docdb`: [v1.11.0](service/docdb/CHANGELOG.md#v1110-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/ebs`: [v1.9.0](service/ebs/CHANGELOG.md#v190-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.21.0](service/ec2/CHANGELOG.md#v1210-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/ecr`: [v1.9.0](service/ecr/CHANGELOG.md#v190-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.11.0](service/ecs/CHANGELOG.md#v1110-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/eks`: [v1.12.0](service/eks/CHANGELOG.md#v1120-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/elasticache`: [v1.13.0](service/elasticache/CHANGELOG.md#v1130-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/elasticsearchservice`: [v1.9.0](service/elasticsearchservice/CHANGELOG.md#v190-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/emrcontainers`: [v1.8.0](service/emrcontainers/CHANGELOG.md#v180-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/finspace`: [v1.4.0](service/finspace/CHANGELOG.md#v140-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/fsx`: [v1.12.0](service/fsx/CHANGELOG.md#v1120-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/gamelift`: [v1.8.0](service/gamelift/CHANGELOG.md#v180-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/health`: [v1.9.0](service/health/CHANGELOG.md#v190-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/iam`: [v1.12.0](service/iam/CHANGELOG.md#v1120-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/internal/eventstreamtesting`: [v1.0.0](service/internal/eventstreamtesting/CHANGELOG.md#v100-2021-11-06) - * **Release**: Protocol support has been added for AWS event stream. -* `github.com/aws/aws-sdk-go-v2/service/iotsitewise`: [v1.13.0](service/iotsitewise/CHANGELOG.md#v1130-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.14.0](service/kendra/CHANGELOG.md#v1140-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/kinesis`: [v1.8.0](service/kinesis/CHANGELOG.md#v180-2021-11-06) - * **Feature**: Support has been added for the SubscribeToShard API. -* `github.com/aws/aws-sdk-go-v2/service/kms`: [v1.9.0](service/kms/CHANGELOG.md#v190-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/lightsail`: [v1.12.0](service/lightsail/CHANGELOG.md#v1120-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/macie2`: [v1.13.0](service/macie2/CHANGELOG.md#v1130-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/mgn`: [v1.6.0](service/mgn/CHANGELOG.md#v160-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/neptune`: [v1.10.0](service/neptune/CHANGELOG.md#v1100-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/networkmanager`: [v1.6.0](service/networkmanager/CHANGELOG.md#v160-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/nimble`: [v1.6.0](service/nimble/CHANGELOG.md#v160-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/opensearch`: [v1.3.0](service/opensearch/CHANGELOG.md#v130-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.14.0](service/quicksight/CHANGELOG.md#v1140-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.11.0](service/rds/CHANGELOG.md#v1110-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/rekognition`: [v1.10.0](service/rekognition/CHANGELOG.md#v1100-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/route53resolver`: [v1.9.0](service/route53resolver/CHANGELOG.md#v190-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.18.0](service/s3/CHANGELOG.md#v1180-2021-11-06) - * **Feature**: Support has been added for the SelectObjectContent API. - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/s3control`: [v1.13.0](service/s3control/CHANGELOG.md#v1130-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.18.0](service/sagemaker/CHANGELOG.md#v1180-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/servicediscovery`: [v1.11.0](service/servicediscovery/CHANGELOG.md#v1110-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/ssmincidents`: [v1.6.0](service/ssmincidents/CHANGELOG.md#v160-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/sso`: [v1.6.0](service/sso/CHANGELOG.md#v160-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/storagegateway`: [v1.8.0](service/storagegateway/CHANGELOG.md#v180-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/support`: [v1.7.0](service/support/CHANGELOG.md#v170-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/textract`: [v1.8.0](service/textract/CHANGELOG.md#v180-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/transcribe`: [v1.10.0](service/transcribe/CHANGELOG.md#v1100-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/transcribestreaming`: [v1.0.0](service/transcribestreaming/CHANGELOG.md#v100-2021-11-06) - * **Release**: New AWS service client module - * **Feature**: Support has been added for the StartStreamTranscription and StartMedicalStreamTranscription APIs. -* `github.com/aws/aws-sdk-go-v2/service/waf`: [v1.6.0](service/waf/CHANGELOG.md#v160-2021-11-06) - * **Feature**: Updated service to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/wisdom`: [v1.2.0](service/wisdom/CHANGELOG.md#v120-2021-11-06) - * **Feature**: Updated service to latest API model. - -# Release (2021-10-21) - -## General Highlights -* **Feature**: Updated to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2`: v1.10.0 - * **Feature**: Adds dynamic signing middleware that switches to unsigned payload when TLS is enabled. -* `github.com/aws/aws-sdk-go-v2/service/appflow`: [v1.8.0](service/appflow/CHANGELOG.md#v180-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/applicationautoscaling`: [v1.8.0](service/applicationautoscaling/CHANGELOG.md#v180-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/autoscaling`: [v1.13.0](service/autoscaling/CHANGELOG.md#v1130-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmessaging`: [v1.3.0](service/chimesdkmessaging/CHANGELOG.md#v130-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudformation`: [v1.11.0](service/cloudformation/CHANGELOG.md#v1110-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudsearch`: [v1.7.0](service/cloudsearch/CHANGELOG.md#v170-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudtrail`: [v1.7.0](service/cloudtrail/CHANGELOG.md#v170-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudwatch`: [v1.9.0](service/cloudwatch/CHANGELOG.md#v190-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudwatchevents`: [v1.7.0](service/cloudwatchevents/CHANGELOG.md#v170-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs`: [v1.8.0](service/cloudwatchlogs/CHANGELOG.md#v180-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/codedeploy`: [v1.7.0](service/codedeploy/CHANGELOG.md#v170-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/configservice`: [v1.10.0](service/configservice/CHANGELOG.md#v1100-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/dataexchange`: [v1.7.0](service/dataexchange/CHANGELOG.md#v170-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/directconnect`: [v1.9.0](service/directconnect/CHANGELOG.md#v190-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/docdb`: [v1.10.0](service/docdb/CHANGELOG.md#v1100-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/dynamodb`: [v1.6.0](service/dynamodb/CHANGELOG.md#v160-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.20.0](service/ec2/CHANGELOG.md#v1200-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ecr`: [v1.8.0](service/ecr/CHANGELOG.md#v180-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.10.0](service/ecs/CHANGELOG.md#v1100-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/efs`: [v1.9.0](service/efs/CHANGELOG.md#v190-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/elasticache`: [v1.12.0](service/elasticache/CHANGELOG.md#v1120-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/elasticloadbalancing`: [v1.7.0](service/elasticloadbalancing/CHANGELOG.md#v170-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2`: [v1.10.0](service/elasticloadbalancingv2/CHANGELOG.md#v1100-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/emr`: [v1.10.0](service/emr/CHANGELOG.md#v1100-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/eventbridge`: [v1.8.0](service/eventbridge/CHANGELOG.md#v180-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/glacier`: [v1.6.0](service/glacier/CHANGELOG.md#v160-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.13.0](service/glue/CHANGELOG.md#v1130-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ivs`: [v1.8.0](service/ivs/CHANGELOG.md#v180-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.13.0](service/kendra/CHANGELOG.md#v1130-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kinesis`: [v1.7.0](service/kinesis/CHANGELOG.md#v170-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kinesisanalyticsv2`: [v1.7.0](service/kinesisanalyticsv2/CHANGELOG.md#v170-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kms`: [v1.8.0](service/kms/CHANGELOG.md#v180-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.10.0](service/lambda/CHANGELOG.md#v1100-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.13.0](service/mediaconvert/CHANGELOG.md#v1130-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mediapackage`: [v1.9.0](service/mediapackage/CHANGELOG.md#v190-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mediapackagevod`: [v1.10.0](service/mediapackagevod/CHANGELOG.md#v1100-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mediatailor`: [v1.9.0](service/mediatailor/CHANGELOG.md#v190-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/neptune`: [v1.9.0](service/neptune/CHANGELOG.md#v190-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/panorama`: [v1.0.0](service/panorama/CHANGELOG.md#v100-2021-10-21) - * **Release**: New AWS service client module -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.13.0](service/quicksight/CHANGELOG.md#v1130-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.10.0](service/rds/CHANGELOG.md#v1100-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/redshift`: [v1.12.0](service/redshift/CHANGELOG.md#v1120-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/robomaker`: [v1.10.0](service/robomaker/CHANGELOG.md#v1100-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.17.0](service/s3/CHANGELOG.md#v1170-2021-10-21) - * **Feature**: Updates S3 streaming operations - PutObject, UploadPart, WriteGetObjectResponse to use unsigned payload signing auth when TLS is enabled. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.17.0](service/sagemaker/CHANGELOG.md#v1170-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.12.0](service/securityhub/CHANGELOG.md#v1120-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sfn`: [v1.6.0](service/sfn/CHANGELOG.md#v160-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sns`: [v1.9.0](service/sns/CHANGELOG.md#v190-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sqs`: [v1.10.0](service/sqs/CHANGELOG.md#v1100-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/storagegateway`: [v1.7.0](service/storagegateway/CHANGELOG.md#v170-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sts`: [v1.8.0](service/sts/CHANGELOG.md#v180-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/swf`: [v1.6.0](service/swf/CHANGELOG.md#v160-2021-10-21) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/workmail`: [v1.8.0](service/workmail/CHANGELOG.md#v180-2021-10-21) - * **Feature**: API client updated - -# Release (2021-10-11) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/feature/ec2/imds`: [v1.6.0](feature/ec2/imds/CHANGELOG.md#v160-2021-10-11) - * **Feature**: Respect passed in Context Deadline/Timeout. Updates the IMDS Client operations to not override the passed in Context's Deadline or Timeout options. If an Client operation is called with a Context with a Deadline or Timeout, the client will no longer override it with the client's default timeout. - * **Bug Fix**: Fix IMDS client's response handling and operation timeout race. Fixes #1253 -* `github.com/aws/aws-sdk-go-v2/service/amplifybackend`: [v1.5.0](service/amplifybackend/CHANGELOG.md#v150-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/applicationautoscaling`: [v1.7.0](service/applicationautoscaling/CHANGELOG.md#v170-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/apprunner`: [v1.3.0](service/apprunner/CHANGELOG.md#v130-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/backup`: [v1.6.0](service/backup/CHANGELOG.md#v160-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/chime`: [v1.11.0](service/chime/CHANGELOG.md#v1110-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/codebuild`: [v1.11.0](service/codebuild/CHANGELOG.md#v1110-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/databrew`: [v1.10.0](service/databrew/CHANGELOG.md#v1100-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.19.0](service/ec2/CHANGELOG.md#v1190-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/efs`: [v1.8.0](service/efs/CHANGELOG.md#v180-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2`: [v1.9.0](service/elasticloadbalancingv2/CHANGELOG.md#v190-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/firehose`: [v1.7.0](service/firehose/CHANGELOG.md#v170-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/frauddetector`: [v1.10.0](service/frauddetector/CHANGELOG.md#v1100-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/fsx`: [v1.10.0](service/fsx/CHANGELOG.md#v1100-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.12.0](service/glue/CHANGELOG.md#v1120-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/grafana`: [v1.0.0](service/grafana/CHANGELOG.md#v100-2021-10-11) - * **Release**: New AWS service client module - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iotevents`: [v1.8.0](service/iotevents/CHANGELOG.md#v180-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.12.0](service/kendra/CHANGELOG.md#v1120-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kms`: [v1.7.0](service/kms/CHANGELOG.md#v170-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lexmodelsv2`: [v1.9.0](service/lexmodelsv2/CHANGELOG.md#v190-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lexruntimev2`: [v1.6.0](service/lexruntimev2/CHANGELOG.md#v160-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/location`: [v1.6.0](service/location/CHANGELOG.md#v160-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.12.0](service/mediaconvert/CHANGELOG.md#v1120-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/medialive`: [v1.10.0](service/medialive/CHANGELOG.md#v1100-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.16.0](service/sagemaker/CHANGELOG.md#v1160-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/secretsmanager`: [v1.7.0](service/secretsmanager/CHANGELOG.md#v170-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.11.0](service/securityhub/CHANGELOG.md#v1110-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.12.0](service/ssm/CHANGELOG.md#v1120-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ssooidc`: [v1.6.0](service/ssooidc/CHANGELOG.md#v160-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/synthetics`: [v1.7.0](service/synthetics/CHANGELOG.md#v170-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/textract`: [v1.6.0](service/textract/CHANGELOG.md#v160-2021-10-11) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/workmail`: [v1.7.0](service/workmail/CHANGELOG.md#v170-2021-10-11) - * **Feature**: API client updated - -# Release (2021-09-30) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/account`: [v1.0.0](service/account/CHANGELOG.md#v100-2021-09-30) - * **Release**: New AWS service client module - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/amp`: [v1.6.0](service/amp/CHANGELOG.md#v160-2021-09-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/appintegrations`: [v1.7.0](service/appintegrations/CHANGELOG.md#v170-2021-09-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudcontrol`: [v1.0.0](service/cloudcontrol/CHANGELOG.md#v100-2021-09-30) - * **Release**: New AWS service client module - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudhsmv2`: [v1.5.0](service/cloudhsmv2/CHANGELOG.md#v150-2021-09-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.8.0](service/connect/CHANGELOG.md#v180-2021-09-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/dataexchange`: [v1.6.0](service/dataexchange/CHANGELOG.md#v160-2021-09-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2`: [v1.8.0](service/elasticloadbalancingv2/CHANGELOG.md#v180-2021-09-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/imagebuilder`: [v1.11.0](service/imagebuilder/CHANGELOG.md#v1110-2021-09-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.9.0](service/lambda/CHANGELOG.md#v190-2021-09-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/macie2`: [v1.11.0](service/macie2/CHANGELOG.md#v1110-2021-09-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/networkfirewall`: [v1.7.0](service/networkfirewall/CHANGELOG.md#v170-2021-09-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/pinpoint`: [v1.8.0](service/pinpoint/CHANGELOG.md#v180-2021-09-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sesv2`: [v1.6.0](service/sesv2/CHANGELOG.md#v160-2021-09-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.8.0](service/transfer/CHANGELOG.md#v180-2021-09-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/voiceid`: [v1.0.0](service/voiceid/CHANGELOG.md#v100-2021-09-30) - * **Release**: New AWS service client module - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/wisdom`: [v1.0.0](service/wisdom/CHANGELOG.md#v100-2021-09-30) - * **Release**: New AWS service client module - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/workmail`: [v1.6.0](service/workmail/CHANGELOG.md#v160-2021-09-30) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/workspaces`: [v1.7.0](service/workspaces/CHANGELOG.md#v170-2021-09-30) - * **Feature**: API client updated - -# Release (2021-09-24) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression`: [v1.2.4](feature/dynamodb/expression/CHANGELOG.md#v124-2021-09-24) - * **Documentation**: Fixes typo in NameBuilder.NamesList example documentation to use the correct variable name. -* `github.com/aws/aws-sdk-go-v2/service/appmesh`: [v1.6.0](service/appmesh/CHANGELOG.md#v160-2021-09-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/appsync`: [v1.7.0](service/appsync/CHANGELOG.md#v170-2021-09-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/auditmanager`: [v1.9.0](service/auditmanager/CHANGELOG.md#v190-2021-09-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/codecommit`: [v1.5.0](service/codecommit/CHANGELOG.md#v150-2021-09-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/comprehend`: [v1.8.0](service/comprehend/CHANGELOG.md#v180-2021-09-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/databasemigrationservice`: [v1.8.0](service/databasemigrationservice/CHANGELOG.md#v180-2021-09-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.18.0](service/ec2/CHANGELOG.md#v1180-2021-09-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ecr`: [v1.7.0](service/ecr/CHANGELOG.md#v170-2021-09-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/elasticsearchservice`: [v1.7.0](service/elasticsearchservice/CHANGELOG.md#v170-2021-09-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iam`: [v1.10.0](service/iam/CHANGELOG.md#v1100-2021-09-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/identitystore`: [v1.6.0](service/identitystore/CHANGELOG.md#v160-2021-09-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/imagebuilder`: [v1.10.0](service/imagebuilder/CHANGELOG.md#v1100-2021-09-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.13.0](service/iot/CHANGELOG.md#v1130-2021-09-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iotevents`: [v1.7.0](service/iotevents/CHANGELOG.md#v170-2021-09-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kafkaconnect`: [v1.1.0](service/kafkaconnect/CHANGELOG.md#v110-2021-09-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lakeformation`: [v1.6.0](service/lakeformation/CHANGELOG.md#v160-2021-09-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lexmodelsv2`: [v1.8.0](service/lexmodelsv2/CHANGELOG.md#v180-2021-09-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lexruntimev2`: [v1.5.0](service/lexruntimev2/CHANGELOG.md#v150-2021-09-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/licensemanager`: [v1.8.0](service/licensemanager/CHANGELOG.md#v180-2021-09-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.11.0](service/mediaconvert/CHANGELOG.md#v1110-2021-09-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mediapackagevod`: [v1.9.0](service/mediapackagevod/CHANGELOG.md#v190-2021-09-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mediatailor`: [v1.8.0](service/mediatailor/CHANGELOG.md#v180-2021-09-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/opensearch`: [v1.1.0](service/opensearch/CHANGELOG.md#v110-2021-09-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.12.0](service/quicksight/CHANGELOG.md#v1120-2021-09-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.11.0](service/ssm/CHANGELOG.md#v1110-2021-09-24) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.10.0](service/wafv2/CHANGELOG.md#v1100-2021-09-24) - * **Feature**: API client updated - -# Release (2021-09-17) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/chime`: [v1.10.0](service/chime/CHANGELOG.md#v1100-2021-09-17) - * **Feature**: Updated API client and endpoints to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/cloudformation`: [v1.10.1](service/cloudformation/CHANGELOG.md#v1101-2021-09-17) - * **Documentation**: Updated API client documentation. -* `github.com/aws/aws-sdk-go-v2/service/comprehend`: [v1.7.0](service/comprehend/CHANGELOG.md#v170-2021-09-17) - * **Feature**: Updated API client and endpoints to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.17.0](service/ec2/CHANGELOG.md#v1170-2021-09-17) - * **Feature**: Updated API client and endpoints to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/ecr`: [v1.6.0](service/ecr/CHANGELOG.md#v160-2021-09-17) - * **Feature**: Updated API client and endpoints to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.12.0](service/iot/CHANGELOG.md#v1120-2021-09-17) - * **Feature**: Updated API client and endpoints to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/kafkaconnect`: [v1.0.0](service/kafkaconnect/CHANGELOG.md#v100-2021-09-17) - * **Release**: New AWS service client module -* `github.com/aws/aws-sdk-go-v2/service/lexmodelsv2`: [v1.7.0](service/lexmodelsv2/CHANGELOG.md#v170-2021-09-17) - * **Feature**: Updated API client and endpoints to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/lexruntimev2`: [v1.4.0](service/lexruntimev2/CHANGELOG.md#v140-2021-09-17) - * **Feature**: Updated API client and endpoints to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/macie2`: [v1.10.0](service/macie2/CHANGELOG.md#v1100-2021-09-17) - * **Feature**: Updated API client and endpoints to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/mediapackagevod`: [v1.8.0](service/mediapackagevod/CHANGELOG.md#v180-2021-09-17) - * **Feature**: Updated API client and endpoints to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/networkfirewall`: [v1.6.0](service/networkfirewall/CHANGELOG.md#v160-2021-09-17) - * **Feature**: Updated API client and endpoints to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/pinpoint`: [v1.7.0](service/pinpoint/CHANGELOG.md#v170-2021-09-17) - * **Feature**: Updated API client and endpoints to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.11.0](service/quicksight/CHANGELOG.md#v1110-2021-09-17) - * **Feature**: Updated API client and endpoints to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.9.0](service/rds/CHANGELOG.md#v190-2021-09-17) - * **Feature**: Updated API client and endpoints to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/robomaker`: [v1.9.0](service/robomaker/CHANGELOG.md#v190-2021-09-17) - * **Feature**: Updated API client and endpoints to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.16.0](service/s3/CHANGELOG.md#v1160-2021-09-17) - * **Feature**: Updated API client and endpoints to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.15.0](service/sagemaker/CHANGELOG.md#v1150-2021-09-17) - * **Feature**: Updated API client and endpoints to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/ssooidc`: [v1.5.0](service/ssooidc/CHANGELOG.md#v150-2021-09-17) - * **Feature**: Updated API client and endpoints to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/transcribe`: [v1.8.0](service/transcribe/CHANGELOG.md#v180-2021-09-17) - * **Feature**: Updated API client and endpoints to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.9.0](service/wafv2/CHANGELOG.md#v190-2021-09-17) - * **Feature**: Updated API client and endpoints to latest revision. - -# Release (2021-09-10) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/credentials`: [v1.4.1](credentials/CHANGELOG.md#v141-2021-09-10) - * **Documentation**: Fixes the AssumeRoleProvider's documentation for using custom TokenProviders. -* `github.com/aws/aws-sdk-go-v2/service/amp`: [v1.5.0](service/amp/CHANGELOG.md#v150-2021-09-10) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/braket`: [v1.7.0](service/braket/CHANGELOG.md#v170-2021-09-10) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/chimesdkidentity`: [v1.2.0](service/chimesdkidentity/CHANGELOG.md#v120-2021-09-10) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmessaging`: [v1.2.0](service/chimesdkmessaging/CHANGELOG.md#v120-2021-09-10) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/codegurureviewer`: [v1.7.0](service/codegurureviewer/CHANGELOG.md#v170-2021-09-10) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/eks`: [v1.10.0](service/eks/CHANGELOG.md#v1100-2021-09-10) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/elasticache`: [v1.11.0](service/elasticache/CHANGELOG.md#v1110-2021-09-10) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/emr`: [v1.9.0](service/emr/CHANGELOG.md#v190-2021-09-10) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/forecast`: [v1.10.0](service/forecast/CHANGELOG.md#v1100-2021-09-10) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/frauddetector`: [v1.9.0](service/frauddetector/CHANGELOG.md#v190-2021-09-10) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kafka`: [v1.7.0](service/kafka/CHANGELOG.md#v170-2021-09-10) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lookoutequipment`: [v1.4.0](service/lookoutequipment/CHANGELOG.md#v140-2021-09-10) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mediapackage`: [v1.8.0](service/mediapackage/CHANGELOG.md#v180-2021-09-10) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/opensearch`: [v1.0.0](service/opensearch/CHANGELOG.md#v100-2021-09-10) - * **Release**: New AWS service client module - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/outposts`: [v1.8.0](service/outposts/CHANGELOG.md#v180-2021-09-10) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ram`: [v1.7.0](service/ram/CHANGELOG.md#v170-2021-09-10) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.14.0](service/sagemaker/CHANGELOG.md#v1140-2021-09-10) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/servicediscovery`: [v1.9.0](service/servicediscovery/CHANGELOG.md#v190-2021-09-10) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ssmcontacts`: [v1.5.0](service/ssmcontacts/CHANGELOG.md#v150-2021-09-10) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/xray`: [v1.6.0](service/xray/CHANGELOG.md#v160-2021-09-10) - * **Feature**: API client updated - -# Release (2021-09-02) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/config`: [v1.8.0](config/CHANGELOG.md#v180-2021-09-02) - * **Feature**: Add support for S3 Multi-Region Access Point ARNs. -* `github.com/aws/aws-sdk-go-v2/service/accessanalyzer`: [v1.7.0](service/accessanalyzer/CHANGELOG.md#v170-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/acmpca`: [v1.8.0](service/acmpca/CHANGELOG.md#v180-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloud9`: [v1.8.0](service/cloud9/CHANGELOG.md#v180-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudformation`: [v1.10.0](service/cloudformation/CHANGELOG.md#v1100-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudtrail`: [v1.6.0](service/cloudtrail/CHANGELOG.md#v160-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/codebuild`: [v1.10.0](service/codebuild/CHANGELOG.md#v1100-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/computeoptimizer`: [v1.9.0](service/computeoptimizer/CHANGELOG.md#v190-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/configservice`: [v1.9.0](service/configservice/CHANGELOG.md#v190-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ebs`: [v1.7.0](service/ebs/CHANGELOG.md#v170-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.16.0](service/ec2/CHANGELOG.md#v1160-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/efs`: [v1.7.0](service/efs/CHANGELOG.md#v170-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/emr`: [v1.8.0](service/emr/CHANGELOG.md#v180-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/firehose`: [v1.6.0](service/firehose/CHANGELOG.md#v160-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/frauddetector`: [v1.8.0](service/frauddetector/CHANGELOG.md#v180-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/fsx`: [v1.9.0](service/fsx/CHANGELOG.md#v190-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/internal/s3shared`: [v1.7.0](service/internal/s3shared/CHANGELOG.md#v170-2021-09-02) - * **Feature**: Add support for S3 Multi-Region Access Point ARNs. -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.11.0](service/iot/CHANGELOG.md#v1110-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iotjobsdataplane`: [v1.5.0](service/iotjobsdataplane/CHANGELOG.md#v150-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ivs`: [v1.7.0](service/ivs/CHANGELOG.md#v170-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kms`: [v1.6.0](service/kms/CHANGELOG.md#v160-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lexmodelbuildingservice`: [v1.9.0](service/lexmodelbuildingservice/CHANGELOG.md#v190-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mediatailor`: [v1.7.0](service/mediatailor/CHANGELOG.md#v170-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/memorydb`: [v1.2.0](service/memorydb/CHANGELOG.md#v120-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mwaa`: [v1.5.0](service/mwaa/CHANGELOG.md#v150-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/polly`: [v1.6.0](service/polly/CHANGELOG.md#v160-2021-09-02) - * **Feature**: API client updated - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.10.0](service/quicksight/CHANGELOG.md#v1100-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.15.0](service/s3/CHANGELOG.md#v1150-2021-09-02) - * **Feature**: API client updated - * **Feature**: Add support for S3 Multi-Region Access Point ARNs. -* `github.com/aws/aws-sdk-go-v2/service/s3control`: [v1.11.0](service/s3control/CHANGELOG.md#v1110-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sagemakerruntime`: [v1.7.0](service/sagemakerruntime/CHANGELOG.md#v170-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/schemas`: [v1.6.0](service/schemas/CHANGELOG.md#v160-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.10.0](service/securityhub/CHANGELOG.md#v1100-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/servicecatalogappregistry`: [v1.5.0](service/servicecatalogappregistry/CHANGELOG.md#v150-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sqs`: [v1.9.0](service/sqs/CHANGELOG.md#v190-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ssmincidents`: [v1.4.0](service/ssmincidents/CHANGELOG.md#v140-2021-09-02) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.7.0](service/transfer/CHANGELOG.md#v170-2021-09-02) - * **Feature**: API client updated - -# Release (2021-08-27) - -## General Highlights -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/credentials`: [v1.4.0](credentials/CHANGELOG.md#v140-2021-08-27) - * **Feature**: Adds support for Tags and TransitiveTagKeys to stscreds.AssumeRoleProvider. Closes https://github.com/aws/aws-sdk-go-v2/issues/723 -* `github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue`: [v1.2.0](feature/dynamodb/attributevalue/CHANGELOG.md#v120-2021-08-27) - * **Bug Fix**: Fix unmarshaler's decoding of AttributeValueMemberN into a type that is a string alias. -* `github.com/aws/aws-sdk-go-v2/service/acmpca`: [v1.7.0](service/acmpca/CHANGELOG.md#v170-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/amplify`: [v1.5.0](service/amplify/CHANGELOG.md#v150-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/amplifybackend`: [v1.4.0](service/amplifybackend/CHANGELOG.md#v140-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/apigateway`: [v1.7.0](service/apigateway/CHANGELOG.md#v170-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/apigatewaymanagementapi`: [v1.4.0](service/apigatewaymanagementapi/CHANGELOG.md#v140-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/appflow`: [v1.7.0](service/appflow/CHANGELOG.md#v170-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/applicationinsights`: [v1.4.0](service/applicationinsights/CHANGELOG.md#v140-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/apprunner`: [v1.2.0](service/apprunner/CHANGELOG.md#v120-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/appstream`: [v1.6.0](service/appstream/CHANGELOG.md#v160-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/appsync`: [v1.6.0](service/appsync/CHANGELOG.md#v160-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/athena`: [v1.6.0](service/athena/CHANGELOG.md#v160-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/auditmanager`: [v1.8.0](service/auditmanager/CHANGELOG.md#v180-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/autoscalingplans`: [v1.5.0](service/autoscalingplans/CHANGELOG.md#v150-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/backup`: [v1.5.0](service/backup/CHANGELOG.md#v150-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/batch`: [v1.7.0](service/batch/CHANGELOG.md#v170-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/braket`: [v1.6.0](service/braket/CHANGELOG.md#v160-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/chimesdkidentity`: [v1.1.0](service/chimesdkidentity/CHANGELOG.md#v110-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmessaging`: [v1.1.0](service/chimesdkmessaging/CHANGELOG.md#v110-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/cloudtrail`: [v1.5.0](service/cloudtrail/CHANGELOG.md#v150-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/cloudwatchevents`: [v1.6.0](service/cloudwatchevents/CHANGELOG.md#v160-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/codeartifact`: [v1.5.0](service/codeartifact/CHANGELOG.md#v150-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/codebuild`: [v1.9.0](service/codebuild/CHANGELOG.md#v190-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/codecommit`: [v1.4.0](service/codecommit/CHANGELOG.md#v140-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/codeguruprofiler`: [v1.5.0](service/codeguruprofiler/CHANGELOG.md#v150-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/codestarnotifications`: [v1.4.0](service/codestarnotifications/CHANGELOG.md#v140-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/cognitoidentity`: [v1.5.0](service/cognitoidentity/CHANGELOG.md#v150-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider`: [v1.6.0](service/cognitoidentityprovider/CHANGELOG.md#v160-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/comprehend`: [v1.6.0](service/comprehend/CHANGELOG.md#v160-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/computeoptimizer`: [v1.8.0](service/computeoptimizer/CHANGELOG.md#v180-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/connectcontactlens`: [v1.5.0](service/connectcontactlens/CHANGELOG.md#v150-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/customerprofiles`: [v1.9.0](service/customerprofiles/CHANGELOG.md#v190-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/databasemigrationservice`: [v1.7.0](service/databasemigrationservice/CHANGELOG.md#v170-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/datasync`: [v1.6.0](service/datasync/CHANGELOG.md#v160-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/dax`: [v1.4.0](service/dax/CHANGELOG.md#v140-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/directoryservice`: [v1.5.0](service/directoryservice/CHANGELOG.md#v150-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/dlm`: [v1.5.0](service/dlm/CHANGELOG.md#v150-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/dynamodbstreams`: [v1.4.0](service/dynamodbstreams/CHANGELOG.md#v140-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.15.0](service/ec2/CHANGELOG.md#v1150-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/ecrpublic`: [v1.5.0](service/ecrpublic/CHANGELOG.md#v150-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/efs`: [v1.6.0](service/efs/CHANGELOG.md#v160-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/eks`: [v1.9.0](service/eks/CHANGELOG.md#v190-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/emrcontainers`: [v1.6.0](service/emrcontainers/CHANGELOG.md#v160-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/eventbridge`: [v1.7.0](service/eventbridge/CHANGELOG.md#v170-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/finspace`: [v1.2.0](service/finspace/CHANGELOG.md#v120-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/finspacedata`: [v1.2.0](service/finspacedata/CHANGELOG.md#v120-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/firehose`: [v1.5.0](service/firehose/CHANGELOG.md#v150-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/fms`: [v1.7.0](service/fms/CHANGELOG.md#v170-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/forecast`: [v1.9.0](service/forecast/CHANGELOG.md#v190-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/forecastquery`: [v1.4.0](service/forecastquery/CHANGELOG.md#v140-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/frauddetector`: [v1.7.0](service/frauddetector/CHANGELOG.md#v170-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/fsx`: [v1.8.0](service/fsx/CHANGELOG.md#v180-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/gamelift`: [v1.6.0](service/gamelift/CHANGELOG.md#v160-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.11.0](service/glue/CHANGELOG.md#v1110-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/groundstation`: [v1.6.0](service/groundstation/CHANGELOG.md#v160-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/guardduty`: [v1.5.0](service/guardduty/CHANGELOG.md#v150-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/health`: [v1.7.0](service/health/CHANGELOG.md#v170-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/healthlake`: [v1.6.0](service/healthlake/CHANGELOG.md#v160-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.10.0](service/iot/CHANGELOG.md#v1100-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/iot1clickdevicesservice`: [v1.4.0](service/iot1clickdevicesservice/CHANGELOG.md#v140-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/iotanalytics`: [v1.5.0](service/iotanalytics/CHANGELOG.md#v150-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/iotdataplane`: [v1.4.0](service/iotdataplane/CHANGELOG.md#v140-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/iotfleethub`: [v1.5.0](service/iotfleethub/CHANGELOG.md#v150-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/iotsitewise`: [v1.11.0](service/iotsitewise/CHANGELOG.md#v1110-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/ivs`: [v1.6.0](service/ivs/CHANGELOG.md#v160-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/lakeformation`: [v1.5.0](service/lakeformation/CHANGELOG.md#v150-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/lexmodelsv2`: [v1.6.0](service/lexmodelsv2/CHANGELOG.md#v160-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/lexruntimev2`: [v1.3.0](service/lexruntimev2/CHANGELOG.md#v130-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/licensemanager`: [v1.7.0](service/licensemanager/CHANGELOG.md#v170-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/lightsail`: [v1.10.0](service/lightsail/CHANGELOG.md#v1100-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/lookoutequipment`: [v1.3.0](service/lookoutequipment/CHANGELOG.md#v130-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/lookoutmetrics`: [v1.3.0](service/lookoutmetrics/CHANGELOG.md#v130-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/macie2`: [v1.9.0](service/macie2/CHANGELOG.md#v190-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.10.0](service/mediaconvert/CHANGELOG.md#v1100-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/mediapackage`: [v1.7.0](service/mediapackage/CHANGELOG.md#v170-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/mediapackagevod`: [v1.7.0](service/mediapackagevod/CHANGELOG.md#v170-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/mq`: [v1.5.0](service/mq/CHANGELOG.md#v150-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/networkfirewall`: [v1.5.0](service/networkfirewall/CHANGELOG.md#v150-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/outposts`: [v1.7.0](service/outposts/CHANGELOG.md#v170-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/pi`: [v1.6.0](service/pi/CHANGELOG.md#v160-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/pinpointsmsvoice`: [v1.4.0](service/pinpointsmsvoice/CHANGELOG.md#v140-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/polly`: [v1.5.0](service/polly/CHANGELOG.md#v150-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/qldb`: [v1.6.0](service/qldb/CHANGELOG.md#v160-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/qldbsession`: [v1.5.0](service/qldbsession/CHANGELOG.md#v150-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/ram`: [v1.6.0](service/ram/CHANGELOG.md#v160-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/rekognition`: [v1.8.0](service/rekognition/CHANGELOG.md#v180-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi`: [v1.5.0](service/resourcegroupstaggingapi/CHANGELOG.md#v150-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/robomaker`: [v1.8.0](service/robomaker/CHANGELOG.md#v180-2021-08-27) - * **Bug Fix**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/route53recoverycontrolconfig`: [v1.1.0](service/route53recoverycontrolconfig/CHANGELOG.md#v110-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/route53resolver`: [v1.7.0](service/route53resolver/CHANGELOG.md#v170-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.14.0](service/s3/CHANGELOG.md#v1140-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/s3control`: [v1.10.0](service/s3control/CHANGELOG.md#v1100-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/s3outposts`: [v1.5.0](service/s3outposts/CHANGELOG.md#v150-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/servicecatalog`: [v1.5.0](service/servicecatalog/CHANGELOG.md#v150-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/servicecatalogappregistry`: [v1.4.0](service/servicecatalogappregistry/CHANGELOG.md#v140-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/signer`: [v1.5.0](service/signer/CHANGELOG.md#v150-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/ssooidc`: [v1.4.0](service/ssooidc/CHANGELOG.md#v140-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/storagegateway`: [v1.6.0](service/storagegateway/CHANGELOG.md#v160-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/synthetics`: [v1.6.0](service/synthetics/CHANGELOG.md#v160-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/textract`: [v1.5.0](service/textract/CHANGELOG.md#v150-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/transcribe`: [v1.7.0](service/transcribe/CHANGELOG.md#v170-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.6.0](service/transfer/CHANGELOG.md#v160-2021-08-27) - * **Feature**: Updated API model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/wafregional`: [v1.5.0](service/wafregional/CHANGELOG.md#v150-2021-08-27) - * **Feature**: Updated API model to latest revision. - -# Release (2021-08-19) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/apigateway`: [v1.6.0](service/apigateway/CHANGELOG.md#v160-2021-08-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/apigatewayv2`: [v1.5.0](service/apigatewayv2/CHANGELOG.md#v150-2021-08-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/appflow`: [v1.6.0](service/appflow/CHANGELOG.md#v160-2021-08-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/applicationautoscaling`: [v1.5.0](service/applicationautoscaling/CHANGELOG.md#v150-2021-08-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloud9`: [v1.6.0](service/cloud9/CHANGELOG.md#v160-2021-08-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/clouddirectory`: [v1.4.0](service/clouddirectory/CHANGELOG.md#v140-2021-08-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs`: [v1.6.0](service/cloudwatchlogs/CHANGELOG.md#v160-2021-08-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/codebuild`: [v1.8.0](service/codebuild/CHANGELOG.md#v180-2021-08-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/configservice`: [v1.7.0](service/configservice/CHANGELOG.md#v170-2021-08-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/costexplorer`: [v1.8.0](service/costexplorer/CHANGELOG.md#v180-2021-08-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/customerprofiles`: [v1.8.0](service/customerprofiles/CHANGELOG.md#v180-2021-08-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/databrew`: [v1.8.0](service/databrew/CHANGELOG.md#v180-2021-08-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/directoryservice`: [v1.4.0](service/directoryservice/CHANGELOG.md#v140-2021-08-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.14.0](service/ec2/CHANGELOG.md#v1140-2021-08-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/elasticache`: [v1.9.0](service/elasticache/CHANGELOG.md#v190-2021-08-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/emr`: [v1.6.0](service/emr/CHANGELOG.md#v160-2021-08-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iotsitewise`: [v1.10.0](service/iotsitewise/CHANGELOG.md#v1100-2021-08-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.7.0](service/lambda/CHANGELOG.md#v170-2021-08-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/licensemanager`: [v1.6.0](service/licensemanager/CHANGELOG.md#v160-2021-08-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/memorydb`: [v1.0.0](service/memorydb/CHANGELOG.md#v100-2021-08-19) - * **Release**: New AWS service client module -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.8.0](service/quicksight/CHANGELOG.md#v180-2021-08-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/route53`: [v1.10.0](service/route53/CHANGELOG.md#v1100-2021-08-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/route53resolver`: [v1.6.0](service/route53resolver/CHANGELOG.md#v160-2021-08-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.13.0](service/s3/CHANGELOG.md#v1130-2021-08-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.12.0](service/sagemaker/CHANGELOG.md#v1120-2021-08-19) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sagemakerruntime`: [v1.5.0](service/sagemakerruntime/CHANGELOG.md#v150-2021-08-19) - * **Feature**: API client updated - -# Release (2021-08-12) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/feature/cloudfront/sign`: [v1.3.1](feature/cloudfront/sign/CHANGELOG.md#v131-2021-08-12) - * **Bug Fix**: Update to not escape HTML when encoding the policy. -* `github.com/aws/aws-sdk-go-v2/service/athena`: [v1.5.0](service/athena/CHANGELOG.md#v150-2021-08-12) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/autoscaling`: [v1.11.0](service/autoscaling/CHANGELOG.md#v1110-2021-08-12) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/chime`: [v1.8.0](service/chime/CHANGELOG.md#v180-2021-08-12) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/chimesdkidentity`: [v1.0.0](service/chimesdkidentity/CHANGELOG.md#v100-2021-08-12) - * **Release**: New AWS service client module - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/chimesdkmessaging`: [v1.0.0](service/chimesdkmessaging/CHANGELOG.md#v100-2021-08-12) - * **Release**: New AWS service client module - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/codebuild`: [v1.7.0](service/codebuild/CHANGELOG.md#v170-2021-08-12) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.6.0](service/connect/CHANGELOG.md#v160-2021-08-12) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ebs`: [v1.5.0](service/ebs/CHANGELOG.md#v150-2021-08-12) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.8.0](service/ecs/CHANGELOG.md#v180-2021-08-12) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lexmodelsv2`: [v1.5.0](service/lexmodelsv2/CHANGELOG.md#v150-2021-08-12) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lightsail`: [v1.9.0](service/lightsail/CHANGELOG.md#v190-2021-08-12) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/nimble`: [v1.3.0](service/nimble/CHANGELOG.md#v130-2021-08-12) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/rekognition`: [v1.7.0](service/rekognition/CHANGELOG.md#v170-2021-08-12) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/route53`: [v1.9.0](service/route53/CHANGELOG.md#v190-2021-08-12) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/snowdevicemanagement`: [v1.0.0](service/snowdevicemanagement/CHANGELOG.md#v100-2021-08-12) - * **Release**: New AWS service client module - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.9.0](service/ssm/CHANGELOG.md#v190-2021-08-12) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/synthetics`: [v1.5.0](service/synthetics/CHANGELOG.md#v150-2021-08-12) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.7.0](service/wafv2/CHANGELOG.md#v170-2021-08-12) - * **Feature**: API client updated - -# Release (2021-08-04) - -## General Highlights -* **Feature**: adds error handling for defered close calls -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version. -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2`: v1.8.0 - * **Bug Fix**: Corrected an issue where the retryer was not using the last attempt's ResultMetadata as the bases for the return result from the stack. ([#1345](https://github.com/aws/aws-sdk-go-v2/pull/1345)) -* `github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression`: [v1.2.0](feature/dynamodb/expression/CHANGELOG.md#v120-2021-08-04) - * **Feature**: Add IsSet helper for ConditionBuilder and KeyConditionBuilder ([#1329](https://github.com/aws/aws-sdk-go-v2/pull/1329)) -* `github.com/aws/aws-sdk-go-v2/service/accessanalyzer`: [v1.5.2](service/accessanalyzer/CHANGELOG.md#v152-2021-08-04) - * **Bug Fix**: Fixed an issue that caused one or more API operations to fail when attempting to resolve the service endpoint. ([#1349](https://github.com/aws/aws-sdk-go-v2/pull/1349)) -* `github.com/aws/aws-sdk-go-v2/service/amp`: [v1.3.1](service/amp/CHANGELOG.md#v131-2021-08-04) - * **Bug Fix**: Fixed an issue that caused one or more API operations to fail when attempting to resolve the service endpoint. ([#1349](https://github.com/aws/aws-sdk-go-v2/pull/1349)) -* `github.com/aws/aws-sdk-go-v2/service/appintegrations`: [v1.5.0](service/appintegrations/CHANGELOG.md#v150-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/appmesh`: [v1.4.2](service/appmesh/CHANGELOG.md#v142-2021-08-04) - * **Bug Fix**: Fixed an issue that caused one or more API operations to fail when attempting to resolve the service endpoint. ([#1349](https://github.com/aws/aws-sdk-go-v2/pull/1349)) -* `github.com/aws/aws-sdk-go-v2/service/appsync`: [v1.5.0](service/appsync/CHANGELOG.md#v150-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/auditmanager`: [v1.7.0](service/auditmanager/CHANGELOG.md#v170-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/batch`: [v1.6.0](service/batch/CHANGELOG.md#v160-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/braket`: [v1.5.2](service/braket/CHANGELOG.md#v152-2021-08-04) - * **Bug Fix**: Fixed an issue that caused one or more API operations to fail when attempting to resolve the service endpoint. ([#1349](https://github.com/aws/aws-sdk-go-v2/pull/1349)) -* `github.com/aws/aws-sdk-go-v2/service/chime`: [v1.7.0](service/chime/CHANGELOG.md#v170-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/cloudformation`: [v1.8.0](service/cloudformation/CHANGELOG.md#v180-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/cloudwatch`: [v1.7.0](service/cloudwatch/CHANGELOG.md#v170-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/codebuild`: [v1.6.0](service/codebuild/CHANGELOG.md#v160-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/codeguruprofiler`: [v1.4.2](service/codeguruprofiler/CHANGELOG.md#v142-2021-08-04) - * **Bug Fix**: Fixed an issue that caused one or more API operations to fail when attempting to resolve the service endpoint. ([#1349](https://github.com/aws/aws-sdk-go-v2/pull/1349)) -* `github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider`: [v1.5.0](service/cognitoidentityprovider/CHANGELOG.md#v150-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/computeoptimizer`: [v1.7.0](service/computeoptimizer/CHANGELOG.md#v170-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/databrew`: [v1.7.0](service/databrew/CHANGELOG.md#v170-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/directconnect`: [v1.7.0](service/directconnect/CHANGELOG.md#v170-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.13.0](service/ec2/CHANGELOG.md#v1130-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.7.0](service/ecs/CHANGELOG.md#v170-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2`: [v1.6.0](service/elasticloadbalancingv2/CHANGELOG.md#v160-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/emr`: [v1.5.0](service/emr/CHANGELOG.md#v150-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/emrcontainers`: [v1.5.0](service/emrcontainers/CHANGELOG.md#v150-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/eventbridge`: [v1.6.0](service/eventbridge/CHANGELOG.md#v160-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.10.0](service/glue/CHANGELOG.md#v1100-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/greengrassv2`: [v1.5.0](service/greengrassv2/CHANGELOG.md#v150-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/groundstation`: [v1.5.2](service/groundstation/CHANGELOG.md#v152-2021-08-04) - * **Bug Fix**: Fixed an issue that caused one or more API operations to fail when attempting to resolve the service endpoint. ([#1349](https://github.com/aws/aws-sdk-go-v2/pull/1349)) -* `github.com/aws/aws-sdk-go-v2/service/iam`: [v1.8.0](service/iam/CHANGELOG.md#v180-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/identitystore`: [v1.4.0](service/identitystore/CHANGELOG.md#v140-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/imagebuilder`: [v1.8.0](service/imagebuilder/CHANGELOG.md#v180-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.9.0](service/iot/CHANGELOG.md#v190-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/iotanalytics`: [v1.4.0](service/iotanalytics/CHANGELOG.md#v140-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/iotsitewise`: [v1.9.0](service/iotsitewise/CHANGELOG.md#v190-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/iotwireless`: [v1.8.0](service/iotwireless/CHANGELOG.md#v180-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.10.0](service/kendra/CHANGELOG.md#v1100-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.6.0](service/lambda/CHANGELOG.md#v160-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/lexmodelbuildingservice`: [v1.7.0](service/lexmodelbuildingservice/CHANGELOG.md#v170-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/lexmodelsv2`: [v1.4.0](service/lexmodelsv2/CHANGELOG.md#v140-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/location`: [v1.4.0](service/location/CHANGELOG.md#v140-2021-08-04) - * **Feature**: Updated to latest API model. - * **Bug Fix**: Fixed an issue that caused one or more API operations to fail when attempting to resolve the service endpoint. ([#1349](https://github.com/aws/aws-sdk-go-v2/pull/1349)) -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.9.0](service/mediaconvert/CHANGELOG.md#v190-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/medialive`: [v1.8.0](service/medialive/CHANGELOG.md#v180-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/mgn`: [v1.3.1](service/mgn/CHANGELOG.md#v131-2021-08-04) - * **Bug Fix**: Fixed an issue that caused one or more API operations to fail when attempting to resolve the service endpoint. ([#1349](https://github.com/aws/aws-sdk-go-v2/pull/1349)) -* `github.com/aws/aws-sdk-go-v2/service/personalize`: [v1.7.0](service/personalize/CHANGELOG.md#v170-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/proton`: [v1.2.0](service/proton/CHANGELOG.md#v120-2021-08-04) - * **Feature**: Updated to latest API model. - * **Bug Fix**: Fixed an issue that caused one or more API operations to fail when attempting to resolve the service endpoint. ([#1349](https://github.com/aws/aws-sdk-go-v2/pull/1349)) -* `github.com/aws/aws-sdk-go-v2/service/qldb`: [v1.5.0](service/qldb/CHANGELOG.md#v150-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.7.0](service/quicksight/CHANGELOG.md#v170-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.7.0](service/rds/CHANGELOG.md#v170-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/redshift`: [v1.10.0](service/redshift/CHANGELOG.md#v1100-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/redshiftdata`: [v1.5.0](service/redshiftdata/CHANGELOG.md#v150-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/robomaker`: [v1.7.0](service/robomaker/CHANGELOG.md#v170-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/route53`: [v1.8.0](service/route53/CHANGELOG.md#v180-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/route53recoverycluster`: [v1.0.0](service/route53recoverycluster/CHANGELOG.md#v100-2021-08-04) - * **Release**: New AWS service client module - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/route53recoverycontrolconfig`: [v1.0.0](service/route53recoverycontrolconfig/CHANGELOG.md#v100-2021-08-04) - * **Release**: New AWS service client module - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/route53recoveryreadiness`: [v1.0.0](service/route53recoveryreadiness/CHANGELOG.md#v100-2021-08-04) - * **Release**: New AWS service client module - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.12.0](service/s3/CHANGELOG.md#v1120-2021-08-04) - * **Feature**: Add `HeadObject` presign support. ([#1346](https://github.com/aws/aws-sdk-go-v2/pull/1346)) -* `github.com/aws/aws-sdk-go-v2/service/s3control`: [v1.9.0](service/s3control/CHANGELOG.md#v190-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/s3outposts`: [v1.4.0](service/s3outposts/CHANGELOG.md#v140-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.11.0](service/sagemaker/CHANGELOG.md#v1110-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/secretsmanager`: [v1.5.0](service/secretsmanager/CHANGELOG.md#v150-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.8.0](service/securityhub/CHANGELOG.md#v180-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/shield`: [v1.6.0](service/shield/CHANGELOG.md#v160-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/ssmcontacts`: [v1.3.0](service/ssmcontacts/CHANGELOG.md#v130-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/ssmincidents`: [v1.2.0](service/ssmincidents/CHANGELOG.md#v120-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/ssoadmin`: [v1.5.0](service/ssoadmin/CHANGELOG.md#v150-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/synthetics`: [v1.4.0](service/synthetics/CHANGELOG.md#v140-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/textract`: [v1.4.0](service/textract/CHANGELOG.md#v140-2021-08-04) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/transcribe`: [v1.6.0](service/transcribe/CHANGELOG.md#v160-2021-08-04) - * **Feature**: Updated to latest API model. - -# Release (2021-07-15) - -## General Highlights -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/config`: [v1.5.0](config/CHANGELOG.md#v150-2021-07-15) - * **Feature**: Support has been added for EC2 IPv6-enabled Instance Metadata Service Endpoints. -* `github.com/aws/aws-sdk-go-v2/feature/ec2/imds`: [v1.3.0](feature/ec2/imds/CHANGELOG.md#v130-2021-07-15) - * **Feature**: Support has been added for EC2 IPv6-enabled Instance Metadata Service Endpoints. -* `github.com/aws/aws-sdk-go-v2/service/acm`: [v1.5.0](service/acm/CHANGELOG.md#v150-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/amp`: [v1.3.0](service/amp/CHANGELOG.md#v130-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/amplify`: [v1.4.0](service/amplify/CHANGELOG.md#v140-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/amplifybackend`: [v1.3.0](service/amplifybackend/CHANGELOG.md#v130-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/autoscaling`: [v1.10.0](service/autoscaling/CHANGELOG.md#v1100-2021-07-15) - * **Feature**: The ErrorCode method on generated service error types has been corrected to match the API model. -* `github.com/aws/aws-sdk-go-v2/service/chime`: [v1.6.0](service/chime/CHANGELOG.md#v160-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/cloudformation`: [v1.7.0](service/cloudformation/CHANGELOG.md#v170-2021-07-15) - * **Feature**: The ErrorCode method on generated service error types has been corrected to match the API model. -* `github.com/aws/aws-sdk-go-v2/service/cloudfront`: [v1.7.0](service/cloudfront/CHANGELOG.md#v170-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/cloudsearch`: [v1.5.0](service/cloudsearch/CHANGELOG.md#v150-2021-07-15) - * **Feature**: The ErrorCode method on generated service error types has been corrected to match the API model. -* `github.com/aws/aws-sdk-go-v2/service/cloudwatch`: [v1.6.0](service/cloudwatch/CHANGELOG.md#v160-2021-07-15) - * **Feature**: The ErrorCode method on generated service error types has been corrected to match the API model. -* `github.com/aws/aws-sdk-go-v2/service/databasemigrationservice`: [v1.6.0](service/databasemigrationservice/CHANGELOG.md#v160-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/devopsguru`: [v1.6.0](service/devopsguru/CHANGELOG.md#v160-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/directconnect`: [v1.6.0](service/directconnect/CHANGELOG.md#v160-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/docdb`: [v1.8.0](service/docdb/CHANGELOG.md#v180-2021-07-15) - * **Feature**: The ErrorCode method on generated service error types has been corrected to match the API model. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.12.0](service/ec2/CHANGELOG.md#v1120-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/eks`: [v1.8.0](service/eks/CHANGELOG.md#v180-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/elasticache`: [v1.8.0](service/elasticache/CHANGELOG.md#v180-2021-07-15) - * **Feature**: The ErrorCode method on generated service error types has been corrected to match the API model. -* `github.com/aws/aws-sdk-go-v2/service/elasticbeanstalk`: [v1.5.0](service/elasticbeanstalk/CHANGELOG.md#v150-2021-07-15) - * **Feature**: The ErrorCode method on generated service error types has been corrected to match the API model. -* `github.com/aws/aws-sdk-go-v2/service/elasticloadbalancing`: [v1.5.0](service/elasticloadbalancing/CHANGELOG.md#v150-2021-07-15) - * **Feature**: The ErrorCode method on generated service error types has been corrected to match the API model. - * **Documentation**: Updated service model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2`: [v1.5.0](service/elasticloadbalancingv2/CHANGELOG.md#v150-2021-07-15) - * **Feature**: The ErrorCode method on generated service error types has been corrected to match the API model. - * **Documentation**: Updated service model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/fms`: [v1.6.0](service/fms/CHANGELOG.md#v160-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/frauddetector`: [v1.6.0](service/frauddetector/CHANGELOG.md#v160-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.9.0](service/glue/CHANGELOG.md#v190-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/health`: [v1.6.0](service/health/CHANGELOG.md#v160-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/healthlake`: [v1.5.0](service/healthlake/CHANGELOG.md#v150-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/iam`: [v1.7.0](service/iam/CHANGELOG.md#v170-2021-07-15) - * **Feature**: The ErrorCode method on generated service error types has been corrected to match the API model. - * **Documentation**: Updated service model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/imagebuilder`: [v1.7.0](service/imagebuilder/CHANGELOG.md#v170-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.8.0](service/iot/CHANGELOG.md#v180-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/iotsitewise`: [v1.8.0](service/iotsitewise/CHANGELOG.md#v180-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.9.0](service/kendra/CHANGELOG.md#v190-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/lambda`: [v1.5.0](service/lambda/CHANGELOG.md#v150-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/lexmodelbuildingservice`: [v1.6.0](service/lexmodelbuildingservice/CHANGELOG.md#v160-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/lightsail`: [v1.8.0](service/lightsail/CHANGELOG.md#v180-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/macie`: [v1.5.1](service/macie/CHANGELOG.md#v151-2021-07-15) - * **Documentation**: Updated service model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/macie2`: [v1.8.1](service/macie2/CHANGELOG.md#v181-2021-07-15) - * **Documentation**: Updated service model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.8.0](service/mediaconvert/CHANGELOG.md#v180-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/mediatailor`: [v1.5.0](service/mediatailor/CHANGELOG.md#v150-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/mgn`: [v1.3.0](service/mgn/CHANGELOG.md#v130-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/mq`: [v1.4.0](service/mq/CHANGELOG.md#v140-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/neptune`: [v1.7.0](service/neptune/CHANGELOG.md#v170-2021-07-15) - * **Feature**: The ErrorCode method on generated service error types has been corrected to match the API model. -* `github.com/aws/aws-sdk-go-v2/service/outposts`: [v1.6.0](service/outposts/CHANGELOG.md#v160-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/pricing`: [v1.5.1](service/pricing/CHANGELOG.md#v151-2021-07-15) - * **Documentation**: Updated service model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.6.0](service/rds/CHANGELOG.md#v160-2021-07-15) - * **Feature**: The ErrorCode method on generated service error types has been corrected to match the API model. -* `github.com/aws/aws-sdk-go-v2/service/redshift`: [v1.9.0](service/redshift/CHANGELOG.md#v190-2021-07-15) - * **Feature**: The ErrorCode method on generated service error types has been corrected to match the API model. - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.10.0](service/sagemaker/CHANGELOG.md#v1100-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/ses`: [v1.5.0](service/ses/CHANGELOG.md#v150-2021-07-15) - * **Feature**: The ErrorCode method on generated service error types has been corrected to match the API model. -* `github.com/aws/aws-sdk-go-v2/service/sns`: [v1.7.0](service/sns/CHANGELOG.md#v170-2021-07-15) - * **Feature**: The ErrorCode method on generated service error types has been corrected to match the API model. - * **Documentation**: Updated service model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/sqs`: [v1.7.0](service/sqs/CHANGELOG.md#v170-2021-07-15) - * **Feature**: The ErrorCode method on generated service error types has been corrected to match the API model. -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.8.0](service/ssm/CHANGELOG.md#v180-2021-07-15) - * **Feature**: Updated service model to latest version. - * **Documentation**: Updated service model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/storagegateway`: [v1.5.0](service/storagegateway/CHANGELOG.md#v150-2021-07-15) - * **Feature**: Updated service model to latest version. -* `github.com/aws/aws-sdk-go-v2/service/sts`: [v1.6.0](service/sts/CHANGELOG.md#v160-2021-07-15) - * **Feature**: The ErrorCode method on generated service error types has been corrected to match the API model. - * **Documentation**: Updated service model to latest revision. -* `github.com/aws/aws-sdk-go-v2/service/wellarchitected`: [v1.5.0](service/wellarchitected/CHANGELOG.md#v150-2021-07-15) - * **Feature**: Updated service model to latest version. - -# Release (2021-07-01) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/internal/ini`: [v1.1.0](internal/ini/CHANGELOG.md#v110-2021-07-01) - * **Feature**: Support for `:`, `=`, `[`, `]` being present in expression values. -* `github.com/aws/aws-sdk-go-v2/service/autoscaling`: [v1.9.0](service/autoscaling/CHANGELOG.md#v190-2021-07-01) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/databrew`: [v1.6.0](service/databrew/CHANGELOG.md#v160-2021-07-01) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.11.0](service/ec2/CHANGELOG.md#v1110-2021-07-01) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.8.0](service/glue/CHANGELOG.md#v180-2021-07-01) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.8.0](service/kendra/CHANGELOG.md#v180-2021-07-01) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.7.0](service/mediaconvert/CHANGELOG.md#v170-2021-07-01) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mediapackagevod`: [v1.6.0](service/mediapackagevod/CHANGELOG.md#v160-2021-07-01) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/redshift`: [v1.8.0](service/redshift/CHANGELOG.md#v180-2021-07-01) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.9.0](service/sagemaker/CHANGELOG.md#v190-2021-07-01) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/servicediscovery`: [v1.7.0](service/servicediscovery/CHANGELOG.md#v170-2021-07-01) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sqs`: [v1.6.0](service/sqs/CHANGELOG.md#v160-2021-07-01) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ssmcontacts`: [v1.2.0](service/ssmcontacts/CHANGELOG.md#v120-2021-07-01) - * **Feature**: API client updated - -# Release (2021-06-25) - -## General Highlights -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2`: v1.7.0 - * **Feature**: Adds configuration values for enabling endpoint discovery. - * **Bug Fix**: Keep Object-Lock headers a header when presigning Sigv4 signing requests -* `github.com/aws/aws-sdk-go-v2/config`: [v1.4.0](config/CHANGELOG.md#v140-2021-06-25) - * **Feature**: Adds configuration setting for enabling endpoint discovery. -* `github.com/aws/aws-sdk-go-v2/credentials`: [v1.3.0](credentials/CHANGELOG.md#v130-2021-06-25) - * **Bug Fix**: Fixed example usages of aws.CredentialsCache ([#1275](https://github.com/aws/aws-sdk-go-v2/pull/1275)) -* `github.com/aws/aws-sdk-go-v2/feature/cloudfront/sign`: [v1.2.0](feature/cloudfront/sign/CHANGELOG.md#v120-2021-06-25) - * **Feature**: Add UnmarshalJSON for AWSEpochTime to correctly unmarshal AWSEpochTime, ([#1298](https://github.com/aws/aws-sdk-go-v2/pull/1298)) -* `github.com/aws/aws-sdk-go-v2/internal/configsources`: [v1.0.0](internal/configsources/CHANGELOG.md#v100-2021-06-25) - * **Release**: Release new modules -* `github.com/aws/aws-sdk-go-v2/service/amp`: [v1.2.0](service/amp/CHANGELOG.md#v120-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/amplify`: [v1.3.0](service/amplify/CHANGELOG.md#v130-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/amplifybackend`: [v1.2.0](service/amplifybackend/CHANGELOG.md#v120-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/appflow`: [v1.5.0](service/appflow/CHANGELOG.md#v150-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/appmesh`: [v1.4.0](service/appmesh/CHANGELOG.md#v140-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/chime`: [v1.5.0](service/chime/CHANGELOG.md#v150-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloud9`: [v1.5.0](service/cloud9/CHANGELOG.md#v150-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudformation`: [v1.6.0](service/cloudformation/CHANGELOG.md#v160-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudfront`: [v1.6.0](service/cloudfront/CHANGELOG.md#v160-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudsearch`: [v1.4.0](service/cloudsearch/CHANGELOG.md#v140-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudwatch`: [v1.5.0](service/cloudwatch/CHANGELOG.md#v150-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cloudwatchevents`: [v1.5.0](service/cloudwatchevents/CHANGELOG.md#v150-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/codebuild`: [v1.5.0](service/codebuild/CHANGELOG.md#v150-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/codegurureviewer`: [v1.5.0](service/codegurureviewer/CHANGELOG.md#v150-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cognitoidentity`: [v1.4.0](service/cognitoidentity/CHANGELOG.md#v140-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider`: [v1.4.0](service/cognitoidentityprovider/CHANGELOG.md#v140-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.5.0](service/connect/CHANGELOG.md#v150-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/dax`: [v1.3.0](service/dax/CHANGELOG.md#v130-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/docdb`: [v1.7.0](service/docdb/CHANGELOG.md#v170-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/dynamodb`: [v1.4.0](service/dynamodb/CHANGELOG.md#v140-2021-06-25) - * **Feature**: Adds support for endpoint discovery. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.10.0](service/ec2/CHANGELOG.md#v1100-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/elasticache`: [v1.7.0](service/elasticache/CHANGELOG.md#v170-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/elasticbeanstalk`: [v1.4.0](service/elasticbeanstalk/CHANGELOG.md#v140-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/elasticloadbalancing`: [v1.4.0](service/elasticloadbalancing/CHANGELOG.md#v140-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2`: [v1.4.0](service/elasticloadbalancingv2/CHANGELOG.md#v140-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/eventbridge`: [v1.5.0](service/eventbridge/CHANGELOG.md#v150-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/greengrass`: [v1.5.0](service/greengrass/CHANGELOG.md#v150-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/greengrassv2`: [v1.4.0](service/greengrassv2/CHANGELOG.md#v140-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iam`: [v1.6.0](service/iam/CHANGELOG.md#v160-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/internal/endpoint-discovery`: [v1.0.0](service/internal/endpoint-discovery/CHANGELOG.md#v100-2021-06-25) - * **Release**: Release new modules - * **Feature**: Module supporting endpoint-discovery across all service clients. -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.7.0](service/iot/CHANGELOG.md#v170-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iotanalytics`: [v1.3.0](service/iotanalytics/CHANGELOG.md#v130-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.7.0](service/kendra/CHANGELOG.md#v170-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kms`: [v1.4.0](service/kms/CHANGELOG.md#v140-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lexmodelsv2`: [v1.3.0](service/lexmodelsv2/CHANGELOG.md#v130-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lexruntimev2`: [v1.2.0](service/lexruntimev2/CHANGELOG.md#v120-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/licensemanager`: [v1.5.0](service/licensemanager/CHANGELOG.md#v150-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lookoutmetrics`: [v1.2.0](service/lookoutmetrics/CHANGELOG.md#v120-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/managedblockchain`: [v1.4.0](service/managedblockchain/CHANGELOG.md#v140-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mediaconnect`: [v1.6.0](service/mediaconnect/CHANGELOG.md#v160-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/medialive`: [v1.7.0](service/medialive/CHANGELOG.md#v170-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mediatailor`: [v1.4.0](service/mediatailor/CHANGELOG.md#v140-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/neptune`: [v1.6.0](service/neptune/CHANGELOG.md#v160-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/proton`: [v1.1.0](service/proton/CHANGELOG.md#v110-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.6.0](service/quicksight/CHANGELOG.md#v160-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ram`: [v1.5.0](service/ram/CHANGELOG.md#v150-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.5.0](service/rds/CHANGELOG.md#v150-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/redshift`: [v1.7.0](service/redshift/CHANGELOG.md#v170-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/redshiftdata`: [v1.4.0](service/redshiftdata/CHANGELOG.md#v140-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/route53`: [v1.7.0](service/route53/CHANGELOG.md#v170-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.8.0](service/sagemaker/CHANGELOG.md#v180-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sagemakerfeaturestoreruntime`: [v1.4.0](service/sagemakerfeaturestoreruntime/CHANGELOG.md#v140-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.7.0](service/securityhub/CHANGELOG.md#v170-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ses`: [v1.4.0](service/ses/CHANGELOG.md#v140-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/snowball`: [v1.5.0](service/snowball/CHANGELOG.md#v150-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sns`: [v1.6.0](service/sns/CHANGELOG.md#v160-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sqs`: [v1.5.0](service/sqs/CHANGELOG.md#v150-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sts`: [v1.5.0](service/sts/CHANGELOG.md#v150-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/timestreamquery`: [v1.3.0](service/timestreamquery/CHANGELOG.md#v130-2021-06-25) - * **Feature**: Adds support for endpoint discovery. -* `github.com/aws/aws-sdk-go-v2/service/timestreamwrite`: [v1.3.0](service/timestreamwrite/CHANGELOG.md#v130-2021-06-25) - * **Feature**: Adds support for endpoint discovery. -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.5.0](service/transfer/CHANGELOG.md#v150-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/waf`: [v1.3.0](service/waf/CHANGELOG.md#v130-2021-06-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/wafv2`: [v1.6.0](service/wafv2/CHANGELOG.md#v160-2021-06-25) - * **Feature**: API client updated - -# Release (2021-06-11) - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/autoscaling`: [v1.7.0](service/autoscaling/CHANGELOG.md#v170-2021-06-11) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/cloudtrail`: [v1.3.2](service/cloudtrail/CHANGELOG.md#v132-2021-06-11) - * **Documentation**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider`: [v1.3.3](service/cognitoidentityprovider/CHANGELOG.md#v133-2021-06-11) - * **Documentation**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/eks`: [v1.6.0](service/eks/CHANGELOG.md#v160-2021-06-11) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/fsx`: [v1.6.0](service/fsx/CHANGELOG.md#v160-2021-06-11) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/glue`: [v1.6.0](service/glue/CHANGELOG.md#v160-2021-06-11) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.6.0](service/kendra/CHANGELOG.md#v160-2021-06-11) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/macie2`: [v1.7.0](service/macie2/CHANGELOG.md#v170-2021-06-11) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/medialive`: [v1.6.0](service/medialive/CHANGELOG.md#v160-2021-06-11) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/pi`: [v1.4.0](service/pi/CHANGELOG.md#v140-2021-06-11) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/proton`: [v1.0.0](service/proton/CHANGELOG.md#v100-2021-06-11) - * **Release**: New AWS service client module -* `github.com/aws/aws-sdk-go-v2/service/qldb`: [v1.3.1](service/qldb/CHANGELOG.md#v131-2021-06-11) - * **Documentation**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/rds`: [v1.4.2](service/rds/CHANGELOG.md#v142-2021-06-11) - * **Documentation**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.7.0](service/sagemaker/CHANGELOG.md#v170-2021-06-11) - * **Feature**: Updated to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.4.1](service/transfer/CHANGELOG.md#v141-2021-06-11) - * **Documentation**: Updated to latest API model. - -# Release (2021-06-04) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/acmpca`: [v1.5.0](service/acmpca/CHANGELOG.md#v150-2021-06-04) - * **Feature**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/autoscaling`: [v1.6.0](service/autoscaling/CHANGELOG.md#v160-2021-06-04) - * **Feature**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/braket`: [v1.4.0](service/braket/CHANGELOG.md#v140-2021-06-04) - * **Feature**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/cloudfront`: [v1.5.2](service/cloudfront/CHANGELOG.md#v152-2021-06-04) - * **Documentation**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/datasync`: [v1.4.0](service/datasync/CHANGELOG.md#v140-2021-06-04) - * **Feature**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/devicefarm`: [v1.3.0](service/devicefarm/CHANGELOG.md#v130-2021-06-04) - * **Feature**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/docdb`: [v1.6.0](service/docdb/CHANGELOG.md#v160-2021-06-04) - * **Feature**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.9.0](service/ec2/CHANGELOG.md#v190-2021-06-04) - * **Feature**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.5.0](service/ecs/CHANGELOG.md#v150-2021-06-04) - * **Feature**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/forecast`: [v1.7.0](service/forecast/CHANGELOG.md#v170-2021-06-04) - * **Feature**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/fsx`: [v1.5.0](service/fsx/CHANGELOG.md#v150-2021-06-04) - * **Feature**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/iam`: [v1.5.1](service/iam/CHANGELOG.md#v151-2021-06-04) - * **Documentation**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/internal/s3shared`: [v1.4.0](service/internal/s3shared/CHANGELOG.md#v140-2021-06-04) - * **Feature**: The handling of AccessPoint and Outpost ARNs have been updated. -* `github.com/aws/aws-sdk-go-v2/service/iotevents`: [v1.4.0](service/iotevents/CHANGELOG.md#v140-2021-06-04) - * **Feature**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/ioteventsdata`: [v1.3.0](service/ioteventsdata/CHANGELOG.md#v130-2021-06-04) - * **Feature**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/iotsitewise`: [v1.6.0](service/iotsitewise/CHANGELOG.md#v160-2021-06-04) - * **Feature**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/iotwireless`: [v1.6.0](service/iotwireless/CHANGELOG.md#v160-2021-06-04) - * **Feature**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/kendra`: [v1.5.0](service/kendra/CHANGELOG.md#v150-2021-06-04) - * **Feature**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/lightsail`: [v1.6.1](service/lightsail/CHANGELOG.md#v161-2021-06-04) - * **Documentation**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/location`: [v1.2.0](service/location/CHANGELOG.md#v120-2021-06-04) - * **Feature**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/mwaa`: [v1.2.0](service/mwaa/CHANGELOG.md#v120-2021-06-04) - * **Feature**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/outposts`: [v1.4.0](service/outposts/CHANGELOG.md#v140-2021-06-04) - * **Feature**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/polly`: [v1.3.0](service/polly/CHANGELOG.md#v130-2021-06-04) - * **Feature**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/qldb`: [v1.3.0](service/qldb/CHANGELOG.md#v130-2021-06-04) - * **Feature**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/resourcegroups`: [v1.3.2](service/resourcegroups/CHANGELOG.md#v132-2021-06-04) - * **Documentation**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/route53`: [v1.6.2](service/route53/CHANGELOG.md#v162-2021-06-04) - * **Documentation**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/route53resolver`: [v1.4.2](service/route53resolver/CHANGELOG.md#v142-2021-06-04) - * **Documentation**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.10.0](service/s3/CHANGELOG.md#v1100-2021-06-04) - * **Feature**: The handling of AccessPoint and Outpost ARNs have been updated. - * **Feature**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/s3control`: [v1.7.0](service/s3control/CHANGELOG.md#v170-2021-06-04) - * **Feature**: The handling of AccessPoint and Outpost ARNs have been updated. - * **Feature**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/servicediscovery`: [v1.5.0](service/servicediscovery/CHANGELOG.md#v150-2021-06-04) - * **Feature**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/sns`: [v1.5.0](service/sns/CHANGELOG.md#v150-2021-06-04) - * **Feature**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/sqs`: [v1.4.2](service/sqs/CHANGELOG.md#v142-2021-06-04) - * **Documentation**: Updated service client to latest API model. -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.6.2](service/ssm/CHANGELOG.md#v162-2021-06-04) - * **Documentation**: Updated service client to latest API model. - -# Release (2021-05-25) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs`: [v1.4.0](service/cloudwatchlogs/CHANGELOG.md#v140-2021-05-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/commander`: [v1.1.0](service/commander/CHANGELOG.md#v110-2021-05-25) - * **Feature**: Deprecated module. The API client was incorrectly named. Use AWS Systems Manager Incident Manager (ssmincidents) instead. -* `github.com/aws/aws-sdk-go-v2/service/computeoptimizer`: [v1.5.0](service/computeoptimizer/CHANGELOG.md#v150-2021-05-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/costexplorer`: [v1.6.0](service/costexplorer/CHANGELOG.md#v160-2021-05-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.8.0](service/ec2/CHANGELOG.md#v180-2021-05-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/efs`: [v1.4.0](service/efs/CHANGELOG.md#v140-2021-05-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/forecast`: [v1.6.0](service/forecast/CHANGELOG.md#v160-2021-05-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.6.0](service/iot/CHANGELOG.md#v160-2021-05-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/opsworkscm`: [v1.4.0](service/opsworkscm/CHANGELOG.md#v140-2021-05-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.5.0](service/quicksight/CHANGELOG.md#v150-2021-05-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.9.0](service/s3/CHANGELOG.md#v190-2021-05-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/ssmincidents`: [v1.0.0](service/ssmincidents/CHANGELOG.md#v100-2021-05-25) - * **Release**: New AWS service client module -* `github.com/aws/aws-sdk-go-v2/service/transfer`: [v1.4.0](service/transfer/CHANGELOG.md#v140-2021-05-25) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/workspaces`: [v1.4.0](service/workspaces/CHANGELOG.md#v140-2021-05-25) - * **Feature**: API client updated - -# Release (2021-05-20) - -## General Highlights -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2`: v1.6.0 - * **Feature**: `internal/ini`: This package has been migrated to a separate module at `github.com/aws/aws-sdk-go-v2/internal/ini`. -* `github.com/aws/aws-sdk-go-v2/config`: [v1.3.0](config/CHANGELOG.md#v130-2021-05-20) - * **Feature**: SSO credentials can now be defined alongside other credential providers within the same configuration profile. - * **Bug Fix**: Profile names were incorrectly normalized to lower-case, which could result in unexpected profile configurations. -* `github.com/aws/aws-sdk-go-v2/internal/ini`: [v1.0.0](internal/ini/CHANGELOG.md#v100-2021-05-20) - * **Release**: The `github.com/aws/aws-sdk-go-v2/internal/ini` package is now a Go Module. -* `github.com/aws/aws-sdk-go-v2/service/applicationcostprofiler`: [v1.0.0](service/applicationcostprofiler/CHANGELOG.md#v100-2021-05-20) - * **Release**: New AWS service client module - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/apprunner`: [v1.0.0](service/apprunner/CHANGELOG.md#v100-2021-05-20) - * **Release**: New AWS service client module - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/autoscaling`: [v1.5.0](service/autoscaling/CHANGELOG.md#v150-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/computeoptimizer`: [v1.4.0](service/computeoptimizer/CHANGELOG.md#v140-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/detective`: [v1.6.0](service/detective/CHANGELOG.md#v160-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/eks`: [v1.5.0](service/eks/CHANGELOG.md#v150-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/elasticache`: [v1.6.0](service/elasticache/CHANGELOG.md#v160-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/elasticsearchservice`: [v1.4.0](service/elasticsearchservice/CHANGELOG.md#v140-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iam`: [v1.5.0](service/iam/CHANGELOG.md#v150-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/imagebuilder`: [v1.5.0](service/imagebuilder/CHANGELOG.md#v150-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.5.0](service/iot/CHANGELOG.md#v150-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iotdeviceadvisor`: [v1.4.0](service/iotdeviceadvisor/CHANGELOG.md#v140-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/iotsitewise`: [v1.5.0](service/iotsitewise/CHANGELOG.md#v150-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kinesis`: [v1.4.0](service/kinesis/CHANGELOG.md#v140-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kinesisanalytics`: [v1.3.0](service/kinesisanalytics/CHANGELOG.md#v130-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/kinesisanalyticsv2`: [v1.4.0](service/kinesisanalyticsv2/CHANGELOG.md#v140-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lexmodelsv2`: [v1.2.0](service/lexmodelsv2/CHANGELOG.md#v120-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/licensemanager`: [v1.4.0](service/licensemanager/CHANGELOG.md#v140-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/lightsail`: [v1.6.0](service/lightsail/CHANGELOG.md#v160-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/macie`: [v1.4.0](service/macie/CHANGELOG.md#v140-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/macie2`: [v1.6.0](service/macie2/CHANGELOG.md#v160-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/mediaconnect`: [v1.5.0](service/mediaconnect/CHANGELOG.md#v150-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/neptune`: [v1.5.0](service/neptune/CHANGELOG.md#v150-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/personalize`: [v1.5.0](service/personalize/CHANGELOG.md#v150-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/quicksight`: [v1.4.0](service/quicksight/CHANGELOG.md#v140-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/rekognition`: [v1.5.0](service/rekognition/CHANGELOG.md#v150-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.8.0](service/s3/CHANGELOG.md#v180-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sagemaker`: [v1.6.0](service/sagemaker/CHANGELOG.md#v160-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/sagemakera2iruntime`: [v1.3.0](service/sagemakera2iruntime/CHANGELOG.md#v130-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/securityhub`: [v1.6.0](service/securityhub/CHANGELOG.md#v160-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/support`: [v1.3.0](service/support/CHANGELOG.md#v130-2021-05-20) - * **Feature**: API client updated -* `github.com/aws/aws-sdk-go-v2/service/transcribe`: [v1.4.0](service/transcribe/CHANGELOG.md#v140-2021-05-20) - * **Feature**: API client updated - -# Release (2021-05-14) - -## General Highlights -* **Feature**: Constant has been added to modules to enable runtime version inspection for reporting. -* **Dependency Update**: Updated to the latest SDK module versions - -## Module Highlights -* `github.com/aws/aws-sdk-go-v2`: v1.5.0 - * **Feature**: `AddSDKAgentKey` and `AddSDKAgentKeyValue` in `aws/middleware` package have been updated to direct metadata to `User-Agent` HTTP header. -* `github.com/aws/aws-sdk-go-v2/service/codeartifact`: [v1.3.0](service/codeartifact/CHANGELOG.md#v130-2021-05-14) - * **Feature**: Updated to latest service API model. -* `github.com/aws/aws-sdk-go-v2/service/commander`: [v1.0.0](service/commander/CHANGELOG.md#v100-2021-05-14) - * **Release**: New AWS service client module - * **Feature**: Updated to latest service API model. -* `github.com/aws/aws-sdk-go-v2/service/configservice`: [v1.5.0](service/configservice/CHANGELOG.md#v150-2021-05-14) - * **Feature**: Updated to latest service API model. -* `github.com/aws/aws-sdk-go-v2/service/connect`: [v1.4.0](service/connect/CHANGELOG.md#v140-2021-05-14) - * **Feature**: Updated to latest service API model. -* `github.com/aws/aws-sdk-go-v2/service/ec2`: [v1.7.0](service/ec2/CHANGELOG.md#v170-2021-05-14) - * **Feature**: Updated to latest service API model. -* `github.com/aws/aws-sdk-go-v2/service/ecs`: [v1.4.0](service/ecs/CHANGELOG.md#v140-2021-05-14) - * **Feature**: Updated to latest service API model. -* `github.com/aws/aws-sdk-go-v2/service/eks`: [v1.4.0](service/eks/CHANGELOG.md#v140-2021-05-14) - * **Feature**: Updated to latest service API model. -* `github.com/aws/aws-sdk-go-v2/service/finspace`: [v1.0.0](service/finspace/CHANGELOG.md#v100-2021-05-14) - * **Release**: New AWS service client module - * **Feature**: Updated to latest service API model. -* `github.com/aws/aws-sdk-go-v2/service/finspacedata`: [v1.0.0](service/finspacedata/CHANGELOG.md#v100-2021-05-14) - * **Release**: New AWS service client module - * **Feature**: Updated to latest service API model. -* `github.com/aws/aws-sdk-go-v2/service/iot`: [v1.4.0](service/iot/CHANGELOG.md#v140-2021-05-14) - * **Feature**: Updated to latest service API model. -* `github.com/aws/aws-sdk-go-v2/service/iotwireless`: [v1.5.0](service/iotwireless/CHANGELOG.md#v150-2021-05-14) - * **Feature**: Updated to latest service API model. -* `github.com/aws/aws-sdk-go-v2/service/kinesis`: [v1.3.0](service/kinesis/CHANGELOG.md#v130-2021-05-14) - * **Feature**: Updated to latest service API model. -* `github.com/aws/aws-sdk-go-v2/service/kinesisanalytics`: [v1.2.0](service/kinesisanalytics/CHANGELOG.md#v120-2021-05-14) - * **Feature**: Updated to latest service API model. -* `github.com/aws/aws-sdk-go-v2/service/kinesisanalyticsv2`: [v1.3.0](service/kinesisanalyticsv2/CHANGELOG.md#v130-2021-05-14) - * **Feature**: Updated to latest service API model. -* `github.com/aws/aws-sdk-go-v2/service/lakeformation`: [v1.3.0](service/lakeformation/CHANGELOG.md#v130-2021-05-14) - * **Feature**: Updated to latest service API model. -* `github.com/aws/aws-sdk-go-v2/service/lookoutmetrics`: [v1.1.0](service/lookoutmetrics/CHANGELOG.md#v110-2021-05-14) - * **Feature**: Updated to latest service API model. -* `github.com/aws/aws-sdk-go-v2/service/mediaconvert`: [v1.5.0](service/mediaconvert/CHANGELOG.md#v150-2021-05-14) - * **Feature**: Updated to latest service API model. -* `github.com/aws/aws-sdk-go-v2/service/route53`: [v1.6.0](service/route53/CHANGELOG.md#v160-2021-05-14) - * **Feature**: Updated to latest service API model. -* `github.com/aws/aws-sdk-go-v2/service/s3`: [v1.7.0](service/s3/CHANGELOG.md#v170-2021-05-14) - * **Feature**: Updated to latest service API model. -* `github.com/aws/aws-sdk-go-v2/service/s3control`: [v1.6.0](service/s3control/CHANGELOG.md#v160-2021-05-14) - * **Feature**: Updated to latest service API model. -* `github.com/aws/aws-sdk-go-v2/service/ssm`: [v1.6.0](service/ssm/CHANGELOG.md#v160-2021-05-14) - * **Feature**: Updated to latest service API model. -* `github.com/aws/aws-sdk-go-v2/service/ssmcontacts`: [v1.0.0](service/ssmcontacts/CHANGELOG.md#v100-2021-05-14) - * **Release**: New AWS service client module - * **Feature**: Updated to latest service API model. - -# Release 2021-05-06 - -## Breaking change -* `service/ec2` - v1.6.0 - * This release contains a breaking change to the Amazon EC2 API client. API number(int/int64/etc) and boolean members were changed from value, to pointer type. Your applications using the EC2 API client will fail to compile after upgrading for all members that were updated. To migrate to this module you'll need to update your application to use pointers for all number and boolean members in the API client module. The SDK provides helper utilities to convert between value and pointer types. For example the [aws.Bool](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/aws#Bool) function to get the address from a bool literal. Similar utilities are available for all other primitive types in the [aws](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/aws) package. - -## Service Client Highlights -* `service/acmpca` - v1.3.0 - * Feature: API client updated -* `service/apigateway` - v1.3.0 - * Feature: API client updated -* `service/auditmanager` - v1.4.0 - * Feature: API client updated -* `service/chime` - v1.3.0 - * Feature: API client updated -* `service/cloudformation` - v1.4.0 - * Feature: API client updated -* `service/cloudfront` - v1.4.0 - * Feature: API client updated -* `service/codegurureviewer` - v1.3.0 - * Feature: API client updated -* `service/connect` - v1.3.0 - * Feature: API client updated -* `service/customerprofiles` - v1.5.0 - * Feature: API client updated -* `service/devopsguru` - v1.3.0 - * Feature: API client updated -* `service/docdb` - v1.4.0 - * Feature: API client updated -* `service/ec2` - v1.6.0 - * Bug Fix: Fix incorrectly modeled Amazon EC2 number and boolean members in structures. The Amazon EC2 API client has been updated with a breaking change to fix all structure number and boolean members to be pointer types instead of value types. Fixes [#1107](https://github.com/aws/aws-sdk-go-v2/issues/1107), [#1178](https://github.com/aws/aws-sdk-go-v2/issues/1178), and [#1190](https://github.com/aws/aws-sdk-go-v2/issues/1190). This breaking change is made within the major version of the client' module, because the client operations failed and were unusable with value type number and boolean members with the EC2 API. - * Feature: API client updated -* `service/ecs` - v1.3.0 - * Feature: API client updated -* `service/eks` - v1.3.0 - * Feature: API client updated -* `service/forecast` - v1.4.0 - * Feature: API client updated -* `service/glue` - v1.4.0 - * Feature: API client updated -* `service/health` - v1.3.0 - * Feature: API client updated -* `service/iotsitewise` - v1.3.0 - * Feature: API client updated -* `service/iotwireless` - v1.4.0 - * Feature: API client updated -* `service/kafka` - v1.3.0 - * Feature: API client updated -* `service/kinesisanalyticsv2` - v1.2.0 - * Feature: API client updated -* `service/macie2` - v1.4.0 - * Feature: API client updated -* `service/marketplacecatalog` - v1.2.0 - * Feature: API client updated -* `service/mediaconvert` - v1.4.0 - * Feature: API client updated -* `service/mediapackage` - v1.4.0 - * Feature: API client updated -* `service/mediapackagevod` - v1.3.0 - * Feature: API client updated -* `service/mturk` - v1.2.0 - * Feature: API client updated -* `service/nimble` - v1.0.0 - * Feature: API client updated -* `service/organizations` - v1.3.0 - * Feature: API client updated -* `service/personalize` - v1.3.0 - * Feature: API client updated -* `service/robomaker` - v1.4.0 - * Feature: API client updated -* `service/route53` - v1.5.0 - * Feature: API client updated -* `service/s3` - v1.6.0 - * Bug Fix: Fix PutObject and UploadPart unseekable stream documentation link to point to the correct location. - * Feature: API client updated -* `service/sagemaker` - v1.4.0 - * Feature: API client updated -* `service/securityhub` - v1.4.0 - * Feature: API client updated -* `service/servicediscovery` - v1.3.0 - * Feature: API client updated -* `service/snowball` - v1.3.0 - * Feature: API client updated -* `service/sns` - v1.3.0 - * Feature: API client updated -* `service/ssm` - v1.5.0 - * Feature: API client updated -## Core SDK Highlights -* Dependency Update: Update smithy-go dependency to v1.4.0 -* Dependency Update: Updated SDK dependencies to their latest versions. -* `aws` - v1.4.0 - * Feature: Add support for FIPS global partition endpoints ([#1242](https://github.com/aws/aws-sdk-go-v2/pull/1242)) - -# Release 2021-04-23 -## Service Client Highlights -* `service/cloudformation` - v1.3.2 - * Documentation: Service Documentation Updates -* `service/cognitoidentityprovider` - v1.2.3 - * Documentation: Service Documentation Updates -* `service/costexplorer` - v1.4.0 - * Feature: Service API Updates -* `service/databasemigrationservice` - v1.3.0 - * Feature: Service API Updates -* `service/detective` - v1.4.0 - * Feature: Service API Updates -* `service/elasticache` - v1.4.0 - * Feature: Service API Updates -* `service/forecast` - v1.3.0 - * Feature: Service API Updates -* `service/groundstation` - v1.3.0 - * Feature: Service API Updates -* `service/kendra` - v1.3.0 - * Feature: Service API Updates -* `service/redshift` - v1.5.0 - * Feature: Service API Updates -* `service/savingsplans` - v1.2.0 - * Feature: Service API Updates -* `service/securityhub` - v1.3.0 - * Feature: Service API Updates -## Core SDK Highlights -* Dependency Update: Updated SDK dependencies to their latest versions. -* `feature/rds/auth` - v1.0.0 - * Feature: Add Support for Amazon RDS IAM Authentication - -# Release 2021-04-14 -## Service Client Highlights -* `service/codebuild` - v1.3.0 - * Feature: API client updated -* `service/codestarconnections` - v1.2.0 - * Feature: API client updated -* `service/comprehendmedical` - v1.2.0 - * Feature: API client updated -* `service/configservice` - v1.4.0 - * Feature: API client updated -* `service/ec2` - v1.5.0 - * Feature: API client updated -* `service/fsx` - v1.3.0 - * Feature: API client updated -* `service/lightsail` - v1.4.0 - * Feature: API client updated -* `service/mediaconnect` - v1.3.0 - * Feature: API client updated -* `service/rds` - v1.3.0 - * Feature: API client updated -* `service/redshift` - v1.4.0 - * Feature: API client updated -* `service/shield` - v1.3.0 - * Feature: API client updated -* `service/sts` - v1.3.0 - * Feature: API client updated -## Core SDK Highlights -* Dependency Update: Updated SDK dependencies to their latest versions. - -# Release 2021-04-08 -## Service Client Highlights -* Feature: API model sync -* `service/lookoutequipment` - v1.0.0 - * v1 Release: new service client -* `service/mgn` - v1.0.0 - * v1 Release: new service client -## Core SDK Highlights -* Dependency Update: smithy-go version bump -* Dependency Update: Updated SDK dependencies to their latest versions. - -# Release 2021-04-01 -## Service Client Highlights -* Bug Fix: Fix URL Path and RawQuery of resolved endpoint being ignored by the API client's request serialization. - * Fixes [issue#1191](https://github.com/aws/aws-sdk-go-v2/issues/1191) -* Refactored internal endpoints model for accessors -* Feature: updated to latest models -* New services - * `service/location` - v1.0.0 - * `service/lookoutmetrics` - v1.0.0 -## Core SDK Highlights -* Dependency Update: update smithy-go module -* Dependency Update: Updated SDK dependencies to their latest versions. - -# Release 2021-03-18 -## Service Client Highlights -* Bug Fix: Updated presign URLs to no longer include the X-Amz-User-Agent header -* Feature: Update API model -* Add New supported API -* `service/internal/s3shared` - v1.2.0 - * Feature: Support for S3 Object Lambda -* `service/s3` - v1.3.0 - * Bug Fix: Adds documentation to the PutObject and UploadPart operations Body member how to upload unseekable objects to an Amazon S3 Bucket. - * Feature: S3 Object Lambda is a new S3 feature that enables users to apply their own custom code to process the output of a standard S3 GET request by automatically invoking a Lambda function with a GET request -* `service/s3control` - v1.3.0 - * Feature: S3 Object Lambda is a new S3 feature that enables users to apply their own custom code to process the output of a standard S3 GET request by automatically invoking a Lambda function with a GET request -## Core SDK Highlights -* Dependency Update: Updated SDK dependencies to their latest versions. -* `aws` - v1.3.0 - * Feature: Add helper to V4 signer package to swap compute payload hash middleware with unsigned payload middleware -* `feature/s3/manager` - v1.1.0 - * Bug Fix: Add support for Amazon S3 Object Lambda feature. - * Feature: Updates for S3 Object Lambda feature - -# Release 2021-03-12 -## Service Client Highlights -* Bug Fix: Fixed a bug that could union shape types to be deserialized incorrectly -* Bug Fix: Fixed a bug where unboxed shapes that were marked as required were not serialized and sent over the wire, causing an API error from the service. -* Bug Fix: Fixed a bug with generated API Paginators' handling of nil input parameters causing a panic. -* Dependency Update: update smithy-go dependency -* `service/detective` - v1.1.2 - * Bug Fix: Fix deserialization of API response timestamp member. -* `service/docdb` - v1.2.0 - * Feature: Client now support presigned URL generation for CopyDBClusterSnapshot and CreateDBCluster operations by specifying the target SourceRegion -* `service/neptune` - v1.2.0 - * Feature: Client now support presigned URL generation for CopyDBClusterSnapshot and CreateDBCluster operations by specifying the target SourceRegion -* `service/s3` - v1.2.1 - * Bug Fix: Fixed an issue where ListObjectsV2 and ListParts paginators could loop infinitely - * Bug Fix: Fixed key encoding when addressing S3 Access Points -## Core SDK Highlights -* Dependency Update: Updated SDK dependencies to their latest versions. -* `config` - v1.1.2 - * Bug Fix: Fixed a panic when using WithEC2IMDSRegion without a specified IMDS client - -# Release 2021-02-09 -## Service Client Highlights -* `service/s3` - v1.2.0 - * Feature: adds support for s3 vpc endpoint interface [#1113](https://github.com/aws/aws-sdk-go-v2/pull/1113) -* `service/s3control` - v1.2.0 - * Feature: adds support for s3 vpc endpoint interface [#1113](https://github.com/aws/aws-sdk-go-v2/pull/1113) -## Core SDK Highlights -* Dependency Update: Updated SDK dependencies to their latest versions. -* `aws` - v1.2.0 - * Feature: support to add endpoint source on context. Adds getter/setter for the endpoint source [#1113](https://github.com/aws/aws-sdk-go-v2/pull/1113) -* `config` - v1.1.1 - * Bug Fix: Only Validate SSO profile configuration when attempting to use SSO credentials [#1103](https://github.com/aws/aws-sdk-go-v2/pull/1103) - * Bug Fix: Environment credentials were not taking precedence over AWS_PROFILE [#1103](https://github.com/aws/aws-sdk-go-v2/pull/1103) - -# Release 2021-01-29 -## Service Client Highlights -* Bug Fix: A serialization bug has been fixed that caused some service operations with empty inputs to not be serialized correctly ([#1071](https://github.com/aws/aws-sdk-go-v2/pull/1071)) -* Bug Fix: Fixes a bug that could cause a waiter to fail when comparing types ([#1083](https://github.com/aws/aws-sdk-go-v2/pull/1083)) -## Core SDK Highlights -* Feature: EndpointResolverFromURL helpers have been added for constructing a service EndpointResolver type ([#1066](https://github.com/aws/aws-sdk-go-v2/pull/1066)) -* Dependency Update: Updated SDK dependencies to their latest versions. -* `aws` - v1.1.0 - * Feature: Add support for specifying the EndpointSource on aws.Endpoint types ([#1070](https://github.com/aws/aws-sdk-go-v2/pull/1070/)) -* `config` - v1.1.0 - * Feature: Add Support for AWS Single Sign-On (SSO) credential provider ([#1072](https://github.com/aws/aws-sdk-go-v2/pull/1072)) -* `credentials` - v1.1.0 - * Feature: Add AWS Single Sign-On (SSO) credential provider ([#1072](https://github.com/aws/aws-sdk-go-v2/pull/1072)) - -# Release 2021-01-19 - -We are excited to announce the [General Availability](https://aws.amazon.com/blogs/developer/aws-sdk-for-go-version-2-general-availability/) -(GA) release of the [AWS SDK for Go version 2 (v2)](https://github.com/aws/aws-sdk-go-v2). -This release follows the [Release candidate](https://aws.amazon.com/blogs/developer/aws-sdk-for-go-version-2-v2-release-candidate) -of the AWS SDK for Go v2. Version 2 incorporates customer feedback from version 1 and takes advantage of modern Go language features. - -## Breaking Changes -* `aws`: Updated Config.Retryer member to be a func that returns aws.Retryer ([#1033](https://github.com/aws/aws-sdk-go-v2/pull/1033)) - * Updates the SDK's references to Config.Retryer to be a function that returns aws.Retryer value. This ensures that custom retry options specified in the `aws.Config` are scoped to individual client instances. - * All API clients created with the config will call the `Config.Retryer` function to get an aws.Retryer. - * Removes duplicate `Retryer` interface from `retry` package. Single definition is `aws.Retryer` now. -* `aws/middleware`: Updates `AddAttemptClockSkewMiddleware` to use appropriate `AddRecordResponseTiming` naming ([#1031](https://github.com/aws/aws-sdk-go-v2/pull/1031)) - * Removes `ResponseMetadata` struct type, and adds its members to middleware metadata directly, to improve discoverability. -* `config`: Updated the `WithRetryer` helper to take a function that returns an aws.Retryer ([#1033](https://github.com/aws/aws-sdk-go-v2/pull/1033)) - * All API clients created with the config will call the `Config.Retryer` function to get an aws.Retryer. -* `API Clients`: Fix SDK's API client enum constant name generation to have expected casing ([#1020](https://github.com/aws/aws-sdk-go-v2/pull/1020)) - * This updates of the generated enum const value names in API client's `types` package to have the expected casing. Prior to this, enum names were being generated with lowercase names instead of camel case. -* `API Clients`: Updates SDK's API client request middleware stack values to be scoped to individual operation call ([#1019](https://github.com/aws/aws-sdk-go-v2/pull/1019)) - * The API client request middleware stack values were mistakenly allowed to escape to nested API operation calls. This broke the SDK's presigners. - * Stack values that should not escape are not scoped to the individual operation call. -* `Multiple API Clients`: Unexported the API client's `WithEndpointResolver` this type wasn't intended to be exported ([#1051](https://github.com/aws/aws-sdk-go-v2/pull/1051)) - * Using the `aws.Config.EndpointResolver` member for setting custom endpoint resolver instead. - -## New Features -* `service/sts`: Add support for presigning GetCallerIdentity operation ([#1030](https://github.com/aws/aws-sdk-go-v2/pull/1030)) - * Adds a PresignClient to the `sts` API client module. Use PresignGetCallerIdentity to obtain presigned URLs for the create presigned URLs for the GetCallerIdentity operation. - * Fixes [#1021](https://github.com/aws/aws-sdk-go-v2/issues/1021) -* `aws/retry`: Add package documentation for retry package ([#1033](https://github.com/aws/aws-sdk-go-v2/pull/1033)) - * Adds documentation for the retry package - -## Bug Fixes -* `Multiple API Clients`: Fix SDK's generated serde for unmodeled operation input/output ([#1050](https://github.com/aws/aws-sdk-go-v2/pull/1050)) - * Fixes [#1047](https://github.com/aws/aws-sdk-go-v2/issues/1047) by fixing the how the SDKs generated serialization and deserialization of API operations that did not have modeled input or output types. This caused the SDK to incorrectly attempt to deserialize response documents that were either empty, or contained unexpected data. -* `service/s3`: Fix Tagging parameter not serialized correctly for presigned PutObject requests ([#1017](https://github.com/aws/aws-sdk-go-v2/pull/1017)) - * Fixes the Tagging parameter incorrectly being serialized to the URL's query string instead of being signed as a HTTP request header. - * When using PresignPutObject make sure to add all signed headers returned by the method to your down stream's HTTP client's request. These headers must be included in the request, or the request will fail with signature errors. - * Fixes [#1016](https://github.com/aws/aws-sdk-go-v2/issues/1016) -* `service/s3`: Fix Unmarshaling `GetObjectAcl` operation's Grantee type response ([#1034](https://github.com/aws/aws-sdk-go-v2/pull/1034)) - * Updates the SDK's codegen for correctly deserializing XML attributes in tags with XML namespaces. - * Fixes [#1013](https://github.com/aws/aws-sdk-go-v2/issues/1013) -* `service/s3`: Fix Unmarshaling `GetBucketLocation` operation's response ([#1027](https://github.com/aws/aws-sdk-go-v2/pull/1027)) - * Fixes [#908](https://github.com/aws/aws-sdk-go-v2/issues/908) - -## Migrating from v2 preview SDK's v0.31.0 to v1.0.0 - -### aws.Config Retryer member - -If your application sets the `Config.Retryer` member the application will need -to be updated to set a function that returns an `aws.Retryer`. In addition, if -your application used the `config.WithRetryer` helper a function that returns -an `aws.Retryer` needs to be used. - -If your application used the `retry.Retryer` type, update to using the -`aws.Retryer` type instead. - -### API Client enum value names - -If your application used the enum values in the API Client's `types` package between v0.31.0 and the latest version of the client module you may need to update the naming of the enum value. The enum value name casing were updated to camel case instead lowercased. - -# Release 2020-12-23 - -We’re happy to announce the Release Candidate (RC) of the AWS SDK for Go v2. -This RC follows the developer preview release of the AWS SDK for Go v2. The SDK -has undergone a major rewrite from the v1 code base to incorporate your -feedback and to take advantage of modern Go language features. - -## Documentation -* Developer Guide: https://aws.github.io/aws-sdk-go-v2/docs/ -* API Reference docs: https://pkg.go.dev/github.com/aws/aws-sdk-go-v2 -* Migration Guide: https://aws.github.io/aws-sdk-go-v2/docs/migrating/ - -## Breaking Changes -* Dependency `github.com/awslabs/smithy-go` has been relocated to `github.com/aws/smithy-go` - * The `smithy-go` repository was moved from the `awslabs` GitHub organization to `aws`. - * `xml`, `httpbinding`, and `json` package relocated under `encoding` package. -* The module `ec2imds` moved to `feature/ec2/imds` path ([#984](https://github.com/aws/aws-sdk-go-v2/pull/984)) - * Moves the `ec2imds` feature module to be in common location as other SDK features. -* `aws/signer/v4`: Refactor AWS Sigv4 Signer and options types to allow function options ([#955](https://github.com/aws/aws-sdk-go-v2/pull/955)) - * Fixes [#917](https://github.com/aws/aws-sdk-go-v2/issues/917), [#960](https://github.com/aws/aws-sdk-go-v2/issues/960), [#958](https://github.com/aws/aws-sdk-go-v2/issues/958) -* `aws`: CredentialCache type updated to require constructor function ([#946](https://github.com/aws/aws-sdk-go-v2/pull/946)) - * Fixes [#940](https://github.com/aws/aws-sdk-go-v2/issues/940) -* `credentials`: ExpiryWindow and Jitter moved from credential provider to `CredentialCache` ([#946](https://github.com/aws/aws-sdk-go-v2/pull/946)) - * Moves ExpiryWindow and Jitter options to common option of the `CredentialCache` instead of duplicated across providers. - * Fixes [#940](https://github.com/aws/aws-sdk-go-v2/issues/940) -* `config`: Ensure shared credentials file has precedence over shared config file ([#990](https://github.com/aws/aws-sdk-go-v2/pull/990)) - * The shared config file was incorrectly overriding the shared credentials file when merging values. -* `config`: Add `context.Context` to `LoadDefaultConfig` ([#951](https://github.com/aws/aws-sdk-go-v2/pull/951)) - * Updates `config#LoadDefaultConfig` function to take `context.Context` as well as functional options for the `config#LoadOptions` type. - * Fixes [#926](https://github.com/aws/aws-sdk-go-v2/issues/926), [#819](https://github.com/aws/aws-sdk-go-v2/issues/819) -* `aws`: Rename `NoOpRetryer` to `NopRetryer` to have consistent naming with rest of SDK ([#987](https://github.com/aws/aws-sdk-go-v2/pull/987)) - * Fixes [#878](https://github.com/aws/aws-sdk-go-v2/issues/878) -* `service/s3control`: Change `S3InitiateRestoreObjectOperation.ExpirationInDays` from value to pointer type ([#988](https://github.com/aws/aws-sdk-go-v2/pull/988)) -* `aws`: `ReaderSeekerCloser` and `WriteAtBuffer` have been relocated to `feature/s3/manager`. - -## New Features -* *Waiters*: Add Waiter utilities for API clients ([aws/smithy-go#237](https://github.com/aws/smithy-go/pull/237)) - * Your application can now use Waiter utilities to wait for AWS resources. -* `feature/dynamodb/attributevalue`: Add Amazon DynamoDB Attribute value marshaler utility ([#948](https://github.com/aws/aws-sdk-go-v2/pull/948)) - * Adds a utility for marshaling Go types too and from Amazon DynamoDB AttributeValues. - * Also includes utility for converting from Amazon DynamoDB Streams AttributeValues to Amazon DynamoDB AttributeValues. -* `feature/dynamodbstreams/attributevalue`: Add Amazon DynamoDB Streams Attribute value marshaler utility ([#948](https://github.com/aws/aws-sdk-go-v2/pull/948)) - * Adds a utility for marshaling Go types too and from Amazon DynamoDB Streams AttributeValues. - * Also includes utility for converting from Amazon DynamoDB AttributeValues to Amazon DynamoDB Streams AttributeValues. -* `feature/dynamodb/expression`: Add Amazon DynamoDB expression utility ([#981](https://github.com/aws/aws-sdk-go-v2/pull/981)) - * Adds the expression utility to the SDK for easily building Amazon DynamoDB operation expressions in code. - -## Bug Fixes -* `service/s3`: Fix Presigner to configure client correctly for Amazon S3 ([#969](https://github.com/aws/aws-sdk-go-v2/pull/969)) -* service/s3: Fix deserialization of CompleteMultipartUpload ([#965](https://github.com/aws/aws-sdk-go-v2/pull/965) - * Fixes [#927](https://github.com/aws/aws-sdk-go-v2/issues/927) -* `codegen`: Fix API client union serialization ([#979](https://github.com/aws/aws-sdk-go-v2/pull/979)) - * Fixes [#978](https://github.com/aws/aws-sdk-go-v2/issues/978) - -## Service Client Highlights -* API Clients have been bumped to version `v0.31.0` -* Regenerate API Clients from updated API models adding waiter utilities, and union parameters. -* `codegen`: - * Add documentation to union API parameters describing valid member types, and usage example ([aws/smithy-go#239](https://github.com/aws/smithy-go/pull/239)) - * Normalize Metadata header map keys to be lower case ([aws/smithy-go#241](https://github.com/aws/smithy-go/pull/241)), ([#982](https://github.com/aws/aws-sdk-go-v2/pull/982)) - * Fixes [#376](https://github.com/aws/aws-sdk-go-v2/issues/376) Amazon S3 Metadata parameters keys are always returned as lower case. - * Fix API client deserialization of XML based responses ([aws/smithy-go#245](https://github.com/aws/smithy-go/pull/245)), ([#992](https://github.com/aws/aws-sdk-go-v2/pull/992)) - * Fixes [#910](https://github.com/aws/aws-sdk-go-v2/issues/910) -* `service/s3`, `service/s3control`: - * Add support for reading `s3_use_arn_region` from shared config file ([#991](https://github.com/aws/aws-sdk-go-v2/pull/991)) - * Add Utility for getting RequestID and HostID of response ([#983](https://github.com/aws/aws-sdk-go-v2/pull/983)) - -## Other changes -* Updates branch `HEAD` points from `master` to `main`. - * This should not impact your application, but if you have pull requests or forks of the SDK you may need to update the upstream branch your fork is based off of. - -## Migrating from v2 preview SDK's v0.30.0 to v0.31.0 release candidate - -### smithy-go module relocation - -If your application uses `smithy-go` utilities for request pipeline your application will need to be updated to refer to the new import path of `github.com/aws/smithy-go`. If you application did *not* use `smithy-go` utilities directly, your application will update automatically. - -### EC2 IMDS module relocation - -If your application used the `ec2imds` module, it has been relocated to `feature/ec2/imds`. Your application will need to update to the new import path, `github.com/aws/aws-sdk-go-v2/feature/ec2/imds`. - -### CredentialsCache Constructor and ExpiryWindow Options - -The `aws#CredentialsCache` type was updated, and a new constructor function, `NewCredentialsCache` was added. This function needs to be used to initialize the `CredentialCache`. The constructor also has function options to specify additional configuration, e.g. ExpiryWindow and Jitter. - -If your application was specifying the `ExpiryWindow` with the `credentials/stscreds#AssumeRoleOptions`, `credentials/stscreds#WebIdentityRoleOptions`, `credentials/processcreds#Options`, or `credentials/ec2rolecrds#Options` types the `ExpiryWindow` option will need to specified on the `CredentialsCache` constructor instead. - -### AWS Sigv4 Signer Refactor - -The `aws/signer/v4` package's `Signer.SignHTTP` and `Signer.PresignHTTP` methods were updated to take functional options. If your application provided a custom implementation for API client's `HTTPSignerV4` or `HTTPPresignerV4` interfaces, that implementation will need to be updated for the new function signature. - -### Configuration Loading - -The `config#LoadDefaultConfig` function has been updated to require a `context.Context` as the first parameter, with additional optional function options as variadic additional arguments. Your application will need to update its usage of `LoadDefaultConfig` to pass in `context.Context` as the first parameter. If your application used the `With...` helpers those should continue to work without issue. - -The v2 SDK corrects its behavior to be inline with the AWS CLI and other AWS SDKs. Refer to https://docs.aws.amazon.com/credref/latest/refdocs/overview.html for more information how to use the shared config and credentials files. - -# Release 2020-11-30 - -## Breaking Change -* `codegen`: Add support for slice and maps generated with value members instead of pointer ([#887](https://github.com/aws/aws-sdk-go-v2/pull/887)) - * This update allow the SDK's code generation to be aware of API shapes and members that are not nullable, and can be rendered as value types by the code generation instead of pointer types. - * Several API client parameter types will change from pointer members to value members for slice, map, number and bool member types. - * See Migration notes for migrating to v0.30.0 with this change. -* `aws/transport/http`: Move aws.BuildableHTTPClient to HTTP transport package ([#898](https://github.com/aws/aws-sdk-go-v2/pull/898)) - * Moves the `BuildableHTTPClient` from the SDK's `aws` package to the `aws/transport/http` package as `BuildableClient` to with other HTTP specific utilities. -* `feature/cloudfront/sign`: Add CloudFront sign feature as module ([#884](https://github.com/aws/aws-sdk-go-v2/pull/884)) - * Moves `service/cloudfront/sign` package out of the `cloudfront` module, and into its own module as `github.com/aws/aws-sdk-go-v2/feature/cloudfront/sign`. - -## New Features -* `config`: Add a WithRetryer provider helper to the config loader ([#897](https://github.com/aws/aws-sdk-go-v2/pull/897)) - * Adds a `WithRetryer` configuration provider to the config loader as a convenience helper to set the `Retryer` on the `aws.Config` when its being loaded. -* `config`: Default to TLS 1.2 for HTTPS requests ([#892](https://github.com/aws/aws-sdk-go-v2/pull/892)) - * Updates the SDK's default HTTP client to use TLS 1.2 as the minimum TLS version for all HTTPS requests by default. - -## Bug Fixes -* `config`: Fix AWS_CA_BUNDLE usage while loading default config ([#912](https://github.com/aws/aws-sdk-go-v2/pull/)) - * Fixes the `LoadDefaultConfig`'s configuration provider order to correctly load a custom HTTP client prior to configuring the client for `AWS_CA_BUNDLE` environment variable. -* `service/s3`: Fix signature mismatch error for s3 ([#913](https://github.com/aws/aws-sdk-go-v2/pull/913)) - * Fixes ([#883](https://github.com/aws/aws-sdk-go-v2/issues/883)) -* `service/s3control`: - * Fix HostPrefix addition behavior for s3control ([#882](https://github.com/aws/aws-sdk-go-v2/pull/882)) - * Fixes ([#863](https://github.com/aws/aws-sdk-go-v2/issues/863)) - * Fix s3control error deserializer ([#875](https://github.com/aws/aws-sdk-go-v2/pull/875)) - * Fixes ([#864](https://github.com/aws/aws-sdk-go-v2/issues/864)) - -## Service Client Highlights -* Pagination support has been added to supported APIs. See [Using Operation Paginators](https://aws.github.io/aws-sdk-go-v2/docs/making-requests/#using-operation-paginators) in the Developer Guide. ([#885](https://github.com/aws/aws-sdk-go-v2/pull/885)) -* Logging support has been added to service clients. See [Logging](https://aws.github.io/aws-sdk-go-v2/docs/configuring-sdk/logging/) in the Developer Guide. ([#872](https://github.com/aws/aws-sdk-go-v2/pull/872)) -* `service`: Add support for pre-signed URL clients for S3, RDS, EC2 service ([#888](https://github.com/aws/aws-sdk-go-v2/pull/888)) - * `service/s3`: operations `PutObject` and `GetObject` are now supported with s3 pre-signed url client. - * `service/ec2`: operation `CopySnapshot` is now supported with ec2 pre-signed url client. - * `service/rds`: operations `CopyDBSnapshot`, `CreateDBInstanceReadReplica`, `CopyDBClusterSnapshot`, `CreateDBCluster` are now supported with rds pre-signed url client. -* `service/s3`: Add support for S3 access point and S3 on outposts access point ARNs ([#870](https://github.com/aws/aws-sdk-go-v2/pull/870)) -* `service/s3control`: Adds support for S3 on outposts access point and S3 on outposts bucket ARNs ([#870](https://github.com/aws/aws-sdk-go-v2/pull/870)) - -## Migrating from v2 preview SDK's v0.29.0 to v0.30.0 - -### aws.BuildableHTTPClient move -The `aws`'s `BuildableHTTPClient` HTTP client implementation was moved to `aws/transport/http` as `BuildableClient`. If your application used the `aws.BuildableHTTPClient` type, update it to use the `BuildableClient` in the `aws/transport/http` package. - -### Slice and Map API member types -This release includes several code generation updates for API client's slice map members. Using API modeling metadata the Slice and map members are now generated as value types instead of pointer types. For your application this means that for these types, the SDK no longer will have pointer member types, and have value member types. - -To migrate to this change you'll need to remove the pointer handling for slice and map members, and instead use value type handling of the member values. - -### Boolean and Number API member types -Similar to the slice and map API member types being generated as value, the SDK's code generation now has metadata where the SDK can generate boolean and number members as value type instead of pointer types. - -To migrate to this change you'll need to remove the pointer handling for numbers and boolean member types, and instead use value handling. - -# Release 2020-10-30 - -## New Features -* Adds HostnameImmutable flag on aws.Endpoint to direct SDK if the associated endpoint is modifiable.([#848](https://github.com/aws/aws-sdk-go-v2/pull/848)) - -## Bug Fixes -* Fix SDK handling of xml based services - xml namespaces ([#858](https://github.com/aws/aws-sdk-go-v2/pull/858)) - * Fixes ([#850](https://github.com/aws/aws-sdk-go-v2/issues/850)) - -## Service Client Highlights -* API Clients have been bumped to version `v0.29.0` - * Regenerate API Clients from update API models. -* Improve client doc generation. - -## Core SDK Highlights -* Dependency Update: Updated SDK dependencies to their latest versions. - -## Migrating from v2 preview SDK's v0.28.0 to v0.29.0 -* API Clients ResolverOptions type renamed to EndpointResolverOptions - -# Release 2020-10-26 - -## New Features -* `service/s3`: Add support for Accelerate, and Dualstack ([#836](https://github.com/aws/aws-sdk-go-v2/pull/836)) -* `service/s3control`: Add support for Dualstack ([#836](https://github.com/aws/aws-sdk-go-v2/pull/836)) - -## Service Client Highlights -* API Clients have been bumped to version `v0.28.0` - * Regenerate API Clients from update API models. -* `service/s3`: Add support for Accelerate, and Dualstack ([#836](https://github.com/aws/aws-sdk-go-v2/pull/836)) -* `service/s3control`: Add support for Dualstack ([#836](https://github.com/aws/aws-sdk-go-v2/pull/836)) -* `service/route53`: Fix sanitizeURL customization to handle leading slash(`/`) [#846](https://github.com/aws/aws-sdk-go-v2/pull/846) - * Fixes [#843](https://github.com/aws/aws-sdk-go-v2/issues/843) -* `service/route53`: Fix codegen to correctly look for operations that need sanitize url ([#851](https://github.com/aws/aws-sdk-go-v2/pull/851)) - -## Core SDK Highlights -* `aws/protocol/restjson`: Fix unexpected JSON error response deserialization ([#837](https://github.com/aws/aws-sdk-go-v2/pull/837)) - * Fixes [#832](https://github.com/aws/aws-sdk-go-v2/issues/832) -* `example/service/s3/listobjects`: Add example for Amazon S3 ListObjectsV2 ([#838](https://github.com/aws/aws-sdk-go-v2/pull/838)) - -# Release 2020-10-16 - -## New Features -* `feature/s3/manager`: - * Initial `v0.1.0` release - * Add the Amazon S3 Upload and Download transfer manager ([#802](https://github.com/aws/aws-sdk-go-v2/pull/802)) - -## Service Client Highlights -* Clients have been bumped to version `v0.27.0` -* `service/machinelearning`: Add customization for setting client endpoint with PredictEndpoint value if set ([#782](https://github.com/aws/aws-sdk-go-v2/pull/782)) -* `service/s3`: Fix empty response body deserialization in case of error response ([#801](https://github.com/aws/aws-sdk-go-v2/pull/801)) - * Fixes xml deserialization util to correctly handle empty response body in case of an error response. -* `service/s3`: Add customization to auto fill Content-Md5 request header for Amazon S3 operations ([#812](https://github.com/aws/aws-sdk-go-v2/pull/812)) -* `service/s3`: Add fallback to using HTTP status code for error code ([#818](https://github.com/aws/aws-sdk-go-v2/pull/818)) - * Adds falling back to using the HTTP status code to create a API Error code when not error code is received from the service, such as HeadObject. -* `service/route53`: Add support for deserialzing `InvalidChangeBatch` API error ([#792](https://github.com/aws/aws-sdk-go-v2/pull/792)) -* `codegen`: Remove API client `Options` getter methods ([#788](https://github.com/aws/aws-sdk-go-v2/pull/788)) -* `codegen`: Regenerate API Client modeled endpoints ([#791](https://github.com/aws/aws-sdk-go-v2/pull/791)) -* `codegen`: Sort API Client struct member paramaters by required and alphabetical ([#787](https://github.com/aws/aws-sdk-go-v2/pull/787)) -* `codegen`: Add package docs to API client modules ([#821](https://github.com/aws/aws-sdk-go-v2/pull/821)) -* `codegen`: Rename `smithy-go`'s `smithy.OperationError` to `smithy.OperationInvokeError`. - -## Core SDK Highlights -* `config`: - * Bumped to `v0.2.0` - * Refactor Config Module, Add Config Package Documentation and Examples, Improve Overall SDK Readme ([#822](https://github.com/aws/aws-sdk-go-v2/pull/822)) -* `credentials`: - * Bumped to `v0.1.2` - * Strip Monotonic Clock Readings when Comparing Credential Expiry Time ([#789](https://github.com/aws/aws-sdk-go-v2/pull/789)) -* `ec2imds`: - * Bumped to `v0.1.2` - * Fix refreshing API token if expired ([#789](https://github.com/aws/aws-sdk-go-v2/pull/789)) - -## Migrating from v0.26.0 to v0.27.0 - -#### Configuration - -The `config` module's exported types were trimmed down to add clarity and reduce confusion. Additional changes to the `config` module' helpers. - -* Refactored `WithCredentialsProvider`, `WithHTTPClient`, and `WithEndpointResolver` to functions instead of structs. -* Removed `MFATokenFuncProvider`, use `AssumeRoleCredentialOptionsProvider` for setting options for `stscreds.AssumeRoleOptions`. -* Renamed `WithWebIdentityCredentialProviderOptions` to `WithWebIdentityRoleCredentialOptions` -* Renamed `AssumeRoleCredentialProviderOptions` to `AssumeRoleCredentialOptionsProvider` -* Renamed `EndpointResolverFuncProvider` to `EndpointResolverProvider` - -#### API Client -* API Client `Options` type getter methods have been removed. Use the struct members instead. -* The error returned by API Client operations was renamed from `smithy.OperationError` to `smithy.OperationInvokeError`. - -# Release 2020-09-30 - -## Service Client Highlights -* Service clients have been bumped to `v0.26.0` simplify the documentation experience when using [pkg.go.dev](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2). -* `service/s3`: Disable automatic decompression of getting Amazon S3 objects with the `Content-Encoding: gzip` metadata header. ([#748](https://github.com/aws/aws-sdk-go-v2/pull/748)) - * This changes the SDK's default behavior with regard to making S3 API calls. The client will no longer automatically set the `Accept-Encoding` HTTP request header, nor will it automatically decompress the gzipped response when the `Content-Encoding: gzip` response header was received. - * If you'd like the client to sent the `Accept-Encoding: gzip` request header, you can add this header to the API operation method call with the [SetHeaderValue](https://pkg.go.dev/github.com/awslabs/smithy-go/transport/http#SetHeaderValue). middleware helper. -* `service/cloudfront/sign`: Fix cloudfront example usage of SignWithPolicy ([#673](https://github.com/aws/aws-sdk-go-v2/pull/673)) - * Fixes [#671](https://github.com/aws/aws-sdk-go-v2/issues/671) documentation typo by correcting the usage of `SignWithPolicy`. - -## Core SDK Highlights -* SDK core module released at `v0.26.0` -* `config` module released at `v0.1.1` -* `credentials` module released at `v0.1.1` -* `ec2imds` module released at `v0.1.1` - -# Release 2020-09-28 -## Announcements -We’re happy to share the updated clients for the v0.25.0 preview version of the AWS SDK for Go V2. - -The updated clients leverage new developments and advancements within AWS and the Go software ecosystem at large since -our original preview announcement. Using the new clients will be a bit different than before. The key differences are: -simplified API operation invocation, performance improvements, support for error wrapping, and a new middleware architecture. -So below we have a guided walkthrough to help try it out and share your feedback in order to better influence the features -you’d like to see in the GA version. - -See [Announcement Blog Post](https://aws.amazon.com/blogs/developer/client-updates-in-the-preview-version-of-the-aws-sdk-for-go-v2/) for more details. - -## Service Client Highlights -* Initial service clients released at version `v0.1.0` -## Core SDK Highlights -* SDK core module released at `v0.25.0` -* `config` module released at `v0.1.0` -* `credentials` module released at `v0.1.0` -* `ec2imds` module released at `v0.1.0` - -## Migrating from v2 preview SDK's v0.24.0 to v0.25.0 - -#### Design changes - -The v2 preview SDK `v0.25.0` release represents a significant stepping stone bringing the v2 SDK closer to its target design and usability. This release includes significant breaking changes to the v2 preview SDK. The updates in the `v0.25.0` release focus on refactoring and modularization of the SDK’s API clients to use the new [client design](https://github.com/aws/aws-sdk-go-v2/issues/438), updated request pipeline (aka [middleware](https://pkg.go.dev/github.com/awslabs/smithy-go/middleware)), refactored [credential providers](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/credentials), and [configuration loading](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/config) packages. - -We've also bumped the minimum supported Go version with this release. Starting with v0.25.0 the SDK requires a minimum version of Go `v1.15`. - -As a part of the refactoring done to v2 preview SDK some components have not been included in this update. The following is a non exhaustive list of features that are not available. - -* API Paginators - [#439](https://github.com/aws/aws-sdk-go-v2/issues/439) -* API Waiters - [#442](https://github.com/aws/aws-sdk-go-v2/issues/442) -* Presign URL - [#794](https://github.com/aws/aws-sdk-go-v2/issues/794) -* Amazon S3 Upload and Download manager - [#802](https://github.com/aws/aws-sdk-go-v2/pull/802) -* Amazon DynamoDB's AttributeValue marshaler, and Expression package - [#790](https://github.com/aws/aws-sdk-go-v2/issues/790) -* Debug Logging - [#594](https://github.com/aws/aws-sdk-go-v2/issues/594) - -We expect additional breaking changes to the v2 preview SDK in the coming releases. We expect these changes to focus on organizational, naming, and hardening the SDK's design for future feature capabilities after it is released for general availability. - -#### Relocated Packages - -In this release packages within the SDK were relocated, and in some cases those packages were converted to Go modules. The following is a list of packages have were relocated. - -* `github.com/aws/aws-sdk-go-v2/aws/external` => `github.com/aws/aws-sdk-go-v2/config` module -* `github.com/aws/aws-sdk-go-v2/aws/ec2metadata` => `github.com/aws/aws-sdk-go-v2/ec2imds` module - -The `github.com/aws/aws-sdk-go-v2/credentials` module contains refactored credentials providers. - -* `github.com/aws/aws-sdk-go-v2/ec2rolecreds` => `github.com/aws/aws-sdk-go-v2/credentials/ec2rolecreds` -* `github.com/aws/aws-sdk-go-v2/endpointcreds` => `github.com/aws/aws-sdk-go-v2/credentials/endpointcreds` -* `github.com/aws/aws-sdk-go-v2/processcreds` => `github.com/aws/aws-sdk-go-v2/credentials/processcreds` -* `github.com/aws/aws-sdk-go-v2/stscreds` => `github.com/aws/aws-sdk-go-v2/credentials/stscreds` - -#### Modularization - -New modules were added to the v2 preview SDK to allow the components to be versioned independently from each other. This allows your application to depend on specific versions of an API client module, and take discrete updates from the SDK core and other API client modules as desired. - -* [github.com/aws/aws-sdk-go-v2/config](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/config) -* [github.com/aws/aws-sdk-go-v2/credentials](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/credentials) -* Module for each API client, e.g. [github.com/aws/aws-sdk-go-v2/service/s3](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3) - -#### API Clients - -The following is a list of the major changes to the API client modules - -* Removed paginators: we plan to add these back once they are implemented to integrate with the SDK's new API client design. -* Removed waiters: we need to further investigate how the V2 SDK should expose waiters, and how their behavior should be modeled. -* API Clients are now Go modules. When migrating to the v2 preview SDK `v0.25.0`, you'll need to add the API client's module to your application's go.mod file. -* API parameter nested types have been moved to a `types` package within the API client's module, e.g. `github.com/aws/aws-sdk-go-v2/service/s3/types` These types were moved to improve documentation and discovery of the API client, operation, and input/output types. For example Amazon S3's ListObject's operation [ListObjectOutput.Contents](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3/#ListObjectsOutput) input parameter is a slice of [types.Object](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3/types#Object). -* The client operation method has been renamed, removing the `Request` suffix. The method now invokes the operation instead of constructing a request, which needed to be invoked separately. The operation methods were also expanded to include functional options for providing operation specific configuration, such as modifying the request pipeline. - -```go -result, err := client.Scan(context.TODO(), &dynamodb.ScanInput{ - TableName: aws.String("exampleTable"), -}, func(o *Options) { - // Limit operation calls to only 1 attempt. - o.Retryer = retry.AddWithMaxAttempts(o.Retryer, 1) -}) -``` - -#### Configuration - -In addition to the `github.com/aws/aws-sdk-go-v2/aws/external` package being made a module at `github.com/aws/aws-sdk-go-v2/config`, the `LoadDefaultAWSConfig` function was renamed to `LoadDefaultConfig`. - -The `github.com/aws/aws-sdk-go-v2/aws/defaults` package has been removed. Its components have been migrated to the `github.com/aws/aws-sdk-go-v2/aws` package, and `github.com/aws/aws-sdk-go-v2/config` module. - -#### Error Handling - -The `github.com/aws/aws-sdk-go-v2/aws/awserr` package was removed as a part of the SDK error handling refactor. The SDK now uses typed errors built around [Go v1.13](https://golang.org/doc/go1.13#error_wrapping)'s [errors.As](https://pkg.go.dev/errors#As) and [errors.Unwrap](https://pkg.go.dev/errors#Unwrap) features. All SDK error types that wrap other errors implement the `Unwrap` method. Generic v2 preview SDK errors created with `fmt.Errorf` use `%w` to wrap the underlying error. - -The SDK API clients now include generated public error types for errors modeled for an API. The SDK will automatically deserialize the error response from the API into the appropriate error type. Your application should use `errors.As` to check if the returned error matches one it is interested in. Your application can also use the generic interface [smithy.APIError](https://pkg.go.dev/github.com/awslabs/smithy-go/#APIError) to test if the API client's operation method returned an API error, but not check against a specific error. - -API client errors returned to the caller will use error wrapping to layer the error values. This allows underlying error types to be specific to their use case, and the SDK's more generic error types to wrap the underlying error. - -For example, if an [Amazon DynamoDB](https://aws.amazon.com/dynamodb/) [Scan](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Scan) operation call cannot find the `TableName` requested, the error returned will contain [dynamodb.ResourceNotFoundException](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb/types#ResourceNotFoundException). The SDK will return this error value wrapped in a couple layers, with each layer adding additional contextual information such as [ResponseError](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/aws/transport/http#ResponseError) for AWS HTTP response error metadata , and [smithy.OperationError](https://pkg.go.dev/github.com/awslabs/smithy-go/#OperationError) for API operation call metadata. - -```go -result, err := client.Scan(context.TODO(), params) -if err != nil { - // To get a specific API error - var notFoundErr *types.ResourceNotFoundException - if errors.As(err, ¬FoundErr) { - log.Printf("scan failed because the table was not found, %v", - notFoundErr.ErrorMessage()) - } - - // To get any API error - var apiErr smithy.APIError - if errors.As(err, &apiErr) { - log.Printf("scan failed because of an API error, Code: %v, Message: %v", - apiErr.ErrorCode(), apiErr.ErrorMessage()) - } - - // To get the AWS response metadata, such as RequestID - var respErr *awshttp.ResponseError // Using import alias "awshttp" for package github.com/aws/aws-sdk-go-v2/aws/transport/http - if errors.As(err, &respErr) { - log.Printf("scan failed with HTTP status code %v, Request ID %v and error %v", - respErr.HTTPStatusCode(), respErr.ServiceRequestID(), respErr) - } - - return err -} -``` - -Logging an error value will include information from each wrapped error. For example, the following is a mock error logged for a Scan operation call that failed because the table was not found. - -> 2020/10/15 16:03:37 operation error DynamoDB: Scan, https response error StatusCode: 400, RequestID: ABCREQUESTID123, ResourceNotFoundException: Requested resource not found - -#### Endpoints - -The `github.com/aws/aws-sdk-go-v2/aws/endpoints` has been removed from the SDK, along with all exported endpoint definitions and iteration behavior. Each generated API client now includes its own endpoint definition internally to the module. - -API clients can optionally be configured with a generic [aws.EndpointResolver](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/aws#EndpointResolver) via the [aws.Config.EndpointResolver](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/aws#Config.EndpointResolver). If the API client is not configured with a custom endpoint resolver it will defer to the endpoint resolver the client module was generated with. diff --git a/vendor/github.com/aws/aws-sdk-go-v2/CODE_OF_CONDUCT.md b/vendor/github.com/aws/aws-sdk-go-v2/CODE_OF_CONDUCT.md deleted file mode 100644 index 5b627cfa6..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,4 +0,0 @@ -## Code of Conduct -This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). -For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact -opensource-codeofconduct@amazon.com with any additional questions or comments. diff --git a/vendor/github.com/aws/aws-sdk-go-v2/CONTRIBUTING.md b/vendor/github.com/aws/aws-sdk-go-v2/CONTRIBUTING.md deleted file mode 100644 index 5e59bba7b..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/CONTRIBUTING.md +++ /dev/null @@ -1,177 +0,0 @@ -# Contributing to the AWS SDK for Go - -Thank you for your interest in contributing to the AWS SDK for Go! -We work hard to provide a high-quality and useful SDK, and we greatly value -feedback and contributions from our community. Whether it's a bug report, -new feature, correction, or additional documentation, we welcome your issues -and pull requests. Please read through this document before submitting any -[issues] or [pull requests][pr] to ensure we have all the necessary information to -effectively respond to your bug report or contribution. - -Jump To: - -* [Bug Reports](#bug-reports) -* [Feature Requests](#feature-requests) -* [Code Contributions](#code-contributions) - -## How to contribute - -*Before you send us a pull request, please be sure that:* - -1. You're working from the latest source on the `main` branch. -2. You check existing open, and recently closed, pull requests to be sure - that someone else hasn't already addressed the problem. -3. You create an issue before working on a contribution that will take a - significant amount of your time. - -*Creating a Pull Request* - -1. Fork the repository. -2. In your fork, make your change in a branch that's based on this repo's `main` branch. -3. Commit the change to your fork, using a clear and descriptive commit message. -4. Create a pull request, answering any questions in the pull request form. - -For contributions that will take a significant amount of time, open a new -issue to pitch your idea before you get started. Explain the problem and -describe the content you want to see added to the documentation. Let us know -if you'll write it yourself or if you'd like us to help. We'll discuss your -proposal with you and let you know whether we're likely to accept it. - -## Bug Reports - -You can file bug reports against the SDK on the [GitHub issues][issues] page. - -If you are filing a report for a bug or regression in the SDK, it's extremely -helpful to provide as much information as possible when opening the original -issue. This helps us reproduce and investigate the possible bug without having -to wait for this extra information to be provided. Please read the following -guidelines prior to filing a bug report. - -1. Search through existing [issues][] to ensure that your specific issue has - not yet been reported. If it is a common issue, it is likely there is - already a bug report for your problem. - -2. Ensure that you have tested the latest version of the SDK. Although you - may have an issue against an older version of the SDK, we cannot provide - bug fixes for old versions. It's also possible that the bug may have been - fixed in the latest release. - -3. Provide as much information about your environment, SDK version, and - relevant dependencies as possible. For example, let us know what version - of Go you are using, which and version of the operating system, and the - the environment your code is running in. e.g Container. - -4. Provide a minimal test case that reproduces your issue or any error - information you related to your problem. We can provide feedback much - more quickly if we know what operations you are calling in the SDK. If - you cannot provide a full test case, provide as much code as you can - to help us diagnose the problem. Any relevant information should be provided - as well, like whether this is a persistent issue, or if it only occurs - some of the time. - -## Feature Requests - -Open an [issue][issues] with the following: - -* A short, descriptive title. Ideally, other community members should be able - to get a good idea of the feature just from reading the title. -* A detailed description of the the proposed feature. - * Why it should be added to the SDK. - * If possible, example code to illustrate how it should work. -* Use Markdown to make the request easier to read; -* If you intend to implement this feature, indicate that you'd like to the issue to be assigned to you. - -## Code Contributions - -We are always happy to receive code and documentation contributions to the SDK. -Please be aware of the following notes prior to opening a pull request: - -1. The SDK is released under the [Apache license][license]. Any code you submit - will be released under that license. For substantial contributions, we may - ask you to sign a [Contributor License Agreement (CLA)][cla]. - -2. If you would like to implement support for a significant feature that is not - yet available in the SDK, please talk to us beforehand to avoid any - duplication of effort. - -3. Wherever possible, pull requests should contain tests as appropriate. - Bugfixes should contain tests that exercise the corrected behavior (i.e., the - test should fail without the bugfix and pass with it), and new features - should be accompanied by tests exercising the feature. - -4. Pull requests that contain failing tests will not be merged until the test - failures are addressed. Pull requests that cause a significant drop in the - SDK's test coverage percentage are unlikely to be merged until tests have - been added. - -5. The JSON files under the SDK's `models` folder are sourced from outside the SDK. - Such as `models/apis/ec2/2016-11-15/api.json`. We will not accept pull requests - directly on these models. If you discover an issue with the models please - create a [GitHub issue][issues] describing the issue. - -### Testing - -To run the tests locally, running the `make unit` command will `go get` the -SDK's testing dependencies, and run vet, link and unit tests for the SDK. - -``` -make unit -``` - -Standard go testing functionality is supported as well. To test SDK code that -is tagged with `codegen` you'll need to set the build tag in the go test -command. The `make unit` command will do this automatically. - -``` -go test -tags codegen ./private/... -``` - -See the `Makefile` for additional testing tags that can be used in testing. - -To test on multiple platform the SDK includes several DockerFiles under the -`awstesting/sandbox` folder, and associated make recipes to to execute -unit testing within environments configured for specific Go versions. - -``` -make sandbox-test-go18 -``` - -To run all sandbox environments use the following make recipe - -``` -# Optionally update the Go tip that will be used during the batch testing -make update-aws-golang-tip - -# Run all SDK tests for supported Go versions in sandboxes -make sandbox-test -``` - -In addition the sandbox environment include make recipes for interactive modes -so you can run command within the Docker container and context of the SDK. - -``` -make sandbox-go18 -``` - -### Changelog Documents - -You can see all release changes in the `CHANGELOG.md` file at the root of the -repository. The release notes added to this file will contain service client -updates, and major SDK changes. When submitting a pull request please include an entry in `CHANGELOG_PENDING.md` under the appropriate changelog type so your changelog entry is included on the following release. - -#### Changelog Types - -* `SDK Features` - For major additive features, internal changes that have -outward impact, or updates to the SDK foundations. This will result in a minor -version change. -* `SDK Enhancements` - For minor additive features or incremental sized changes. -This will result in a patch version change. -* `SDK Bugs` - For minor changes that resolve an issue. This will result in a -patch version change. - -[issues]: https://github.com/aws/aws-sdk-go-v2/issues -[pr]: https://github.com/aws/aws-sdk-go-v2/pulls -[license]: http://aws.amazon.com/apache2.0/ -[cla]: http://en.wikipedia.org/wiki/Contributor_License_Agreement -[releasenotes]: https://github.com/aws/aws-sdk-go-v2/releases - diff --git a/vendor/github.com/aws/aws-sdk-go-v2/DESIGN.md b/vendor/github.com/aws/aws-sdk-go-v2/DESIGN.md deleted file mode 100644 index 4c9be94a2..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/DESIGN.md +++ /dev/null @@ -1,15 +0,0 @@ -Open Discussions ---- -The following issues are currently open for community feedback. -All discourse must adhere to the [Code of Conduct] policy. - -* [Refactoring API Client Paginators](https://github.com/aws/aws-sdk-go-v2/issues/439) -* [Refactoring API Client Waiters](https://github.com/aws/aws-sdk-go-v2/issues/442) -* [Refactoring API Client Enums and Types to Discrete Packages](https://github.com/aws/aws-sdk-go-v2/issues/445) -* [SDK Modularization](https://github.com/aws/aws-sdk-go-v2/issues/444) - -Past Discussions ---- -The issues listed here are for documentation purposes, and is used to capture issues and their associated discussions. - -[Code of Conduct]: https://github.com/aws/aws-sdk-go-v2/blob/main/CODE_OF_CONDUCT.md diff --git a/vendor/github.com/aws/aws-sdk-go-v2/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/LICENSE.txt deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/LICENSE.txt +++ /dev/null @@ -1,202 +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/aws/aws-sdk-go-v2/Makefile b/vendor/github.com/aws/aws-sdk-go-v2/Makefile deleted file mode 100644 index 9dc36fe4e..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/Makefile +++ /dev/null @@ -1,538 +0,0 @@ -# Lint rules to ignore -LINTIGNORESINGLEFIGHT='internal/sync/singleflight/singleflight.go:.+error should be the last type' -LINT_IGNORE_S3MANAGER_INPUT='feature/s3/manager/upload.go:.+struct field SSEKMSKeyId should be SSEKMSKeyID' -# Names of these are tied to endpoint rules and they're internal so ignore them -LINT_IGNORE_AWSRULESFN_ARN='internal/endpoints/awsrulesfn/arn.go' -LINT_IGNORE_AWSRULESFN_PARTITION='internal/endpoints/awsrulesfn/partition.go' - -UNIT_TEST_TAGS= -BUILD_TAGS=-tags "example,codegen,integration,ec2env,perftest" - -SMITHY_GO_SRC ?= $(shell pwd)/../smithy-go - -SDK_MIN_GO_VERSION ?= 1.15 - -EACHMODULE_FAILFAST ?= true -EACHMODULE_FAILFAST_FLAG=-fail-fast=${EACHMODULE_FAILFAST} - -EACHMODULE_CONCURRENCY ?= 1 -EACHMODULE_CONCURRENCY_FLAG=-c ${EACHMODULE_CONCURRENCY} - -EACHMODULE_SKIP ?= -EACHMODULE_SKIP_FLAG=-skip="${EACHMODULE_SKIP}" - -EACHMODULE_FLAGS=${EACHMODULE_CONCURRENCY_FLAG} ${EACHMODULE_FAILFAST_FLAG} ${EACHMODULE_SKIP_FLAG} - -# SDK's Core and client packages that are compatible with Go 1.9+. -SDK_CORE_PKGS=./aws/... ./internal/... -SDK_CLIENT_PKGS=./service/... -SDK_COMPA_PKGS=${SDK_CORE_PKGS} ${SDK_CLIENT_PKGS} - -# SDK additional packages that are used for development of the SDK. -SDK_EXAMPLES_PKGS= -SDK_ALL_PKGS=${SDK_COMPA_PKGS} ${SDK_EXAMPLES_PKGS} - -RUN_NONE=-run NONE -RUN_INTEG=-run '^TestInteg_' - -CODEGEN_RESOURCES_PATH=$(shell pwd)/codegen/smithy-aws-go-codegen/src/main/resources/software/amazon/smithy/aws/go/codegen -CODEGEN_API_MODELS_PATH=$(shell pwd)/codegen/sdk-codegen/aws-models -ENDPOINTS_JSON=${CODEGEN_RESOURCES_PATH}/endpoints.json -ENDPOINT_PREFIX_JSON=${CODEGEN_RESOURCES_PATH}/endpoint-prefix.json - -LICENSE_FILE=$(shell pwd)/LICENSE.txt - -SMITHY_GO_VERSION ?= -PRE_RELEASE_VERSION ?= -RELEASE_MANIFEST_FILE ?= -RELEASE_CHGLOG_DESC_FILE ?= - -REPOTOOLS_VERSION ?= latest -REPOTOOLS_MODULE = github.com/awslabs/aws-go-multi-module-repository-tools -REPOTOOLS_CMD_ANNOTATE_STABLE_GEN = ${REPOTOOLS_MODULE}/cmd/annotatestablegen@${REPOTOOLS_VERSION} -REPOTOOLS_CMD_MAKE_RELATIVE = ${REPOTOOLS_MODULE}/cmd/makerelative@${REPOTOOLS_VERSION} -REPOTOOLS_CMD_CALCULATE_RELEASE = ${REPOTOOLS_MODULE}/cmd/calculaterelease@${REPOTOOLS_VERSION} -REPOTOOLS_CMD_UPDATE_REQUIRES = ${REPOTOOLS_MODULE}/cmd/updaterequires@${REPOTOOLS_VERSION} -REPOTOOLS_CMD_UPDATE_MODULE_METADATA = ${REPOTOOLS_MODULE}/cmd/updatemodulemeta@${REPOTOOLS_VERSION} -REPOTOOLS_CMD_GENERATE_CHANGELOG = ${REPOTOOLS_MODULE}/cmd/generatechangelog@${REPOTOOLS_VERSION} -REPOTOOLS_CMD_CHANGELOG = ${REPOTOOLS_MODULE}/cmd/changelog@${REPOTOOLS_VERSION} -REPOTOOLS_CMD_TAG_RELEASE = ${REPOTOOLS_MODULE}/cmd/tagrelease@${REPOTOOLS_VERSION} -REPOTOOLS_CMD_EDIT_MODULE_DEPENDENCY = ${REPOTOOLS_MODULE}/cmd/editmoduledependency@${REPOTOOLS_VERSION} - -REPOTOOLS_CALCULATE_RELEASE_VERBOSE ?= false -REPOTOOLS_CALCULATE_RELEASE_VERBOSE_FLAG=-v=${REPOTOOLS_CALCULATE_RELEASE_VERBOSE} - -REPOTOOLS_CALCULATE_RELEASE_ADDITIONAL_ARGS ?= - -ifneq ($(PRE_RELEASE_VERSION),) - REPOTOOLS_CALCULATE_RELEASE_ADDITIONAL_ARGS += -preview=${PRE_RELEASE_VERSION} -endif - -.PHONY: all -all: generate unit - -################### -# Code Generation # -################### -.PHONY: generate smithy-generate smithy-build smithy-build-% smithy-clean smithy-go-publish-local format \ -gen-config-asserts gen-repo-mod-replace gen-mod-replace-smithy gen-mod-dropreplace-smithy-% gen-aws-ptrs tidy-modules-% \ -add-module-license-files sync-models sync-endpoints-model sync-endpoints.json clone-v1-models gen-internal-codegen \ -sync-api-models copy-attributevalue-feature min-go-version-% update-requires smithy-annotate-stable \ -update-module-metadata download-modules-% - -generate: smithy-generate update-requires gen-repo-mod-replace update-module-metadata smithy-annotate-stable \ -gen-config-asserts gen-internal-codegen copy-attributevalue-feature gen-mod-dropreplace-smithy-. min-go-version-. \ -tidy-modules-. add-module-license-files gen-aws-ptrs format - -generate-tmpreplace-smithy: smithy-generate update-requires gen-repo-mod-replace update-module-metadata smithy-annotate-stable \ -gen-config-asserts gen-internal-codegen copy-attributevalue-feature gen-mod-replace-smithy-. min-go-version-. \ -tidy-modules-. add-module-license-files gen-aws-ptrs format gen-mod-dropreplace-smithy-. reset-sum - -reset-sum: - find . -name go.sum -exec git checkout -- {} \; - -smithy-generate: - cd codegen && ./gradlew clean build -Plog-tests && ./gradlew clean - -smithy-build: - cd codegen && ./gradlew clean build -Plog-tests - -smithy-build-%: - @# smithy-build- command that uses the pattern to define build filter that - @# the smithy API model service id starts with. Strips off the - @# "smithy-build-". - @# - @# e.g. smithy-build-com.amazonaws.rds - @# e.g. smithy-build-com.amazonaws.rds#AmazonRDSv19 - cd codegen && \ - SMITHY_GO_BUILD_API="$(subst smithy-build-,,$@)" ./gradlew clean build -Plog-tests - -smithy-annotate-stable: - go run ${REPOTOOLS_CMD_ANNOTATE_STABLE_GEN} - -smithy-clean: - cd codegen && ./gradlew clean - -smithy-go-publish-local: - rm -rf /tmp/smithy-go-local - git clone https://github.com/aws/smithy-go /tmp/smithy-go-local - make -C /tmp/smithy-go-local smithy-clean smithy-publish-local - -format: - gofmt -w -s . - -gen-config-asserts: - @echo "Generating SDK config package implementor assertions" - cd config \ - && go mod tidy \ - && go generate - -gen-internal-codegen: - @echo "Generating internal/codegen" - cd internal/codegen \ - && go mod tidy \ - && go generate - -gen-repo-mod-replace: - @echo "Generating go.mod replace for repo modules" - go run ${REPOTOOLS_CMD_MAKE_RELATIVE} - -gen-mod-replace-smithy-%: - @# gen-mod-replace-smithy- command that uses the pattern to define build filter that - @# for modules to add replace to. Strips off the "gen-mod-replace-smithy-". - @# - @# SMITHY_GO_SRC environment variable is the path to add replace to - @# - @# e.g. gen-mod-replace-smithy-service_ssooidc - cd ./internal/repotools/cmd/eachmodule \ - && go run . -p $(subst _,/,$(subst gen-mod-replace-smithy-,,$@)) ${EACHMODULE_FLAGS} \ - "go mod edit -replace github.com/aws/smithy-go=${SMITHY_GO_SRC}" - -gen-mod-dropreplace-smithy-%: - @# gen-mod-dropreplace-smithy- command that uses the pattern to define build filter that - @# for modules to add replace to. Strips off the "gen-mod-dropreplace-smithy-". - @# - @# e.g. gen-mod-dropreplace-smithy-service_ssooidc - cd ./internal/repotools/cmd/eachmodule \ - && go run . -p $(subst _,/,$(subst gen-mod-dropreplace-smithy-,,$@)) ${EACHMODULE_FLAGS} \ - "go mod edit -dropreplace github.com/aws/smithy-go" - -gen-aws-ptrs: - cd aws && go generate - -tidy-modules-%: - @# tidy command that uses the pattern to define the root path that the - @# module testing will start from. Strips off the "tidy-modules-" and - @# replaces all "_" with "/". - @# - @# e.g. tidy-modules-internal_protocoltest - cd ./internal/repotools/cmd/eachmodule \ - && go run . -p $(subst _,/,$(subst tidy-modules-,,$@)) ${EACHMODULE_FLAGS} \ - "go mod tidy" - -download-modules-%: - @# download command that uses the pattern to define the root path that the - @# module testing will start from. Strips off the "download-modules-" and - @# replaces all "_" with "/". - @# - @# e.g. download-modules-internal_protocoltest - cd ./internal/repotools/cmd/eachmodule \ - && go run . -p $(subst _,/,$(subst download-modules-,,$@)) ${EACHMODULE_FLAGS} \ - "go mod download all" - -add-module-license-files: - cd internal/repotools/cmd/eachmodule && \ - go run . -skip-root \ - "cp $(LICENSE_FILE) ." - -sync-models: sync-endpoints-model sync-api-models - -sync-endpoints-model: sync-endpoints.json - -sync-endpoints.json: - [[ ! -z "${ENDPOINTS_MODEL}" ]] && cp ${ENDPOINTS_MODEL} ${ENDPOINTS_JSON} || echo "ENDPOINTS_MODEL not set, must not be empty" - -clone-v1-models: - rm -rf /tmp/aws-sdk-go-model-sync - git clone https://github.com/aws/aws-sdk-go.git --depth 1 /tmp/aws-sdk-go-model-sync - -sync-api-models: - cd internal/repotools/cmd/syncAPIModels && \ - go run . \ - -m ${API_MODELS} \ - -o ${CODEGEN_API_MODELS_PATH} - -copy-attributevalue-feature: - cd ./feature/dynamodbstreams/attributevalue && \ - find . -name "*.go" | grep -v "doc.go" | xargs -I % rm % && \ - find ../../dynamodb/attributevalue -name "*.go" | grep -v "doc.go" | xargs -I % cp % . && \ - ls *.go | grep -v "convert.go" | grep -v "doc.go" | \ - xargs -I % sed -i.bk -E 's:github.com/aws/aws-sdk-go-v2/(service|feature)/dynamodb:github.com/aws/aws-sdk-go-v2/\1/dynamodbstreams:g' % && \ - ls *.go | grep -v "convert.go" | grep -v "doc.go" | \ - xargs -I % sed -i.bk 's:DynamoDB:DynamoDBStreams:g' % && \ - ls *.go | grep -v "doc.go" | \ - xargs -I % sed -i.bk 's:dynamodb\.:dynamodbstreams.:g' % && \ - sed -i.bk 's:streams\.:ddbtypes.:g' "convert.go" && \ - sed -i.bk 's:ddb\.:streams.:g' "convert.go" && \ - sed -i.bk 's:ddbtypes\.:ddb.:g' "convert.go" &&\ - sed -i.bk 's:Streams::g' "convert.go" && \ - rm -rf ./*.bk && \ - go mod tidy && \ - gofmt -w -s . && \ - go test . - -min-go-version-%: - cd ./internal/repotools/cmd/eachmodule \ - && go run . -p $(subst _,/,$(subst min-go-version-,,$@)) ${EACHMODULE_FLAGS} \ - "go mod edit -go=${SDK_MIN_GO_VERSION}" - -update-requires: - go run ${REPOTOOLS_CMD_UPDATE_REQUIRES} - -update-module-metadata: - go run ${REPOTOOLS_CMD_UPDATE_MODULE_METADATA} - -################ -# Unit Testing # -################ -.PHONY: unit unit-race unit-test unit-race-test unit-race-modules-% unit-modules-% build build-modules-% \ -go-build-modules-% test test-race-modules-% test-modules-% cachedep cachedep-modules-% api-diff-modules-% - -unit: lint unit-modules-. -unit-race: lint unit-race-modules-. - -unit-test: test-modules-. -unit-race-test: test-race-modules-. - -unit-race-modules-%: - @# unit command that uses the pattern to define the root path that the - @# module testing will start from. Strips off the "unit-race-modules-" and - @# replaces all "_" with "/". - @# - @# e.g. unit-race-modules-internal_protocoltest - cd ./internal/repotools/cmd/eachmodule \ - && go run . -p $(subst _,/,$(subst unit-race-modules-,,$@)) ${EACHMODULE_FLAGS} \ - "go vet ${BUILD_TAGS} --all ./..." \ - "go test ${BUILD_TAGS} ${RUN_NONE} ./..." \ - "go test -timeout=1m ${UNIT_TEST_TAGS} -race -cpu=4 ./..." - -unit-modules-%: - @# unit command that uses the pattern to define the root path that the - @# module testing will start from. Strips off the "unit-modules-" and - @# replaces all "_" with "/". - @# - @# e.g. unit-modules-internal_protocoltest - cd ./internal/repotools/cmd/eachmodule \ - && go run . -p $(subst _,/,$(subst unit-modules-,,$@)) ${EACHMODULE_FLAGS} \ - "go vet ${BUILD_TAGS} --all ./..." \ - "go test ${BUILD_TAGS} ${RUN_NONE} ./..." \ - "go test -timeout=1m ${UNIT_TEST_TAGS} ./..." - -build: build-modules-. - -build-modules-%: - @# build command that uses the pattern to define the root path that the - @# module testing will start from. Strips off the "build-modules-" and - @# replaces all "_" with "/". - @# - @# e.g. build-modules-internal_protocoltest - cd ./internal/repotools/cmd/eachmodule \ - && go run . -p $(subst _,/,$(subst build-modules-,,$@)) ${EACHMODULE_FLAGS} \ - "go test ${BUILD_TAGS} ${RUN_NONE} ./..." - -go-build-modules-%: - @# build command that uses the pattern to define the root path that the - @# module testing will start from. Strips off the "build-modules-" and - @# replaces all "_" with "/". - @# - @# Validates that all modules in the repo have buildable Go files. - @# - @# e.g. go-build-modules-internal_protocoltest - cd ./internal/repotools/cmd/eachmodule \ - && go run . -p $(subst _,/,$(subst go-build-modules-,,$@)) ${EACHMODULE_FLAGS} \ - "go build ${BUILD_TAGS} ./..." - -test: test-modules-. - -test-race-modules-%: - @# Test command that uses the pattern to define the root path that the - @# module testing will start from. Strips off the "test-race-modules-" and - @# replaces all "_" with "/". - @# - @# e.g. test-race-modules-internal_protocoltest - cd ./internal/repotools/cmd/eachmodule \ - && go run . -p $(subst _,/,$(subst test-race-modules-,,$@)) ${EACHMODULE_FLAGS} \ - "go test -timeout=1m ${UNIT_TEST_TAGS} -race -cpu=4 ./..." - -test-modules-%: - @# Test command that uses the pattern to define the root path that the - @# module testing will start from. Strips off the "test-modules-" and - @# replaces all "_" with "/". - @# - @# e.g. test-modules-internal_protocoltest - cd ./internal/repotools/cmd/eachmodule \ - && go run . -p $(subst _,/,$(subst test-modules-,,$@)) ${EACHMODULE_FLAGS} \ - "go test -timeout=1m ${UNIT_TEST_TAGS} ./..." - -cachedep: cachedep-modules-. - -cachedep-modules-%: - @# build command that uses the pattern to define the root path that the - @# module caching will start from. Strips off the "cachedep-modules-" and - @# replaces all "_" with "/". - @# - @# e.g. cachedep-modules-internal_protocoltest - cd ./internal/repotools/cmd/eachmodule \ - && go run . -p $(subst _,/,$(subst cachedep-modules-,,$@)) ${EACHMODULE_FLAGS} \ - "go mod download" - -api-diff-modules-%: - @# Command that uses the pattern to define the root path that the - @# module testing will start from. Strips off the "api-diff-modules-" and - @# replaces all "_" with "/". - @# - @# Requires golang.org/x/exp/cmd/gorelease to be available in the GOPATH. - @# - @# e.g. api-diff-modules-internal_protocoltest - cd ./internal/repotools/cmd/eachmodule \ - && go run . -p $(subst _,/,$(subst api-diff-modules-,,$@)) \ - -fail-fast=true \ - -c 1 \ - -skip="internal/repotools" \ - "$$(go env GOPATH)/bin/gorelease" - -############## -# CI Testing # -############## -.PHONY: ci-test ci-test-no-generate ci-test-generate-validate - -ci-test: generate unit-race ci-test-generate-validate -ci-test-no-generate: unit-race - -ci-test-generate-validate: - @echo "CI test validate no generated code changes" - git update-index --assume-unchanged go.mod go.sum - git add . -A - gitstatus=`git diff --cached --ignore-space-change`; \ - echo "$$gitstatus"; \ - if [ "$$gitstatus" != "" ] && [ "$$gitstatus" != "skipping validation" ]; then echo "$$gitstatus"; exit 1; fi - git update-index --no-assume-unchanged go.mod go.sum - -ci-lint: ci-lint-. - -ci-lint-%: - @# Run golangci-lint command that uses the pattern to define the root path that the - @# module check will start from. Strips off the "ci-lint-" and - @# replaces all "_" with "/". - @# - @# e.g. ci-lint-internal_protocoltest - cd ./internal/repotools/cmd/eachmodule \ - && go run . -p $(subst _,/,$(subst ci-lint-,,$@)) \ - -fail-fast=false \ - -c 1 \ - -skip="internal/repotools" \ - "golangci-lint run" - -ci-lint-install: - @# Installs golangci-lint at GoPATH. - @# This should be used to run golangci-lint locally. - @# - go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest - -####################### -# Integration Testing # -####################### -.PHONY: integration integ-modules-% cleanup-integ-buckets - -integration: integ-modules-service - -integ-modules-%: - @# integration command that uses the pattern to define the root path that - @# the module testing will start from. Strips off the "integ-modules-" and - @# replaces all "_" with "/". - @# - @# e.g. test-modules-service_dynamodb - cd ./internal/repotools/cmd/eachmodule \ - && go run . -p $(subst _,/,$(subst integ-modules-,,$@)) ${EACHMODULE_FLAGS} \ - "go test -timeout=10m -tags "integration" -v ${RUN_INTEG} -count 1 ./..." - -cleanup-integ-buckets: - @echo "Cleaning up SDK integration resources" - go run -tags "integration" ./internal/awstesting/cmd/bucket_cleanup/main.go "aws-sdk-go-integration" - -############## -# Benchmarks # -############## -.PHONY: bench bench-modules-% - -bench: bench-modules-. - -bench-modules-%: - @# benchmark command that uses the pattern to define the root path that - @# the module testing will start from. Strips off the "bench-modules-" and - @# replaces all "_" with "/". - @# - @# e.g. bench-modules-service_dynamodb - cd ./internal/repotools/cmd/eachmodule \ - && go run . -p $(subst _,/,$(subst bench-modules-,,$@)) ${EACHMODULE_FLAGS} \ - "go test -timeout=10m -bench . --benchmem ${BUILD_TAGS} ${RUN_NONE} ./..." - -##################### -# Release Process # -##################### -.PHONY: preview-release pre-release-validation release - -ls-changes: - go run ${REPOTOOLS_CMD_CHANGELOG} ls - -preview-release: - go run ${REPOTOOLS_CMD_CALCULATE_RELEASE} ${REPOTOOLS_CALCULATE_RELEASE_VERBOSE_FLAG} ${REPOTOOLS_CALCULATE_RELEASE_ADDITIONAL_ARGS} - -pre-release-validation: - @if [[ -z "${RELEASE_MANIFEST_FILE}" ]]; then \ - echo "RELEASE_MANIFEST_FILE is required to specify the file to write the release manifest" && false; \ - fi - @if [[ -z "${RELEASE_CHGLOG_DESC_FILE}" ]]; then \ - echo "RELEASE_CHGLOG_DESC_FILE is required to specify the file to write the release notes" && false; \ - fi - -release: pre-release-validation - go run ${REPOTOOLS_CMD_CALCULATE_RELEASE} -o ${RELEASE_MANIFEST_FILE} ${REPOTOOLS_CALCULATE_RELEASE_VERBOSE_FLAG} ${REPOTOOLS_CALCULATE_RELEASE_ADDITIONAL_ARGS} - go run ${REPOTOOLS_CMD_UPDATE_REQUIRES} -release ${RELEASE_MANIFEST_FILE} - go run ${REPOTOOLS_CMD_UPDATE_MODULE_METADATA} -release ${RELEASE_MANIFEST_FILE} - go run ${REPOTOOLS_CMD_GENERATE_CHANGELOG} -release ${RELEASE_MANIFEST_FILE} -o ${RELEASE_CHGLOG_DESC_FILE} - go run ${REPOTOOLS_CMD_CHANGELOG} rm -all - go run ${REPOTOOLS_CMD_TAG_RELEASE} -release ${RELEASE_MANIFEST_FILE} - -############## -# Repo Tools # -############## -.PHONY: install-repotools - -install-repotools: - go install ${REPOTOOLS_MODULE}/cmd/changelog@${REPOTOOLS_VERSION} - -set-smithy-go-version: - @if [[ -z "${SMITHY_GO_VERSION}" ]]; then \ - echo "SMITHY_GO_VERSION is required to update SDK's smithy-go module dependency version" && false; \ - fi - go run ${REPOTOOLS_CMD_EDIT_MODULE_DEPENDENCY} -s "github.com/aws/smithy-go" -v "${SMITHY_GO_VERSION}" - -################## -# Linting/Verify # -################## -.PHONY: verify lint vet vet-modules-% sdkv1check - -verify: lint vet sdkv1check - -lint: - @echo "go lint SDK and vendor packages" - @lint=`golint ./...`; \ - dolint=`echo "$$lint" | grep -E -v \ - -e ${LINT_IGNORE_S3MANAGER_INPUT} \ - -e ${LINTIGNORESINGLEFIGHT} \ - -e ${LINT_IGNORE_AWSRULESFN_ARN} \ - -e ${LINT_IGNORE_AWSRULESFN_PARTITION}`; \ - echo "$$dolint"; \ - if [ "$$dolint" != "" ]; then exit 1; fi - -vet: vet-modules-. - -vet-modules-%: - cd ./internal/repotools/cmd/eachmodule \ - && go run . -p $(subst _,/,$(subst vet-modules-,,$@)) ${EACHMODULE_FLAGS} \ - "go vet ${BUILD_TAGS} --all ./..." - -sdkv1check: - @echo "Checking for usage of AWS SDK for Go v1" - @sdkv1usage=`go list -test -f '''{{ if not .Standard }}{{ range $$_, $$name := .Imports }} * {{ $$.ImportPath }} -> {{ $$name }}{{ print "\n" }}{{ end }}{{ range $$_, $$name := .TestImports }} *: {{ $$.ImportPath }} -> {{ $$name }}{{ print "\n" }}{{ end }}{{ end}}''' ./... | sort -u | grep '''/aws-sdk-go/'''`; \ - echo "$$sdkv1usage"; \ - if [ "$$sdkv1usage" != "" ]; then exit 1; fi - -list-deps: list-deps-. - -list-deps-%: - @# command that uses the pattern to define the root path that the - @# module testing will start from. Strips off the "list-deps-" and - @# replaces all "_" with "/". - @# - @# Trim output to only include stdout for list of dependencies only. - @# make list-deps 2>&- - @# - @# e.g. list-deps-internal_protocoltest - @cd ./internal/repotools/cmd/eachmodule \ - && go run . -p $(subst _,/,$(subst list-deps-,,$@)) ${EACHMODULE_FLAGS} \ - "go list -m all | grep -v 'github.com/aws/aws-sdk-go-v2'" | sort -u - -################### -# Sandbox Testing # -################### -.PHONY: sandbox-tests sandbox-build-% sandbox-run-% sandbox-test-% update-aws-golang-tip - -sandbox-tests: sandbox-test-go1.15 sandbox-test-go1.16 sandbox-test-go1.17 sandbox-test-go1.18 sandbox-test-go1.19 sandbox-test-go1.20 sandbox-test-gotip - -sandbox-build-%: - @# sandbox-build-go1.17 - @# sandbox-build-gotip - @if [ $@ == sandbox-build-gotip ]; then\ - docker build \ - -f ./internal/awstesting/sandbox/Dockerfile.test.gotip \ - -t "aws-sdk-go-$(subst sandbox-build-,,$@)" . ;\ - else\ - docker build \ - --build-arg GO_VERSION=$(subst sandbox-build-go,,$@) \ - -f ./internal/awstesting/sandbox/Dockerfile.test.goversion \ - -t "aws-sdk-go-$(subst sandbox-build-,,$@)" . ;\ - fi - -sandbox-run-%: sandbox-build-% - @# sandbox-run-go1.17 - @# sandbox-run-gotip - docker run -i -t "aws-sdk-go-$(subst sandbox-run-,,$@)" bash -sandbox-test-%: sandbox-build-% - @# sandbox-test-go1.17 - @# sandbox-test-gotip - docker run -t "aws-sdk-go-$(subst sandbox-test-,,$@)" - -update-aws-golang-tip: - docker build --no-cache=true -f ./internal/awstesting/sandbox/Dockerfile.golang-tip -t "aws-golang:tip" . diff --git a/vendor/github.com/aws/aws-sdk-go-v2/NOTICE.txt b/vendor/github.com/aws/aws-sdk-go-v2/NOTICE.txt deleted file mode 100644 index 899129ecc..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/NOTICE.txt +++ /dev/null @@ -1,3 +0,0 @@ -AWS SDK for Go -Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. -Copyright 2014-2015 Stripe, Inc. diff --git a/vendor/github.com/aws/aws-sdk-go-v2/README.md b/vendor/github.com/aws/aws-sdk-go-v2/README.md deleted file mode 100644 index 54626706f..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/README.md +++ /dev/null @@ -1,156 +0,0 @@ -# AWS SDK for Go v2 - -[![Go Build status](https://github.com/aws/aws-sdk-go-v2/actions/workflows/go.yml/badge.svg?branch=main)](https://github.com/aws/aws-sdk-go-v2/actions/workflows/go.yml)[![Codegen Build status](https://github.com/aws/aws-sdk-go-v2/actions/workflows/codegen.yml/badge.svg?branch=main)](https://github.com/aws/aws-sdk-go-v2/actions/workflows/codegen.yml) [![SDK Documentation](https://img.shields.io/badge/SDK-Documentation-blue)](https://aws.github.io/aws-sdk-go-v2/docs/) [![Migration Guide](https://img.shields.io/badge/Migration-Guide-blue)](https://aws.github.io/aws-sdk-go-v2/docs/migrating/) [![API Reference](https://img.shields.io/badge/api-reference-blue.svg)](https://pkg.go.dev/mod/github.com/aws/aws-sdk-go-v2) [![Apache V2 License](https://img.shields.io/badge/license-Apache%20V2-blue.svg)](https://github.com/aws/aws-sdk-go-v2/blob/main/LICENSE.txt) - -`aws-sdk-go-v2` is the v2 AWS SDK for the Go programming language. - -The v2 SDK requires a minimum version of `Go 1.15`. - -Check out the [release notes](https://github.com/aws/aws-sdk-go-v2/blob/main/CHANGELOG.md) for information about the latest bug -fixes, updates, and features added to the SDK. - -Jump To: -* [Getting Started](#getting-started) -* [Getting Help](#getting-help) -* [Contributing](#feedback-and-contributing) -* [More Resources](#resources) - -## Maintenance and support for SDK major versions - -For information about maintenance and support for SDK major versions and their underlying dependencies, see the -following in the AWS SDKs and Tools Shared Configuration and Credentials Reference Guide: - -* [AWS SDKs and Tools Maintenance Policy](https://docs.aws.amazon.com/credref/latest/refdocs/maint-policy.html) -* [AWS SDKs and Tools Version Support Matrix](https://docs.aws.amazon.com/credref/latest/refdocs/version-support-matrix.html) - -## Getting started -To get started working with the SDK setup your project for Go modules, and retrieve the SDK dependencies with `go get`. -This example shows how you can use the v2 SDK to make an API request using the SDK's [Amazon DynamoDB] client. - -###### Initialize Project -```sh -$ mkdir ~/helloaws -$ cd ~/helloaws -$ go mod init helloaws -``` -###### Add SDK Dependencies -```sh -$ go get github.com/aws/aws-sdk-go-v2/aws -$ go get github.com/aws/aws-sdk-go-v2/config -$ go get github.com/aws/aws-sdk-go-v2/service/dynamodb -``` - -###### Write Code -In your preferred editor add the following content to `main.go` - -```go -package main - -import ( - "context" - "fmt" - "log" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/config" - "github.com/aws/aws-sdk-go-v2/service/dynamodb" -) - -func main() { - // Using the SDK's default configuration, loading additional config - // and credentials values from the environment variables, shared - // credentials, and shared configuration files - cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion("us-west-2")) - if err != nil { - log.Fatalf("unable to load SDK config, %v", err) - } - - // Using the Config value, create the DynamoDB client - svc := dynamodb.NewFromConfig(cfg) - - // Build the request with its input parameters - resp, err := svc.ListTables(context.TODO(), &dynamodb.ListTablesInput{ - Limit: aws.Int32(5), - }) - if err != nil { - log.Fatalf("failed to list tables, %v", err) - } - - fmt.Println("Tables:") - for _, tableName := range resp.TableNames { - fmt.Println(tableName) - } -} -``` - -###### Compile and Execute -```sh -$ go run . -Tables: -tableOne -tableTwo -``` - -## Getting Help - -Please use these community resources for getting help. We use the GitHub issues -for tracking bugs and feature requests. - -* Ask us a [question](https://github.com/aws/aws-sdk-go-v2/discussions/new?category=q-a) or open a [discussion](https://github.com/aws/aws-sdk-go-v2/discussions/new?category=general). -* If you think you may have found a bug, please open an [issue](https://github.com/aws/aws-sdk-go-v2/issues/new/choose). -* Open a support ticket with [AWS Support](http://docs.aws.amazon.com/awssupport/latest/user/getting-started.html). - -This SDK implements AWS service APIs. For general issues regarding the AWS services and their limitations, you may also take a look at the [Amazon Web Services Discussion Forums](https://forums.aws.amazon.com/). - -### Opening Issues - -If you encounter a bug with the AWS SDK for Go we would like to hear about it. -Search the [existing issues][Issues] and see -if others are also experiencing the same issue before opening a new issue. Please -include the version of AWS SDK for Go, Go language, and OS you’re using. Please -also include reproduction case when appropriate. - -The GitHub issues are intended for bug reports and feature requests. For help -and questions with using AWS SDK for Go please make use of the resources listed -in the [Getting Help](#getting-help) section. -Keeping the list of open issues lean will help us respond in a timely manner. - -## Feedback and contributing - -The v2 SDK will use GitHub [Issues] to track feature requests and issues with the SDK. In addition, we'll use GitHub [Projects] to track large tasks spanning multiple pull requests, such as refactoring the SDK's internal request lifecycle. You can provide feedback to us in several ways. - -**GitHub issues**. To provide feedback or report bugs, file GitHub [Issues] on the SDK. This is the preferred mechanism to give feedback so that other users can engage in the conversation, +1 issues, etc. Issues you open will be evaluated, and included in our roadmap for the GA launch. - -**Contributing**. You can open pull requests for fixes or additions to the AWS SDK for Go 2.0. All pull requests must be submitted under the Apache 2.0 license and will be reviewed by an SDK team member before being merged in. Accompanying unit tests, where possible, are appreciated. - -## Resources - -[SDK Developer Guide](https://aws.github.io/aws-sdk-go-v2/docs/) - Use this document to learn how to get started and -use the AWS SDK for Go V2. - -[SDK Migration Guide](https://aws.github.io/aws-sdk-go-v2/docs/migrating/) - Use this document to learn how to migrate to V2 from the AWS SDK for Go. - -[SDK API Reference Documentation](https://pkg.go.dev/mod/github.com/aws/aws-sdk-go-v2) - Use this -document to look up all API operation input and output parameters for AWS -services supported by the SDK. The API reference also includes documentation of -the SDK, and examples how to using the SDK, service client API operations, and -API operation require parameters. - -[Service Documentation](https://aws.amazon.com/documentation/) - Use this -documentation to learn how to interface with AWS services. These guides are -great for getting started with a service, or when looking for more -information about a service. While this document is not required for coding, -services may supply helpful samples to look out for. - -[Forum](https://forums.aws.amazon.com/forum.jspa?forumID=293) - Ask questions, get help, and give feedback - -[Issues] - Report issues, submit pull requests, and get involved - (see [Apache 2.0 License][license]) - -[Dep]: https://github.com/golang/dep -[Issues]: https://github.com/aws/aws-sdk-go-v2/issues -[Projects]: https://github.com/aws/aws-sdk-go-v2/projects -[CHANGELOG]: https://github.com/aws/aws-sdk-go-v2/blob/main/CHANGELOG.md -[Amazon DynamoDB]: https://aws.amazon.com/dynamodb/ -[design]: https://github.com/aws/aws-sdk-go-v2/blob/main/DESIGN.md -[license]: http://aws.amazon.com/apache2.0/ diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/config.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/config.go deleted file mode 100644 index fe7aacbfa..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/config.go +++ /dev/null @@ -1,193 +0,0 @@ -package aws - -import ( - "net/http" - - smithybearer "github.com/aws/smithy-go/auth/bearer" - "github.com/aws/smithy-go/logging" - "github.com/aws/smithy-go/middleware" -) - -// HTTPClient provides the interface to provide custom HTTPClients. Generally -// *http.Client is sufficient for most use cases. The HTTPClient should not -// follow 301 or 302 redirects. -type HTTPClient interface { - Do(*http.Request) (*http.Response, error) -} - -// A Config provides service configuration for service clients. -type Config struct { - // The region to send requests to. This parameter is required and must - // be configured globally or on a per-client basis unless otherwise - // noted. A full list of regions is found in the "Regions and Endpoints" - // document. - // - // See http://docs.aws.amazon.com/general/latest/gr/rande.html for - // information on AWS regions. - Region string - - // The credentials object to use when signing requests. - // Use the LoadDefaultConfig to load configuration from all the SDK's supported - // sources, and resolve credentials using the SDK's default credential chain. - Credentials CredentialsProvider - - // The Bearer Authentication token provider to use for authenticating API - // operation calls with a Bearer Authentication token. The API clients and - // operation must support Bearer Authentication scheme in order for the - // token provider to be used. API clients created with NewFromConfig will - // automatically be configured with this option, if the API client support - // Bearer Authentication. - // - // The SDK's config.LoadDefaultConfig can automatically populate this - // option for external configuration options such as SSO session. - // https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html - BearerAuthTokenProvider smithybearer.TokenProvider - - // The HTTP Client the SDK's API clients will use to invoke HTTP requests. - // The SDK defaults to a BuildableClient allowing API clients to create - // copies of the HTTP Client for service specific customizations. - // - // Use a (*http.Client) for custom behavior. Using a custom http.Client - // will prevent the SDK from modifying the HTTP client. - HTTPClient HTTPClient - - // An endpoint resolver that can be used to provide or override an endpoint - // for the given service and region. - // - // See the `aws.EndpointResolver` documentation for additional usage - // information. - // - // Deprecated: See Config.EndpointResolverWithOptions - EndpointResolver EndpointResolver - - // An endpoint resolver that can be used to provide or override an endpoint - // for the given service and region. - // - // When EndpointResolverWithOptions is specified, it will be used by a - // service client rather than using EndpointResolver if also specified. - // - // See the `aws.EndpointResolverWithOptions` documentation for additional - // usage information. - // - // Deprecated: with the release of endpoint resolution v2 in API clients, - // EndpointResolver and EndpointResolverWithOptions are deprecated. - // Providing a value for this field will likely prevent you from using - // newer endpoint-related service features. See API client options - // EndpointResolverV2 and BaseEndpoint. - EndpointResolverWithOptions EndpointResolverWithOptions - - // RetryMaxAttempts specifies the maximum number attempts an API client - // will call an operation that fails with a retryable error. - // - // API Clients will only use this value to construct a retryer if the - // Config.Retryer member is not nil. This value will be ignored if - // Retryer is not nil. - RetryMaxAttempts int - - // RetryMode specifies the retry model the API client will be created with. - // - // API Clients will only use this value to construct a retryer if the - // Config.Retryer member is not nil. This value will be ignored if - // Retryer is not nil. - RetryMode RetryMode - - // Retryer is a function that provides a Retryer implementation. A Retryer - // guides how HTTP requests should be retried in case of recoverable - // failures. When nil the API client will use a default retryer. - // - // In general, the provider function should return a new instance of a - // Retryer if you are attempting to provide a consistent Retryer - // configuration across all clients. This will ensure that each client will - // be provided a new instance of the Retryer implementation, and will avoid - // issues such as sharing the same retry token bucket across services. - // - // If not nil, RetryMaxAttempts, and RetryMode will be ignored by API - // clients. - Retryer func() Retryer - - // ConfigSources are the sources that were used to construct the Config. - // Allows for additional configuration to be loaded by clients. - ConfigSources []interface{} - - // APIOptions provides the set of middleware mutations modify how the API - // client requests will be handled. This is useful for adding additional - // tracing data to a request, or changing behavior of the SDK's client. - APIOptions []func(*middleware.Stack) error - - // The logger writer interface to write logging messages to. Defaults to - // standard error. - Logger logging.Logger - - // Configures the events that will be sent to the configured logger. This - // can be used to configure the logging of signing, retries, request, and - // responses of the SDK clients. - // - // See the ClientLogMode type documentation for the complete set of logging - // modes and available configuration. - ClientLogMode ClientLogMode - - // The configured DefaultsMode. If not specified, service clients will - // default to legacy. - // - // Supported modes are: auto, cross-region, in-region, legacy, mobile, - // standard - DefaultsMode DefaultsMode - - // The RuntimeEnvironment configuration, only populated if the DefaultsMode - // is set to DefaultsModeAuto and is initialized by - // `config.LoadDefaultConfig`. You should not populate this structure - // programmatically, or rely on the values here within your applications. - RuntimeEnvironment RuntimeEnvironment - - // AppId is an optional application specific identifier that can be set. - // When set it will be appended to the User-Agent header of every request - // in the form of App/{AppId}. This variable is sourced from environment - // variable AWS_SDK_UA_APP_ID or the shared config profile attribute sdk_ua_app_id. - // See https://docs.aws.amazon.com/sdkref/latest/guide/settings-reference.html for - // more information on environment variables and shared config settings. - AppID string -} - -// NewConfig returns a new Config pointer that can be chained with builder -// methods to set multiple configuration values inline without using pointers. -func NewConfig() *Config { - return &Config{} -} - -// Copy will return a shallow copy of the Config object. If any additional -// configurations are provided they will be merged into the new config returned. -func (c Config) Copy() Config { - cp := c - return cp -} - -// EndpointDiscoveryEnableState indicates if endpoint discovery is -// enabled, disabled, auto or unset state. -// -// Default behavior (Auto or Unset) indicates operations that require endpoint -// discovery will use Endpoint Discovery by default. Operations that -// optionally use Endpoint Discovery will not use Endpoint Discovery -// unless EndpointDiscovery is explicitly enabled. -type EndpointDiscoveryEnableState uint - -// Enumeration values for EndpointDiscoveryEnableState -const ( - // EndpointDiscoveryUnset represents EndpointDiscoveryEnableState is unset. - // Users do not need to use this value explicitly. The behavior for unset - // is the same as for EndpointDiscoveryAuto. - EndpointDiscoveryUnset EndpointDiscoveryEnableState = iota - - // EndpointDiscoveryAuto represents an AUTO state that allows endpoint - // discovery only when required by the api. This is the default - // configuration resolved by the client if endpoint discovery is neither - // enabled or disabled. - EndpointDiscoveryAuto // default state - - // EndpointDiscoveryDisabled indicates client MUST not perform endpoint - // discovery even when required. - EndpointDiscoveryDisabled - - // EndpointDiscoveryEnabled indicates client MUST always perform endpoint - // discovery if supported for the operation. - EndpointDiscoveryEnabled -) diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/context.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/context.go deleted file mode 100644 index 4d8e26ef3..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/context.go +++ /dev/null @@ -1,22 +0,0 @@ -package aws - -import ( - "context" - "time" -) - -type suppressedContext struct { - context.Context -} - -func (s *suppressedContext) Deadline() (deadline time.Time, ok bool) { - return time.Time{}, false -} - -func (s *suppressedContext) Done() <-chan struct{} { - return nil -} - -func (s *suppressedContext) Err() error { - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/credential_cache.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/credential_cache.go deleted file mode 100644 index 781ac0ae2..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/credential_cache.go +++ /dev/null @@ -1,224 +0,0 @@ -package aws - -import ( - "context" - "fmt" - "sync/atomic" - "time" - - sdkrand "github.com/aws/aws-sdk-go-v2/internal/rand" - "github.com/aws/aws-sdk-go-v2/internal/sync/singleflight" -) - -// CredentialsCacheOptions are the options -type CredentialsCacheOptions struct { - - // ExpiryWindow will allow the credentials to trigger refreshing prior to - // the credentials actually expiring. This is beneficial so race conditions - // with expiring credentials do not cause request to fail unexpectedly - // due to ExpiredTokenException exceptions. - // - // An ExpiryWindow of 10s would cause calls to IsExpired() to return true - // 10 seconds before the credentials are actually expired. This can cause an - // increased number of requests to refresh the credentials to occur. - // - // If ExpiryWindow is 0 or less it will be ignored. - ExpiryWindow time.Duration - - // ExpiryWindowJitterFrac provides a mechanism for randomizing the - // expiration of credentials within the configured ExpiryWindow by a random - // percentage. Valid values are between 0.0 and 1.0. - // - // As an example if ExpiryWindow is 60 seconds and ExpiryWindowJitterFrac - // is 0.5 then credentials will be set to expire between 30 to 60 seconds - // prior to their actual expiration time. - // - // If ExpiryWindow is 0 or less then ExpiryWindowJitterFrac is ignored. - // If ExpiryWindowJitterFrac is 0 then no randomization will be applied to the window. - // If ExpiryWindowJitterFrac < 0 the value will be treated as 0. - // If ExpiryWindowJitterFrac > 1 the value will be treated as 1. - ExpiryWindowJitterFrac float64 -} - -// CredentialsCache provides caching and concurrency safe credentials retrieval -// via the provider's retrieve method. -// -// CredentialsCache will look for optional interfaces on the Provider to adjust -// how the credential cache handles credentials caching. -// -// - HandleFailRefreshCredentialsCacheStrategy - Allows provider to handle -// credential refresh failures. This could return an updated Credentials -// value, or attempt another means of retrieving credentials. -// -// - AdjustExpiresByCredentialsCacheStrategy - Allows provider to adjust how -// credentials Expires is modified. This could modify how the Credentials -// Expires is adjusted based on the CredentialsCache ExpiryWindow option. -// Such as providing a floor not to reduce the Expires below. -type CredentialsCache struct { - provider CredentialsProvider - - options CredentialsCacheOptions - creds atomic.Value - sf singleflight.Group -} - -// NewCredentialsCache returns a CredentialsCache that wraps provider. Provider -// is expected to not be nil. A variadic list of one or more functions can be -// provided to modify the CredentialsCache configuration. This allows for -// configuration of credential expiry window and jitter. -func NewCredentialsCache(provider CredentialsProvider, optFns ...func(options *CredentialsCacheOptions)) *CredentialsCache { - options := CredentialsCacheOptions{} - - for _, fn := range optFns { - fn(&options) - } - - if options.ExpiryWindow < 0 { - options.ExpiryWindow = 0 - } - - if options.ExpiryWindowJitterFrac < 0 { - options.ExpiryWindowJitterFrac = 0 - } else if options.ExpiryWindowJitterFrac > 1 { - options.ExpiryWindowJitterFrac = 1 - } - - return &CredentialsCache{ - provider: provider, - options: options, - } -} - -// Retrieve returns the credentials. If the credentials have already been -// retrieved, and not expired the cached credentials will be returned. If the -// credentials have not been retrieved yet, or expired the provider's Retrieve -// method will be called. -// -// Returns and error if the provider's retrieve method returns an error. -func (p *CredentialsCache) Retrieve(ctx context.Context) (Credentials, error) { - if creds, ok := p.getCreds(); ok && !creds.Expired() { - return creds, nil - } - - resCh := p.sf.DoChan("", func() (interface{}, error) { - return p.singleRetrieve(&suppressedContext{ctx}) - }) - select { - case res := <-resCh: - return res.Val.(Credentials), res.Err - case <-ctx.Done(): - return Credentials{}, &RequestCanceledError{Err: ctx.Err()} - } -} - -func (p *CredentialsCache) singleRetrieve(ctx context.Context) (interface{}, error) { - currCreds, ok := p.getCreds() - if ok && !currCreds.Expired() { - return currCreds, nil - } - - newCreds, err := p.provider.Retrieve(ctx) - if err != nil { - handleFailToRefresh := defaultHandleFailToRefresh - if cs, ok := p.provider.(HandleFailRefreshCredentialsCacheStrategy); ok { - handleFailToRefresh = cs.HandleFailToRefresh - } - newCreds, err = handleFailToRefresh(ctx, currCreds, err) - if err != nil { - return Credentials{}, fmt.Errorf("failed to refresh cached credentials, %w", err) - } - } - - if newCreds.CanExpire && p.options.ExpiryWindow > 0 { - adjustExpiresBy := defaultAdjustExpiresBy - if cs, ok := p.provider.(AdjustExpiresByCredentialsCacheStrategy); ok { - adjustExpiresBy = cs.AdjustExpiresBy - } - - randFloat64, err := sdkrand.CryptoRandFloat64() - if err != nil { - return Credentials{}, fmt.Errorf("failed to get random provider, %w", err) - } - - var jitter time.Duration - if p.options.ExpiryWindowJitterFrac > 0 { - jitter = time.Duration(randFloat64 * - p.options.ExpiryWindowJitterFrac * float64(p.options.ExpiryWindow)) - } - - newCreds, err = adjustExpiresBy(newCreds, -(p.options.ExpiryWindow - jitter)) - if err != nil { - return Credentials{}, fmt.Errorf("failed to adjust credentials expires, %w", err) - } - } - - p.creds.Store(&newCreds) - return newCreds, nil -} - -// getCreds returns the currently stored credentials and true. Returning false -// if no credentials were stored. -func (p *CredentialsCache) getCreds() (Credentials, bool) { - v := p.creds.Load() - if v == nil { - return Credentials{}, false - } - - c := v.(*Credentials) - if c == nil || !c.HasKeys() { - return Credentials{}, false - } - - return *c, true -} - -// Invalidate will invalidate the cached credentials. The next call to Retrieve -// will cause the provider's Retrieve method to be called. -func (p *CredentialsCache) Invalidate() { - p.creds.Store((*Credentials)(nil)) -} - -// IsCredentialsProvider returns whether credential provider wrapped by CredentialsCache -// matches the target provider type. -func (p *CredentialsCache) IsCredentialsProvider(target CredentialsProvider) bool { - return IsCredentialsProvider(p.provider, target) -} - -// HandleFailRefreshCredentialsCacheStrategy is an interface for -// CredentialsCache to allow CredentialsProvider how failed to refresh -// credentials is handled. -type HandleFailRefreshCredentialsCacheStrategy interface { - // Given the previously cached Credentials, if any, and refresh error, may - // returns new or modified set of Credentials, or error. - // - // Credential caches may use default implementation if nil. - HandleFailToRefresh(context.Context, Credentials, error) (Credentials, error) -} - -// defaultHandleFailToRefresh returns the passed in error. -func defaultHandleFailToRefresh(ctx context.Context, _ Credentials, err error) (Credentials, error) { - return Credentials{}, err -} - -// AdjustExpiresByCredentialsCacheStrategy is an interface for CredentialCache -// to allow CredentialsProvider to intercept adjustments to Credentials expiry -// based on expectations and use cases of CredentialsProvider. -// -// Credential caches may use default implementation if nil. -type AdjustExpiresByCredentialsCacheStrategy interface { - // Given a Credentials as input, applying any mutations and - // returning the potentially updated Credentials, or error. - AdjustExpiresBy(Credentials, time.Duration) (Credentials, error) -} - -// defaultAdjustExpiresBy adds the duration to the passed in credentials Expires, -// and returns the updated credentials value. If Credentials value's CanExpire -// is false, the passed in credentials are returned unchanged. -func defaultAdjustExpiresBy(creds Credentials, dur time.Duration) (Credentials, error) { - if !creds.CanExpire { - return creds, nil - } - - creds.Expires = creds.Expires.Add(dur) - return creds, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/credentials.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/credentials.go deleted file mode 100644 index 714d4ad85..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/credentials.go +++ /dev/null @@ -1,170 +0,0 @@ -package aws - -import ( - "context" - "fmt" - "reflect" - "time" - - "github.com/aws/aws-sdk-go-v2/internal/sdk" -) - -// AnonymousCredentials provides a sentinel CredentialsProvider that should be -// used to instruct the SDK's signing middleware to not sign the request. -// -// Using `nil` credentials when configuring an API client will achieve the same -// result. The AnonymousCredentials type allows you to configure the SDK's -// external config loading to not attempt to source credentials from the shared -// config or environment. -// -// For example you can use this CredentialsProvider with an API client's -// Options to instruct the client not to sign a request for accessing public -// S3 bucket objects. -// -// The following example demonstrates using the AnonymousCredentials to prevent -// SDK's external config loading attempt to resolve credentials. -// -// cfg, err := config.LoadDefaultConfig(context.TODO(), -// config.WithCredentialsProvider(aws.AnonymousCredentials{}), -// ) -// if err != nil { -// log.Fatalf("failed to load config, %v", err) -// } -// -// client := s3.NewFromConfig(cfg) -// -// Alternatively you can leave the API client Option's `Credential` member to -// nil. If using the `NewFromConfig` constructor you'll need to explicitly set -// the `Credentials` member to nil, if the external config resolved a -// credential provider. -// -// client := s3.New(s3.Options{ -// // Credentials defaults to a nil value. -// }) -// -// This can also be configured for specific operations calls too. -// -// cfg, err := config.LoadDefaultConfig(context.TODO()) -// if err != nil { -// log.Fatalf("failed to load config, %v", err) -// } -// -// client := s3.NewFromConfig(config) -// -// result, err := client.GetObject(context.TODO(), s3.GetObject{ -// Bucket: aws.String("example-bucket"), -// Key: aws.String("example-key"), -// }, func(o *s3.Options) { -// o.Credentials = nil -// // Or -// o.Credentials = aws.AnonymousCredentials{} -// }) -type AnonymousCredentials struct{} - -// Retrieve implements the CredentialsProvider interface, but will always -// return error, and cannot be used to sign a request. The AnonymousCredentials -// type is used as a sentinel type instructing the AWS request signing -// middleware to not sign a request. -func (AnonymousCredentials) Retrieve(context.Context) (Credentials, error) { - return Credentials{Source: "AnonymousCredentials"}, - fmt.Errorf("the AnonymousCredentials is not a valid credential provider, and cannot be used to sign AWS requests with") -} - -// A Credentials is the AWS credentials value for individual credential fields. -type Credentials struct { - // AWS Access key ID - AccessKeyID string - - // AWS Secret Access Key - SecretAccessKey string - - // AWS Session Token - SessionToken string - - // Source of the credentials - Source string - - // States if the credentials can expire or not. - CanExpire bool - - // The time the credentials will expire at. Should be ignored if CanExpire - // is false. - Expires time.Time -} - -// Expired returns if the credentials have expired. -func (v Credentials) Expired() bool { - if v.CanExpire { - // Calling Round(0) on the current time will truncate the monotonic - // reading only. Ensures credential expiry time is always based on - // reported wall-clock time. - return !v.Expires.After(sdk.NowTime().Round(0)) - } - - return false -} - -// HasKeys returns if the credentials keys are set. -func (v Credentials) HasKeys() bool { - return len(v.AccessKeyID) > 0 && len(v.SecretAccessKey) > 0 -} - -// A CredentialsProvider is the interface for any component which will provide -// credentials Credentials. A CredentialsProvider is required to manage its own -// Expired state, and what to be expired means. -// -// A credentials provider implementation can be wrapped with a CredentialCache -// to cache the credential value retrieved. Without the cache the SDK will -// attempt to retrieve the credentials for every request. -type CredentialsProvider interface { - // Retrieve returns nil if it successfully retrieved the value. - // Error is returned if the value were not obtainable, or empty. - Retrieve(ctx context.Context) (Credentials, error) -} - -// CredentialsProviderFunc provides a helper wrapping a function value to -// satisfy the CredentialsProvider interface. -type CredentialsProviderFunc func(context.Context) (Credentials, error) - -// Retrieve delegates to the function value the CredentialsProviderFunc wraps. -func (fn CredentialsProviderFunc) Retrieve(ctx context.Context) (Credentials, error) { - return fn(ctx) -} - -type isCredentialsProvider interface { - IsCredentialsProvider(CredentialsProvider) bool -} - -// IsCredentialsProvider returns whether the target CredentialProvider is the same type as provider when comparing the -// implementation type. -// -// If provider has a method IsCredentialsProvider(CredentialsProvider) bool it will be responsible for validating -// whether target matches the credential provider type. -// -// When comparing the CredentialProvider implementations provider and target for equality, the following rules are used: -// -// If provider is of type T and target is of type V, true if type *T is the same as type *V, otherwise false -// If provider is of type *T and target is of type V, true if type *T is the same as type *V, otherwise false -// If provider is of type T and target is of type *V, true if type *T is the same as type *V, otherwise false -// If provider is of type *T and target is of type *V,true if type *T is the same as type *V, otherwise false -func IsCredentialsProvider(provider, target CredentialsProvider) bool { - if target == nil || provider == nil { - return provider == target - } - - if x, ok := provider.(isCredentialsProvider); ok { - return x.IsCredentialsProvider(target) - } - - targetType := reflect.TypeOf(target) - if targetType.Kind() != reflect.Ptr { - targetType = reflect.PtrTo(targetType) - } - - providerType := reflect.TypeOf(provider) - if providerType.Kind() != reflect.Ptr { - providerType = reflect.PtrTo(providerType) - } - - return targetType.AssignableTo(providerType) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/defaults/auto.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/defaults/auto.go deleted file mode 100644 index fd408e518..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/defaults/auto.go +++ /dev/null @@ -1,38 +0,0 @@ -package defaults - -import ( - "github.com/aws/aws-sdk-go-v2/aws" - "runtime" - "strings" -) - -var getGOOS = func() string { - return runtime.GOOS -} - -// ResolveDefaultsModeAuto is used to determine the effective aws.DefaultsMode when the mode -// is set to aws.DefaultsModeAuto. -func ResolveDefaultsModeAuto(region string, environment aws.RuntimeEnvironment) aws.DefaultsMode { - goos := getGOOS() - if goos == "android" || goos == "ios" { - return aws.DefaultsModeMobile - } - - var currentRegion string - if len(environment.EnvironmentIdentifier) > 0 { - currentRegion = environment.Region - } - - if len(currentRegion) == 0 && len(environment.EC2InstanceMetadataRegion) > 0 { - currentRegion = environment.EC2InstanceMetadataRegion - } - - if len(region) > 0 && len(currentRegion) > 0 { - if strings.EqualFold(region, currentRegion) { - return aws.DefaultsModeInRegion - } - return aws.DefaultsModeCrossRegion - } - - return aws.DefaultsModeStandard -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/defaults/configuration.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/defaults/configuration.go deleted file mode 100644 index 8b7e01fa2..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/defaults/configuration.go +++ /dev/null @@ -1,43 +0,0 @@ -package defaults - -import ( - "time" - - "github.com/aws/aws-sdk-go-v2/aws" -) - -// Configuration is the set of SDK configuration options that are determined based -// on the configured DefaultsMode. -type Configuration struct { - // RetryMode is the configuration's default retry mode API clients should - // use for constructing a Retryer. - RetryMode aws.RetryMode - - // ConnectTimeout is the maximum amount of time a dial will wait for - // a connect to complete. - // - // See https://pkg.go.dev/net#Dialer.Timeout - ConnectTimeout *time.Duration - - // TLSNegotiationTimeout specifies the maximum amount of time waiting to - // wait for a TLS handshake. - // - // See https://pkg.go.dev/net/http#Transport.TLSHandshakeTimeout - TLSNegotiationTimeout *time.Duration -} - -// GetConnectTimeout returns the ConnectTimeout value, returns false if the value is not set. -func (c *Configuration) GetConnectTimeout() (time.Duration, bool) { - if c.ConnectTimeout == nil { - return 0, false - } - return *c.ConnectTimeout, true -} - -// GetTLSNegotiationTimeout returns the TLSNegotiationTimeout value, returns false if the value is not set. -func (c *Configuration) GetTLSNegotiationTimeout() (time.Duration, bool) { - if c.TLSNegotiationTimeout == nil { - return 0, false - } - return *c.TLSNegotiationTimeout, true -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/defaults/defaults.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/defaults/defaults.go deleted file mode 100644 index dbaa873dc..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/defaults/defaults.go +++ /dev/null @@ -1,50 +0,0 @@ -// Code generated by github.com/aws/aws-sdk-go-v2/internal/codegen/cmd/defaultsconfig. DO NOT EDIT. - -package defaults - -import ( - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - "time" -) - -// GetModeConfiguration returns the default Configuration descriptor for the given mode. -// -// Supports the following modes: cross-region, in-region, mobile, standard -func GetModeConfiguration(mode aws.DefaultsMode) (Configuration, error) { - var mv aws.DefaultsMode - mv.SetFromString(string(mode)) - - switch mv { - case aws.DefaultsModeCrossRegion: - settings := Configuration{ - ConnectTimeout: aws.Duration(3100 * time.Millisecond), - RetryMode: aws.RetryMode("standard"), - TLSNegotiationTimeout: aws.Duration(3100 * time.Millisecond), - } - return settings, nil - case aws.DefaultsModeInRegion: - settings := Configuration{ - ConnectTimeout: aws.Duration(1100 * time.Millisecond), - RetryMode: aws.RetryMode("standard"), - TLSNegotiationTimeout: aws.Duration(1100 * time.Millisecond), - } - return settings, nil - case aws.DefaultsModeMobile: - settings := Configuration{ - ConnectTimeout: aws.Duration(30000 * time.Millisecond), - RetryMode: aws.RetryMode("standard"), - TLSNegotiationTimeout: aws.Duration(30000 * time.Millisecond), - } - return settings, nil - case aws.DefaultsModeStandard: - settings := Configuration{ - ConnectTimeout: aws.Duration(3100 * time.Millisecond), - RetryMode: aws.RetryMode("standard"), - TLSNegotiationTimeout: aws.Duration(3100 * time.Millisecond), - } - return settings, nil - default: - return Configuration{}, fmt.Errorf("unsupported defaults mode: %v", mode) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/defaults/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/defaults/doc.go deleted file mode 100644 index 2d90011b4..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/defaults/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package defaults provides recommended configuration values for AWS SDKs and CLIs. -package defaults diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/defaultsmode.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/defaultsmode.go deleted file mode 100644 index fcf9387c2..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/defaultsmode.go +++ /dev/null @@ -1,95 +0,0 @@ -// Code generated by github.com/aws/aws-sdk-go-v2/internal/codegen/cmd/defaultsmode. DO NOT EDIT. - -package aws - -import ( - "strings" -) - -// DefaultsMode is the SDK defaults mode setting. -type DefaultsMode string - -// The DefaultsMode constants. -const ( - // DefaultsModeAuto is an experimental mode that builds on the standard mode. - // The SDK will attempt to discover the execution environment to determine the - // appropriate settings automatically. - // - // Note that the auto detection is heuristics-based and does not guarantee 100% - // accuracy. STANDARD mode will be used if the execution environment cannot - // be determined. The auto detection might query EC2 Instance Metadata service - // (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html), - // which might introduce latency. Therefore we recommend choosing an explicit - // defaults_mode instead if startup latency is critical to your application - DefaultsModeAuto DefaultsMode = "auto" - - // DefaultsModeCrossRegion builds on the standard mode and includes optimization - // tailored for applications which call AWS services in a different region - // - // Note that the default values vended from this mode might change as best practices - // may evolve. As a result, it is encouraged to perform tests when upgrading - // the SDK - DefaultsModeCrossRegion DefaultsMode = "cross-region" - - // DefaultsModeInRegion builds on the standard mode and includes optimization - // tailored for applications which call AWS services from within the same AWS - // region - // - // Note that the default values vended from this mode might change as best practices - // may evolve. As a result, it is encouraged to perform tests when upgrading - // the SDK - DefaultsModeInRegion DefaultsMode = "in-region" - - // DefaultsModeLegacy provides default settings that vary per SDK and were used - // prior to establishment of defaults_mode - DefaultsModeLegacy DefaultsMode = "legacy" - - // DefaultsModeMobile builds on the standard mode and includes optimization - // tailored for mobile applications - // - // Note that the default values vended from this mode might change as best practices - // may evolve. As a result, it is encouraged to perform tests when upgrading - // the SDK - DefaultsModeMobile DefaultsMode = "mobile" - - // DefaultsModeStandard provides the latest recommended default values that - // should be safe to run in most scenarios - // - // Note that the default values vended from this mode might change as best practices - // may evolve. As a result, it is encouraged to perform tests when upgrading - // the SDK - DefaultsModeStandard DefaultsMode = "standard" -) - -// SetFromString sets the DefaultsMode value to one of the pre-defined constants that matches -// the provided string when compared using EqualFold. If the value does not match a known -// constant it will be set to as-is and the function will return false. As a special case, if the -// provided value is a zero-length string, the mode will be set to LegacyDefaultsMode. -func (d *DefaultsMode) SetFromString(v string) (ok bool) { - switch { - case strings.EqualFold(v, string(DefaultsModeAuto)): - *d = DefaultsModeAuto - ok = true - case strings.EqualFold(v, string(DefaultsModeCrossRegion)): - *d = DefaultsModeCrossRegion - ok = true - case strings.EqualFold(v, string(DefaultsModeInRegion)): - *d = DefaultsModeInRegion - ok = true - case strings.EqualFold(v, string(DefaultsModeLegacy)): - *d = DefaultsModeLegacy - ok = true - case strings.EqualFold(v, string(DefaultsModeMobile)): - *d = DefaultsModeMobile - ok = true - case strings.EqualFold(v, string(DefaultsModeStandard)): - *d = DefaultsModeStandard - ok = true - case len(v) == 0: - *d = DefaultsModeLegacy - ok = true - default: - *d = DefaultsMode(v) - } - return ok -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/doc.go deleted file mode 100644 index d8b6e09e5..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/doc.go +++ /dev/null @@ -1,62 +0,0 @@ -// Package aws provides the core SDK's utilities and shared types. Use this package's -// utilities to simplify setting and reading API operations parameters. -// -// # Value and Pointer Conversion Utilities -// -// This package includes a helper conversion utility for each scalar type the SDK's -// API use. These utilities make getting a pointer of the scalar, and dereferencing -// a pointer easier. -// -// Each conversion utility comes in two forms. Value to Pointer and Pointer to Value. -// The Pointer to value will safely dereference the pointer and return its value. -// If the pointer was nil, the scalar's zero value will be returned. -// -// The value to pointer functions will be named after the scalar type. So get a -// *string from a string value use the "String" function. This makes it easy to -// to get pointer of a literal string value, because getting the address of a -// literal requires assigning the value to a variable first. -// -// var strPtr *string -// -// // Without the SDK's conversion functions -// str := "my string" -// strPtr = &str -// -// // With the SDK's conversion functions -// strPtr = aws.String("my string") -// -// // Convert *string to string value -// str = aws.ToString(strPtr) -// -// In addition to scalars the aws package also includes conversion utilities for -// map and slice for commonly types used in API parameters. The map and slice -// conversion functions use similar naming pattern as the scalar conversion -// functions. -// -// var strPtrs []*string -// var strs []string = []string{"Go", "Gophers", "Go"} -// -// // Convert []string to []*string -// strPtrs = aws.StringSlice(strs) -// -// // Convert []*string to []string -// strs = aws.ToStringSlice(strPtrs) -// -// # SDK Default HTTP Client -// -// The SDK will use the http.DefaultClient if a HTTP client is not provided to -// the SDK's Session, or service client constructor. This means that if the -// http.DefaultClient is modified by other components of your application the -// modifications will be picked up by the SDK as well. -// -// In some cases this might be intended, but it is a better practice to create -// a custom HTTP Client to share explicitly through your application. You can -// configure the SDK to use the custom HTTP Client by setting the HTTPClient -// value of the SDK's Config type when creating a Session or service client. -package aws - -// generate.go uses a build tag of "ignore", go run doesn't need to specify -// this because go run ignores all build flags when running a go file directly. -//go:generate go run -tags codegen generate.go -//go:generate go run -tags codegen logging_generate.go -//go:generate gofmt -w -s . diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/endpoints.go deleted file mode 100644 index aa10a9b40..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/endpoints.go +++ /dev/null @@ -1,229 +0,0 @@ -package aws - -import ( - "fmt" -) - -// DualStackEndpointState is a constant to describe the dual-stack endpoint resolution behavior. -type DualStackEndpointState uint - -const ( - // DualStackEndpointStateUnset is the default value behavior for dual-stack endpoint resolution. - DualStackEndpointStateUnset DualStackEndpointState = iota - - // DualStackEndpointStateEnabled enables dual-stack endpoint resolution for service endpoints. - DualStackEndpointStateEnabled - - // DualStackEndpointStateDisabled disables dual-stack endpoint resolution for endpoints. - DualStackEndpointStateDisabled -) - -// GetUseDualStackEndpoint takes a service's EndpointResolverOptions and returns the UseDualStackEndpoint value. -// Returns boolean false if the provided options does not have a method to retrieve the DualStackEndpointState. -func GetUseDualStackEndpoint(options ...interface{}) (value DualStackEndpointState, found bool) { - type iface interface { - GetUseDualStackEndpoint() DualStackEndpointState - } - for _, option := range options { - if i, ok := option.(iface); ok { - value = i.GetUseDualStackEndpoint() - found = true - break - } - } - return value, found -} - -// FIPSEndpointState is a constant to describe the FIPS endpoint resolution behavior. -type FIPSEndpointState uint - -const ( - // FIPSEndpointStateUnset is the default value behavior for FIPS endpoint resolution. - FIPSEndpointStateUnset FIPSEndpointState = iota - - // FIPSEndpointStateEnabled enables FIPS endpoint resolution for service endpoints. - FIPSEndpointStateEnabled - - // FIPSEndpointStateDisabled disables FIPS endpoint resolution for endpoints. - FIPSEndpointStateDisabled -) - -// GetUseFIPSEndpoint takes a service's EndpointResolverOptions and returns the UseDualStackEndpoint value. -// Returns boolean false if the provided options does not have a method to retrieve the DualStackEndpointState. -func GetUseFIPSEndpoint(options ...interface{}) (value FIPSEndpointState, found bool) { - type iface interface { - GetUseFIPSEndpoint() FIPSEndpointState - } - for _, option := range options { - if i, ok := option.(iface); ok { - value = i.GetUseFIPSEndpoint() - found = true - break - } - } - return value, found -} - -// Endpoint represents the endpoint a service client should make API operation -// calls to. -// -// The SDK will automatically resolve these endpoints per API client using an -// internal endpoint resolvers. If you'd like to provide custom endpoint -// resolving behavior you can implement the EndpointResolver interface. -type Endpoint struct { - // The base URL endpoint the SDK API clients will use to make API calls to. - // The SDK will suffix URI path and query elements to this endpoint. - URL string - - // Specifies if the endpoint's hostname can be modified by the SDK's API - // client. - // - // If the hostname is mutable the SDK API clients may modify any part of - // the hostname based on the requirements of the API, (e.g. adding, or - // removing content in the hostname). Such as, Amazon S3 API client - // prefixing "bucketname" to the hostname, or changing the - // hostname service name component from "s3." to "s3-accesspoint.dualstack." - // for the dualstack endpoint of an S3 Accesspoint resource. - // - // Care should be taken when providing a custom endpoint for an API. If the - // endpoint hostname is mutable, and the client cannot modify the endpoint - // correctly, the operation call will most likely fail, or have undefined - // behavior. - // - // If hostname is immutable, the SDK API clients will not modify the - // hostname of the URL. This may cause the API client not to function - // correctly if the API requires the operation specific hostname values - // to be used by the client. - // - // This flag does not modify the API client's behavior if this endpoint - // will be used instead of Endpoint Discovery, or if the endpoint will be - // used to perform Endpoint Discovery. That behavior is configured via the - // API Client's Options. - HostnameImmutable bool - - // The AWS partition the endpoint belongs to. - PartitionID string - - // The service name that should be used for signing the requests to the - // endpoint. - SigningName string - - // The region that should be used for signing the request to the endpoint. - SigningRegion string - - // The signing method that should be used for signing the requests to the - // endpoint. - SigningMethod string - - // The source of the Endpoint. By default, this will be EndpointSourceServiceMetadata. - // When providing a custom endpoint, you should set the source as EndpointSourceCustom. - // If source is not provided when providing a custom endpoint, the SDK may not - // perform required host mutations correctly. Source should be used along with - // HostnameImmutable property as per the usage requirement. - Source EndpointSource -} - -// EndpointSource is the endpoint source type. -type EndpointSource int - -const ( - // EndpointSourceServiceMetadata denotes service modeled endpoint metadata is used as Endpoint Source. - EndpointSourceServiceMetadata EndpointSource = iota - - // EndpointSourceCustom denotes endpoint is a custom endpoint. This source should be used when - // user provides a custom endpoint to be used by the SDK. - EndpointSourceCustom -) - -// EndpointNotFoundError is a sentinel error to indicate that the -// EndpointResolver implementation was unable to resolve an endpoint for the -// given service and region. Resolvers should use this to indicate that an API -// client should fallback and attempt to use it's internal default resolver to -// resolve the endpoint. -type EndpointNotFoundError struct { - Err error -} - -// Error is the error message. -func (e *EndpointNotFoundError) Error() string { - return fmt.Sprintf("endpoint not found, %v", e.Err) -} - -// Unwrap returns the underlying error. -func (e *EndpointNotFoundError) Unwrap() error { - return e.Err -} - -// EndpointResolver is an endpoint resolver that can be used to provide or -// override an endpoint for the given service and region. API clients will -// attempt to use the EndpointResolver first to resolve an endpoint if -// available. If the EndpointResolver returns an EndpointNotFoundError error, -// API clients will fallback to attempting to resolve the endpoint using its -// internal default endpoint resolver. -// -// Deprecated: See EndpointResolverWithOptions -type EndpointResolver interface { - ResolveEndpoint(service, region string) (Endpoint, error) -} - -// EndpointResolverFunc wraps a function to satisfy the EndpointResolver interface. -// -// Deprecated: See EndpointResolverWithOptionsFunc -type EndpointResolverFunc func(service, region string) (Endpoint, error) - -// ResolveEndpoint calls the wrapped function and returns the results. -// -// Deprecated: See EndpointResolverWithOptions.ResolveEndpoint -func (e EndpointResolverFunc) ResolveEndpoint(service, region string) (Endpoint, error) { - return e(service, region) -} - -// EndpointResolverWithOptions is an endpoint resolver that can be used to provide or -// override an endpoint for the given service, region, and the service client's EndpointOptions. API clients will -// attempt to use the EndpointResolverWithOptions first to resolve an endpoint if -// available. If the EndpointResolverWithOptions returns an EndpointNotFoundError error, -// API clients will fallback to attempting to resolve the endpoint using its -// internal default endpoint resolver. -type EndpointResolverWithOptions interface { - ResolveEndpoint(service, region string, options ...interface{}) (Endpoint, error) -} - -// EndpointResolverWithOptionsFunc wraps a function to satisfy the EndpointResolverWithOptions interface. -type EndpointResolverWithOptionsFunc func(service, region string, options ...interface{}) (Endpoint, error) - -// ResolveEndpoint calls the wrapped function and returns the results. -func (e EndpointResolverWithOptionsFunc) ResolveEndpoint(service, region string, options ...interface{}) (Endpoint, error) { - return e(service, region, options...) -} - -// GetDisableHTTPS takes a service's EndpointResolverOptions and returns the DisableHTTPS value. -// Returns boolean false if the provided options does not have a method to retrieve the DisableHTTPS. -func GetDisableHTTPS(options ...interface{}) (value bool, found bool) { - type iface interface { - GetDisableHTTPS() bool - } - for _, option := range options { - if i, ok := option.(iface); ok { - value = i.GetDisableHTTPS() - found = true - break - } - } - return value, found -} - -// GetResolvedRegion takes a service's EndpointResolverOptions and returns the ResolvedRegion value. -// Returns boolean false if the provided options does not have a method to retrieve the ResolvedRegion. -func GetResolvedRegion(options ...interface{}) (value string, found bool) { - type iface interface { - GetResolvedRegion() string - } - for _, option := range options { - if i, ok := option.(iface); ok { - value = i.GetResolvedRegion() - found = true - break - } - } - return value, found -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/errors.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/errors.go deleted file mode 100644 index f390a08f9..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/errors.go +++ /dev/null @@ -1,9 +0,0 @@ -package aws - -// MissingRegionError is an error that is returned if region configuration -// value was not found. -type MissingRegionError struct{} - -func (*MissingRegionError) Error() string { - return "an AWS region is required, but was not found" -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/from_ptr.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/from_ptr.go deleted file mode 100644 index 2394418e9..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/from_ptr.go +++ /dev/null @@ -1,365 +0,0 @@ -// Code generated by aws/generate.go DO NOT EDIT. - -package aws - -import ( - "github.com/aws/smithy-go/ptr" - "time" -) - -// ToBool returns bool value dereferenced if the passed -// in pointer was not nil. Returns a bool zero value if the -// pointer was nil. -func ToBool(p *bool) (v bool) { - return ptr.ToBool(p) -} - -// ToBoolSlice returns a slice of bool values, that are -// dereferenced if the passed in pointer was not nil. Returns a bool -// zero value if the pointer was nil. -func ToBoolSlice(vs []*bool) []bool { - return ptr.ToBoolSlice(vs) -} - -// ToBoolMap returns a map of bool values, that are -// dereferenced if the passed in pointer was not nil. The bool -// zero value is used if the pointer was nil. -func ToBoolMap(vs map[string]*bool) map[string]bool { - return ptr.ToBoolMap(vs) -} - -// ToByte returns byte value dereferenced if the passed -// in pointer was not nil. Returns a byte zero value if the -// pointer was nil. -func ToByte(p *byte) (v byte) { - return ptr.ToByte(p) -} - -// ToByteSlice returns a slice of byte values, that are -// dereferenced if the passed in pointer was not nil. Returns a byte -// zero value if the pointer was nil. -func ToByteSlice(vs []*byte) []byte { - return ptr.ToByteSlice(vs) -} - -// ToByteMap returns a map of byte values, that are -// dereferenced if the passed in pointer was not nil. The byte -// zero value is used if the pointer was nil. -func ToByteMap(vs map[string]*byte) map[string]byte { - return ptr.ToByteMap(vs) -} - -// ToString returns string value dereferenced if the passed -// in pointer was not nil. Returns a string zero value if the -// pointer was nil. -func ToString(p *string) (v string) { - return ptr.ToString(p) -} - -// ToStringSlice returns a slice of string values, that are -// dereferenced if the passed in pointer was not nil. Returns a string -// zero value if the pointer was nil. -func ToStringSlice(vs []*string) []string { - return ptr.ToStringSlice(vs) -} - -// ToStringMap returns a map of string values, that are -// dereferenced if the passed in pointer was not nil. The string -// zero value is used if the pointer was nil. -func ToStringMap(vs map[string]*string) map[string]string { - return ptr.ToStringMap(vs) -} - -// ToInt returns int value dereferenced if the passed -// in pointer was not nil. Returns a int zero value if the -// pointer was nil. -func ToInt(p *int) (v int) { - return ptr.ToInt(p) -} - -// ToIntSlice returns a slice of int values, that are -// dereferenced if the passed in pointer was not nil. Returns a int -// zero value if the pointer was nil. -func ToIntSlice(vs []*int) []int { - return ptr.ToIntSlice(vs) -} - -// ToIntMap returns a map of int values, that are -// dereferenced if the passed in pointer was not nil. The int -// zero value is used if the pointer was nil. -func ToIntMap(vs map[string]*int) map[string]int { - return ptr.ToIntMap(vs) -} - -// ToInt8 returns int8 value dereferenced if the passed -// in pointer was not nil. Returns a int8 zero value if the -// pointer was nil. -func ToInt8(p *int8) (v int8) { - return ptr.ToInt8(p) -} - -// ToInt8Slice returns a slice of int8 values, that are -// dereferenced if the passed in pointer was not nil. Returns a int8 -// zero value if the pointer was nil. -func ToInt8Slice(vs []*int8) []int8 { - return ptr.ToInt8Slice(vs) -} - -// ToInt8Map returns a map of int8 values, that are -// dereferenced if the passed in pointer was not nil. The int8 -// zero value is used if the pointer was nil. -func ToInt8Map(vs map[string]*int8) map[string]int8 { - return ptr.ToInt8Map(vs) -} - -// ToInt16 returns int16 value dereferenced if the passed -// in pointer was not nil. Returns a int16 zero value if the -// pointer was nil. -func ToInt16(p *int16) (v int16) { - return ptr.ToInt16(p) -} - -// ToInt16Slice returns a slice of int16 values, that are -// dereferenced if the passed in pointer was not nil. Returns a int16 -// zero value if the pointer was nil. -func ToInt16Slice(vs []*int16) []int16 { - return ptr.ToInt16Slice(vs) -} - -// ToInt16Map returns a map of int16 values, that are -// dereferenced if the passed in pointer was not nil. The int16 -// zero value is used if the pointer was nil. -func ToInt16Map(vs map[string]*int16) map[string]int16 { - return ptr.ToInt16Map(vs) -} - -// ToInt32 returns int32 value dereferenced if the passed -// in pointer was not nil. Returns a int32 zero value if the -// pointer was nil. -func ToInt32(p *int32) (v int32) { - return ptr.ToInt32(p) -} - -// ToInt32Slice returns a slice of int32 values, that are -// dereferenced if the passed in pointer was not nil. Returns a int32 -// zero value if the pointer was nil. -func ToInt32Slice(vs []*int32) []int32 { - return ptr.ToInt32Slice(vs) -} - -// ToInt32Map returns a map of int32 values, that are -// dereferenced if the passed in pointer was not nil. The int32 -// zero value is used if the pointer was nil. -func ToInt32Map(vs map[string]*int32) map[string]int32 { - return ptr.ToInt32Map(vs) -} - -// ToInt64 returns int64 value dereferenced if the passed -// in pointer was not nil. Returns a int64 zero value if the -// pointer was nil. -func ToInt64(p *int64) (v int64) { - return ptr.ToInt64(p) -} - -// ToInt64Slice returns a slice of int64 values, that are -// dereferenced if the passed in pointer was not nil. Returns a int64 -// zero value if the pointer was nil. -func ToInt64Slice(vs []*int64) []int64 { - return ptr.ToInt64Slice(vs) -} - -// ToInt64Map returns a map of int64 values, that are -// dereferenced if the passed in pointer was not nil. The int64 -// zero value is used if the pointer was nil. -func ToInt64Map(vs map[string]*int64) map[string]int64 { - return ptr.ToInt64Map(vs) -} - -// ToUint returns uint value dereferenced if the passed -// in pointer was not nil. Returns a uint zero value if the -// pointer was nil. -func ToUint(p *uint) (v uint) { - return ptr.ToUint(p) -} - -// ToUintSlice returns a slice of uint values, that are -// dereferenced if the passed in pointer was not nil. Returns a uint -// zero value if the pointer was nil. -func ToUintSlice(vs []*uint) []uint { - return ptr.ToUintSlice(vs) -} - -// ToUintMap returns a map of uint values, that are -// dereferenced if the passed in pointer was not nil. The uint -// zero value is used if the pointer was nil. -func ToUintMap(vs map[string]*uint) map[string]uint { - return ptr.ToUintMap(vs) -} - -// ToUint8 returns uint8 value dereferenced if the passed -// in pointer was not nil. Returns a uint8 zero value if the -// pointer was nil. -func ToUint8(p *uint8) (v uint8) { - return ptr.ToUint8(p) -} - -// ToUint8Slice returns a slice of uint8 values, that are -// dereferenced if the passed in pointer was not nil. Returns a uint8 -// zero value if the pointer was nil. -func ToUint8Slice(vs []*uint8) []uint8 { - return ptr.ToUint8Slice(vs) -} - -// ToUint8Map returns a map of uint8 values, that are -// dereferenced if the passed in pointer was not nil. The uint8 -// zero value is used if the pointer was nil. -func ToUint8Map(vs map[string]*uint8) map[string]uint8 { - return ptr.ToUint8Map(vs) -} - -// ToUint16 returns uint16 value dereferenced if the passed -// in pointer was not nil. Returns a uint16 zero value if the -// pointer was nil. -func ToUint16(p *uint16) (v uint16) { - return ptr.ToUint16(p) -} - -// ToUint16Slice returns a slice of uint16 values, that are -// dereferenced if the passed in pointer was not nil. Returns a uint16 -// zero value if the pointer was nil. -func ToUint16Slice(vs []*uint16) []uint16 { - return ptr.ToUint16Slice(vs) -} - -// ToUint16Map returns a map of uint16 values, that are -// dereferenced if the passed in pointer was not nil. The uint16 -// zero value is used if the pointer was nil. -func ToUint16Map(vs map[string]*uint16) map[string]uint16 { - return ptr.ToUint16Map(vs) -} - -// ToUint32 returns uint32 value dereferenced if the passed -// in pointer was not nil. Returns a uint32 zero value if the -// pointer was nil. -func ToUint32(p *uint32) (v uint32) { - return ptr.ToUint32(p) -} - -// ToUint32Slice returns a slice of uint32 values, that are -// dereferenced if the passed in pointer was not nil. Returns a uint32 -// zero value if the pointer was nil. -func ToUint32Slice(vs []*uint32) []uint32 { - return ptr.ToUint32Slice(vs) -} - -// ToUint32Map returns a map of uint32 values, that are -// dereferenced if the passed in pointer was not nil. The uint32 -// zero value is used if the pointer was nil. -func ToUint32Map(vs map[string]*uint32) map[string]uint32 { - return ptr.ToUint32Map(vs) -} - -// ToUint64 returns uint64 value dereferenced if the passed -// in pointer was not nil. Returns a uint64 zero value if the -// pointer was nil. -func ToUint64(p *uint64) (v uint64) { - return ptr.ToUint64(p) -} - -// ToUint64Slice returns a slice of uint64 values, that are -// dereferenced if the passed in pointer was not nil. Returns a uint64 -// zero value if the pointer was nil. -func ToUint64Slice(vs []*uint64) []uint64 { - return ptr.ToUint64Slice(vs) -} - -// ToUint64Map returns a map of uint64 values, that are -// dereferenced if the passed in pointer was not nil. The uint64 -// zero value is used if the pointer was nil. -func ToUint64Map(vs map[string]*uint64) map[string]uint64 { - return ptr.ToUint64Map(vs) -} - -// ToFloat32 returns float32 value dereferenced if the passed -// in pointer was not nil. Returns a float32 zero value if the -// pointer was nil. -func ToFloat32(p *float32) (v float32) { - return ptr.ToFloat32(p) -} - -// ToFloat32Slice returns a slice of float32 values, that are -// dereferenced if the passed in pointer was not nil. Returns a float32 -// zero value if the pointer was nil. -func ToFloat32Slice(vs []*float32) []float32 { - return ptr.ToFloat32Slice(vs) -} - -// ToFloat32Map returns a map of float32 values, that are -// dereferenced if the passed in pointer was not nil. The float32 -// zero value is used if the pointer was nil. -func ToFloat32Map(vs map[string]*float32) map[string]float32 { - return ptr.ToFloat32Map(vs) -} - -// ToFloat64 returns float64 value dereferenced if the passed -// in pointer was not nil. Returns a float64 zero value if the -// pointer was nil. -func ToFloat64(p *float64) (v float64) { - return ptr.ToFloat64(p) -} - -// ToFloat64Slice returns a slice of float64 values, that are -// dereferenced if the passed in pointer was not nil. Returns a float64 -// zero value if the pointer was nil. -func ToFloat64Slice(vs []*float64) []float64 { - return ptr.ToFloat64Slice(vs) -} - -// ToFloat64Map returns a map of float64 values, that are -// dereferenced if the passed in pointer was not nil. The float64 -// zero value is used if the pointer was nil. -func ToFloat64Map(vs map[string]*float64) map[string]float64 { - return ptr.ToFloat64Map(vs) -} - -// ToTime returns time.Time value dereferenced if the passed -// in pointer was not nil. Returns a time.Time zero value if the -// pointer was nil. -func ToTime(p *time.Time) (v time.Time) { - return ptr.ToTime(p) -} - -// ToTimeSlice returns a slice of time.Time values, that are -// dereferenced if the passed in pointer was not nil. Returns a time.Time -// zero value if the pointer was nil. -func ToTimeSlice(vs []*time.Time) []time.Time { - return ptr.ToTimeSlice(vs) -} - -// ToTimeMap returns a map of time.Time values, that are -// dereferenced if the passed in pointer was not nil. The time.Time -// zero value is used if the pointer was nil. -func ToTimeMap(vs map[string]*time.Time) map[string]time.Time { - return ptr.ToTimeMap(vs) -} - -// ToDuration returns time.Duration value dereferenced if the passed -// in pointer was not nil. Returns a time.Duration zero value if the -// pointer was nil. -func ToDuration(p *time.Duration) (v time.Duration) { - return ptr.ToDuration(p) -} - -// ToDurationSlice returns a slice of time.Duration values, that are -// dereferenced if the passed in pointer was not nil. Returns a time.Duration -// zero value if the pointer was nil. -func ToDurationSlice(vs []*time.Duration) []time.Duration { - return ptr.ToDurationSlice(vs) -} - -// ToDurationMap returns a map of time.Duration values, that are -// dereferenced if the passed in pointer was not nil. The time.Duration -// zero value is used if the pointer was nil. -func ToDurationMap(vs map[string]*time.Duration) map[string]time.Duration { - return ptr.ToDurationMap(vs) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/go_module_metadata.go deleted file mode 100644 index 8cd672b6f..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/go_module_metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. - -package aws - -// goModuleVersion is the tagged release for this module -const goModuleVersion = "1.21.0" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/logging.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/logging.go deleted file mode 100644 index 91c94d987..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/logging.go +++ /dev/null @@ -1,119 +0,0 @@ -// Code generated by aws/logging_generate.go DO NOT EDIT. - -package aws - -// ClientLogMode represents the logging mode of SDK clients. The client logging mode is a bit-field where -// each bit is a flag that describes the logging behavior for one or more client components. -// The entire 64-bit group is reserved for later expansion by the SDK. -// -// Example: Setting ClientLogMode to enable logging of retries and requests -// -// clientLogMode := aws.LogRetries | aws.LogRequest -// -// Example: Adding an additional log mode to an existing ClientLogMode value -// -// clientLogMode |= aws.LogResponse -type ClientLogMode uint64 - -// Supported ClientLogMode bits that can be configured to toggle logging of specific SDK events. -const ( - LogSigning ClientLogMode = 1 << (64 - 1 - iota) - LogRetries - LogRequest - LogRequestWithBody - LogResponse - LogResponseWithBody - LogDeprecatedUsage - LogRequestEventMessage - LogResponseEventMessage -) - -// IsSigning returns whether the Signing logging mode bit is set -func (m ClientLogMode) IsSigning() bool { - return m&LogSigning != 0 -} - -// IsRetries returns whether the Retries logging mode bit is set -func (m ClientLogMode) IsRetries() bool { - return m&LogRetries != 0 -} - -// IsRequest returns whether the Request logging mode bit is set -func (m ClientLogMode) IsRequest() bool { - return m&LogRequest != 0 -} - -// IsRequestWithBody returns whether the RequestWithBody logging mode bit is set -func (m ClientLogMode) IsRequestWithBody() bool { - return m&LogRequestWithBody != 0 -} - -// IsResponse returns whether the Response logging mode bit is set -func (m ClientLogMode) IsResponse() bool { - return m&LogResponse != 0 -} - -// IsResponseWithBody returns whether the ResponseWithBody logging mode bit is set -func (m ClientLogMode) IsResponseWithBody() bool { - return m&LogResponseWithBody != 0 -} - -// IsDeprecatedUsage returns whether the DeprecatedUsage logging mode bit is set -func (m ClientLogMode) IsDeprecatedUsage() bool { - return m&LogDeprecatedUsage != 0 -} - -// IsRequestEventMessage returns whether the RequestEventMessage logging mode bit is set -func (m ClientLogMode) IsRequestEventMessage() bool { - return m&LogRequestEventMessage != 0 -} - -// IsResponseEventMessage returns whether the ResponseEventMessage logging mode bit is set -func (m ClientLogMode) IsResponseEventMessage() bool { - return m&LogResponseEventMessage != 0 -} - -// ClearSigning clears the Signing logging mode bit -func (m *ClientLogMode) ClearSigning() { - *m &^= LogSigning -} - -// ClearRetries clears the Retries logging mode bit -func (m *ClientLogMode) ClearRetries() { - *m &^= LogRetries -} - -// ClearRequest clears the Request logging mode bit -func (m *ClientLogMode) ClearRequest() { - *m &^= LogRequest -} - -// ClearRequestWithBody clears the RequestWithBody logging mode bit -func (m *ClientLogMode) ClearRequestWithBody() { - *m &^= LogRequestWithBody -} - -// ClearResponse clears the Response logging mode bit -func (m *ClientLogMode) ClearResponse() { - *m &^= LogResponse -} - -// ClearResponseWithBody clears the ResponseWithBody logging mode bit -func (m *ClientLogMode) ClearResponseWithBody() { - *m &^= LogResponseWithBody -} - -// ClearDeprecatedUsage clears the DeprecatedUsage logging mode bit -func (m *ClientLogMode) ClearDeprecatedUsage() { - *m &^= LogDeprecatedUsage -} - -// ClearRequestEventMessage clears the RequestEventMessage logging mode bit -func (m *ClientLogMode) ClearRequestEventMessage() { - *m &^= LogRequestEventMessage -} - -// ClearResponseEventMessage clears the ResponseEventMessage logging mode bit -func (m *ClientLogMode) ClearResponseEventMessage() { - *m &^= LogResponseEventMessage -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/logging_generate.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/logging_generate.go deleted file mode 100644 index 6ecc2231a..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/logging_generate.go +++ /dev/null @@ -1,95 +0,0 @@ -//go:build clientlogmode -// +build clientlogmode - -package main - -import ( - "fmt" - "log" - "os" - "strings" - "text/template" -) - -var config = struct { - ModeBits []string -}{ - // Items should be appended only to keep bit-flag positions stable - ModeBits: []string{ - "Signing", - "Retries", - "Request", - "RequestWithBody", - "Response", - "ResponseWithBody", - "DeprecatedUsage", - "RequestEventMessage", - "ResponseEventMessage", - }, -} - -func bitName(name string) string { - return strings.ToUpper(name[:1]) + name[1:] -} - -var tmpl = template.Must(template.New("ClientLogMode").Funcs(map[string]interface{}{ - "symbolName": func(name string) string { - return "Log" + bitName(name) - }, - "bitName": bitName, -}).Parse(`// Code generated by aws/logging_generate.go DO NOT EDIT. - -package aws - -// ClientLogMode represents the logging mode of SDK clients. The client logging mode is a bit-field where -// each bit is a flag that describes the logging behavior for one or more client components. -// The entire 64-bit group is reserved for later expansion by the SDK. -// -// Example: Setting ClientLogMode to enable logging of retries and requests -// clientLogMode := aws.LogRetries | aws.LogRequest -// -// Example: Adding an additional log mode to an existing ClientLogMode value -// clientLogMode |= aws.LogResponse -type ClientLogMode uint64 - -// Supported ClientLogMode bits that can be configured to toggle logging of specific SDK events. -const ( -{{- range $index, $field := .ModeBits }} - {{ (symbolName $field) }}{{- if (eq 0 $index) }} ClientLogMode = 1 << (64 - 1 - iota){{- end }} -{{- end }} -) -{{ range $_, $field := .ModeBits }} -// Is{{- bitName $field }} returns whether the {{ bitName $field }} logging mode bit is set -func (m ClientLogMode) Is{{- bitName $field }}() bool { - return m&{{- (symbolName $field) }} != 0 -} -{{ end }} -{{- range $_, $field := .ModeBits }} -// Clear{{- bitName $field }} clears the {{ bitName $field }} logging mode bit -func (m *ClientLogMode) Clear{{- bitName $field }}() { - *m &^= {{ (symbolName $field) }} -} -{{ end -}} -`)) - -func main() { - uniqueBitFields := make(map[string]struct{}) - - for _, bitName := range config.ModeBits { - if _, ok := uniqueBitFields[strings.ToLower(bitName)]; ok { - panic(fmt.Sprintf("duplicate bit field: %s", bitName)) - } - uniqueBitFields[bitName] = struct{}{} - } - - file, err := os.Create("logging.go") - if err != nil { - log.Fatal(err) - } - defer file.Close() - - err = tmpl.Execute(file, config) - if err != nil { - log.Fatal(err) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/metadata.go deleted file mode 100644 index 2de15528c..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/metadata.go +++ /dev/null @@ -1,201 +0,0 @@ -package middleware - -import ( - "context" - - "github.com/aws/aws-sdk-go-v2/aws" - - "github.com/aws/smithy-go/middleware" -) - -// RegisterServiceMetadata registers metadata about the service and operation into the middleware context -// so that it is available at runtime for other middleware to introspect. -type RegisterServiceMetadata struct { - ServiceID string - SigningName string - Region string - OperationName string -} - -// ID returns the middleware identifier. -func (s *RegisterServiceMetadata) ID() string { - return "RegisterServiceMetadata" -} - -// HandleInitialize registers service metadata information into the middleware context, allowing for introspection. -func (s RegisterServiceMetadata) HandleInitialize( - ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler, -) (out middleware.InitializeOutput, metadata middleware.Metadata, err error) { - if len(s.ServiceID) > 0 { - ctx = SetServiceID(ctx, s.ServiceID) - } - if len(s.SigningName) > 0 { - ctx = SetSigningName(ctx, s.SigningName) - } - if len(s.Region) > 0 { - ctx = setRegion(ctx, s.Region) - } - if len(s.OperationName) > 0 { - ctx = setOperationName(ctx, s.OperationName) - } - return next.HandleInitialize(ctx, in) -} - -// service metadata keys for storing and lookup of runtime stack information. -type ( - serviceIDKey struct{} - signingNameKey struct{} - signingRegionKey struct{} - regionKey struct{} - operationNameKey struct{} - partitionIDKey struct{} - requiresLegacyEndpointsKey struct{} -) - -// GetServiceID retrieves the service id from the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func GetServiceID(ctx context.Context) (v string) { - v, _ = middleware.GetStackValue(ctx, serviceIDKey{}).(string) - return v -} - -// GetSigningName retrieves the service signing name from the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func GetSigningName(ctx context.Context) (v string) { - v, _ = middleware.GetStackValue(ctx, signingNameKey{}).(string) - return v -} - -// GetSigningRegion retrieves the region from the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func GetSigningRegion(ctx context.Context) (v string) { - v, _ = middleware.GetStackValue(ctx, signingRegionKey{}).(string) - return v -} - -// GetRegion retrieves the endpoint region from the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func GetRegion(ctx context.Context) (v string) { - v, _ = middleware.GetStackValue(ctx, regionKey{}).(string) - return v -} - -// GetOperationName retrieves the service operation metadata from the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func GetOperationName(ctx context.Context) (v string) { - v, _ = middleware.GetStackValue(ctx, operationNameKey{}).(string) - return v -} - -// GetPartitionID retrieves the endpoint partition id from the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func GetPartitionID(ctx context.Context) string { - v, _ := middleware.GetStackValue(ctx, partitionIDKey{}).(string) - return v -} - -// GetRequiresLegacyEndpoints the flag used to indicate if legacy endpoint -// customizations need to be executed. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func GetRequiresLegacyEndpoints(ctx context.Context) bool { - v, _ := middleware.GetStackValue(ctx, requiresLegacyEndpointsKey{}).(bool) - return v -} - -// SetRequiresLegacyEndpoints set or modifies the flag indicated that -// legacy endpoint customizations are needed. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func SetRequiresLegacyEndpoints(ctx context.Context, value bool) context.Context { - return middleware.WithStackValue(ctx, requiresLegacyEndpointsKey{}, value) -} - -// SetSigningName set or modifies the signing name on the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func SetSigningName(ctx context.Context, value string) context.Context { - return middleware.WithStackValue(ctx, signingNameKey{}, value) -} - -// SetSigningRegion sets or modifies the region on the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func SetSigningRegion(ctx context.Context, value string) context.Context { - return middleware.WithStackValue(ctx, signingRegionKey{}, value) -} - -// SetServiceID sets the service id on the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func SetServiceID(ctx context.Context, value string) context.Context { - return middleware.WithStackValue(ctx, serviceIDKey{}, value) -} - -// setRegion sets the endpoint region on the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func setRegion(ctx context.Context, value string) context.Context { - return middleware.WithStackValue(ctx, regionKey{}, value) -} - -// setOperationName sets the service operation on the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func setOperationName(ctx context.Context, value string) context.Context { - return middleware.WithStackValue(ctx, operationNameKey{}, value) -} - -// SetPartitionID sets the partition id of a resolved region on the context -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func SetPartitionID(ctx context.Context, value string) context.Context { - return middleware.WithStackValue(ctx, partitionIDKey{}, value) -} - -// EndpointSource key -type endpointSourceKey struct{} - -// GetEndpointSource returns an endpoint source if set on context -func GetEndpointSource(ctx context.Context) (v aws.EndpointSource) { - v, _ = middleware.GetStackValue(ctx, endpointSourceKey{}).(aws.EndpointSource) - return v -} - -// SetEndpointSource sets endpoint source on context -func SetEndpointSource(ctx context.Context, value aws.EndpointSource) context.Context { - return middleware.WithStackValue(ctx, endpointSourceKey{}, value) -} - -type signingCredentialsKey struct{} - -// GetSigningCredentials returns the credentials that were used for signing if set on context. -func GetSigningCredentials(ctx context.Context) (v aws.Credentials) { - v, _ = middleware.GetStackValue(ctx, signingCredentialsKey{}).(aws.Credentials) - return v -} - -// SetSigningCredentials sets the credentails used for signing on the context. -func SetSigningCredentials(ctx context.Context, value aws.Credentials) context.Context { - return middleware.WithStackValue(ctx, signingCredentialsKey{}, value) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/middleware.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/middleware.go deleted file mode 100644 index 9bd0dfb15..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/middleware.go +++ /dev/null @@ -1,168 +0,0 @@ -package middleware - -import ( - "context" - "fmt" - "time" - - "github.com/aws/aws-sdk-go-v2/internal/rand" - "github.com/aws/aws-sdk-go-v2/internal/sdk" - "github.com/aws/smithy-go/logging" - "github.com/aws/smithy-go/middleware" - smithyrand "github.com/aws/smithy-go/rand" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// ClientRequestID is a Smithy BuildMiddleware that will generate a unique ID for logical API operation -// invocation. -type ClientRequestID struct{} - -// ID the identifier for the ClientRequestID -func (r *ClientRequestID) ID() string { - return "ClientRequestID" -} - -// HandleBuild attaches a unique operation invocation id for the operation to the request -func (r ClientRequestID) HandleBuild(ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler) ( - out middleware.BuildOutput, metadata middleware.Metadata, err error, -) { - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", req) - } - - invocationID, err := smithyrand.NewUUID(rand.Reader).GetUUID() - if err != nil { - return out, metadata, err - } - - const invocationIDHeader = "Amz-Sdk-Invocation-Id" - req.Header[invocationIDHeader] = append(req.Header[invocationIDHeader][:0], invocationID) - - return next.HandleBuild(ctx, in) -} - -// RecordResponseTiming records the response timing for the SDK client requests. -type RecordResponseTiming struct{} - -// ID is the middleware identifier -func (a *RecordResponseTiming) ID() string { - return "RecordResponseTiming" -} - -// HandleDeserialize calculates response metadata and clock skew -func (a RecordResponseTiming) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( - out middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err = next.HandleDeserialize(ctx, in) - responseAt := sdk.NowTime() - setResponseAt(&metadata, responseAt) - - var serverTime time.Time - - switch resp := out.RawResponse.(type) { - case *smithyhttp.Response: - respDateHeader := resp.Header.Get("Date") - if len(respDateHeader) == 0 { - break - } - var parseErr error - serverTime, parseErr = smithyhttp.ParseTime(respDateHeader) - if parseErr != nil { - logger := middleware.GetLogger(ctx) - logger.Logf(logging.Warn, "failed to parse response Date header value, got %v", - parseErr.Error()) - break - } - setServerTime(&metadata, serverTime) - } - - if !serverTime.IsZero() { - attemptSkew := serverTime.Sub(responseAt) - setAttemptSkew(&metadata, attemptSkew) - } - - return out, metadata, err -} - -type responseAtKey struct{} - -// GetResponseAt returns the time response was received at. -func GetResponseAt(metadata middleware.Metadata) (v time.Time, ok bool) { - v, ok = metadata.Get(responseAtKey{}).(time.Time) - return v, ok -} - -// setResponseAt sets the response time on the metadata. -func setResponseAt(metadata *middleware.Metadata, v time.Time) { - metadata.Set(responseAtKey{}, v) -} - -type serverTimeKey struct{} - -// GetServerTime returns the server time for response. -func GetServerTime(metadata middleware.Metadata) (v time.Time, ok bool) { - v, ok = metadata.Get(serverTimeKey{}).(time.Time) - return v, ok -} - -// setServerTime sets the server time on the metadata. -func setServerTime(metadata *middleware.Metadata, v time.Time) { - metadata.Set(serverTimeKey{}, v) -} - -type attemptSkewKey struct{} - -// GetAttemptSkew returns Attempt clock skew for response from metadata. -func GetAttemptSkew(metadata middleware.Metadata) (v time.Duration, ok bool) { - v, ok = metadata.Get(attemptSkewKey{}).(time.Duration) - return v, ok -} - -// setAttemptSkew sets the attempt clock skew on the metadata. -func setAttemptSkew(metadata *middleware.Metadata, v time.Duration) { - metadata.Set(attemptSkewKey{}, v) -} - -// AddClientRequestIDMiddleware adds ClientRequestID to the middleware stack -func AddClientRequestIDMiddleware(stack *middleware.Stack) error { - return stack.Build.Add(&ClientRequestID{}, middleware.After) -} - -// AddRecordResponseTiming adds RecordResponseTiming middleware to the -// middleware stack. -func AddRecordResponseTiming(stack *middleware.Stack) error { - return stack.Deserialize.Add(&RecordResponseTiming{}, middleware.After) -} - -// rawResponseKey is the accessor key used to store and access the -// raw response within the response metadata. -type rawResponseKey struct{} - -// addRawResponse middleware adds raw response on to the metadata -type addRawResponse struct{} - -// ID the identifier for the ClientRequestID -func (m *addRawResponse) ID() string { - return "AddRawResponseToMetadata" -} - -// HandleDeserialize adds raw response on the middleware metadata -func (m addRawResponse) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( - out middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err = next.HandleDeserialize(ctx, in) - metadata.Set(rawResponseKey{}, out.RawResponse) - return out, metadata, err -} - -// AddRawResponseToMetadata adds middleware to the middleware stack that -// store raw response on to the metadata. -func AddRawResponseToMetadata(stack *middleware.Stack) error { - return stack.Deserialize.Add(&addRawResponse{}, middleware.Before) -} - -// GetRawResponse returns raw response set on metadata -func GetRawResponse(metadata middleware.Metadata) interface{} { - return metadata.Get(rawResponseKey{}) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/osname.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/osname.go deleted file mode 100644 index ba262dadc..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/osname.go +++ /dev/null @@ -1,24 +0,0 @@ -//go:build go1.16 -// +build go1.16 - -package middleware - -import "runtime" - -func getNormalizedOSName() (os string) { - switch runtime.GOOS { - case "android": - os = "android" - case "linux": - os = "linux" - case "windows": - os = "windows" - case "darwin": - os = "macos" - case "ios": - os = "ios" - default: - os = "other" - } - return os -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/osname_go115.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/osname_go115.go deleted file mode 100644 index e14a1e4ec..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/osname_go115.go +++ /dev/null @@ -1,24 +0,0 @@ -//go:build !go1.16 -// +build !go1.16 - -package middleware - -import "runtime" - -func getNormalizedOSName() (os string) { - switch runtime.GOOS { - case "android": - os = "android" - case "linux": - os = "linux" - case "windows": - os = "windows" - case "darwin": - // Due to Apple M1 we can't distinguish between macOS and iOS when GOOS/GOARCH is darwin/amd64 - // For now declare this as "other" until we have a better detection mechanism. - fallthrough - default: - os = "other" - } - return os -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/recursion_detection.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/recursion_detection.go deleted file mode 100644 index 3f6aaf231..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/recursion_detection.go +++ /dev/null @@ -1,94 +0,0 @@ -package middleware - -import ( - "context" - "fmt" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" - "os" -) - -const envAwsLambdaFunctionName = "AWS_LAMBDA_FUNCTION_NAME" -const envAmznTraceID = "_X_AMZN_TRACE_ID" -const amznTraceIDHeader = "X-Amzn-Trace-Id" - -// AddRecursionDetection adds recursionDetection to the middleware stack -func AddRecursionDetection(stack *middleware.Stack) error { - return stack.Build.Add(&RecursionDetection{}, middleware.After) -} - -// RecursionDetection detects Lambda environment and sets its X-Ray trace ID to request header if absent -// to avoid recursion invocation in Lambda -type RecursionDetection struct{} - -// ID returns the middleware identifier -func (m *RecursionDetection) ID() string { - return "RecursionDetection" -} - -// HandleBuild detects Lambda environment and adds its trace ID to request header if absent -func (m *RecursionDetection) HandleBuild( - ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler, -) ( - out middleware.BuildOutput, metadata middleware.Metadata, err error, -) { - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown request type %T", req) - } - - _, hasLambdaEnv := os.LookupEnv(envAwsLambdaFunctionName) - xAmznTraceID, hasTraceID := os.LookupEnv(envAmznTraceID) - value := req.Header.Get(amznTraceIDHeader) - // only set the X-Amzn-Trace-Id header when it is not set initially, the - // current environment is Lambda and the _X_AMZN_TRACE_ID env variable exists - if value != "" || !hasLambdaEnv || !hasTraceID { - return next.HandleBuild(ctx, in) - } - - req.Header.Set(amznTraceIDHeader, percentEncode(xAmznTraceID)) - return next.HandleBuild(ctx, in) -} - -func percentEncode(s string) string { - upperhex := "0123456789ABCDEF" - hexCount := 0 - for i := 0; i < len(s); i++ { - c := s[i] - if shouldEncode(c) { - hexCount++ - } - } - - if hexCount == 0 { - return s - } - - required := len(s) + 2*hexCount - t := make([]byte, required) - j := 0 - for i := 0; i < len(s); i++ { - if c := s[i]; shouldEncode(c) { - t[j] = '%' - t[j+1] = upperhex[c>>4] - t[j+2] = upperhex[c&15] - j += 3 - } else { - t[j] = c - j++ - } - } - return string(t) -} - -func shouldEncode(c byte) bool { - if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' { - return false - } - switch c { - case '-', '=', ';', ':', '+', '&', '[', ']', '{', '}', '"', '\'', ',': - return false - default: - return true - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/request_id.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/request_id.go deleted file mode 100644 index dd3391fe4..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/request_id.go +++ /dev/null @@ -1,27 +0,0 @@ -package middleware - -import ( - "github.com/aws/smithy-go/middleware" -) - -// requestIDKey is used to retrieve request id from response metadata -type requestIDKey struct{} - -// SetRequestIDMetadata sets the provided request id over middleware metadata -func SetRequestIDMetadata(metadata *middleware.Metadata, id string) { - metadata.Set(requestIDKey{}, id) -} - -// GetRequestIDMetadata retrieves the request id from middleware metadata -// returns string and bool indicating value of request id, whether request id was set. -func GetRequestIDMetadata(metadata middleware.Metadata) (string, bool) { - if !metadata.Has(requestIDKey{}) { - return "", false - } - - v, ok := metadata.Get(requestIDKey{}).(string) - if !ok { - return "", true - } - return v, true -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/request_id_retriever.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/request_id_retriever.go deleted file mode 100644 index 7ce48c611..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/request_id_retriever.go +++ /dev/null @@ -1,49 +0,0 @@ -package middleware - -import ( - "context" - - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// AddRequestIDRetrieverMiddleware adds request id retriever middleware -func AddRequestIDRetrieverMiddleware(stack *middleware.Stack) error { - // add error wrapper middleware before operation deserializers so that it can wrap the error response - // returned by operation deserializers - return stack.Deserialize.Insert(&requestIDRetriever{}, "OperationDeserializer", middleware.Before) -} - -type requestIDRetriever struct { -} - -// ID returns the middleware identifier -func (m *requestIDRetriever) ID() string { - return "RequestIDRetriever" -} - -func (m *requestIDRetriever) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( - out middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err = next.HandleDeserialize(ctx, in) - - resp, ok := out.RawResponse.(*smithyhttp.Response) - if !ok { - // No raw response to wrap with. - return out, metadata, err - } - - // Different header which can map to request id - requestIDHeaderList := []string{"X-Amzn-Requestid", "X-Amz-RequestId"} - - for _, h := range requestIDHeaderList { - // check for headers known to contain Request id - if v := resp.Header.Get(h); len(v) != 0 { - // set reqID on metadata for successful responses. - SetRequestIDMetadata(&metadata, v) - break - } - } - - return out, metadata, err -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/user_agent.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/user_agent.go deleted file mode 100644 index af3447ddc..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/user_agent.go +++ /dev/null @@ -1,261 +0,0 @@ -package middleware - -import ( - "context" - "fmt" - "os" - "runtime" - "strings" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -var languageVersion = strings.TrimPrefix(runtime.Version(), "go") - -// SDKAgentKeyType is the metadata type to add to the SDK agent string -type SDKAgentKeyType int - -// The set of valid SDKAgentKeyType constants. If an unknown value is assigned for SDKAgentKeyType it will -// be mapped to AdditionalMetadata. -const ( - _ SDKAgentKeyType = iota - APIMetadata - OperatingSystemMetadata - LanguageMetadata - EnvironmentMetadata - FeatureMetadata - ConfigMetadata - FrameworkMetadata - AdditionalMetadata - ApplicationIdentifier -) - -func (k SDKAgentKeyType) string() string { - switch k { - case APIMetadata: - return "api" - case OperatingSystemMetadata: - return "os" - case LanguageMetadata: - return "lang" - case EnvironmentMetadata: - return "exec-env" - case FeatureMetadata: - return "ft" - case ConfigMetadata: - return "cfg" - case FrameworkMetadata: - return "lib" - case ApplicationIdentifier: - return "app" - case AdditionalMetadata: - fallthrough - default: - return "md" - } -} - -const execEnvVar = `AWS_EXECUTION_ENV` - -var validChars = map[rune]bool{ - '!': true, '#': true, '$': true, '%': true, '&': true, '\'': true, '*': true, '+': true, - '-': true, '.': true, '^': true, '_': true, '`': true, '|': true, '~': true, -} - -// requestUserAgent is a build middleware that set the User-Agent for the request. -type requestUserAgent struct { - sdkAgent, userAgent *smithyhttp.UserAgentBuilder -} - -// newRequestUserAgent returns a new requestUserAgent which will set the User-Agent and X-Amz-User-Agent for the -// request. -// -// User-Agent example: -// -// aws-sdk-go-v2/1.2.3 -// -// X-Amz-User-Agent example: -// -// aws-sdk-go-v2/1.2.3 md/GOOS/linux md/GOARCH/amd64 lang/go/1.15 -func newRequestUserAgent() *requestUserAgent { - userAgent, sdkAgent := smithyhttp.NewUserAgentBuilder(), smithyhttp.NewUserAgentBuilder() - addProductName(userAgent) - addProductName(sdkAgent) - - r := &requestUserAgent{ - sdkAgent: sdkAgent, - userAgent: userAgent, - } - - addSDKMetadata(r) - - return r -} - -func addSDKMetadata(r *requestUserAgent) { - r.AddSDKAgentKey(OperatingSystemMetadata, getNormalizedOSName()) - r.AddSDKAgentKeyValue(LanguageMetadata, "go", languageVersion) - r.AddSDKAgentKeyValue(AdditionalMetadata, "GOOS", runtime.GOOS) - r.AddSDKAgentKeyValue(AdditionalMetadata, "GOARCH", runtime.GOARCH) - if ev := os.Getenv(execEnvVar); len(ev) > 0 { - r.AddSDKAgentKey(EnvironmentMetadata, ev) - } -} - -func addProductName(builder *smithyhttp.UserAgentBuilder) { - builder.AddKeyValue(aws.SDKName, aws.SDKVersion) -} - -// AddUserAgentKey retrieves a requestUserAgent from the provided stack, or initializes one. -func AddUserAgentKey(key string) func(*middleware.Stack) error { - return func(stack *middleware.Stack) error { - requestUserAgent, err := getOrAddRequestUserAgent(stack) - if err != nil { - return err - } - requestUserAgent.AddUserAgentKey(key) - return nil - } -} - -// AddUserAgentKeyValue retrieves a requestUserAgent from the provided stack, or initializes one. -func AddUserAgentKeyValue(key, value string) func(*middleware.Stack) error { - return func(stack *middleware.Stack) error { - requestUserAgent, err := getOrAddRequestUserAgent(stack) - if err != nil { - return err - } - requestUserAgent.AddUserAgentKeyValue(key, value) - return nil - } -} - -// AddSDKAgentKey retrieves a requestUserAgent from the provided stack, or initializes one. -func AddSDKAgentKey(keyType SDKAgentKeyType, key string) func(*middleware.Stack) error { - return func(stack *middleware.Stack) error { - requestUserAgent, err := getOrAddRequestUserAgent(stack) - if err != nil { - return err - } - requestUserAgent.AddSDKAgentKey(keyType, key) - return nil - } -} - -// AddSDKAgentKeyValue retrieves a requestUserAgent from the provided stack, or initializes one. -func AddSDKAgentKeyValue(keyType SDKAgentKeyType, key, value string) func(*middleware.Stack) error { - return func(stack *middleware.Stack) error { - requestUserAgent, err := getOrAddRequestUserAgent(stack) - if err != nil { - return err - } - requestUserAgent.AddSDKAgentKeyValue(keyType, key, value) - return nil - } -} - -// AddRequestUserAgentMiddleware registers a requestUserAgent middleware on the stack if not present. -func AddRequestUserAgentMiddleware(stack *middleware.Stack) error { - _, err := getOrAddRequestUserAgent(stack) - return err -} - -func getOrAddRequestUserAgent(stack *middleware.Stack) (*requestUserAgent, error) { - id := (*requestUserAgent)(nil).ID() - bm, ok := stack.Build.Get(id) - if !ok { - bm = newRequestUserAgent() - err := stack.Build.Add(bm, middleware.After) - if err != nil { - return nil, err - } - } - - requestUserAgent, ok := bm.(*requestUserAgent) - if !ok { - return nil, fmt.Errorf("%T for %s middleware did not match expected type", bm, id) - } - - return requestUserAgent, nil -} - -// AddUserAgentKey adds the component identified by name to the User-Agent string. -func (u *requestUserAgent) AddUserAgentKey(key string) { - u.userAgent.AddKey(strings.Map(rules, key)) -} - -// AddUserAgentKeyValue adds the key identified by the given name and value to the User-Agent string. -func (u *requestUserAgent) AddUserAgentKeyValue(key, value string) { - u.userAgent.AddKeyValue(strings.Map(rules, key), strings.Map(rules, value)) -} - -// AddUserAgentKey adds the component identified by name to the User-Agent string. -func (u *requestUserAgent) AddSDKAgentKey(keyType SDKAgentKeyType, key string) { - // TODO: should target sdkAgent - u.userAgent.AddKey(keyType.string() + "/" + strings.Map(rules, key)) -} - -// AddUserAgentKeyValue adds the key identified by the given name and value to the User-Agent string. -func (u *requestUserAgent) AddSDKAgentKeyValue(keyType SDKAgentKeyType, key, value string) { - // TODO: should target sdkAgent - u.userAgent.AddKeyValue(keyType.string(), strings.Map(rules, key)+"#"+strings.Map(rules, value)) -} - -// ID the name of the middleware. -func (u *requestUserAgent) ID() string { - return "UserAgent" -} - -// HandleBuild adds or appends the constructed user agent to the request. -func (u *requestUserAgent) HandleBuild(ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler) ( - out middleware.BuildOutput, metadata middleware.Metadata, err error, -) { - switch req := in.Request.(type) { - case *smithyhttp.Request: - u.addHTTPUserAgent(req) - // TODO: To be re-enabled - // u.addHTTPSDKAgent(req) - default: - return out, metadata, fmt.Errorf("unknown transport type %T", in) - } - - return next.HandleBuild(ctx, in) -} - -func (u *requestUserAgent) addHTTPUserAgent(request *smithyhttp.Request) { - const userAgent = "User-Agent" - updateHTTPHeader(request, userAgent, u.userAgent.Build()) -} - -func (u *requestUserAgent) addHTTPSDKAgent(request *smithyhttp.Request) { - const sdkAgent = "X-Amz-User-Agent" - updateHTTPHeader(request, sdkAgent, u.sdkAgent.Build()) -} - -func updateHTTPHeader(request *smithyhttp.Request, header string, value string) { - var current string - if v := request.Header[header]; len(v) > 0 { - current = v[0] - } - if len(current) > 0 { - current = value + " " + current - } else { - current = value - } - request.Header[header] = append(request.Header[header][:0], current) -} - -func rules(r rune) rune { - switch { - case r >= '0' && r <= '9': - return r - case r >= 'A' && r <= 'Z' || r >= 'a' && r <= 'z': - return r - case validChars[r]: - return r - default: - return '-' - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/array.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/array.go deleted file mode 100644 index 47ebc0f54..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/array.go +++ /dev/null @@ -1,72 +0,0 @@ -package query - -import ( - "fmt" - "net/url" -) - -// Array represents the encoding of Query lists and sets. A Query array is a -// representation of a list of values of a fixed type. A serialized array might -// look like the following: -// -// ListName.member.1=foo -// &ListName.member.2=bar -// &Listname.member.3=baz -type Array struct { - // The query values to add the array to. - values url.Values - // The array's prefix, which includes the names of all parent structures - // and ends with the name of the list. For example, the prefix might be - // "ParentStructure.ListName". This prefix will be used to form the full - // keys for each element in the list. For example, an entry might have the - // key "ParentStructure.ListName.member.MemberName.1". - // - // While this is currently represented as a string that gets added to, it - // could also be represented as a stack that only gets condensed into a - // string when a finalized key is created. This could potentially reduce - // allocations. - prefix string - // Whether the list is flat or not. A list that is not flat will produce the - // following entry to the url.Values for a given entry: - // ListName.MemberName.1=value - // A list that is flat will produce the following: - // ListName.1=value - flat bool - // The location name of the member. In most cases this should be "member". - memberName string - // Elements are stored in values, so we keep track of the list size here. - size int32 - // Empty lists are encoded as "=", if we add a value later we will - // remove this encoding - emptyValue Value -} - -func newArray(values url.Values, prefix string, flat bool, memberName string) *Array { - emptyValue := newValue(values, prefix, flat) - emptyValue.String("") - - return &Array{ - values: values, - prefix: prefix, - flat: flat, - memberName: memberName, - emptyValue: emptyValue, - } -} - -// Value adds a new element to the Query Array. Returns a Value type used to -// encode the array element. -func (a *Array) Value() Value { - if a.size == 0 { - delete(a.values, a.emptyValue.key) - } - - // Query lists start a 1, so adjust the size first - a.size++ - prefix := a.prefix - if !a.flat { - prefix = fmt.Sprintf("%s.%s", prefix, a.memberName) - } - // Lists can't have flat members - return newValue(a.values, fmt.Sprintf("%s.%d", prefix, a.size), false) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/encoder.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/encoder.go deleted file mode 100644 index 2ecf9241c..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/encoder.go +++ /dev/null @@ -1,80 +0,0 @@ -package query - -import ( - "io" - "net/url" - "sort" -) - -// Encoder is a Query encoder that supports construction of Query body -// values using methods. -type Encoder struct { - // The query values that will be built up to manage encoding. - values url.Values - // The writer that the encoded body will be written to. - writer io.Writer - Value -} - -// NewEncoder returns a new Query body encoder -func NewEncoder(writer io.Writer) *Encoder { - values := url.Values{} - return &Encoder{ - values: values, - writer: writer, - Value: newBaseValue(values), - } -} - -// Encode returns the []byte slice representing the current -// state of the Query encoder. -func (e Encoder) Encode() error { - ws, ok := e.writer.(interface{ WriteString(string) (int, error) }) - if !ok { - // Fall back to less optimal byte slice casting if WriteString isn't available. - ws = &wrapWriteString{writer: e.writer} - } - - // Get the keys and sort them to have a stable output - keys := make([]string, 0, len(e.values)) - for k := range e.values { - keys = append(keys, k) - } - sort.Strings(keys) - isFirstEntry := true - for _, key := range keys { - queryValues := e.values[key] - escapedKey := url.QueryEscape(key) - for _, value := range queryValues { - if !isFirstEntry { - if _, err := ws.WriteString(`&`); err != nil { - return err - } - } else { - isFirstEntry = false - } - if _, err := ws.WriteString(escapedKey); err != nil { - return err - } - if _, err := ws.WriteString(`=`); err != nil { - return err - } - if _, err := ws.WriteString(url.QueryEscape(value)); err != nil { - return err - } - } - } - return nil -} - -// wrapWriteString wraps an io.Writer to provide a WriteString method -// where one is not available. -type wrapWriteString struct { - writer io.Writer -} - -// WriteString writes a string to the wrapped writer by casting it to -// a byte array first. -func (w wrapWriteString) WriteString(v string) (int, error) { - return w.writer.Write([]byte(v)) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/map.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/map.go deleted file mode 100644 index dea242b8b..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/map.go +++ /dev/null @@ -1,78 +0,0 @@ -package query - -import ( - "fmt" - "net/url" -) - -// Map represents the encoding of Query maps. A Query map is a representation -// of a mapping of arbitrary string keys to arbitrary values of a fixed type. -// A Map differs from an Object in that the set of keys is not fixed, in that -// the values must all be of the same type, and that map entries are ordered. -// A serialized map might look like the following: -// -// MapName.entry.1.key=Foo -// &MapName.entry.1.value=spam -// &MapName.entry.2.key=Bar -// &MapName.entry.2.value=eggs -type Map struct { - // The query values to add the map to. - values url.Values - // The map's prefix, which includes the names of all parent structures - // and ends with the name of the object. For example, the prefix might be - // "ParentStructure.MapName". This prefix will be used to form the full - // keys for each key-value pair of the map. For example, a value might have - // the key "ParentStructure.MapName.1.value". - // - // While this is currently represented as a string that gets added to, it - // could also be represented as a stack that only gets condensed into a - // string when a finalized key is created. This could potentially reduce - // allocations. - prefix string - // Whether the map is flat or not. A map that is not flat will produce the - // following entries to the url.Values for a given key-value pair: - // MapName.entry.1.KeyLocationName=mykey - // MapName.entry.1.ValueLocationName=myvalue - // A map that is flat will produce the following: - // MapName.1.KeyLocationName=mykey - // MapName.1.ValueLocationName=myvalue - flat bool - // The location name of the key. In most cases this should be "key". - keyLocationName string - // The location name of the value. In most cases this should be "value". - valueLocationName string - // Elements are stored in values, so we keep track of the list size here. - size int32 -} - -func newMap(values url.Values, prefix string, flat bool, keyLocationName string, valueLocationName string) *Map { - return &Map{ - values: values, - prefix: prefix, - flat: flat, - keyLocationName: keyLocationName, - valueLocationName: valueLocationName, - } -} - -// Key adds the given named key to the Query map. -// Returns a Value encoder that should be used to encode a Query value type. -func (m *Map) Key(name string) Value { - // Query lists start a 1, so adjust the size first - m.size++ - var key string - var value string - if m.flat { - key = fmt.Sprintf("%s.%d.%s", m.prefix, m.size, m.keyLocationName) - value = fmt.Sprintf("%s.%d.%s", m.prefix, m.size, m.valueLocationName) - } else { - key = fmt.Sprintf("%s.entry.%d.%s", m.prefix, m.size, m.keyLocationName) - value = fmt.Sprintf("%s.entry.%d.%s", m.prefix, m.size, m.valueLocationName) - } - - // The key can only be a string, so we just go ahead and set it here - newValue(m.values, key, false).String(name) - - // Maps can't have flat members - return newValue(m.values, value, false) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/middleware.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/middleware.go deleted file mode 100644 index 360344791..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/middleware.go +++ /dev/null @@ -1,62 +0,0 @@ -package query - -import ( - "context" - "fmt" - "io/ioutil" - - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// AddAsGetRequestMiddleware adds a middleware to the Serialize stack after the -// operation serializer that will convert the query request body to a GET -// operation with the query message in the HTTP request querystring. -func AddAsGetRequestMiddleware(stack *middleware.Stack) error { - return stack.Serialize.Insert(&asGetRequest{}, "OperationSerializer", middleware.After) -} - -type asGetRequest struct{} - -func (*asGetRequest) ID() string { return "Query:AsGetRequest" } - -func (m *asGetRequest) HandleSerialize( - ctx context.Context, input middleware.SerializeInput, next middleware.SerializeHandler, -) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - req, ok := input.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("expect smithy HTTP Request, got %T", input.Request) - } - - req.Method = "GET" - - // If the stream is not set, nothing else to do. - stream := req.GetStream() - if stream == nil { - return next.HandleSerialize(ctx, input) - } - - // Clear the stream since there will not be any body. - req.Header.Del("Content-Type") - req, err = req.SetStream(nil) - if err != nil { - return out, metadata, fmt.Errorf("unable update request body %w", err) - } - input.Request = req - - // Update request query with the body's query string value. - delim := "" - if len(req.URL.RawQuery) != 0 { - delim = "&" - } - - b, err := ioutil.ReadAll(stream) - if err != nil { - return out, metadata, fmt.Errorf("unable to get request body %w", err) - } - req.URL.RawQuery += delim + string(b) - - return next.HandleSerialize(ctx, input) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/object.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/object.go deleted file mode 100644 index 455b92515..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/object.go +++ /dev/null @@ -1,69 +0,0 @@ -package query - -import ( - "fmt" - "net/url" -) - -// Object represents the encoding of Query structures and unions. A Query -// object is a representation of a mapping of string keys to arbitrary -// values where there is a fixed set of keys whose values each have their -// own known type. A serialized object might look like the following: -// -// ObjectName.Foo=value -// &ObjectName.Bar=5 -type Object struct { - // The query values to add the object to. - values url.Values - // The object's prefix, which includes the names of all parent structures - // and ends with the name of the object. For example, the prefix might be - // "ParentStructure.ObjectName". This prefix will be used to form the full - // keys for each member of the object. For example, a member might have the - // key "ParentStructure.ObjectName.MemberName". - // - // While this is currently represented as a string that gets added to, it - // could also be represented as a stack that only gets condensed into a - // string when a finalized key is created. This could potentially reduce - // allocations. - prefix string -} - -func newObject(values url.Values, prefix string) *Object { - return &Object{ - values: values, - prefix: prefix, - } -} - -// Key adds the given named key to the Query object. -// Returns a Value encoder that should be used to encode a Query value type. -func (o *Object) Key(name string) Value { - return o.key(name, false) -} - -// KeyWithValues adds the given named key to the Query object. -// Returns a Value encoder that should be used to encode a Query list of values. -func (o *Object) KeyWithValues(name string) Value { - return o.keyWithValues(name, false) -} - -// FlatKey adds the given named key to the Query object. -// Returns a Value encoder that should be used to encode a Query value type. The -// value will be flattened if it is a map or array. -func (o *Object) FlatKey(name string) Value { - return o.key(name, true) -} - -func (o *Object) key(name string, flatValue bool) Value { - if o.prefix != "" { - return newValue(o.values, fmt.Sprintf("%s.%s", o.prefix, name), flatValue) - } - return newValue(o.values, name, flatValue) -} - -func (o *Object) keyWithValues(name string, flatValue bool) Value { - if o.prefix != "" { - return newAppendValue(o.values, fmt.Sprintf("%s.%s", o.prefix, name), flatValue) - } - return newAppendValue(o.values, name, flatValue) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/value.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/value.go deleted file mode 100644 index a9251521f..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/value.go +++ /dev/null @@ -1,115 +0,0 @@ -package query - -import ( - "math/big" - "net/url" - - "github.com/aws/smithy-go/encoding/httpbinding" -) - -// Value represents a Query Value type. -type Value struct { - // The query values to add the value to. - values url.Values - // The value's key, which will form the prefix for complex types. - key string - // Whether the value should be flattened or not if it's a flattenable type. - flat bool - queryValue httpbinding.QueryValue -} - -func newValue(values url.Values, key string, flat bool) Value { - return Value{ - values: values, - key: key, - flat: flat, - queryValue: httpbinding.NewQueryValue(values, key, false), - } -} - -func newAppendValue(values url.Values, key string, flat bool) Value { - return Value{ - values: values, - key: key, - flat: flat, - queryValue: httpbinding.NewQueryValue(values, key, true), - } -} - -func newBaseValue(values url.Values) Value { - return Value{ - values: values, - queryValue: httpbinding.NewQueryValue(nil, "", false), - } -} - -// Array returns a new Array encoder. -func (qv Value) Array(locationName string) *Array { - return newArray(qv.values, qv.key, qv.flat, locationName) -} - -// Object returns a new Object encoder. -func (qv Value) Object() *Object { - return newObject(qv.values, qv.key) -} - -// Map returns a new Map encoder. -func (qv Value) Map(keyLocationName string, valueLocationName string) *Map { - return newMap(qv.values, qv.key, qv.flat, keyLocationName, valueLocationName) -} - -// Base64EncodeBytes encodes v as a base64 query string value. -// This is intended to enable compatibility with the JSON encoder. -func (qv Value) Base64EncodeBytes(v []byte) { - qv.queryValue.Blob(v) -} - -// Boolean encodes v as a query string value -func (qv Value) Boolean(v bool) { - qv.queryValue.Boolean(v) -} - -// String encodes v as a query string value -func (qv Value) String(v string) { - qv.queryValue.String(v) -} - -// Byte encodes v as a query string value -func (qv Value) Byte(v int8) { - qv.queryValue.Byte(v) -} - -// Short encodes v as a query string value -func (qv Value) Short(v int16) { - qv.queryValue.Short(v) -} - -// Integer encodes v as a query string value -func (qv Value) Integer(v int32) { - qv.queryValue.Integer(v) -} - -// Long encodes v as a query string value -func (qv Value) Long(v int64) { - qv.queryValue.Long(v) -} - -// Float encodes v as a query string value -func (qv Value) Float(v float32) { - qv.queryValue.Float(v) -} - -// Double encodes v as a query string value -func (qv Value) Double(v float64) { - qv.queryValue.Double(v) -} - -// BigInteger encodes v as a query string value -func (qv Value) BigInteger(v *big.Int) { - qv.queryValue.BigInteger(v) -} - -// BigDecimal encodes v as a query string value -func (qv Value) BigDecimal(v *big.Float) { - qv.queryValue.BigDecimal(v) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/restjson/decoder_util.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/restjson/decoder_util.go deleted file mode 100644 index 1bce78a4d..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/restjson/decoder_util.go +++ /dev/null @@ -1,85 +0,0 @@ -package restjson - -import ( - "encoding/json" - "io" - "strings" - - "github.com/aws/smithy-go" -) - -// GetErrorInfo util looks for code, __type, and message members in the -// json body. These members are optionally available, and the function -// returns the value of member if it is available. This function is useful to -// identify the error code, msg in a REST JSON error response. -func GetErrorInfo(decoder *json.Decoder) (errorType string, message string, err error) { - var errInfo struct { - Code string - Type string `json:"__type"` - Message string - } - - err = decoder.Decode(&errInfo) - if err != nil { - if err == io.EOF { - return errorType, message, nil - } - return errorType, message, err - } - - // assign error type - if len(errInfo.Code) != 0 { - errorType = errInfo.Code - } else if len(errInfo.Type) != 0 { - errorType = errInfo.Type - } - - // assign error message - if len(errInfo.Message) != 0 { - message = errInfo.Message - } - - // sanitize error - if len(errorType) != 0 { - errorType = SanitizeErrorCode(errorType) - } - - return errorType, message, nil -} - -// SanitizeErrorCode sanitizes the errorCode string . -// The rule for sanitizing is if a `:` character is present, then take only the -// contents before the first : character in the value. -// If a # character is present, then take only the contents after the -// first # character in the value. -func SanitizeErrorCode(errorCode string) string { - if strings.ContainsAny(errorCode, ":") { - errorCode = strings.SplitN(errorCode, ":", 2)[0] - } - - if strings.ContainsAny(errorCode, "#") { - errorCode = strings.SplitN(errorCode, "#", 2)[1] - } - - return errorCode -} - -// GetSmithyGenericAPIError returns smithy generic api error and an error interface. -// Takes in json decoder, and error Code string as args. The function retrieves error message -// and error code from the decoder body. If errorCode of length greater than 0 is passed in as -// an argument, it is used instead. -func GetSmithyGenericAPIError(decoder *json.Decoder, errorCode string) (*smithy.GenericAPIError, error) { - errorType, message, err := GetErrorInfo(decoder) - if err != nil { - return nil, err - } - - if len(errorCode) == 0 { - errorCode = errorType - } - - return &smithy.GenericAPIError{ - Code: errorCode, - Message: message, - }, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/xml/error_utils.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/xml/error_utils.go deleted file mode 100644 index 6975ce652..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/xml/error_utils.go +++ /dev/null @@ -1,48 +0,0 @@ -package xml - -import ( - "encoding/xml" - "fmt" - "io" -) - -// ErrorComponents represents the error response fields -// that will be deserialized from an xml error response body -type ErrorComponents struct { - Code string - Message string - RequestID string -} - -// GetErrorResponseComponents returns the error fields from an xml error response body -func GetErrorResponseComponents(r io.Reader, noErrorWrapping bool) (ErrorComponents, error) { - if noErrorWrapping { - var errResponse noWrappedErrorResponse - if err := xml.NewDecoder(r).Decode(&errResponse); err != nil && err != io.EOF { - return ErrorComponents{}, fmt.Errorf("error while deserializing xml error response: %w", err) - } - return ErrorComponents(errResponse), nil - } - - var errResponse wrappedErrorResponse - if err := xml.NewDecoder(r).Decode(&errResponse); err != nil && err != io.EOF { - return ErrorComponents{}, fmt.Errorf("error while deserializing xml error response: %w", err) - } - return ErrorComponents(errResponse), nil -} - -// noWrappedErrorResponse represents the error response body with -// no internal Error wrapping -type noWrappedErrorResponse struct { - Code string `xml:"Code"` - Message string `xml:"Message"` - RequestID string `xml:"RequestId"` -} - -// wrappedErrorResponse represents the error response body -// wrapped within Error -type wrappedErrorResponse struct { - Code string `xml:"Error>Code"` - Message string `xml:"Error>Message"` - RequestID string `xml:"RequestId"` -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/ratelimit/token_bucket.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/ratelimit/token_bucket.go deleted file mode 100644 index 974ef594f..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/ratelimit/token_bucket.go +++ /dev/null @@ -1,96 +0,0 @@ -package ratelimit - -import ( - "sync" -) - -// TokenBucket provides a concurrency safe utility for adding and removing -// tokens from the available token bucket. -type TokenBucket struct { - remainingTokens uint - maxCapacity uint - minCapacity uint - mu sync.Mutex -} - -// NewTokenBucket returns an initialized TokenBucket with the capacity -// specified. -func NewTokenBucket(i uint) *TokenBucket { - return &TokenBucket{ - remainingTokens: i, - maxCapacity: i, - minCapacity: 1, - } -} - -// Retrieve attempts to reduce the available tokens by the amount requested. If -// there are tokens available true will be returned along with the number of -// available tokens remaining. If amount requested is larger than the available -// capacity, false will be returned along with the available capacity. If the -// amount is less than the available capacity, the capacity will be reduced by -// that amount, and the remaining capacity and true will be returned. -func (t *TokenBucket) Retrieve(amount uint) (available uint, retrieved bool) { - t.mu.Lock() - defer t.mu.Unlock() - - if amount > t.remainingTokens { - return t.remainingTokens, false - } - - t.remainingTokens -= amount - return t.remainingTokens, true -} - -// Refund returns the amount of tokens back to the available token bucket, up -// to the initial capacity. -func (t *TokenBucket) Refund(amount uint) { - t.mu.Lock() - defer t.mu.Unlock() - - // Capacity cannot exceed max capacity. - t.remainingTokens = uintMin(t.remainingTokens+amount, t.maxCapacity) -} - -// Capacity returns the maximum capacity of tokens that the bucket could -// contain. -func (t *TokenBucket) Capacity() uint { - t.mu.Lock() - defer t.mu.Unlock() - - return t.maxCapacity -} - -// Remaining returns the number of tokens that remaining in the bucket. -func (t *TokenBucket) Remaining() uint { - t.mu.Lock() - defer t.mu.Unlock() - - return t.remainingTokens -} - -// Resize adjusts the size of the token bucket. Returns the capacity remaining. -func (t *TokenBucket) Resize(size uint) uint { - t.mu.Lock() - defer t.mu.Unlock() - - t.maxCapacity = uintMax(size, t.minCapacity) - - // Capacity needs to be capped at max capacity, if max size reduced. - t.remainingTokens = uintMin(t.remainingTokens, t.maxCapacity) - - return t.remainingTokens -} - -func uintMin(a, b uint) uint { - if a < b { - return a - } - return b -} - -func uintMax(a, b uint) uint { - if a > b { - return a - } - return b -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/ratelimit/token_rate_limit.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/ratelimit/token_rate_limit.go deleted file mode 100644 index d89090ad3..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/ratelimit/token_rate_limit.go +++ /dev/null @@ -1,83 +0,0 @@ -package ratelimit - -import ( - "context" - "fmt" -) - -type rateToken struct { - tokenCost uint - bucket *TokenBucket -} - -func (t rateToken) release() error { - t.bucket.Refund(t.tokenCost) - return nil -} - -// TokenRateLimit provides a Token Bucket RateLimiter implementation -// that limits the overall number of retry attempts that can be made across -// operation invocations. -type TokenRateLimit struct { - bucket *TokenBucket -} - -// NewTokenRateLimit returns an TokenRateLimit with default values. -// Functional options can configure the retry rate limiter. -func NewTokenRateLimit(tokens uint) *TokenRateLimit { - return &TokenRateLimit{ - bucket: NewTokenBucket(tokens), - } -} - -type canceledError struct { - Err error -} - -func (c canceledError) CanceledError() bool { return true } -func (c canceledError) Unwrap() error { return c.Err } -func (c canceledError) Error() string { - return fmt.Sprintf("canceled, %v", c.Err) -} - -// GetToken may cause a available pool of retry quota to be -// decremented. Will return an error if the decremented value can not be -// reduced from the retry quota. -func (l *TokenRateLimit) GetToken(ctx context.Context, cost uint) (func() error, error) { - select { - case <-ctx.Done(): - return nil, canceledError{Err: ctx.Err()} - default: - } - if avail, ok := l.bucket.Retrieve(cost); !ok { - return nil, QuotaExceededError{Available: avail, Requested: cost} - } - - return rateToken{ - tokenCost: cost, - bucket: l.bucket, - }.release, nil -} - -// AddTokens increments the token bucket by a fixed amount. -func (l *TokenRateLimit) AddTokens(v uint) error { - l.bucket.Refund(v) - return nil -} - -// Remaining returns the number of remaining tokens in the bucket. -func (l *TokenRateLimit) Remaining() uint { - return l.bucket.Remaining() -} - -// QuotaExceededError provides the SDK error when the retries for a given -// token bucket have been exhausted. -type QuotaExceededError struct { - Available uint - Requested uint -} - -func (e QuotaExceededError) Error() string { - return fmt.Sprintf("retry quota exceeded, %d available, %d requested", - e.Available, e.Requested) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/request.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/request.go deleted file mode 100644 index d8d00e615..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/request.go +++ /dev/null @@ -1,25 +0,0 @@ -package aws - -import ( - "fmt" -) - -// TODO remove replace with smithy.CanceledError - -// RequestCanceledError is the error that will be returned by an API request -// that was canceled. Requests given a Context may return this error when -// canceled. -type RequestCanceledError struct { - Err error -} - -// CanceledError returns true to satisfy interfaces checking for canceled errors. -func (*RequestCanceledError) CanceledError() bool { return true } - -// Unwrap returns the underlying error, if there was one. -func (e *RequestCanceledError) Unwrap() error { - return e.Err -} -func (e *RequestCanceledError) Error() string { - return fmt.Sprintf("request canceled, %v", e.Err) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/adaptive.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/adaptive.go deleted file mode 100644 index 4dfde8573..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/adaptive.go +++ /dev/null @@ -1,156 +0,0 @@ -package retry - -import ( - "context" - "fmt" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/internal/sdk" -) - -const ( - // DefaultRequestCost is the cost of a single request from the adaptive - // rate limited token bucket. - DefaultRequestCost uint = 1 -) - -// DefaultThrottles provides the set of errors considered throttle errors that -// are checked by default. -var DefaultThrottles = []IsErrorThrottle{ - ThrottleErrorCode{ - Codes: DefaultThrottleErrorCodes, - }, -} - -// AdaptiveModeOptions provides the functional options for configuring the -// adaptive retry mode, and delay behavior. -type AdaptiveModeOptions struct { - // If the adaptive token bucket is empty, when an attempt will be made - // AdaptiveMode will sleep until a token is available. This can occur when - // attempts fail with throttle errors. Use this option to disable the sleep - // until token is available, and return error immediately. - FailOnNoAttemptTokens bool - - // The cost of an attempt from the AdaptiveMode's adaptive token bucket. - RequestCost uint - - // Set of strategies to determine if the attempt failed due to a throttle - // error. - // - // It is safe to append to this list in NewAdaptiveMode's functional options. - Throttles []IsErrorThrottle - - // Set of options for standard retry mode that AdaptiveMode is built on top - // of. AdaptiveMode may apply its own defaults to Standard retry mode that - // are different than the defaults of NewStandard. Use these options to - // override the default options. - StandardOptions []func(*StandardOptions) -} - -// AdaptiveMode provides an experimental retry strategy that expands on the -// Standard retry strategy, adding client attempt rate limits. The attempt rate -// limit is initially unrestricted, but becomes restricted when the attempt -// fails with for a throttle error. When restricted AdaptiveMode may need to -// sleep before an attempt is made, if too many throttles have been received. -// AdaptiveMode's sleep can be canceled with context cancel. Set -// AdaptiveModeOptions FailOnNoAttemptTokens to change the behavior from sleep, -// to fail fast. -// -// Eventually unrestricted attempt rate limit will be restored once attempts no -// longer are failing due to throttle errors. -type AdaptiveMode struct { - options AdaptiveModeOptions - throttles IsErrorThrottles - - retryer aws.RetryerV2 - rateLimit *adaptiveRateLimit -} - -// NewAdaptiveMode returns an initialized AdaptiveMode retry strategy. -func NewAdaptiveMode(optFns ...func(*AdaptiveModeOptions)) *AdaptiveMode { - o := AdaptiveModeOptions{ - RequestCost: DefaultRequestCost, - Throttles: append([]IsErrorThrottle{}, DefaultThrottles...), - } - for _, fn := range optFns { - fn(&o) - } - - return &AdaptiveMode{ - options: o, - throttles: IsErrorThrottles(o.Throttles), - retryer: NewStandard(o.StandardOptions...), - rateLimit: newAdaptiveRateLimit(), - } -} - -// IsErrorRetryable returns if the failed attempt is retryable. This check -// should determine if the error can be retried, or if the error is -// terminal. -func (a *AdaptiveMode) IsErrorRetryable(err error) bool { - return a.retryer.IsErrorRetryable(err) -} - -// MaxAttempts returns the maximum number of attempts that can be made for -// an attempt before failing. A value of 0 implies that the attempt should -// be retried until it succeeds if the errors are retryable. -func (a *AdaptiveMode) MaxAttempts() int { - return a.retryer.MaxAttempts() -} - -// RetryDelay returns the delay that should be used before retrying the -// attempt. Will return error if the if the delay could not be determined. -func (a *AdaptiveMode) RetryDelay(attempt int, opErr error) ( - time.Duration, error, -) { - return a.retryer.RetryDelay(attempt, opErr) -} - -// GetRetryToken attempts to deduct the retry cost from the retry token pool. -// Returning the token release function, or error. -func (a *AdaptiveMode) GetRetryToken(ctx context.Context, opErr error) ( - releaseToken func(error) error, err error, -) { - return a.retryer.GetRetryToken(ctx, opErr) -} - -// GetInitialToken returns the initial attempt token that can increment the -// retry token pool if the attempt is successful. -// -// Deprecated: This method does not provide a way to block using Context, -// nor can it return an error. Use RetryerV2, and GetAttemptToken instead. Only -// present to implement Retryer interface. -func (a *AdaptiveMode) GetInitialToken() (releaseToken func(error) error) { - return nopRelease -} - -// GetAttemptToken returns the attempt token that can be used to rate limit -// attempt calls. Will be used by the SDK's retry package's Attempt -// middleware to get an attempt token prior to calling the temp and releasing -// the attempt token after the attempt has been made. -func (a *AdaptiveMode) GetAttemptToken(ctx context.Context) (func(error) error, error) { - for { - acquiredToken, waitTryAgain := a.rateLimit.AcquireToken(a.options.RequestCost) - if acquiredToken { - break - } - if a.options.FailOnNoAttemptTokens { - return nil, fmt.Errorf( - "unable to get attempt token, and FailOnNoAttemptTokens enables") - } - - if err := sdk.SleepWithContext(ctx, waitTryAgain); err != nil { - return nil, fmt.Errorf("failed to wait for token to be available, %w", err) - } - } - - return a.handleResponse, nil -} - -func (a *AdaptiveMode) handleResponse(opErr error) error { - throttled := a.throttles.IsErrorThrottle(opErr).Bool() - - a.rateLimit.Update(throttled) - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/adaptive_ratelimit.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/adaptive_ratelimit.go deleted file mode 100644 index ad96d9b8c..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/adaptive_ratelimit.go +++ /dev/null @@ -1,158 +0,0 @@ -package retry - -import ( - "math" - "sync" - "time" - - "github.com/aws/aws-sdk-go-v2/internal/sdk" -) - -type adaptiveRateLimit struct { - tokenBucketEnabled bool - - smooth float64 - beta float64 - scaleConstant float64 - minFillRate float64 - - fillRate float64 - calculatedRate float64 - lastRefilled time.Time - measuredTxRate float64 - lastTxRateBucket float64 - requestCount int64 - lastMaxRate float64 - lastThrottleTime time.Time - timeWindow float64 - - tokenBucket *adaptiveTokenBucket - - mu sync.Mutex -} - -func newAdaptiveRateLimit() *adaptiveRateLimit { - now := sdk.NowTime() - return &adaptiveRateLimit{ - smooth: 0.8, - beta: 0.7, - scaleConstant: 0.4, - - minFillRate: 0.5, - - lastTxRateBucket: math.Floor(timeFloat64Seconds(now)), - lastThrottleTime: now, - - tokenBucket: newAdaptiveTokenBucket(0), - } -} - -func (a *adaptiveRateLimit) Enable(v bool) { - a.mu.Lock() - defer a.mu.Unlock() - - a.tokenBucketEnabled = v -} - -func (a *adaptiveRateLimit) AcquireToken(amount uint) ( - tokenAcquired bool, waitTryAgain time.Duration, -) { - a.mu.Lock() - defer a.mu.Unlock() - - if !a.tokenBucketEnabled { - return true, 0 - } - - a.tokenBucketRefill() - - available, ok := a.tokenBucket.Retrieve(float64(amount)) - if !ok { - waitDur := float64Seconds((float64(amount) - available) / a.fillRate) - return false, waitDur - } - - return true, 0 -} - -func (a *adaptiveRateLimit) Update(throttled bool) { - a.mu.Lock() - defer a.mu.Unlock() - - a.updateMeasuredRate() - - if throttled { - rateToUse := a.measuredTxRate - if a.tokenBucketEnabled { - rateToUse = math.Min(a.measuredTxRate, a.fillRate) - } - - a.lastMaxRate = rateToUse - a.calculateTimeWindow() - a.lastThrottleTime = sdk.NowTime() - a.calculatedRate = a.cubicThrottle(rateToUse) - a.tokenBucketEnabled = true - } else { - a.calculateTimeWindow() - a.calculatedRate = a.cubicSuccess(sdk.NowTime()) - } - - newRate := math.Min(a.calculatedRate, 2*a.measuredTxRate) - a.tokenBucketUpdateRate(newRate) -} - -func (a *adaptiveRateLimit) cubicSuccess(t time.Time) float64 { - dt := secondsFloat64(t.Sub(a.lastThrottleTime)) - return (a.scaleConstant * math.Pow(dt-a.timeWindow, 3)) + a.lastMaxRate -} - -func (a *adaptiveRateLimit) cubicThrottle(rateToUse float64) float64 { - return rateToUse * a.beta -} - -func (a *adaptiveRateLimit) calculateTimeWindow() { - a.timeWindow = math.Pow((a.lastMaxRate*(1.-a.beta))/a.scaleConstant, 1./3.) -} - -func (a *adaptiveRateLimit) tokenBucketUpdateRate(newRPS float64) { - a.tokenBucketRefill() - a.fillRate = math.Max(newRPS, a.minFillRate) - a.tokenBucket.Resize(newRPS) -} - -func (a *adaptiveRateLimit) updateMeasuredRate() { - now := sdk.NowTime() - timeBucket := math.Floor(timeFloat64Seconds(now)*2.) / 2. - a.requestCount++ - - if timeBucket > a.lastTxRateBucket { - currentRate := float64(a.requestCount) / (timeBucket - a.lastTxRateBucket) - a.measuredTxRate = (currentRate * a.smooth) + (a.measuredTxRate * (1. - a.smooth)) - a.requestCount = 0 - a.lastTxRateBucket = timeBucket - } -} - -func (a *adaptiveRateLimit) tokenBucketRefill() { - now := sdk.NowTime() - if a.lastRefilled.IsZero() { - a.lastRefilled = now - return - } - - fillAmount := secondsFloat64(now.Sub(a.lastRefilled)) * a.fillRate - a.tokenBucket.Refund(fillAmount) - a.lastRefilled = now -} - -func float64Seconds(v float64) time.Duration { - return time.Duration(v * float64(time.Second)) -} - -func secondsFloat64(v time.Duration) float64 { - return float64(v) / float64(time.Second) -} - -func timeFloat64Seconds(v time.Time) float64 { - return float64(v.UnixNano()) / float64(time.Second) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/adaptive_token_bucket.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/adaptive_token_bucket.go deleted file mode 100644 index 052723e8e..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/adaptive_token_bucket.go +++ /dev/null @@ -1,83 +0,0 @@ -package retry - -import ( - "math" - "sync" -) - -// adaptiveTokenBucket provides a concurrency safe utility for adding and -// removing tokens from the available token bucket. -type adaptiveTokenBucket struct { - remainingTokens float64 - maxCapacity float64 - minCapacity float64 - mu sync.Mutex -} - -// newAdaptiveTokenBucket returns an initialized adaptiveTokenBucket with the -// capacity specified. -func newAdaptiveTokenBucket(i float64) *adaptiveTokenBucket { - return &adaptiveTokenBucket{ - remainingTokens: i, - maxCapacity: i, - minCapacity: 1, - } -} - -// Retrieve attempts to reduce the available tokens by the amount requested. If -// there are tokens available true will be returned along with the number of -// available tokens remaining. If amount requested is larger than the available -// capacity, false will be returned along with the available capacity. If the -// amount is less than the available capacity, the capacity will be reduced by -// that amount, and the remaining capacity and true will be returned. -func (t *adaptiveTokenBucket) Retrieve(amount float64) (available float64, retrieved bool) { - t.mu.Lock() - defer t.mu.Unlock() - - if amount > t.remainingTokens { - return t.remainingTokens, false - } - - t.remainingTokens -= amount - return t.remainingTokens, true -} - -// Refund returns the amount of tokens back to the available token bucket, up -// to the initial capacity. -func (t *adaptiveTokenBucket) Refund(amount float64) { - t.mu.Lock() - defer t.mu.Unlock() - - // Capacity cannot exceed max capacity. - t.remainingTokens = math.Min(t.remainingTokens+amount, t.maxCapacity) -} - -// Capacity returns the maximum capacity of tokens that the bucket could -// contain. -func (t *adaptiveTokenBucket) Capacity() float64 { - t.mu.Lock() - defer t.mu.Unlock() - - return t.maxCapacity -} - -// Remaining returns the number of tokens that remaining in the bucket. -func (t *adaptiveTokenBucket) Remaining() float64 { - t.mu.Lock() - defer t.mu.Unlock() - - return t.remainingTokens -} - -// Resize adjusts the size of the token bucket. Returns the capacity remaining. -func (t *adaptiveTokenBucket) Resize(size float64) float64 { - t.mu.Lock() - defer t.mu.Unlock() - - t.maxCapacity = math.Max(size, t.minCapacity) - - // Capacity needs to be capped at max capacity, if max size reduced. - t.remainingTokens = math.Min(t.remainingTokens, t.maxCapacity) - - return t.remainingTokens -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/doc.go deleted file mode 100644 index 3a08ebe0a..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/doc.go +++ /dev/null @@ -1,80 +0,0 @@ -// Package retry provides interfaces and implementations for SDK request retry behavior. -// -// # Retryer Interface and Implementations -// -// This package defines Retryer interface that is used to either implement custom retry behavior -// or to extend the existing retry implementations provided by the SDK. This package provides a single -// retry implementation: Standard. -// -// # Standard -// -// Standard is the default retryer implementation used by service clients. The standard retryer is a rate limited -// retryer that has a configurable max attempts to limit the number of retry attempts when a retryable error occurs. -// In addition, the retryer uses a configurable token bucket to rate limit the retry attempts across the client, -// and uses an additional delay policy to limit the time between a requests subsequent attempts. -// -// By default the standard retryer uses the DefaultRetryables slice of IsErrorRetryable types to determine whether -// a given error is retryable. By default this list of retryables includes the following: -// - Retrying errors that implement the RetryableError method, and return true. -// - Connection Errors -// - Errors that implement a ConnectionError, Temporary, or Timeout method that return true. -// - Connection Reset Errors. -// - net.OpErr types that are dialing errors or are temporary. -// - HTTP Status Codes: 500, 502, 503, and 504. -// - API Error Codes -// - RequestTimeout, RequestTimeoutException -// - Throttling, ThrottlingException, ThrottledException, RequestThrottledException, TooManyRequestsException, -// RequestThrottled, SlowDown, EC2ThrottledException -// - ProvisionedThroughputExceededException, RequestLimitExceeded, BandwidthLimitExceeded, LimitExceededException -// - TransactionInProgressException, PriorRequestNotComplete -// -// The standard retryer will not retry a request in the event if the context associated with the request -// has been cancelled. Applications must handle this case explicitly if they wish to retry with a different context -// value. -// -// You can configure the standard retryer implementation to fit your applications by constructing a standard retryer -// using the NewStandard function, and providing one more functional argument that mutate the StandardOptions -// structure. StandardOptions provides the ability to modify the token bucket rate limiter, retryable error conditions, -// and the retry delay policy. -// -// For example to modify the default retry attempts for the standard retryer: -// -// // configure the custom retryer -// customRetry := retry.NewStandard(func(o *retry.StandardOptions) { -// o.MaxAttempts = 5 -// }) -// -// // create a service client with the retryer -// s3.NewFromConfig(cfg, func(o *s3.Options) { -// o.Retryer = customRetry -// }) -// -// # Utilities -// -// A number of package functions have been provided to easily wrap retryer implementations in an implementation agnostic -// way. These are: -// -// AddWithErrorCodes - Provides the ability to add additional API error codes that should be considered retryable -// in addition to those considered retryable by the provided retryer. -// -// AddWithMaxAttempts - Provides the ability to set the max number of attempts for retrying a request by wrapping -// a retryer implementation. -// -// AddWithMaxBackoffDelay - Provides the ability to set the max back off delay that can occur before retrying a -// request by wrapping a retryer implementation. -// -// The following package functions have been provided to easily satisfy different retry interfaces to further customize -// a given retryer's behavior: -// -// BackoffDelayerFunc - Can be used to wrap a function to satisfy the BackoffDelayer interface. For example, -// you can use this method to easily create custom back off policies to be used with the -// standard retryer. -// -// IsErrorRetryableFunc - Can be used to wrap a function to satisfy the IsErrorRetryable interface. For example, -// this can be used to extend the standard retryer to add additional logic to determine if an -// error should be retried. -// -// IsErrorTimeoutFunc - Can be used to wrap a function to satisfy IsErrorTimeout interface. For example, -// this can be used to extend the standard retryer to add additional logic to determine if an -// error should be considered a timeout. -package retry diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/errors.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/errors.go deleted file mode 100644 index 3e432eefe..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/errors.go +++ /dev/null @@ -1,20 +0,0 @@ -package retry - -import "fmt" - -// MaxAttemptsError provides the error when the maximum number of attempts have -// been exceeded. -type MaxAttemptsError struct { - Attempt int - Err error -} - -func (e *MaxAttemptsError) Error() string { - return fmt.Sprintf("exceeded maximum number of attempts, %d, %v", e.Attempt, e.Err) -} - -// Unwrap returns the nested error causing the max attempts error. Provides the -// implementation for errors.Is and errors.As to unwrap nested errors. -func (e *MaxAttemptsError) Unwrap() error { - return e.Err -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/jitter_backoff.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/jitter_backoff.go deleted file mode 100644 index c266996de..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/jitter_backoff.go +++ /dev/null @@ -1,49 +0,0 @@ -package retry - -import ( - "math" - "time" - - "github.com/aws/aws-sdk-go-v2/internal/rand" - "github.com/aws/aws-sdk-go-v2/internal/timeconv" -) - -// ExponentialJitterBackoff provides backoff delays with jitter based on the -// number of attempts. -type ExponentialJitterBackoff struct { - maxBackoff time.Duration - // precomputed number of attempts needed to reach max backoff. - maxBackoffAttempts float64 - - randFloat64 func() (float64, error) -} - -// NewExponentialJitterBackoff returns an ExponentialJitterBackoff configured -// for the max backoff. -func NewExponentialJitterBackoff(maxBackoff time.Duration) *ExponentialJitterBackoff { - return &ExponentialJitterBackoff{ - maxBackoff: maxBackoff, - maxBackoffAttempts: math.Log2( - float64(maxBackoff) / float64(time.Second)), - randFloat64: rand.CryptoRandFloat64, - } -} - -// BackoffDelay returns the duration to wait before the next attempt should be -// made. Returns an error if unable get a duration. -func (j *ExponentialJitterBackoff) BackoffDelay(attempt int, err error) (time.Duration, error) { - if attempt > int(j.maxBackoffAttempts) { - return j.maxBackoff, nil - } - - b, err := j.randFloat64() - if err != nil { - return 0, err - } - - // [0.0, 1.0) * 2 ^ attempts - ri := int64(1 << uint64(attempt)) - delaySeconds := b * float64(ri) - - return timeconv.FloatSecondsDur(delaySeconds), nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/metadata.go deleted file mode 100644 index 7a3f18301..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/metadata.go +++ /dev/null @@ -1,52 +0,0 @@ -package retry - -import ( - awsmiddle "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/smithy-go/middleware" -) - -// attemptResultsKey is a metadata accessor key to retrieve metadata -// for all request attempts. -type attemptResultsKey struct { -} - -// GetAttemptResults retrieves attempts results from middleware metadata. -func GetAttemptResults(metadata middleware.Metadata) (AttemptResults, bool) { - m, ok := metadata.Get(attemptResultsKey{}).(AttemptResults) - return m, ok -} - -// AttemptResults represents struct containing metadata returned by all request attempts. -type AttemptResults struct { - - // Results is a slice consisting attempt result from all request attempts. - // Results are stored in order request attempt is made. - Results []AttemptResult -} - -// AttemptResult represents attempt result returned by a single request attempt. -type AttemptResult struct { - - // Err is the error if received for the request attempt. - Err error - - // Retryable denotes if request may be retried. This states if an - // error is considered retryable. - Retryable bool - - // Retried indicates if this request was retried. - Retried bool - - // ResponseMetadata is any existing metadata passed via the response middlewares. - ResponseMetadata middleware.Metadata -} - -// addAttemptResults adds attempt results to middleware metadata -func addAttemptResults(metadata *middleware.Metadata, v AttemptResults) { - metadata.Set(attemptResultsKey{}, v) -} - -// GetRawResponse returns raw response recorded for the attempt result -func (a AttemptResult) GetRawResponse() interface{} { - return awsmiddle.GetRawResponse(a.ResponseMetadata) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/middleware.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/middleware.go deleted file mode 100644 index 822fc920a..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/middleware.go +++ /dev/null @@ -1,330 +0,0 @@ -package retry - -import ( - "context" - "fmt" - "strconv" - "strings" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - awsmiddle "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/internal/sdk" - "github.com/aws/smithy-go/logging" - smithymiddle "github.com/aws/smithy-go/middleware" - "github.com/aws/smithy-go/transport/http" -) - -// RequestCloner is a function that can take an input request type and clone -// the request for use in a subsequent retry attempt. -type RequestCloner func(interface{}) interface{} - -type retryMetadata struct { - AttemptNum int - AttemptTime time.Time - MaxAttempts int - AttemptClockSkew time.Duration -} - -// Attempt is a Smithy Finalize middleware that handles retry attempts using -// the provided Retryer implementation. -type Attempt struct { - // Enable the logging of retry attempts performed by the SDK. This will - // include logging retry attempts, unretryable errors, and when max - // attempts are reached. - LogAttempts bool - - retryer aws.RetryerV2 - requestCloner RequestCloner -} - -// NewAttemptMiddleware returns a new Attempt retry middleware. -func NewAttemptMiddleware(retryer aws.Retryer, requestCloner RequestCloner, optFns ...func(*Attempt)) *Attempt { - m := &Attempt{ - retryer: wrapAsRetryerV2(retryer), - requestCloner: requestCloner, - } - for _, fn := range optFns { - fn(m) - } - return m -} - -// ID returns the middleware identifier -func (r *Attempt) ID() string { return "Retry" } - -func (r Attempt) logf(logger logging.Logger, classification logging.Classification, format string, v ...interface{}) { - if !r.LogAttempts { - return - } - logger.Logf(classification, format, v...) -} - -// HandleFinalize utilizes the provider Retryer implementation to attempt -// retries over the next handler -func (r *Attempt) HandleFinalize(ctx context.Context, in smithymiddle.FinalizeInput, next smithymiddle.FinalizeHandler) ( - out smithymiddle.FinalizeOutput, metadata smithymiddle.Metadata, err error, -) { - var attemptNum int - var attemptClockSkew time.Duration - var attemptResults AttemptResults - - maxAttempts := r.retryer.MaxAttempts() - releaseRetryToken := nopRelease - - for { - attemptNum++ - attemptInput := in - attemptInput.Request = r.requestCloner(attemptInput.Request) - - // Record the metadata for the for attempt being started. - attemptCtx := setRetryMetadata(ctx, retryMetadata{ - AttemptNum: attemptNum, - AttemptTime: sdk.NowTime().UTC(), - MaxAttempts: maxAttempts, - AttemptClockSkew: attemptClockSkew, - }) - - var attemptResult AttemptResult - out, attemptResult, releaseRetryToken, err = r.handleAttempt(attemptCtx, attemptInput, releaseRetryToken, next) - attemptClockSkew, _ = awsmiddle.GetAttemptSkew(attemptResult.ResponseMetadata) - - // AttemptResult Retried states that the attempt was not successful, and - // should be retried. - shouldRetry := attemptResult.Retried - - // Add attempt metadata to list of all attempt metadata - attemptResults.Results = append(attemptResults.Results, attemptResult) - - if !shouldRetry { - // Ensure the last response's metadata is used as the bases for result - // metadata returned by the stack. The Slice of attempt results - // will be added to this cloned metadata. - metadata = attemptResult.ResponseMetadata.Clone() - - break - } - } - - addAttemptResults(&metadata, attemptResults) - return out, metadata, err -} - -// handleAttempt handles an individual request attempt. -func (r *Attempt) handleAttempt( - ctx context.Context, in smithymiddle.FinalizeInput, releaseRetryToken func(error) error, next smithymiddle.FinalizeHandler, -) ( - out smithymiddle.FinalizeOutput, attemptResult AttemptResult, _ func(error) error, err error, -) { - defer func() { - attemptResult.Err = err - }() - - // Short circuit if this attempt never can succeed because the context is - // canceled. This reduces the chance of token pools being modified for - // attempts that will not be made - select { - case <-ctx.Done(): - return out, attemptResult, nopRelease, ctx.Err() - default: - } - - //------------------------------ - // Get Attempt Token - //------------------------------ - releaseAttemptToken, err := r.retryer.GetAttemptToken(ctx) - if err != nil { - return out, attemptResult, nopRelease, fmt.Errorf( - "failed to get retry Send token, %w", err) - } - - //------------------------------ - // Send Attempt - //------------------------------ - logger := smithymiddle.GetLogger(ctx) - service, operation := awsmiddle.GetServiceID(ctx), awsmiddle.GetOperationName(ctx) - retryMetadata, _ := getRetryMetadata(ctx) - attemptNum := retryMetadata.AttemptNum - maxAttempts := retryMetadata.MaxAttempts - - // Following attempts must ensure the request payload stream starts in a - // rewound state. - if attemptNum > 1 { - if rewindable, ok := in.Request.(interface{ RewindStream() error }); ok { - if rewindErr := rewindable.RewindStream(); rewindErr != nil { - return out, attemptResult, nopRelease, fmt.Errorf( - "failed to rewind transport stream for retry, %w", rewindErr) - } - } - - r.logf(logger, logging.Debug, "retrying request %s/%s, attempt %d", - service, operation, attemptNum) - } - - var metadata smithymiddle.Metadata - out, metadata, err = next.HandleFinalize(ctx, in) - attemptResult.ResponseMetadata = metadata - - //------------------------------ - // Bookkeeping - //------------------------------ - // Release the retry token based on the state of the attempt's error (if any). - if releaseError := releaseRetryToken(err); releaseError != nil && err != nil { - return out, attemptResult, nopRelease, fmt.Errorf( - "failed to release retry token after request error, %w", err) - } - // Release the attempt token based on the state of the attempt's error (if any). - if releaseError := releaseAttemptToken(err); releaseError != nil && err != nil { - return out, attemptResult, nopRelease, fmt.Errorf( - "failed to release initial token after request error, %w", err) - } - // If there was no error making the attempt, nothing further to do. There - // will be nothing to retry. - if err == nil { - return out, attemptResult, nopRelease, err - } - - //------------------------------ - // Is Retryable and Should Retry - //------------------------------ - // If the attempt failed with an unretryable error, nothing further to do - // but return, and inform the caller about the terminal failure. - retryable := r.retryer.IsErrorRetryable(err) - if !retryable { - r.logf(logger, logging.Debug, "request failed with unretryable error %v", err) - return out, attemptResult, nopRelease, err - } - - // set retryable to true - attemptResult.Retryable = true - - // Once the maximum number of attempts have been exhausted there is nothing - // further to do other than inform the caller about the terminal failure. - if maxAttempts > 0 && attemptNum >= maxAttempts { - r.logf(logger, logging.Debug, "max retry attempts exhausted, max %d", maxAttempts) - err = &MaxAttemptsError{ - Attempt: attemptNum, - Err: err, - } - return out, attemptResult, nopRelease, err - } - - //------------------------------ - // Get Retry (aka Retry Quota) Token - //------------------------------ - // Get a retry token that will be released after the - releaseRetryToken, retryTokenErr := r.retryer.GetRetryToken(ctx, err) - if retryTokenErr != nil { - return out, attemptResult, nopRelease, retryTokenErr - } - - //------------------------------ - // Retry Delay and Sleep - //------------------------------ - // Get the retry delay before another attempt can be made, and sleep for - // that time. Potentially early exist if the sleep is canceled via the - // context. - retryDelay, reqErr := r.retryer.RetryDelay(attemptNum, err) - if reqErr != nil { - return out, attemptResult, releaseRetryToken, reqErr - } - if reqErr = sdk.SleepWithContext(ctx, retryDelay); reqErr != nil { - err = &aws.RequestCanceledError{Err: reqErr} - return out, attemptResult, releaseRetryToken, err - } - - // The request should be re-attempted. - attemptResult.Retried = true - - return out, attemptResult, releaseRetryToken, err -} - -// MetricsHeader attaches SDK request metric header for retries to the transport -type MetricsHeader struct{} - -// ID returns the middleware identifier -func (r *MetricsHeader) ID() string { - return "RetryMetricsHeader" -} - -// HandleFinalize attaches the SDK request metric header to the transport layer -func (r MetricsHeader) HandleFinalize(ctx context.Context, in smithymiddle.FinalizeInput, next smithymiddle.FinalizeHandler) ( - out smithymiddle.FinalizeOutput, metadata smithymiddle.Metadata, err error, -) { - retryMetadata, _ := getRetryMetadata(ctx) - - const retryMetricHeader = "Amz-Sdk-Request" - var parts []string - - parts = append(parts, "attempt="+strconv.Itoa(retryMetadata.AttemptNum)) - if retryMetadata.MaxAttempts != 0 { - parts = append(parts, "max="+strconv.Itoa(retryMetadata.MaxAttempts)) - } - - var ttl time.Time - if deadline, ok := ctx.Deadline(); ok { - ttl = deadline - } - - // Only append the TTL if it can be determined. - if !ttl.IsZero() && retryMetadata.AttemptClockSkew > 0 { - const unixTimeFormat = "20060102T150405Z" - ttl = ttl.Add(retryMetadata.AttemptClockSkew) - parts = append(parts, "ttl="+ttl.Format(unixTimeFormat)) - } - - switch req := in.Request.(type) { - case *http.Request: - req.Header[retryMetricHeader] = append(req.Header[retryMetricHeader][:0], strings.Join(parts, "; ")) - default: - return out, metadata, fmt.Errorf("unknown transport type %T", req) - } - - return next.HandleFinalize(ctx, in) -} - -type retryMetadataKey struct{} - -// getRetryMetadata retrieves retryMetadata from the context and a bool -// indicating if it was set. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func getRetryMetadata(ctx context.Context) (metadata retryMetadata, ok bool) { - metadata, ok = smithymiddle.GetStackValue(ctx, retryMetadataKey{}).(retryMetadata) - return metadata, ok -} - -// setRetryMetadata sets the retryMetadata on the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func setRetryMetadata(ctx context.Context, metadata retryMetadata) context.Context { - return smithymiddle.WithStackValue(ctx, retryMetadataKey{}, metadata) -} - -// AddRetryMiddlewaresOptions is the set of options that can be passed to -// AddRetryMiddlewares for configuring retry associated middleware. -type AddRetryMiddlewaresOptions struct { - Retryer aws.Retryer - - // Enable the logging of retry attempts performed by the SDK. This will - // include logging retry attempts, unretryable errors, and when max - // attempts are reached. - LogRetryAttempts bool -} - -// AddRetryMiddlewares adds retry middleware to operation middleware stack -func AddRetryMiddlewares(stack *smithymiddle.Stack, options AddRetryMiddlewaresOptions) error { - attempt := NewAttemptMiddleware(options.Retryer, http.RequestCloner, func(middleware *Attempt) { - middleware.LogAttempts = options.LogRetryAttempts - }) - - if err := stack.Finalize.Add(attempt, smithymiddle.After); err != nil { - return err - } - if err := stack.Finalize.Add(&MetricsHeader{}, smithymiddle.After); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/retry.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/retry.go deleted file mode 100644 index af81635b3..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/retry.go +++ /dev/null @@ -1,90 +0,0 @@ -package retry - -import ( - "context" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" -) - -// AddWithErrorCodes returns a Retryer with additional error codes considered -// for determining if the error should be retried. -func AddWithErrorCodes(r aws.Retryer, codes ...string) aws.Retryer { - retryable := &RetryableErrorCode{ - Codes: map[string]struct{}{}, - } - for _, c := range codes { - retryable.Codes[c] = struct{}{} - } - - return &withIsErrorRetryable{ - RetryerV2: wrapAsRetryerV2(r), - Retryable: retryable, - } -} - -type withIsErrorRetryable struct { - aws.RetryerV2 - Retryable IsErrorRetryable -} - -func (r *withIsErrorRetryable) IsErrorRetryable(err error) bool { - if v := r.Retryable.IsErrorRetryable(err); v != aws.UnknownTernary { - return v.Bool() - } - return r.RetryerV2.IsErrorRetryable(err) -} - -// AddWithMaxAttempts returns a Retryer with MaxAttempts set to the value -// specified. -func AddWithMaxAttempts(r aws.Retryer, max int) aws.Retryer { - return &withMaxAttempts{ - RetryerV2: wrapAsRetryerV2(r), - Max: max, - } -} - -type withMaxAttempts struct { - aws.RetryerV2 - Max int -} - -func (w *withMaxAttempts) MaxAttempts() int { - return w.Max -} - -// AddWithMaxBackoffDelay returns a retryer wrapping the passed in retryer -// overriding the RetryDelay behavior for a alternate minimum initial backoff -// delay. -func AddWithMaxBackoffDelay(r aws.Retryer, delay time.Duration) aws.Retryer { - return &withMaxBackoffDelay{ - RetryerV2: wrapAsRetryerV2(r), - backoff: NewExponentialJitterBackoff(delay), - } -} - -type withMaxBackoffDelay struct { - aws.RetryerV2 - backoff *ExponentialJitterBackoff -} - -func (r *withMaxBackoffDelay) RetryDelay(attempt int, err error) (time.Duration, error) { - return r.backoff.BackoffDelay(attempt, err) -} - -type wrappedAsRetryerV2 struct { - aws.Retryer -} - -func wrapAsRetryerV2(r aws.Retryer) aws.RetryerV2 { - v, ok := r.(aws.RetryerV2) - if !ok { - v = wrappedAsRetryerV2{Retryer: r} - } - - return v -} - -func (w wrappedAsRetryerV2) GetAttemptToken(context.Context) (func(error) error, error) { - return w.Retryer.GetInitialToken(), nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/retryable_error.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/retryable_error.go deleted file mode 100644 index 00d7d3eee..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/retryable_error.go +++ /dev/null @@ -1,191 +0,0 @@ -package retry - -import ( - "errors" - "net" - "net/url" - "strings" - - "github.com/aws/aws-sdk-go-v2/aws" -) - -// IsErrorRetryable provides the interface of an implementation to determine if -// a error as the result of an operation is retryable. -type IsErrorRetryable interface { - IsErrorRetryable(error) aws.Ternary -} - -// IsErrorRetryables is a collection of checks to determine of the error is -// retryable. Iterates through the checks and returns the state of retryable -// if any check returns something other than unknown. -type IsErrorRetryables []IsErrorRetryable - -// IsErrorRetryable returns if the error is retryable if any of the checks in -// the list return a value other than unknown. -func (r IsErrorRetryables) IsErrorRetryable(err error) aws.Ternary { - for _, re := range r { - if v := re.IsErrorRetryable(err); v != aws.UnknownTernary { - return v - } - } - return aws.UnknownTernary -} - -// IsErrorRetryableFunc wraps a function with the IsErrorRetryable interface. -type IsErrorRetryableFunc func(error) aws.Ternary - -// IsErrorRetryable returns if the error is retryable. -func (fn IsErrorRetryableFunc) IsErrorRetryable(err error) aws.Ternary { - return fn(err) -} - -// RetryableError is an IsErrorRetryable implementation which uses the -// optional interface Retryable on the error value to determine if the error is -// retryable. -type RetryableError struct{} - -// IsErrorRetryable returns if the error is retryable if it satisfies the -// Retryable interface, and returns if the attempt should be retried. -func (RetryableError) IsErrorRetryable(err error) aws.Ternary { - var v interface{ RetryableError() bool } - - if !errors.As(err, &v) { - return aws.UnknownTernary - } - - return aws.BoolTernary(v.RetryableError()) -} - -// NoRetryCanceledError detects if the error was an request canceled error and -// returns if so. -type NoRetryCanceledError struct{} - -// IsErrorRetryable returns the error is not retryable if the request was -// canceled. -func (NoRetryCanceledError) IsErrorRetryable(err error) aws.Ternary { - var v interface{ CanceledError() bool } - - if !errors.As(err, &v) { - return aws.UnknownTernary - } - - if v.CanceledError() { - return aws.FalseTernary - } - return aws.UnknownTernary -} - -// RetryableConnectionError determines if the underlying error is an HTTP -// connection and returns if it should be retried. -// -// Includes errors such as connection reset, connection refused, net dial, -// temporary, and timeout errors. -type RetryableConnectionError struct{} - -// IsErrorRetryable returns if the error is caused by and HTTP connection -// error, and should be retried. -func (r RetryableConnectionError) IsErrorRetryable(err error) aws.Ternary { - if err == nil { - return aws.UnknownTernary - } - var retryable bool - - var conErr interface{ ConnectionError() bool } - var tempErr interface{ Temporary() bool } - var timeoutErr interface{ Timeout() bool } - var urlErr *url.Error - var netOpErr *net.OpError - var dnsError *net.DNSError - - switch { - case errors.As(err, &dnsError): - // NXDOMAIN errors should not be retried - retryable = !dnsError.IsNotFound && dnsError.IsTemporary - - case errors.As(err, &conErr) && conErr.ConnectionError(): - retryable = true - - case strings.Contains(err.Error(), "connection reset"): - retryable = true - - case errors.As(err, &urlErr): - // Refused connections should be retried as the service may not yet be - // running on the port. Go TCP dial considers refused connections as - // not temporary. - if strings.Contains(urlErr.Error(), "connection refused") { - retryable = true - } else { - return r.IsErrorRetryable(errors.Unwrap(urlErr)) - } - - case errors.As(err, &netOpErr): - // Network dial, or temporary network errors are always retryable. - if strings.EqualFold(netOpErr.Op, "dial") || netOpErr.Temporary() { - retryable = true - } else { - return r.IsErrorRetryable(errors.Unwrap(netOpErr)) - } - - case errors.As(err, &tempErr) && tempErr.Temporary(): - // Fallback to the generic temporary check, with temporary errors - // retryable. - retryable = true - - case errors.As(err, &timeoutErr) && timeoutErr.Timeout(): - // Fallback to the generic timeout check, with timeout errors - // retryable. - retryable = true - - default: - return aws.UnknownTernary - } - - return aws.BoolTernary(retryable) - -} - -// RetryableHTTPStatusCode provides a IsErrorRetryable based on HTTP status -// codes. -type RetryableHTTPStatusCode struct { - Codes map[int]struct{} -} - -// IsErrorRetryable return if the passed in error is retryable based on the -// HTTP status code. -func (r RetryableHTTPStatusCode) IsErrorRetryable(err error) aws.Ternary { - var v interface{ HTTPStatusCode() int } - - if !errors.As(err, &v) { - return aws.UnknownTernary - } - - _, ok := r.Codes[v.HTTPStatusCode()] - if !ok { - return aws.UnknownTernary - } - - return aws.TrueTernary -} - -// RetryableErrorCode determines if an attempt should be retried based on the -// API error code. -type RetryableErrorCode struct { - Codes map[string]struct{} -} - -// IsErrorRetryable return if the error is retryable based on the error codes. -// Returns unknown if the error doesn't have a code or it is unknown. -func (r RetryableErrorCode) IsErrorRetryable(err error) aws.Ternary { - var v interface{ ErrorCode() string } - - if !errors.As(err, &v) { - return aws.UnknownTernary - } - - _, ok := r.Codes[v.ErrorCode()] - if !ok { - return aws.UnknownTernary - } - - return aws.TrueTernary -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/standard.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/standard.go deleted file mode 100644 index 25abffc81..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/standard.go +++ /dev/null @@ -1,258 +0,0 @@ -package retry - -import ( - "context" - "fmt" - "time" - - "github.com/aws/aws-sdk-go-v2/aws/ratelimit" -) - -// BackoffDelayer provides the interface for determining the delay to before -// another request attempt, that previously failed. -type BackoffDelayer interface { - BackoffDelay(attempt int, err error) (time.Duration, error) -} - -// BackoffDelayerFunc provides a wrapper around a function to determine the -// backoff delay of an attempt retry. -type BackoffDelayerFunc func(int, error) (time.Duration, error) - -// BackoffDelay returns the delay before attempt to retry a request. -func (fn BackoffDelayerFunc) BackoffDelay(attempt int, err error) (time.Duration, error) { - return fn(attempt, err) -} - -const ( - // DefaultMaxAttempts is the maximum of attempts for an API request - DefaultMaxAttempts int = 3 - - // DefaultMaxBackoff is the maximum back off delay between attempts - DefaultMaxBackoff time.Duration = 20 * time.Second -) - -// Default retry token quota values. -const ( - DefaultRetryRateTokens uint = 500 - DefaultRetryCost uint = 5 - DefaultRetryTimeoutCost uint = 10 - DefaultNoRetryIncrement uint = 1 -) - -// DefaultRetryableHTTPStatusCodes is the default set of HTTP status codes the SDK -// should consider as retryable errors. -var DefaultRetryableHTTPStatusCodes = map[int]struct{}{ - 500: {}, - 502: {}, - 503: {}, - 504: {}, -} - -// DefaultRetryableErrorCodes provides the set of API error codes that should -// be retried. -var DefaultRetryableErrorCodes = map[string]struct{}{ - "RequestTimeout": {}, - "RequestTimeoutException": {}, -} - -// DefaultThrottleErrorCodes provides the set of API error codes that are -// considered throttle errors. -var DefaultThrottleErrorCodes = map[string]struct{}{ - "Throttling": {}, - "ThrottlingException": {}, - "ThrottledException": {}, - "RequestThrottledException": {}, - "TooManyRequestsException": {}, - "ProvisionedThroughputExceededException": {}, - "TransactionInProgressException": {}, - "RequestLimitExceeded": {}, - "BandwidthLimitExceeded": {}, - "LimitExceededException": {}, - "RequestThrottled": {}, - "SlowDown": {}, - "PriorRequestNotComplete": {}, - "EC2ThrottledException": {}, -} - -// DefaultRetryables provides the set of retryable checks that are used by -// default. -var DefaultRetryables = []IsErrorRetryable{ - NoRetryCanceledError{}, - RetryableError{}, - RetryableConnectionError{}, - RetryableHTTPStatusCode{ - Codes: DefaultRetryableHTTPStatusCodes, - }, - RetryableErrorCode{ - Codes: DefaultRetryableErrorCodes, - }, - RetryableErrorCode{ - Codes: DefaultThrottleErrorCodes, - }, -} - -// DefaultTimeouts provides the set of timeout checks that are used by default. -var DefaultTimeouts = []IsErrorTimeout{ - TimeouterError{}, -} - -// StandardOptions provides the functional options for configuring the standard -// retryable, and delay behavior. -type StandardOptions struct { - // Maximum number of attempts that should be made. - MaxAttempts int - - // MaxBackoff duration between retried attempts. - MaxBackoff time.Duration - - // Provides the backoff strategy the retryer will use to determine the - // delay between retry attempts. - Backoff BackoffDelayer - - // Set of strategies to determine if the attempt should be retried based on - // the error response received. - // - // It is safe to append to this list in NewStandard's functional options. - Retryables []IsErrorRetryable - - // Set of strategies to determine if the attempt failed due to a timeout - // error. - // - // It is safe to append to this list in NewStandard's functional options. - Timeouts []IsErrorTimeout - - // Provides the rate limiting strategy for rate limiting attempt retries - // across all attempts the retryer is being used with. - RateLimiter RateLimiter - - // The cost to deduct from the RateLimiter's token bucket per retry. - RetryCost uint - - // The cost to deduct from the RateLimiter's token bucket per retry caused - // by timeout error. - RetryTimeoutCost uint - - // The cost to payback to the RateLimiter's token bucket for successful - // attempts. - NoRetryIncrement uint -} - -// RateLimiter provides the interface for limiting the rate of attempt retries -// allowed by the retryer. -type RateLimiter interface { - GetToken(ctx context.Context, cost uint) (releaseToken func() error, err error) - AddTokens(uint) error -} - -// Standard is the standard retry pattern for the SDK. It uses a set of -// retryable checks to determine of the failed attempt should be retried, and -// what retry delay should be used. -type Standard struct { - options StandardOptions - - timeout IsErrorTimeout - retryable IsErrorRetryable - backoff BackoffDelayer -} - -// NewStandard initializes a standard retry behavior with defaults that can be -// overridden via functional options. -func NewStandard(fnOpts ...func(*StandardOptions)) *Standard { - o := StandardOptions{ - MaxAttempts: DefaultMaxAttempts, - MaxBackoff: DefaultMaxBackoff, - Retryables: append([]IsErrorRetryable{}, DefaultRetryables...), - Timeouts: append([]IsErrorTimeout{}, DefaultTimeouts...), - - RateLimiter: ratelimit.NewTokenRateLimit(DefaultRetryRateTokens), - RetryCost: DefaultRetryCost, - RetryTimeoutCost: DefaultRetryTimeoutCost, - NoRetryIncrement: DefaultNoRetryIncrement, - } - for _, fn := range fnOpts { - fn(&o) - } - if o.MaxAttempts <= 0 { - o.MaxAttempts = DefaultMaxAttempts - } - - backoff := o.Backoff - if backoff == nil { - backoff = NewExponentialJitterBackoff(o.MaxBackoff) - } - - return &Standard{ - options: o, - backoff: backoff, - retryable: IsErrorRetryables(o.Retryables), - timeout: IsErrorTimeouts(o.Timeouts), - } -} - -// MaxAttempts returns the maximum number of attempts that can be made for a -// request before failing. -func (s *Standard) MaxAttempts() int { - return s.options.MaxAttempts -} - -// IsErrorRetryable returns if the error is can be retried or not. Should not -// consider the number of attempts made. -func (s *Standard) IsErrorRetryable(err error) bool { - return s.retryable.IsErrorRetryable(err).Bool() -} - -// RetryDelay returns the delay to use before another request attempt is made. -func (s *Standard) RetryDelay(attempt int, err error) (time.Duration, error) { - return s.backoff.BackoffDelay(attempt, err) -} - -// GetAttemptToken returns the token to be released after then attempt completes. -// The release token will add NoRetryIncrement to the RateLimiter token pool if -// the attempt was successful. If the attempt failed, nothing will be done. -func (s *Standard) GetAttemptToken(context.Context) (func(error) error, error) { - return s.GetInitialToken(), nil -} - -// GetInitialToken returns a token for adding the NoRetryIncrement to the -// RateLimiter token if the attempt completed successfully without error. -// -// InitialToken applies to result of the each attempt, including the first. -// Whereas the RetryToken applies to the result of subsequent attempts. -// -// Deprecated: use GetAttemptToken instead. -func (s *Standard) GetInitialToken() func(error) error { - return releaseToken(s.noRetryIncrement).release -} - -func (s *Standard) noRetryIncrement() error { - return s.options.RateLimiter.AddTokens(s.options.NoRetryIncrement) -} - -// GetRetryToken attempts to deduct the retry cost from the retry token pool. -// Returning the token release function, or error. -func (s *Standard) GetRetryToken(ctx context.Context, opErr error) (func(error) error, error) { - cost := s.options.RetryCost - - if s.timeout.IsErrorTimeout(opErr).Bool() { - cost = s.options.RetryTimeoutCost - } - - fn, err := s.options.RateLimiter.GetToken(ctx, cost) - if err != nil { - return nil, fmt.Errorf("failed to get rate limit token, %w", err) - } - - return releaseToken(fn).release, nil -} - -func nopRelease(error) error { return nil } - -type releaseToken func() error - -func (f releaseToken) release(err error) error { - if err != nil { - return nil - } - - return f() -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/throttle_error.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/throttle_error.go deleted file mode 100644 index c4b844d15..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/throttle_error.go +++ /dev/null @@ -1,60 +0,0 @@ -package retry - -import ( - "errors" - - "github.com/aws/aws-sdk-go-v2/aws" -) - -// IsErrorThrottle provides the interface of an implementation to determine if -// a error response from an operation is a throttling error. -type IsErrorThrottle interface { - IsErrorThrottle(error) aws.Ternary -} - -// IsErrorThrottles is a collection of checks to determine of the error a -// throttle error. Iterates through the checks and returns the state of -// throttle if any check returns something other than unknown. -type IsErrorThrottles []IsErrorThrottle - -// IsErrorThrottle returns if the error is a throttle error if any of the -// checks in the list return a value other than unknown. -func (r IsErrorThrottles) IsErrorThrottle(err error) aws.Ternary { - for _, re := range r { - if v := re.IsErrorThrottle(err); v != aws.UnknownTernary { - return v - } - } - return aws.UnknownTernary -} - -// IsErrorThrottleFunc wraps a function with the IsErrorThrottle interface. -type IsErrorThrottleFunc func(error) aws.Ternary - -// IsErrorThrottle returns if the error is a throttle error. -func (fn IsErrorThrottleFunc) IsErrorThrottle(err error) aws.Ternary { - return fn(err) -} - -// ThrottleErrorCode determines if an attempt should be retried based on the -// API error code. -type ThrottleErrorCode struct { - Codes map[string]struct{} -} - -// IsErrorThrottle return if the error is a throttle error based on the error -// codes. Returns unknown if the error doesn't have a code or it is unknown. -func (r ThrottleErrorCode) IsErrorThrottle(err error) aws.Ternary { - var v interface{ ErrorCode() string } - - if !errors.As(err, &v) { - return aws.UnknownTernary - } - - _, ok := r.Codes[v.ErrorCode()] - if !ok { - return aws.UnknownTernary - } - - return aws.TrueTernary -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/timeout_error.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/timeout_error.go deleted file mode 100644 index 3d47870d2..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/timeout_error.go +++ /dev/null @@ -1,52 +0,0 @@ -package retry - -import ( - "errors" - - "github.com/aws/aws-sdk-go-v2/aws" -) - -// IsErrorTimeout provides the interface of an implementation to determine if -// a error matches. -type IsErrorTimeout interface { - IsErrorTimeout(err error) aws.Ternary -} - -// IsErrorTimeouts is a collection of checks to determine of the error is -// retryable. Iterates through the checks and returns the state of retryable -// if any check returns something other than unknown. -type IsErrorTimeouts []IsErrorTimeout - -// IsErrorTimeout returns if the error is retryable if any of the checks in -// the list return a value other than unknown. -func (ts IsErrorTimeouts) IsErrorTimeout(err error) aws.Ternary { - for _, t := range ts { - if v := t.IsErrorTimeout(err); v != aws.UnknownTernary { - return v - } - } - return aws.UnknownTernary -} - -// IsErrorTimeoutFunc wraps a function with the IsErrorTimeout interface. -type IsErrorTimeoutFunc func(error) aws.Ternary - -// IsErrorTimeout returns if the error is retryable. -func (fn IsErrorTimeoutFunc) IsErrorTimeout(err error) aws.Ternary { - return fn(err) -} - -// TimeouterError provides the IsErrorTimeout implementation for determining if -// an error is a timeout based on type with the Timeout method. -type TimeouterError struct{} - -// IsErrorTimeout returns if the error is a timeout error. -func (t TimeouterError) IsErrorTimeout(err error) aws.Ternary { - var v interface{ Timeout() bool } - - if !errors.As(err, &v) { - return aws.UnknownTernary - } - - return aws.BoolTernary(v.Timeout()) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retryer.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retryer.go deleted file mode 100644 index b0ba4cb2f..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retryer.go +++ /dev/null @@ -1,127 +0,0 @@ -package aws - -import ( - "context" - "fmt" - "time" -) - -// RetryMode provides the mode the API client will use to create a retryer -// based on. -type RetryMode string - -const ( - // RetryModeStandard model provides rate limited retry attempts with - // exponential backoff delay. - RetryModeStandard RetryMode = "standard" - - // RetryModeAdaptive model provides attempt send rate limiting on throttle - // responses in addition to standard mode's retry rate limiting. - // - // Adaptive retry mode is experimental and is subject to change in the - // future. - RetryModeAdaptive RetryMode = "adaptive" -) - -// ParseRetryMode attempts to parse a RetryMode from the given string. -// Returning error if the value is not a known RetryMode. -func ParseRetryMode(v string) (mode RetryMode, err error) { - switch v { - case "standard": - return RetryModeStandard, nil - case "adaptive": - return RetryModeAdaptive, nil - default: - return mode, fmt.Errorf("unknown RetryMode, %v", v) - } -} - -func (m RetryMode) String() string { return string(m) } - -// Retryer is an interface to determine if a given error from a -// attempt should be retried, and if so what backoff delay to apply. The -// default implementation used by most services is the retry package's Standard -// type. Which contains basic retry logic using exponential backoff. -type Retryer interface { - // IsErrorRetryable returns if the failed attempt is retryable. This check - // should determine if the error can be retried, or if the error is - // terminal. - IsErrorRetryable(error) bool - - // MaxAttempts returns the maximum number of attempts that can be made for - // an attempt before failing. A value of 0 implies that the attempt should - // be retried until it succeeds if the errors are retryable. - MaxAttempts() int - - // RetryDelay returns the delay that should be used before retrying the - // attempt. Will return error if the delay could not be determined. - RetryDelay(attempt int, opErr error) (time.Duration, error) - - // GetRetryToken attempts to deduct the retry cost from the retry token pool. - // Returning the token release function, or error. - GetRetryToken(ctx context.Context, opErr error) (releaseToken func(error) error, err error) - - // GetInitialToken returns the initial attempt token that can increment the - // retry token pool if the attempt is successful. - GetInitialToken() (releaseToken func(error) error) -} - -// RetryerV2 is an interface to determine if a given error from an attempt -// should be retried, and if so what backoff delay to apply. The default -// implementation used by most services is the retry package's Standard type. -// Which contains basic retry logic using exponential backoff. -// -// RetryerV2 replaces the Retryer interface, deprecating the GetInitialToken -// method in favor of GetAttemptToken which takes a context, and can return an error. -// -// The SDK's retry package's Attempt middleware, and utilities will always -// wrap a Retryer as a RetryerV2. Delegating to GetInitialToken, only if -// GetAttemptToken is not implemented. -type RetryerV2 interface { - Retryer - - // GetInitialToken returns the initial attempt token that can increment the - // retry token pool if the attempt is successful. - // - // Deprecated: This method does not provide a way to block using Context, - // nor can it return an error. Use RetryerV2, and GetAttemptToken instead. - GetInitialToken() (releaseToken func(error) error) - - // GetAttemptToken returns the send token that can be used to rate limit - // attempt calls. Will be used by the SDK's retry package's Attempt - // middleware to get a send token prior to calling the temp and releasing - // the send token after the attempt has been made. - GetAttemptToken(context.Context) (func(error) error, error) -} - -// NopRetryer provides a RequestRetryDecider implementation that will flag -// all attempt errors as not retryable, with a max attempts of 1. -type NopRetryer struct{} - -// IsErrorRetryable returns false for all error values. -func (NopRetryer) IsErrorRetryable(error) bool { return false } - -// MaxAttempts always returns 1 for the original attempt. -func (NopRetryer) MaxAttempts() int { return 1 } - -// RetryDelay is not valid for the NopRetryer. Will always return error. -func (NopRetryer) RetryDelay(int, error) (time.Duration, error) { - return 0, fmt.Errorf("not retrying any attempt errors") -} - -// GetRetryToken returns a stub function that does nothing. -func (NopRetryer) GetRetryToken(context.Context, error) (func(error) error, error) { - return nopReleaseToken, nil -} - -// GetInitialToken returns a stub function that does nothing. -func (NopRetryer) GetInitialToken() func(error) error { - return nopReleaseToken -} - -// GetAttemptToken returns a stub function that does nothing. -func (NopRetryer) GetAttemptToken(context.Context) (func(error) error, error) { - return nopReleaseToken, nil -} - -func nopReleaseToken(error) error { return nil } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/runtime.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/runtime.go deleted file mode 100644 index 3af9b2b33..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/runtime.go +++ /dev/null @@ -1,14 +0,0 @@ -package aws - -// ExecutionEnvironmentID is the AWS execution environment runtime identifier. -type ExecutionEnvironmentID string - -// RuntimeEnvironment is a collection of values that are determined at runtime -// based on the environment that the SDK is executing in. Some of these values -// may or may not be present based on the executing environment and certain SDK -// configuration properties that drive whether these values are populated.. -type RuntimeEnvironment struct { - EnvironmentIdentifier ExecutionEnvironmentID - Region string - EC2InstanceMetadataRegion string -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/cache.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/cache.go deleted file mode 100644 index cbf22f1d0..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/cache.go +++ /dev/null @@ -1,115 +0,0 @@ -package v4 - -import ( - "strings" - "sync" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" -) - -func lookupKey(service, region string) string { - var s strings.Builder - s.Grow(len(region) + len(service) + 3) - s.WriteString(region) - s.WriteRune('/') - s.WriteString(service) - return s.String() -} - -type derivedKey struct { - AccessKey string - Date time.Time - Credential []byte -} - -type derivedKeyCache struct { - values map[string]derivedKey - mutex sync.RWMutex -} - -func newDerivedKeyCache() derivedKeyCache { - return derivedKeyCache{ - values: make(map[string]derivedKey), - } -} - -func (s *derivedKeyCache) Get(credentials aws.Credentials, service, region string, signingTime SigningTime) []byte { - key := lookupKey(service, region) - s.mutex.RLock() - if cred, ok := s.get(key, credentials, signingTime.Time); ok { - s.mutex.RUnlock() - return cred - } - s.mutex.RUnlock() - - s.mutex.Lock() - if cred, ok := s.get(key, credentials, signingTime.Time); ok { - s.mutex.Unlock() - return cred - } - cred := deriveKey(credentials.SecretAccessKey, service, region, signingTime) - entry := derivedKey{ - AccessKey: credentials.AccessKeyID, - Date: signingTime.Time, - Credential: cred, - } - s.values[key] = entry - s.mutex.Unlock() - - return cred -} - -func (s *derivedKeyCache) get(key string, credentials aws.Credentials, signingTime time.Time) ([]byte, bool) { - cacheEntry, ok := s.retrieveFromCache(key) - if ok && cacheEntry.AccessKey == credentials.AccessKeyID && isSameDay(signingTime, cacheEntry.Date) { - return cacheEntry.Credential, true - } - return nil, false -} - -func (s *derivedKeyCache) retrieveFromCache(key string) (derivedKey, bool) { - if v, ok := s.values[key]; ok { - return v, true - } - return derivedKey{}, false -} - -// SigningKeyDeriver derives a signing key from a set of credentials -type SigningKeyDeriver struct { - cache derivedKeyCache -} - -// NewSigningKeyDeriver returns a new SigningKeyDeriver -func NewSigningKeyDeriver() *SigningKeyDeriver { - return &SigningKeyDeriver{ - cache: newDerivedKeyCache(), - } -} - -// DeriveKey returns a derived signing key from the given credentials to be used with SigV4 signing. -func (k *SigningKeyDeriver) DeriveKey(credential aws.Credentials, service, region string, signingTime SigningTime) []byte { - return k.cache.Get(credential, service, region, signingTime) -} - -func deriveKey(secret, service, region string, t SigningTime) []byte { - hmacDate := HMACSHA256([]byte("AWS4"+secret), []byte(t.ShortTimeFormat())) - hmacRegion := HMACSHA256(hmacDate, []byte(region)) - hmacService := HMACSHA256(hmacRegion, []byte(service)) - return HMACSHA256(hmacService, []byte("aws4_request")) -} - -func isSameDay(x, y time.Time) bool { - xYear, xMonth, xDay := x.Date() - yYear, yMonth, yDay := y.Date() - - if xYear != yYear { - return false - } - - if xMonth != yMonth { - return false - } - - return xDay == yDay -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/const.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/const.go deleted file mode 100644 index a23cb003b..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/const.go +++ /dev/null @@ -1,40 +0,0 @@ -package v4 - -// Signature Version 4 (SigV4) Constants -const ( - // EmptyStringSHA256 is the hex encoded sha256 value of an empty string - EmptyStringSHA256 = `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855` - - // UnsignedPayload indicates that the request payload body is unsigned - UnsignedPayload = "UNSIGNED-PAYLOAD" - - // AmzAlgorithmKey indicates the signing algorithm - AmzAlgorithmKey = "X-Amz-Algorithm" - - // AmzSecurityTokenKey indicates the security token to be used with temporary credentials - AmzSecurityTokenKey = "X-Amz-Security-Token" - - // AmzDateKey is the UTC timestamp for the request in the format YYYYMMDD'T'HHMMSS'Z' - AmzDateKey = "X-Amz-Date" - - // AmzCredentialKey is the access key ID and credential scope - AmzCredentialKey = "X-Amz-Credential" - - // AmzSignedHeadersKey is the set of headers signed for the request - AmzSignedHeadersKey = "X-Amz-SignedHeaders" - - // AmzSignatureKey is the query parameter to store the SigV4 signature - AmzSignatureKey = "X-Amz-Signature" - - // TimeFormat is the time format to be used in the X-Amz-Date header or query parameter - TimeFormat = "20060102T150405Z" - - // ShortTimeFormat is the shorten time format used in the credential scope - ShortTimeFormat = "20060102" - - // ContentSHAKey is the SHA256 of request body - ContentSHAKey = "X-Amz-Content-Sha256" - - // StreamingEventsPayload indicates that the request payload body is a signed event stream. - StreamingEventsPayload = "STREAMING-AWS4-HMAC-SHA256-EVENTS" -) diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/header_rules.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/header_rules.go deleted file mode 100644 index c61955ad5..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/header_rules.go +++ /dev/null @@ -1,82 +0,0 @@ -package v4 - -import ( - sdkstrings "github.com/aws/aws-sdk-go-v2/internal/strings" -) - -// Rules houses a set of Rule needed for validation of a -// string value -type Rules []Rule - -// Rule interface allows for more flexible rules and just simply -// checks whether or not a value adheres to that Rule -type Rule interface { - IsValid(value string) bool -} - -// IsValid will iterate through all rules and see if any rules -// apply to the value and supports nested rules -func (r Rules) IsValid(value string) bool { - for _, rule := range r { - if rule.IsValid(value) { - return true - } - } - return false -} - -// MapRule generic Rule for maps -type MapRule map[string]struct{} - -// IsValid for the map Rule satisfies whether it exists in the map -func (m MapRule) IsValid(value string) bool { - _, ok := m[value] - return ok -} - -// AllowList is a generic Rule for include listing -type AllowList struct { - Rule -} - -// IsValid for AllowList checks if the value is within the AllowList -func (w AllowList) IsValid(value string) bool { - return w.Rule.IsValid(value) -} - -// ExcludeList is a generic Rule for exclude listing -type ExcludeList struct { - Rule -} - -// IsValid for AllowList checks if the value is within the AllowList -func (b ExcludeList) IsValid(value string) bool { - return !b.Rule.IsValid(value) -} - -// Patterns is a list of strings to match against -type Patterns []string - -// IsValid for Patterns checks each pattern and returns if a match has -// been found -func (p Patterns) IsValid(value string) bool { - for _, pattern := range p { - if sdkstrings.HasPrefixFold(value, pattern) { - return true - } - } - return false -} - -// InclusiveRules rules allow for rules to depend on one another -type InclusiveRules []Rule - -// IsValid will return true if all rules are true -func (r InclusiveRules) IsValid(value string) bool { - for _, rule := range r { - if !rule.IsValid(value) { - return false - } - } - return true -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/headers.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/headers.go deleted file mode 100644 index 71b1a3521..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/headers.go +++ /dev/null @@ -1,70 +0,0 @@ -package v4 - -// IgnoredHeaders is a list of headers that are ignored during signing -var IgnoredHeaders = Rules{ - ExcludeList{ - MapRule{ - "Authorization": struct{}{}, - "User-Agent": struct{}{}, - "X-Amzn-Trace-Id": struct{}{}, - "Expect": struct{}{}, - }, - }, -} - -// RequiredSignedHeaders is a allow list for Build canonical headers. -var RequiredSignedHeaders = Rules{ - AllowList{ - MapRule{ - "Cache-Control": struct{}{}, - "Content-Disposition": struct{}{}, - "Content-Encoding": struct{}{}, - "Content-Language": struct{}{}, - "Content-Md5": struct{}{}, - "Content-Type": struct{}{}, - "Expires": struct{}{}, - "If-Match": struct{}{}, - "If-Modified-Since": struct{}{}, - "If-None-Match": struct{}{}, - "If-Unmodified-Since": struct{}{}, - "Range": struct{}{}, - "X-Amz-Acl": struct{}{}, - "X-Amz-Copy-Source": struct{}{}, - "X-Amz-Copy-Source-If-Match": struct{}{}, - "X-Amz-Copy-Source-If-Modified-Since": struct{}{}, - "X-Amz-Copy-Source-If-None-Match": struct{}{}, - "X-Amz-Copy-Source-If-Unmodified-Since": struct{}{}, - "X-Amz-Copy-Source-Range": struct{}{}, - "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Algorithm": struct{}{}, - "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key": struct{}{}, - "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key-Md5": struct{}{}, - "X-Amz-Grant-Full-control": struct{}{}, - "X-Amz-Grant-Read": struct{}{}, - "X-Amz-Grant-Read-Acp": struct{}{}, - "X-Amz-Grant-Write": struct{}{}, - "X-Amz-Grant-Write-Acp": struct{}{}, - "X-Amz-Metadata-Directive": struct{}{}, - "X-Amz-Mfa": struct{}{}, - "X-Amz-Request-Payer": struct{}{}, - "X-Amz-Server-Side-Encryption": struct{}{}, - "X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id": struct{}{}, - "X-Amz-Server-Side-Encryption-Context": struct{}{}, - "X-Amz-Server-Side-Encryption-Customer-Algorithm": struct{}{}, - "X-Amz-Server-Side-Encryption-Customer-Key": struct{}{}, - "X-Amz-Server-Side-Encryption-Customer-Key-Md5": struct{}{}, - "X-Amz-Storage-Class": struct{}{}, - "X-Amz-Website-Redirect-Location": struct{}{}, - "X-Amz-Content-Sha256": struct{}{}, - "X-Amz-Tagging": struct{}{}, - }, - }, - Patterns{"X-Amz-Object-Lock-"}, - Patterns{"X-Amz-Meta-"}, -} - -// AllowedQueryHoisting is a allowed list for Build query headers. The boolean value -// represents whether or not it is a pattern. -var AllowedQueryHoisting = InclusiveRules{ - ExcludeList{RequiredSignedHeaders}, - Patterns{"X-Amz-"}, -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/hmac.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/hmac.go deleted file mode 100644 index e7fa7a1b1..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/hmac.go +++ /dev/null @@ -1,13 +0,0 @@ -package v4 - -import ( - "crypto/hmac" - "crypto/sha256" -) - -// HMACSHA256 computes a HMAC-SHA256 of data given the provided key. -func HMACSHA256(key []byte, data []byte) []byte { - hash := hmac.New(sha256.New, key) - hash.Write(data) - return hash.Sum(nil) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/host.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/host.go deleted file mode 100644 index bf93659a4..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/host.go +++ /dev/null @@ -1,75 +0,0 @@ -package v4 - -import ( - "net/http" - "strings" -) - -// SanitizeHostForHeader removes default port from host and updates request.Host -func SanitizeHostForHeader(r *http.Request) { - host := getHost(r) - port := portOnly(host) - if port != "" && isDefaultPort(r.URL.Scheme, port) { - r.Host = stripPort(host) - } -} - -// Returns host from request -func getHost(r *http.Request) string { - if r.Host != "" { - return r.Host - } - - return r.URL.Host -} - -// Hostname returns u.Host, without any port number. -// -// If Host is an IPv6 literal with a port number, Hostname returns the -// IPv6 literal without the square brackets. IPv6 literals may include -// a zone identifier. -// -// Copied from the Go 1.8 standard library (net/url) -func stripPort(hostport string) string { - colon := strings.IndexByte(hostport, ':') - if colon == -1 { - return hostport - } - if i := strings.IndexByte(hostport, ']'); i != -1 { - return strings.TrimPrefix(hostport[:i], "[") - } - return hostport[:colon] -} - -// Port returns the port part of u.Host, without the leading colon. -// If u.Host doesn't contain a port, Port returns an empty string. -// -// Copied from the Go 1.8 standard library (net/url) -func portOnly(hostport string) string { - colon := strings.IndexByte(hostport, ':') - if colon == -1 { - return "" - } - if i := strings.Index(hostport, "]:"); i != -1 { - return hostport[i+len("]:"):] - } - if strings.Contains(hostport, "]") { - return "" - } - return hostport[colon+len(":"):] -} - -// Returns true if the specified URI is using the standard port -// (i.e. port 80 for HTTP URIs or 443 for HTTPS URIs) -func isDefaultPort(scheme, port string) bool { - if port == "" { - return true - } - - lowerCaseScheme := strings.ToLower(scheme) - if (lowerCaseScheme == "http" && port == "80") || (lowerCaseScheme == "https" && port == "443") { - return true - } - - return false -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/scope.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/scope.go deleted file mode 100644 index fc7887909..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/scope.go +++ /dev/null @@ -1,13 +0,0 @@ -package v4 - -import "strings" - -// BuildCredentialScope builds the Signature Version 4 (SigV4) signing scope -func BuildCredentialScope(signingTime SigningTime, region, service string) string { - return strings.Join([]string{ - signingTime.ShortTimeFormat(), - region, - service, - "aws4_request", - }, "/") -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/time.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/time.go deleted file mode 100644 index 1de06a765..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/time.go +++ /dev/null @@ -1,36 +0,0 @@ -package v4 - -import "time" - -// SigningTime provides a wrapper around a time.Time which provides cached values for SigV4 signing. -type SigningTime struct { - time.Time - timeFormat string - shortTimeFormat string -} - -// NewSigningTime creates a new SigningTime given a time.Time -func NewSigningTime(t time.Time) SigningTime { - return SigningTime{ - Time: t, - } -} - -// TimeFormat provides a time formatted in the X-Amz-Date format. -func (m *SigningTime) TimeFormat() string { - return m.format(&m.timeFormat, TimeFormat) -} - -// ShortTimeFormat provides a time formatted of 20060102. -func (m *SigningTime) ShortTimeFormat() string { - return m.format(&m.shortTimeFormat, ShortTimeFormat) -} - -func (m *SigningTime) format(target *string, format string) string { - if len(*target) > 0 { - return *target - } - v := m.Time.Format(format) - *target = v - return v -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/util.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/util.go deleted file mode 100644 index d025dbaa0..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/util.go +++ /dev/null @@ -1,80 +0,0 @@ -package v4 - -import ( - "net/url" - "strings" -) - -const doubleSpace = " " - -// StripExcessSpaces will rewrite the passed in slice's string values to not -// contain multiple side-by-side spaces. -func StripExcessSpaces(str string) string { - var j, k, l, m, spaces int - // Trim trailing spaces - for j = len(str) - 1; j >= 0 && str[j] == ' '; j-- { - } - - // Trim leading spaces - for k = 0; k < j && str[k] == ' '; k++ { - } - str = str[k : j+1] - - // Strip multiple spaces. - j = strings.Index(str, doubleSpace) - if j < 0 { - return str - } - - buf := []byte(str) - for k, m, l = j, j, len(buf); k < l; k++ { - if buf[k] == ' ' { - if spaces == 0 { - // First space. - buf[m] = buf[k] - m++ - } - spaces++ - } else { - // End of multiple spaces. - spaces = 0 - buf[m] = buf[k] - m++ - } - } - - return string(buf[:m]) -} - -// GetURIPath returns the escaped URI component from the provided URL. -func GetURIPath(u *url.URL) string { - var uriPath string - - if len(u.Opaque) > 0 { - const schemeSep, pathSep, queryStart = "//", "/", "?" - - opaque := u.Opaque - // Cut off the query string if present. - if idx := strings.Index(opaque, queryStart); idx >= 0 { - opaque = opaque[:idx] - } - - // Cutout the scheme separator if present. - if strings.Index(opaque, schemeSep) == 0 { - opaque = opaque[len(schemeSep):] - } - - // capture URI path starting with first path separator. - if idx := strings.Index(opaque, pathSep); idx >= 0 { - uriPath = opaque[idx:] - } - } else { - uriPath = u.EscapedPath() - } - - if len(uriPath) == 0 { - uriPath = "/" - } - - return uriPath -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/middleware.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/middleware.go deleted file mode 100644 index 0fb9b24e4..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/middleware.go +++ /dev/null @@ -1,408 +0,0 @@ -package v4 - -import ( - "context" - "crypto/sha256" - "encoding/hex" - "fmt" - "io" - "net/http" - "strings" - - "github.com/aws/aws-sdk-go-v2/aws" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - v4Internal "github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - "github.com/aws/aws-sdk-go-v2/internal/sdk" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -const computePayloadHashMiddlewareID = "ComputePayloadHash" - -// HashComputationError indicates an error occurred while computing the signing hash -type HashComputationError struct { - Err error -} - -// Error is the error message -func (e *HashComputationError) Error() string { - return fmt.Sprintf("failed to compute payload hash: %v", e.Err) -} - -// Unwrap returns the underlying error if one is set -func (e *HashComputationError) Unwrap() error { - return e.Err -} - -// SigningError indicates an error condition occurred while performing SigV4 signing -type SigningError struct { - Err error -} - -func (e *SigningError) Error() string { - return fmt.Sprintf("failed to sign request: %v", e.Err) -} - -// Unwrap returns the underlying error cause -func (e *SigningError) Unwrap() error { - return e.Err -} - -// UseDynamicPayloadSigningMiddleware swaps the compute payload sha256 middleware with a resolver middleware that -// switches between unsigned and signed payload based on TLS state for request. -// This middleware should not be used for AWS APIs that do not support unsigned payload signing auth. -// By default, SDK uses this middleware for known AWS APIs that support such TLS based auth selection . -// -// Usage example - -// S3 PutObject API allows unsigned payload signing auth usage when TLS is enabled, and uses this middleware to -// dynamically switch between unsigned and signed payload based on TLS state for request. -func UseDynamicPayloadSigningMiddleware(stack *middleware.Stack) error { - _, err := stack.Build.Swap(computePayloadHashMiddlewareID, &dynamicPayloadSigningMiddleware{}) - return err -} - -// dynamicPayloadSigningMiddleware dynamically resolves the middleware that computes and set payload sha256 middleware. -type dynamicPayloadSigningMiddleware struct { -} - -// ID returns the resolver identifier -func (m *dynamicPayloadSigningMiddleware) ID() string { - return computePayloadHashMiddlewareID -} - -// HandleBuild sets a resolver that directs to the payload sha256 compute handler. -func (m *dynamicPayloadSigningMiddleware) HandleBuild( - ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler, -) ( - out middleware.BuildOutput, metadata middleware.Metadata, err error, -) { - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - // if TLS is enabled, use unsigned payload when supported - if req.IsHTTPS() { - return (&unsignedPayload{}).HandleBuild(ctx, in, next) - } - - // else fall back to signed payload - return (&computePayloadSHA256{}).HandleBuild(ctx, in, next) -} - -// unsignedPayload sets the SigV4 request payload hash to unsigned. -// -// Will not set the Unsigned Payload magic SHA value, if a SHA has already been -// stored in the context. (e.g. application pre-computed SHA256 before making -// API call). -// -// This middleware does not check the X-Amz-Content-Sha256 header, if that -// header is serialized a middleware must translate it into the context. -type unsignedPayload struct{} - -// AddUnsignedPayloadMiddleware adds unsignedPayload to the operation -// middleware stack -func AddUnsignedPayloadMiddleware(stack *middleware.Stack) error { - return stack.Build.Add(&unsignedPayload{}, middleware.After) -} - -// ID returns the unsignedPayload identifier -func (m *unsignedPayload) ID() string { - return computePayloadHashMiddlewareID -} - -// HandleBuild sets the payload hash to be an unsigned payload -func (m *unsignedPayload) HandleBuild( - ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler, -) ( - out middleware.BuildOutput, metadata middleware.Metadata, err error, -) { - // This should not compute the content SHA256 if the value is already - // known. (e.g. application pre-computed SHA256 before making API call). - // Does not have any tight coupling to the X-Amz-Content-Sha256 header, if - // that header is provided a middleware must translate it into the context. - contentSHA := GetPayloadHash(ctx) - if len(contentSHA) == 0 { - contentSHA = v4Internal.UnsignedPayload - } - - ctx = SetPayloadHash(ctx, contentSHA) - return next.HandleBuild(ctx, in) -} - -// computePayloadSHA256 computes SHA256 payload hash to sign. -// -// Will not set the Unsigned Payload magic SHA value, if a SHA has already been -// stored in the context. (e.g. application pre-computed SHA256 before making -// API call). -// -// This middleware does not check the X-Amz-Content-Sha256 header, if that -// header is serialized a middleware must translate it into the context. -type computePayloadSHA256 struct{} - -// AddComputePayloadSHA256Middleware adds computePayloadSHA256 to the -// operation middleware stack -func AddComputePayloadSHA256Middleware(stack *middleware.Stack) error { - return stack.Build.Add(&computePayloadSHA256{}, middleware.After) -} - -// RemoveComputePayloadSHA256Middleware removes computePayloadSHA256 from the -// operation middleware stack -func RemoveComputePayloadSHA256Middleware(stack *middleware.Stack) error { - _, err := stack.Build.Remove(computePayloadHashMiddlewareID) - return err -} - -// ID is the middleware name -func (m *computePayloadSHA256) ID() string { - return computePayloadHashMiddlewareID -} - -// HandleBuild compute the payload hash for the request payload -func (m *computePayloadSHA256) HandleBuild( - ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler, -) ( - out middleware.BuildOutput, metadata middleware.Metadata, err error, -) { - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, &HashComputationError{ - Err: fmt.Errorf("unexpected request middleware type %T", in.Request), - } - } - - // This should not compute the content SHA256 if the value is already - // known. (e.g. application pre-computed SHA256 before making API call) - // Does not have any tight coupling to the X-Amz-Content-Sha256 header, if - // that header is provided a middleware must translate it into the context. - if contentSHA := GetPayloadHash(ctx); len(contentSHA) != 0 { - return next.HandleBuild(ctx, in) - } - - hash := sha256.New() - if stream := req.GetStream(); stream != nil { - _, err = io.Copy(hash, stream) - if err != nil { - return out, metadata, &HashComputationError{ - Err: fmt.Errorf("failed to compute payload hash, %w", err), - } - } - - if err := req.RewindStream(); err != nil { - return out, metadata, &HashComputationError{ - Err: fmt.Errorf("failed to seek body to start, %w", err), - } - } - } - - ctx = SetPayloadHash(ctx, hex.EncodeToString(hash.Sum(nil))) - - return next.HandleBuild(ctx, in) -} - -// SwapComputePayloadSHA256ForUnsignedPayloadMiddleware replaces the -// ComputePayloadSHA256 middleware with the UnsignedPayload middleware. -// -// Use this to disable computing the Payload SHA256 checksum and instead use -// UNSIGNED-PAYLOAD for the SHA256 value. -func SwapComputePayloadSHA256ForUnsignedPayloadMiddleware(stack *middleware.Stack) error { - _, err := stack.Build.Swap(computePayloadHashMiddlewareID, &unsignedPayload{}) - return err -} - -// contentSHA256Header sets the X-Amz-Content-Sha256 header value to -// the Payload hash stored in the context. -type contentSHA256Header struct{} - -// AddContentSHA256HeaderMiddleware adds ContentSHA256Header to the -// operation middleware stack -func AddContentSHA256HeaderMiddleware(stack *middleware.Stack) error { - return stack.Build.Insert(&contentSHA256Header{}, computePayloadHashMiddlewareID, middleware.After) -} - -// RemoveContentSHA256HeaderMiddleware removes contentSHA256Header middleware -// from the operation middleware stack -func RemoveContentSHA256HeaderMiddleware(stack *middleware.Stack) error { - _, err := stack.Build.Remove((*contentSHA256Header)(nil).ID()) - return err -} - -// ID returns the ContentSHA256HeaderMiddleware identifier -func (m *contentSHA256Header) ID() string { - return "SigV4ContentSHA256Header" -} - -// HandleBuild sets the X-Amz-Content-Sha256 header value to the Payload hash -// stored in the context. -func (m *contentSHA256Header) HandleBuild( - ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler, -) ( - out middleware.BuildOutput, metadata middleware.Metadata, err error, -) { - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, &HashComputationError{Err: fmt.Errorf("unexpected request middleware type %T", in.Request)} - } - - req.Header.Set(v4Internal.ContentSHAKey, GetPayloadHash(ctx)) - - return next.HandleBuild(ctx, in) -} - -// SignHTTPRequestMiddlewareOptions is the configuration options for the SignHTTPRequestMiddleware middleware. -type SignHTTPRequestMiddlewareOptions struct { - CredentialsProvider aws.CredentialsProvider - Signer HTTPSigner - LogSigning bool -} - -// SignHTTPRequestMiddleware is a `FinalizeMiddleware` implementation for SigV4 HTTP Signing -type SignHTTPRequestMiddleware struct { - credentialsProvider aws.CredentialsProvider - signer HTTPSigner - logSigning bool -} - -// NewSignHTTPRequestMiddleware constructs a SignHTTPRequestMiddleware using the given Signer for signing requests -func NewSignHTTPRequestMiddleware(options SignHTTPRequestMiddlewareOptions) *SignHTTPRequestMiddleware { - return &SignHTTPRequestMiddleware{ - credentialsProvider: options.CredentialsProvider, - signer: options.Signer, - logSigning: options.LogSigning, - } -} - -// ID is the SignHTTPRequestMiddleware identifier -func (s *SignHTTPRequestMiddleware) ID() string { - return "Signing" -} - -// HandleFinalize will take the provided input and sign the request using the SigV4 authentication scheme -func (s *SignHTTPRequestMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( - out middleware.FinalizeOutput, metadata middleware.Metadata, err error, -) { - if !haveCredentialProvider(s.credentialsProvider) { - return next.HandleFinalize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, &SigningError{Err: fmt.Errorf("unexpected request middleware type %T", in.Request)} - } - - signingName, signingRegion := awsmiddleware.GetSigningName(ctx), awsmiddleware.GetSigningRegion(ctx) - payloadHash := GetPayloadHash(ctx) - if len(payloadHash) == 0 { - return out, metadata, &SigningError{Err: fmt.Errorf("computed payload hash missing from context")} - } - - credentials, err := s.credentialsProvider.Retrieve(ctx) - if err != nil { - return out, metadata, &SigningError{Err: fmt.Errorf("failed to retrieve credentials: %w", err)} - } - - signerOptions := []func(o *SignerOptions){ - func(o *SignerOptions) { - o.Logger = middleware.GetLogger(ctx) - o.LogSigning = s.logSigning - }, - } - - // existing DisableURIPathEscaping is equivalent in purpose - // to authentication scheme property DisableDoubleEncoding - disableDoubleEncoding, overridden := internalauth.GetDisableDoubleEncoding(ctx) - if overridden { - signerOptions = append(signerOptions, func(o *SignerOptions) { - o.DisableURIPathEscaping = disableDoubleEncoding - }) - } - - err = s.signer.SignHTTP(ctx, credentials, req.Request, payloadHash, signingName, signingRegion, sdk.NowTime(), signerOptions...) - if err != nil { - return out, metadata, &SigningError{Err: fmt.Errorf("failed to sign http request, %w", err)} - } - - ctx = awsmiddleware.SetSigningCredentials(ctx, credentials) - - return next.HandleFinalize(ctx, in) -} - -type streamingEventsPayload struct{} - -// AddStreamingEventsPayload adds the streamingEventsPayload middleware to the stack. -func AddStreamingEventsPayload(stack *middleware.Stack) error { - return stack.Build.Add(&streamingEventsPayload{}, middleware.After) -} - -func (s *streamingEventsPayload) ID() string { - return computePayloadHashMiddlewareID -} - -func (s *streamingEventsPayload) HandleBuild( - ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler, -) ( - out middleware.BuildOutput, metadata middleware.Metadata, err error, -) { - contentSHA := GetPayloadHash(ctx) - if len(contentSHA) == 0 { - contentSHA = v4Internal.StreamingEventsPayload - } - - ctx = SetPayloadHash(ctx, contentSHA) - - return next.HandleBuild(ctx, in) -} - -// GetSignedRequestSignature attempts to extract the signature of the request. -// Returning an error if the request is unsigned, or unable to extract the -// signature. -func GetSignedRequestSignature(r *http.Request) ([]byte, error) { - const authHeaderSignatureElem = "Signature=" - - if auth := r.Header.Get(authorizationHeader); len(auth) != 0 { - ps := strings.Split(auth, ", ") - for _, p := range ps { - if idx := strings.Index(p, authHeaderSignatureElem); idx >= 0 { - sig := p[len(authHeaderSignatureElem):] - if len(sig) == 0 { - return nil, fmt.Errorf("invalid request signature authorization header") - } - return hex.DecodeString(sig) - } - } - } - - if sig := r.URL.Query().Get("X-Amz-Signature"); len(sig) != 0 { - return hex.DecodeString(sig) - } - - return nil, fmt.Errorf("request not signed") -} - -func haveCredentialProvider(p aws.CredentialsProvider) bool { - if p == nil { - return false - } - - return !aws.IsCredentialsProvider(p, (*aws.AnonymousCredentials)(nil)) -} - -type payloadHashKey struct{} - -// GetPayloadHash retrieves the payload hash to use for signing -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func GetPayloadHash(ctx context.Context) (v string) { - v, _ = middleware.GetStackValue(ctx, payloadHashKey{}).(string) - return v -} - -// SetPayloadHash sets the payload hash to be used for signing the request -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func SetPayloadHash(ctx context.Context, hash string) context.Context { - return middleware.WithStackValue(ctx, payloadHashKey{}, hash) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/presign_middleware.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/presign_middleware.go deleted file mode 100644 index e1a066512..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/presign_middleware.go +++ /dev/null @@ -1,127 +0,0 @@ -package v4 - -import ( - "context" - "fmt" - "net/http" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/internal/sdk" - "github.com/aws/smithy-go/middleware" - smithyHTTP "github.com/aws/smithy-go/transport/http" -) - -// HTTPPresigner is an interface to a SigV4 signer that can sign create a -// presigned URL for a HTTP requests. -type HTTPPresigner interface { - PresignHTTP( - ctx context.Context, credentials aws.Credentials, r *http.Request, - payloadHash string, service string, region string, signingTime time.Time, - optFns ...func(*SignerOptions), - ) (url string, signedHeader http.Header, err error) -} - -// PresignedHTTPRequest provides the URL and signed headers that are included -// in the presigned URL. -type PresignedHTTPRequest struct { - URL string - Method string - SignedHeader http.Header -} - -// PresignHTTPRequestMiddlewareOptions is the options for the PresignHTTPRequestMiddleware middleware. -type PresignHTTPRequestMiddlewareOptions struct { - CredentialsProvider aws.CredentialsProvider - Presigner HTTPPresigner - LogSigning bool -} - -// PresignHTTPRequestMiddleware provides the Finalize middleware for creating a -// presigned URL for an HTTP request. -// -// Will short circuit the middleware stack and not forward onto the next -// Finalize handler. -type PresignHTTPRequestMiddleware struct { - credentialsProvider aws.CredentialsProvider - presigner HTTPPresigner - logSigning bool -} - -// NewPresignHTTPRequestMiddleware returns a new PresignHTTPRequestMiddleware -// initialized with the presigner. -func NewPresignHTTPRequestMiddleware(options PresignHTTPRequestMiddlewareOptions) *PresignHTTPRequestMiddleware { - return &PresignHTTPRequestMiddleware{ - credentialsProvider: options.CredentialsProvider, - presigner: options.Presigner, - logSigning: options.LogSigning, - } -} - -// ID provides the middleware ID. -func (*PresignHTTPRequestMiddleware) ID() string { return "PresignHTTPRequest" } - -// HandleFinalize will take the provided input and create a presigned url for -// the http request using the SigV4 presign authentication scheme. -// -// Since the signed request is not a valid HTTP request -func (s *PresignHTTPRequestMiddleware) HandleFinalize( - ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler, -) ( - out middleware.FinalizeOutput, metadata middleware.Metadata, err error, -) { - req, ok := in.Request.(*smithyHTTP.Request) - if !ok { - return out, metadata, &SigningError{ - Err: fmt.Errorf("unexpected request middleware type %T", in.Request), - } - } - - httpReq := req.Build(ctx) - if !haveCredentialProvider(s.credentialsProvider) { - out.Result = &PresignedHTTPRequest{ - URL: httpReq.URL.String(), - Method: httpReq.Method, - SignedHeader: http.Header{}, - } - - return out, metadata, nil - } - - signingName := awsmiddleware.GetSigningName(ctx) - signingRegion := awsmiddleware.GetSigningRegion(ctx) - payloadHash := GetPayloadHash(ctx) - if len(payloadHash) == 0 { - return out, metadata, &SigningError{ - Err: fmt.Errorf("computed payload hash missing from context"), - } - } - - credentials, err := s.credentialsProvider.Retrieve(ctx) - if err != nil { - return out, metadata, &SigningError{ - Err: fmt.Errorf("failed to retrieve credentials: %w", err), - } - } - - u, h, err := s.presigner.PresignHTTP(ctx, credentials, - httpReq, payloadHash, signingName, signingRegion, sdk.NowTime(), - func(o *SignerOptions) { - o.Logger = middleware.GetLogger(ctx) - o.LogSigning = s.logSigning - }) - if err != nil { - return out, metadata, &SigningError{ - Err: fmt.Errorf("failed to sign http request, %w", err), - } - } - - out.Result = &PresignedHTTPRequest{ - URL: u, - Method: httpReq.Method, - SignedHeader: h, - } - - return out, metadata, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/stream.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/stream.go deleted file mode 100644 index 66aa2bd6a..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/stream.go +++ /dev/null @@ -1,86 +0,0 @@ -package v4 - -import ( - "context" - "crypto/sha256" - "encoding/hex" - "github.com/aws/aws-sdk-go-v2/aws" - v4Internal "github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4" - "strings" - "time" -) - -// EventStreamSigner is an AWS EventStream protocol signer. -type EventStreamSigner interface { - GetSignature(ctx context.Context, headers, payload []byte, signingTime time.Time, optFns ...func(*StreamSignerOptions)) ([]byte, error) -} - -// StreamSignerOptions is the configuration options for StreamSigner. -type StreamSignerOptions struct{} - -// StreamSigner implements Signature Version 4 (SigV4) signing of event stream encoded payloads. -type StreamSigner struct { - options StreamSignerOptions - - credentials aws.Credentials - service string - region string - - prevSignature []byte - - signingKeyDeriver *v4Internal.SigningKeyDeriver -} - -// NewStreamSigner returns a new AWS EventStream protocol signer. -func NewStreamSigner(credentials aws.Credentials, service, region string, seedSignature []byte, optFns ...func(*StreamSignerOptions)) *StreamSigner { - o := StreamSignerOptions{} - - for _, fn := range optFns { - fn(&o) - } - - return &StreamSigner{ - options: o, - credentials: credentials, - service: service, - region: region, - signingKeyDeriver: v4Internal.NewSigningKeyDeriver(), - prevSignature: seedSignature, - } -} - -// GetSignature signs the provided header and payload bytes. -func (s *StreamSigner) GetSignature(ctx context.Context, headers, payload []byte, signingTime time.Time, optFns ...func(*StreamSignerOptions)) ([]byte, error) { - options := s.options - - for _, fn := range optFns { - fn(&options) - } - - prevSignature := s.prevSignature - - st := v4Internal.NewSigningTime(signingTime) - - sigKey := s.signingKeyDeriver.DeriveKey(s.credentials, s.service, s.region, st) - - scope := v4Internal.BuildCredentialScope(st, s.region, s.service) - - stringToSign := s.buildEventStreamStringToSign(headers, payload, prevSignature, scope, &st) - - signature := v4Internal.HMACSHA256(sigKey, []byte(stringToSign)) - s.prevSignature = signature - - return signature, nil -} - -func (s *StreamSigner) buildEventStreamStringToSign(headers, payload, previousSignature []byte, credentialScope string, signingTime *v4Internal.SigningTime) string { - hash := sha256.New() - return strings.Join([]string{ - "AWS4-HMAC-SHA256-PAYLOAD", - signingTime.TimeFormat(), - credentialScope, - hex.EncodeToString(previousSignature), - hex.EncodeToString(makeHash(hash, headers)), - hex.EncodeToString(makeHash(hash, payload)), - }, "\n") -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/v4.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/v4.go deleted file mode 100644 index 4d162556b..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/v4.go +++ /dev/null @@ -1,548 +0,0 @@ -// Package v4 implements signing for AWS V4 signer -// -// Provides request signing for request that need to be signed with -// AWS V4 Signatures. -// -// # Standalone Signer -// -// Generally using the signer outside of the SDK should not require any additional -// -// The signer does this by taking advantage of the URL.EscapedPath method. If your request URI requires -// -// additional escaping you many need to use the URL.Opaque to define what the raw URI should be sent -// to the service as. -// -// The signer will first check the URL.Opaque field, and use its value if set. -// The signer does require the URL.Opaque field to be set in the form of: -// -// "///" -// -// // e.g. -// "//example.com/some/path" -// -// The leading "//" and hostname are required or the URL.Opaque escaping will -// not work correctly. -// -// If URL.Opaque is not set the signer will fallback to the URL.EscapedPath() -// method and using the returned value. -// -// AWS v4 signature validation requires that the canonical string's URI path -// element must be the URI escaped form of the HTTP request's path. -// http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html -// -// The Go HTTP client will perform escaping automatically on the request. Some -// of these escaping may cause signature validation errors because the HTTP -// request differs from the URI path or query that the signature was generated. -// https://golang.org/pkg/net/url/#URL.EscapedPath -// -// Because of this, it is recommended that when using the signer outside of the -// SDK that explicitly escaping the request prior to being signed is preferable, -// and will help prevent signature validation errors. This can be done by setting -// the URL.Opaque or URL.RawPath. The SDK will use URL.Opaque first and then -// call URL.EscapedPath() if Opaque is not set. -// -// Test `TestStandaloneSign` provides a complete example of using the signer -// outside of the SDK and pre-escaping the URI path. -package v4 - -import ( - "context" - "crypto/sha256" - "encoding/hex" - "fmt" - "hash" - "net/http" - "net/textproto" - "net/url" - "sort" - "strconv" - "strings" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - v4Internal "github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4" - "github.com/aws/smithy-go/encoding/httpbinding" - "github.com/aws/smithy-go/logging" -) - -const ( - signingAlgorithm = "AWS4-HMAC-SHA256" - authorizationHeader = "Authorization" -) - -// HTTPSigner is an interface to a SigV4 signer that can sign HTTP requests -type HTTPSigner interface { - SignHTTP(ctx context.Context, credentials aws.Credentials, r *http.Request, payloadHash string, service string, region string, signingTime time.Time, optFns ...func(*SignerOptions)) error -} - -type keyDerivator interface { - DeriveKey(credential aws.Credentials, service, region string, signingTime v4Internal.SigningTime) []byte -} - -// SignerOptions is the SigV4 Signer options. -type SignerOptions struct { - // Disables the Signer's moving HTTP header key/value pairs from the HTTP - // request header to the request's query string. This is most commonly used - // with pre-signed requests preventing headers from being added to the - // request's query string. - DisableHeaderHoisting bool - - // Disables the automatic escaping of the URI path of the request for the - // siganture's canonical string's path. For services that do not need additional - // escaping then use this to disable the signer escaping the path. - // - // S3 is an example of a service that does not need additional escaping. - // - // http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html - DisableURIPathEscaping bool - - // The logger to send log messages to. - Logger logging.Logger - - // Enable logging of signed requests. - // This will enable logging of the canonical request, the string to sign, and for presigning the subsequent - // presigned URL. - LogSigning bool -} - -// Signer applies AWS v4 signing to given request. Use this to sign requests -// that need to be signed with AWS V4 Signatures. -type Signer struct { - options SignerOptions - keyDerivator keyDerivator -} - -// NewSigner returns a new SigV4 Signer -func NewSigner(optFns ...func(signer *SignerOptions)) *Signer { - options := SignerOptions{} - - for _, fn := range optFns { - fn(&options) - } - - return &Signer{options: options, keyDerivator: v4Internal.NewSigningKeyDeriver()} -} - -type httpSigner struct { - Request *http.Request - ServiceName string - Region string - Time v4Internal.SigningTime - Credentials aws.Credentials - KeyDerivator keyDerivator - IsPreSign bool - - PayloadHash string - - DisableHeaderHoisting bool - DisableURIPathEscaping bool -} - -func (s *httpSigner) Build() (signedRequest, error) { - req := s.Request - - query := req.URL.Query() - headers := req.Header - - s.setRequiredSigningFields(headers, query) - - // Sort Each Query Key's Values - for key := range query { - sort.Strings(query[key]) - } - - v4Internal.SanitizeHostForHeader(req) - - credentialScope := s.buildCredentialScope() - credentialStr := s.Credentials.AccessKeyID + "/" + credentialScope - if s.IsPreSign { - query.Set(v4Internal.AmzCredentialKey, credentialStr) - } - - unsignedHeaders := headers - if s.IsPreSign && !s.DisableHeaderHoisting { - var urlValues url.Values - urlValues, unsignedHeaders = buildQuery(v4Internal.AllowedQueryHoisting, headers) - for k := range urlValues { - query[k] = urlValues[k] - } - } - - host := req.URL.Host - if len(req.Host) > 0 { - host = req.Host - } - - signedHeaders, signedHeadersStr, canonicalHeaderStr := s.buildCanonicalHeaders(host, v4Internal.IgnoredHeaders, unsignedHeaders, s.Request.ContentLength) - - if s.IsPreSign { - query.Set(v4Internal.AmzSignedHeadersKey, signedHeadersStr) - } - - var rawQuery strings.Builder - rawQuery.WriteString(strings.Replace(query.Encode(), "+", "%20", -1)) - - canonicalURI := v4Internal.GetURIPath(req.URL) - if !s.DisableURIPathEscaping { - canonicalURI = httpbinding.EscapePath(canonicalURI, false) - } - - canonicalString := s.buildCanonicalString( - req.Method, - canonicalURI, - rawQuery.String(), - signedHeadersStr, - canonicalHeaderStr, - ) - - strToSign := s.buildStringToSign(credentialScope, canonicalString) - signingSignature, err := s.buildSignature(strToSign) - if err != nil { - return signedRequest{}, err - } - - if s.IsPreSign { - rawQuery.WriteString("&X-Amz-Signature=") - rawQuery.WriteString(signingSignature) - } else { - headers[authorizationHeader] = append(headers[authorizationHeader][:0], buildAuthorizationHeader(credentialStr, signedHeadersStr, signingSignature)) - } - - req.URL.RawQuery = rawQuery.String() - - return signedRequest{ - Request: req, - SignedHeaders: signedHeaders, - CanonicalString: canonicalString, - StringToSign: strToSign, - PreSigned: s.IsPreSign, - }, nil -} - -func buildAuthorizationHeader(credentialStr, signedHeadersStr, signingSignature string) string { - const credential = "Credential=" - const signedHeaders = "SignedHeaders=" - const signature = "Signature=" - const commaSpace = ", " - - var parts strings.Builder - parts.Grow(len(signingAlgorithm) + 1 + - len(credential) + len(credentialStr) + 2 + - len(signedHeaders) + len(signedHeadersStr) + 2 + - len(signature) + len(signingSignature), - ) - parts.WriteString(signingAlgorithm) - parts.WriteRune(' ') - parts.WriteString(credential) - parts.WriteString(credentialStr) - parts.WriteString(commaSpace) - parts.WriteString(signedHeaders) - parts.WriteString(signedHeadersStr) - parts.WriteString(commaSpace) - parts.WriteString(signature) - parts.WriteString(signingSignature) - return parts.String() -} - -// SignHTTP signs AWS v4 requests with the provided payload hash, service name, region the -// request is made to, and time the request is signed at. The signTime allows -// you to specify that a request is signed for the future, and cannot be -// used until then. -// -// The payloadHash is the hex encoded SHA-256 hash of the request payload, and -// must be provided. Even if the request has no payload (aka body). If the -// request has no payload you should use the hex encoded SHA-256 of an empty -// string as the payloadHash value. -// -// "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" -// -// Some services such as Amazon S3 accept alternative values for the payload -// hash, such as "UNSIGNED-PAYLOAD" for requests where the body will not be -// included in the request signature. -// -// https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html -// -// Sign differs from Presign in that it will sign the request using HTTP -// header values. This type of signing is intended for http.Request values that -// will not be shared, or are shared in a way the header values on the request -// will not be lost. -// -// The passed in request will be modified in place. -func (s Signer) SignHTTP(ctx context.Context, credentials aws.Credentials, r *http.Request, payloadHash string, service string, region string, signingTime time.Time, optFns ...func(options *SignerOptions)) error { - options := s.options - - for _, fn := range optFns { - fn(&options) - } - - signer := &httpSigner{ - Request: r, - PayloadHash: payloadHash, - ServiceName: service, - Region: region, - Credentials: credentials, - Time: v4Internal.NewSigningTime(signingTime.UTC()), - DisableHeaderHoisting: options.DisableHeaderHoisting, - DisableURIPathEscaping: options.DisableURIPathEscaping, - KeyDerivator: s.keyDerivator, - } - - signedRequest, err := signer.Build() - if err != nil { - return err - } - - logSigningInfo(ctx, options, &signedRequest, false) - - return nil -} - -// PresignHTTP signs AWS v4 requests with the payload hash, service name, region -// the request is made to, and time the request is signed at. The signTime -// allows you to specify that a request is signed for the future, and cannot -// be used until then. -// -// Returns the signed URL and the map of HTTP headers that were included in the -// signature or an error if signing the request failed. For presigned requests -// these headers and their values must be included on the HTTP request when it -// is made. This is helpful to know what header values need to be shared with -// the party the presigned request will be distributed to. -// -// The payloadHash is the hex encoded SHA-256 hash of the request payload, and -// must be provided. Even if the request has no payload (aka body). If the -// request has no payload you should use the hex encoded SHA-256 of an empty -// string as the payloadHash value. -// -// "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" -// -// Some services such as Amazon S3 accept alternative values for the payload -// hash, such as "UNSIGNED-PAYLOAD" for requests where the body will not be -// included in the request signature. -// -// https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html -// -// PresignHTTP differs from SignHTTP in that it will sign the request using -// query string instead of header values. This allows you to share the -// Presigned Request's URL with third parties, or distribute it throughout your -// system with minimal dependencies. -// -// PresignHTTP will not set the expires time of the presigned request -// automatically. To specify the expire duration for a request add the -// "X-Amz-Expires" query parameter on the request with the value as the -// duration in seconds the presigned URL should be considered valid for. This -// parameter is not used by all AWS services, and is most notable used by -// Amazon S3 APIs. -// -// expires := 20 * time.Minute -// query := req.URL.Query() -// query.Set("X-Amz-Expires", strconv.FormatInt(int64(expires/time.Second), 10)) -// req.URL.RawQuery = query.Encode() -// -// This method does not modify the provided request. -func (s *Signer) PresignHTTP( - ctx context.Context, credentials aws.Credentials, r *http.Request, - payloadHash string, service string, region string, signingTime time.Time, - optFns ...func(*SignerOptions), -) (signedURI string, signedHeaders http.Header, err error) { - options := s.options - - for _, fn := range optFns { - fn(&options) - } - - signer := &httpSigner{ - Request: r.Clone(r.Context()), - PayloadHash: payloadHash, - ServiceName: service, - Region: region, - Credentials: credentials, - Time: v4Internal.NewSigningTime(signingTime.UTC()), - IsPreSign: true, - DisableHeaderHoisting: options.DisableHeaderHoisting, - DisableURIPathEscaping: options.DisableURIPathEscaping, - KeyDerivator: s.keyDerivator, - } - - signedRequest, err := signer.Build() - if err != nil { - return "", nil, err - } - - logSigningInfo(ctx, options, &signedRequest, true) - - signedHeaders = make(http.Header) - - // For the signed headers we canonicalize the header keys in the returned map. - // This avoids situations where can standard library double headers like host header. For example the standard - // library will set the Host header, even if it is present in lower-case form. - for k, v := range signedRequest.SignedHeaders { - key := textproto.CanonicalMIMEHeaderKey(k) - signedHeaders[key] = append(signedHeaders[key], v...) - } - - return signedRequest.Request.URL.String(), signedHeaders, nil -} - -func (s *httpSigner) buildCredentialScope() string { - return v4Internal.BuildCredentialScope(s.Time, s.Region, s.ServiceName) -} - -func buildQuery(r v4Internal.Rule, header http.Header) (url.Values, http.Header) { - query := url.Values{} - unsignedHeaders := http.Header{} - for k, h := range header { - if r.IsValid(k) { - query[k] = h - } else { - unsignedHeaders[k] = h - } - } - - return query, unsignedHeaders -} - -func (s *httpSigner) buildCanonicalHeaders(host string, rule v4Internal.Rule, header http.Header, length int64) (signed http.Header, signedHeaders, canonicalHeadersStr string) { - signed = make(http.Header) - - var headers []string - const hostHeader = "host" - headers = append(headers, hostHeader) - signed[hostHeader] = append(signed[hostHeader], host) - - const contentLengthHeader = "content-length" - if length > 0 { - headers = append(headers, contentLengthHeader) - signed[contentLengthHeader] = append(signed[contentLengthHeader], strconv.FormatInt(length, 10)) - } - - for k, v := range header { - if !rule.IsValid(k) { - continue // ignored header - } - if strings.EqualFold(k, contentLengthHeader) { - // prevent signing already handled content-length header. - continue - } - - lowerCaseKey := strings.ToLower(k) - if _, ok := signed[lowerCaseKey]; ok { - // include additional values - signed[lowerCaseKey] = append(signed[lowerCaseKey], v...) - continue - } - - headers = append(headers, lowerCaseKey) - signed[lowerCaseKey] = v - } - sort.Strings(headers) - - signedHeaders = strings.Join(headers, ";") - - var canonicalHeaders strings.Builder - n := len(headers) - const colon = ':' - for i := 0; i < n; i++ { - if headers[i] == hostHeader { - canonicalHeaders.WriteString(hostHeader) - canonicalHeaders.WriteRune(colon) - canonicalHeaders.WriteString(v4Internal.StripExcessSpaces(host)) - } else { - canonicalHeaders.WriteString(headers[i]) - canonicalHeaders.WriteRune(colon) - // Trim out leading, trailing, and dedup inner spaces from signed header values. - values := signed[headers[i]] - for j, v := range values { - cleanedValue := strings.TrimSpace(v4Internal.StripExcessSpaces(v)) - canonicalHeaders.WriteString(cleanedValue) - if j < len(values)-1 { - canonicalHeaders.WriteRune(',') - } - } - } - canonicalHeaders.WriteRune('\n') - } - canonicalHeadersStr = canonicalHeaders.String() - - return signed, signedHeaders, canonicalHeadersStr -} - -func (s *httpSigner) buildCanonicalString(method, uri, query, signedHeaders, canonicalHeaders string) string { - return strings.Join([]string{ - method, - uri, - query, - canonicalHeaders, - signedHeaders, - s.PayloadHash, - }, "\n") -} - -func (s *httpSigner) buildStringToSign(credentialScope, canonicalRequestString string) string { - return strings.Join([]string{ - signingAlgorithm, - s.Time.TimeFormat(), - credentialScope, - hex.EncodeToString(makeHash(sha256.New(), []byte(canonicalRequestString))), - }, "\n") -} - -func makeHash(hash hash.Hash, b []byte) []byte { - hash.Reset() - hash.Write(b) - return hash.Sum(nil) -} - -func (s *httpSigner) buildSignature(strToSign string) (string, error) { - key := s.KeyDerivator.DeriveKey(s.Credentials, s.ServiceName, s.Region, s.Time) - return hex.EncodeToString(v4Internal.HMACSHA256(key, []byte(strToSign))), nil -} - -func (s *httpSigner) setRequiredSigningFields(headers http.Header, query url.Values) { - amzDate := s.Time.TimeFormat() - - if s.IsPreSign { - query.Set(v4Internal.AmzAlgorithmKey, signingAlgorithm) - if sessionToken := s.Credentials.SessionToken; len(sessionToken) > 0 { - query.Set("X-Amz-Security-Token", sessionToken) - } - - query.Set(v4Internal.AmzDateKey, amzDate) - return - } - - headers[v4Internal.AmzDateKey] = append(headers[v4Internal.AmzDateKey][:0], amzDate) - - if len(s.Credentials.SessionToken) > 0 { - headers[v4Internal.AmzSecurityTokenKey] = append(headers[v4Internal.AmzSecurityTokenKey][:0], s.Credentials.SessionToken) - } -} - -func logSigningInfo(ctx context.Context, options SignerOptions, request *signedRequest, isPresign bool) { - if !options.LogSigning { - return - } - signedURLMsg := "" - if isPresign { - signedURLMsg = fmt.Sprintf(logSignedURLMsg, request.Request.URL.String()) - } - logger := logging.WithContext(ctx, options.Logger) - logger.Logf(logging.Debug, logSignInfoMsg, request.CanonicalString, request.StringToSign, signedURLMsg) -} - -type signedRequest struct { - Request *http.Request - SignedHeaders http.Header - CanonicalString string - StringToSign string - PreSigned bool -} - -const logSignInfoMsg = `Request Signature: ----[ CANONICAL STRING ]----------------------------- -%s ----[ STRING TO SIGN ]-------------------------------- -%s%s ------------------------------------------------------` -const logSignedURLMsg = ` ----[ SIGNED URL ]------------------------------------ -%s` diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/to_ptr.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/to_ptr.go deleted file mode 100644 index f3fc4d610..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/to_ptr.go +++ /dev/null @@ -1,297 +0,0 @@ -// Code generated by aws/generate.go DO NOT EDIT. - -package aws - -import ( - "github.com/aws/smithy-go/ptr" - "time" -) - -// Bool returns a pointer value for the bool value passed in. -func Bool(v bool) *bool { - return ptr.Bool(v) -} - -// BoolSlice returns a slice of bool pointers from the values -// passed in. -func BoolSlice(vs []bool) []*bool { - return ptr.BoolSlice(vs) -} - -// BoolMap returns a map of bool pointers from the values -// passed in. -func BoolMap(vs map[string]bool) map[string]*bool { - return ptr.BoolMap(vs) -} - -// Byte returns a pointer value for the byte value passed in. -func Byte(v byte) *byte { - return ptr.Byte(v) -} - -// ByteSlice returns a slice of byte pointers from the values -// passed in. -func ByteSlice(vs []byte) []*byte { - return ptr.ByteSlice(vs) -} - -// ByteMap returns a map of byte pointers from the values -// passed in. -func ByteMap(vs map[string]byte) map[string]*byte { - return ptr.ByteMap(vs) -} - -// String returns a pointer value for the string value passed in. -func String(v string) *string { - return ptr.String(v) -} - -// StringSlice returns a slice of string pointers from the values -// passed in. -func StringSlice(vs []string) []*string { - return ptr.StringSlice(vs) -} - -// StringMap returns a map of string pointers from the values -// passed in. -func StringMap(vs map[string]string) map[string]*string { - return ptr.StringMap(vs) -} - -// Int returns a pointer value for the int value passed in. -func Int(v int) *int { - return ptr.Int(v) -} - -// IntSlice returns a slice of int pointers from the values -// passed in. -func IntSlice(vs []int) []*int { - return ptr.IntSlice(vs) -} - -// IntMap returns a map of int pointers from the values -// passed in. -func IntMap(vs map[string]int) map[string]*int { - return ptr.IntMap(vs) -} - -// Int8 returns a pointer value for the int8 value passed in. -func Int8(v int8) *int8 { - return ptr.Int8(v) -} - -// Int8Slice returns a slice of int8 pointers from the values -// passed in. -func Int8Slice(vs []int8) []*int8 { - return ptr.Int8Slice(vs) -} - -// Int8Map returns a map of int8 pointers from the values -// passed in. -func Int8Map(vs map[string]int8) map[string]*int8 { - return ptr.Int8Map(vs) -} - -// Int16 returns a pointer value for the int16 value passed in. -func Int16(v int16) *int16 { - return ptr.Int16(v) -} - -// Int16Slice returns a slice of int16 pointers from the values -// passed in. -func Int16Slice(vs []int16) []*int16 { - return ptr.Int16Slice(vs) -} - -// Int16Map returns a map of int16 pointers from the values -// passed in. -func Int16Map(vs map[string]int16) map[string]*int16 { - return ptr.Int16Map(vs) -} - -// Int32 returns a pointer value for the int32 value passed in. -func Int32(v int32) *int32 { - return ptr.Int32(v) -} - -// Int32Slice returns a slice of int32 pointers from the values -// passed in. -func Int32Slice(vs []int32) []*int32 { - return ptr.Int32Slice(vs) -} - -// Int32Map returns a map of int32 pointers from the values -// passed in. -func Int32Map(vs map[string]int32) map[string]*int32 { - return ptr.Int32Map(vs) -} - -// Int64 returns a pointer value for the int64 value passed in. -func Int64(v int64) *int64 { - return ptr.Int64(v) -} - -// Int64Slice returns a slice of int64 pointers from the values -// passed in. -func Int64Slice(vs []int64) []*int64 { - return ptr.Int64Slice(vs) -} - -// Int64Map returns a map of int64 pointers from the values -// passed in. -func Int64Map(vs map[string]int64) map[string]*int64 { - return ptr.Int64Map(vs) -} - -// Uint returns a pointer value for the uint value passed in. -func Uint(v uint) *uint { - return ptr.Uint(v) -} - -// UintSlice returns a slice of uint pointers from the values -// passed in. -func UintSlice(vs []uint) []*uint { - return ptr.UintSlice(vs) -} - -// UintMap returns a map of uint pointers from the values -// passed in. -func UintMap(vs map[string]uint) map[string]*uint { - return ptr.UintMap(vs) -} - -// Uint8 returns a pointer value for the uint8 value passed in. -func Uint8(v uint8) *uint8 { - return ptr.Uint8(v) -} - -// Uint8Slice returns a slice of uint8 pointers from the values -// passed in. -func Uint8Slice(vs []uint8) []*uint8 { - return ptr.Uint8Slice(vs) -} - -// Uint8Map returns a map of uint8 pointers from the values -// passed in. -func Uint8Map(vs map[string]uint8) map[string]*uint8 { - return ptr.Uint8Map(vs) -} - -// Uint16 returns a pointer value for the uint16 value passed in. -func Uint16(v uint16) *uint16 { - return ptr.Uint16(v) -} - -// Uint16Slice returns a slice of uint16 pointers from the values -// passed in. -func Uint16Slice(vs []uint16) []*uint16 { - return ptr.Uint16Slice(vs) -} - -// Uint16Map returns a map of uint16 pointers from the values -// passed in. -func Uint16Map(vs map[string]uint16) map[string]*uint16 { - return ptr.Uint16Map(vs) -} - -// Uint32 returns a pointer value for the uint32 value passed in. -func Uint32(v uint32) *uint32 { - return ptr.Uint32(v) -} - -// Uint32Slice returns a slice of uint32 pointers from the values -// passed in. -func Uint32Slice(vs []uint32) []*uint32 { - return ptr.Uint32Slice(vs) -} - -// Uint32Map returns a map of uint32 pointers from the values -// passed in. -func Uint32Map(vs map[string]uint32) map[string]*uint32 { - return ptr.Uint32Map(vs) -} - -// Uint64 returns a pointer value for the uint64 value passed in. -func Uint64(v uint64) *uint64 { - return ptr.Uint64(v) -} - -// Uint64Slice returns a slice of uint64 pointers from the values -// passed in. -func Uint64Slice(vs []uint64) []*uint64 { - return ptr.Uint64Slice(vs) -} - -// Uint64Map returns a map of uint64 pointers from the values -// passed in. -func Uint64Map(vs map[string]uint64) map[string]*uint64 { - return ptr.Uint64Map(vs) -} - -// Float32 returns a pointer value for the float32 value passed in. -func Float32(v float32) *float32 { - return ptr.Float32(v) -} - -// Float32Slice returns a slice of float32 pointers from the values -// passed in. -func Float32Slice(vs []float32) []*float32 { - return ptr.Float32Slice(vs) -} - -// Float32Map returns a map of float32 pointers from the values -// passed in. -func Float32Map(vs map[string]float32) map[string]*float32 { - return ptr.Float32Map(vs) -} - -// Float64 returns a pointer value for the float64 value passed in. -func Float64(v float64) *float64 { - return ptr.Float64(v) -} - -// Float64Slice returns a slice of float64 pointers from the values -// passed in. -func Float64Slice(vs []float64) []*float64 { - return ptr.Float64Slice(vs) -} - -// Float64Map returns a map of float64 pointers from the values -// passed in. -func Float64Map(vs map[string]float64) map[string]*float64 { - return ptr.Float64Map(vs) -} - -// Time returns a pointer value for the time.Time value passed in. -func Time(v time.Time) *time.Time { - return ptr.Time(v) -} - -// TimeSlice returns a slice of time.Time pointers from the values -// passed in. -func TimeSlice(vs []time.Time) []*time.Time { - return ptr.TimeSlice(vs) -} - -// TimeMap returns a map of time.Time pointers from the values -// passed in. -func TimeMap(vs map[string]time.Time) map[string]*time.Time { - return ptr.TimeMap(vs) -} - -// Duration returns a pointer value for the time.Duration value passed in. -func Duration(v time.Duration) *time.Duration { - return ptr.Duration(v) -} - -// DurationSlice returns a slice of time.Duration pointers from the values -// passed in. -func DurationSlice(vs []time.Duration) []*time.Duration { - return ptr.DurationSlice(vs) -} - -// DurationMap returns a map of time.Duration pointers from the values -// passed in. -func DurationMap(vs map[string]time.Duration) map[string]*time.Duration { - return ptr.DurationMap(vs) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/client.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/client.go deleted file mode 100644 index 26d90719b..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/client.go +++ /dev/null @@ -1,310 +0,0 @@ -package http - -import ( - "crypto/tls" - "github.com/aws/aws-sdk-go-v2/aws" - "net" - "net/http" - "reflect" - "sync" - "time" -) - -// Defaults for the HTTPTransportBuilder. -var ( - // Default connection pool options - DefaultHTTPTransportMaxIdleConns = 100 - DefaultHTTPTransportMaxIdleConnsPerHost = 10 - - // Default connection timeouts - DefaultHTTPTransportIdleConnTimeout = 90 * time.Second - DefaultHTTPTransportTLSHandleshakeTimeout = 10 * time.Second - DefaultHTTPTransportExpectContinueTimeout = 1 * time.Second - - // Default to TLS 1.2 for all HTTPS requests. - DefaultHTTPTransportTLSMinVersion uint16 = tls.VersionTLS12 -) - -// Timeouts for net.Dialer's network connection. -var ( - DefaultDialConnectTimeout = 30 * time.Second - DefaultDialKeepAliveTimeout = 30 * time.Second -) - -// BuildableClient provides a HTTPClient implementation with options to -// create copies of the HTTPClient when additional configuration is provided. -// -// The client's methods will not share the http.Transport value between copies -// of the BuildableClient. Only exported member values of the Transport and -// optional Dialer will be copied between copies of BuildableClient. -type BuildableClient struct { - transport *http.Transport - dialer *net.Dialer - - initOnce sync.Once - - clientTimeout time.Duration - client *http.Client -} - -// NewBuildableClient returns an initialized client for invoking HTTP -// requests. -func NewBuildableClient() *BuildableClient { - return &BuildableClient{} -} - -// Do implements the HTTPClient interface's Do method to invoke a HTTP request, -// and receive the response. Uses the BuildableClient's current -// configuration to invoke the http.Request. -// -// If connection pooling is enabled (aka HTTP KeepAlive) the client will only -// share pooled connections with its own instance. Copies of the -// BuildableClient will have their own connection pools. -// -// Redirect (3xx) responses will not be followed, the HTTP response received -// will returned instead. -func (b *BuildableClient) Do(req *http.Request) (*http.Response, error) { - b.initOnce.Do(b.build) - - return b.client.Do(req) -} - -// Freeze returns a frozen aws.HTTPClient implementation that is no longer a BuildableClient. -// Use this to prevent the SDK from applying DefaultMode configuration values to a buildable client. -func (b *BuildableClient) Freeze() aws.HTTPClient { - cpy := b.clone() - cpy.build() - return cpy.client -} - -func (b *BuildableClient) build() { - b.client = wrapWithLimitedRedirect(&http.Client{ - Timeout: b.clientTimeout, - Transport: b.GetTransport(), - }) -} - -func (b *BuildableClient) clone() *BuildableClient { - cpy := NewBuildableClient() - cpy.transport = b.GetTransport() - cpy.dialer = b.GetDialer() - cpy.clientTimeout = b.clientTimeout - - return cpy -} - -// WithTransportOptions copies the BuildableClient and returns it with the -// http.Transport options applied. -// -// If a non (*http.Transport) was set as the round tripper, the round tripper -// will be replaced with a default Transport value before invoking the option -// functions. -func (b *BuildableClient) WithTransportOptions(opts ...func(*http.Transport)) *BuildableClient { - cpy := b.clone() - - tr := cpy.GetTransport() - for _, opt := range opts { - opt(tr) - } - cpy.transport = tr - - return cpy -} - -// WithDialerOptions copies the BuildableClient and returns it with the -// net.Dialer options applied. Will set the client's http.Transport DialContext -// member. -func (b *BuildableClient) WithDialerOptions(opts ...func(*net.Dialer)) *BuildableClient { - cpy := b.clone() - - dialer := cpy.GetDialer() - for _, opt := range opts { - opt(dialer) - } - cpy.dialer = dialer - - tr := cpy.GetTransport() - tr.DialContext = cpy.dialer.DialContext - cpy.transport = tr - - return cpy -} - -// WithTimeout Sets the timeout used by the client for all requests. -func (b *BuildableClient) WithTimeout(timeout time.Duration) *BuildableClient { - cpy := b.clone() - cpy.clientTimeout = timeout - return cpy -} - -// GetTransport returns a copy of the client's HTTP Transport. -func (b *BuildableClient) GetTransport() *http.Transport { - var tr *http.Transport - if b.transport != nil { - tr = b.transport.Clone() - } else { - tr = defaultHTTPTransport() - } - - return tr -} - -// GetDialer returns a copy of the client's network dialer. -func (b *BuildableClient) GetDialer() *net.Dialer { - var dialer *net.Dialer - if b.dialer != nil { - dialer = shallowCopyStruct(b.dialer).(*net.Dialer) - } else { - dialer = defaultDialer() - } - - return dialer -} - -// GetTimeout returns a copy of the client's timeout to cancel requests with. -func (b *BuildableClient) GetTimeout() time.Duration { - return b.clientTimeout -} - -func defaultDialer() *net.Dialer { - return &net.Dialer{ - Timeout: DefaultDialConnectTimeout, - KeepAlive: DefaultDialKeepAliveTimeout, - DualStack: true, - } -} - -func defaultHTTPTransport() *http.Transport { - dialer := defaultDialer() - - tr := &http.Transport{ - Proxy: http.ProxyFromEnvironment, - DialContext: dialer.DialContext, - TLSHandshakeTimeout: DefaultHTTPTransportTLSHandleshakeTimeout, - MaxIdleConns: DefaultHTTPTransportMaxIdleConns, - MaxIdleConnsPerHost: DefaultHTTPTransportMaxIdleConnsPerHost, - IdleConnTimeout: DefaultHTTPTransportIdleConnTimeout, - ExpectContinueTimeout: DefaultHTTPTransportExpectContinueTimeout, - ForceAttemptHTTP2: true, - TLSClientConfig: &tls.Config{ - MinVersion: DefaultHTTPTransportTLSMinVersion, - }, - } - - return tr -} - -// shallowCopyStruct creates a shallow copy of the passed in source struct, and -// returns that copy of the same struct type. -func shallowCopyStruct(src interface{}) interface{} { - srcVal := reflect.ValueOf(src) - srcValType := srcVal.Type() - - var returnAsPtr bool - if srcValType.Kind() == reflect.Ptr { - srcVal = srcVal.Elem() - srcValType = srcValType.Elem() - returnAsPtr = true - } - dstVal := reflect.New(srcValType).Elem() - - for i := 0; i < srcValType.NumField(); i++ { - ft := srcValType.Field(i) - if len(ft.PkgPath) != 0 { - // unexported fields have a PkgPath - continue - } - - dstVal.Field(i).Set(srcVal.Field(i)) - } - - if returnAsPtr { - dstVal = dstVal.Addr() - } - - return dstVal.Interface() -} - -// wrapWithLimitedRedirect updates the Client's Transport and CheckRedirect to -// not follow any redirect other than 307 and 308. No other redirect will be -// followed. -// -// If the client does not have a Transport defined will use a new SDK default -// http.Transport configuration. -func wrapWithLimitedRedirect(c *http.Client) *http.Client { - tr := c.Transport - if tr == nil { - tr = defaultHTTPTransport() - } - - cc := *c - cc.CheckRedirect = limitedRedirect - cc.Transport = suppressBadHTTPRedirectTransport{ - tr: tr, - } - - return &cc -} - -// limitedRedirect is a CheckRedirect that prevents the client from following -// any non 307/308 HTTP status code redirects. -// -// The 307 and 308 redirects are allowed because the client must use the -// original HTTP method for the redirected to location. Whereas 301 and 302 -// allow the client to switch to GET for the redirect. -// -// Suppresses all redirect requests with a URL of badHTTPRedirectLocation. -func limitedRedirect(r *http.Request, via []*http.Request) error { - // Request.Response, in CheckRedirect is the response that is triggering - // the redirect. - resp := r.Response - if r.URL.String() == badHTTPRedirectLocation { - resp.Header.Del(badHTTPRedirectLocation) - return http.ErrUseLastResponse - } - - switch resp.StatusCode { - case 307, 308: - // Only allow 307 and 308 redirects as they preserve the method. - return nil - } - - return http.ErrUseLastResponse -} - -// suppressBadHTTPRedirectTransport provides an http.RoundTripper -// implementation that wraps another http.RoundTripper to prevent HTTP client -// receiving 301 and 302 HTTP responses redirects without the required location -// header. -// -// Clients using this utility must have a CheckRedirect, e.g. limitedRedirect, -// that check for responses with having a URL of baseHTTPRedirectLocation, and -// suppress the redirect. -type suppressBadHTTPRedirectTransport struct { - tr http.RoundTripper -} - -const badHTTPRedirectLocation = `https://amazonaws.com/badhttpredirectlocation` - -// RoundTrip backfills a stub location when a 301/302 response is received -// without a location. This stub location is used by limitedRedirect to prevent -// the HTTP client from failing attempting to use follow a redirect without a -// location value. -func (t suppressBadHTTPRedirectTransport) RoundTrip(r *http.Request) (*http.Response, error) { - resp, err := t.tr.RoundTrip(r) - if err != nil { - return resp, err - } - - // S3 is the only known service to return 301 without location header. - // The Go standard library HTTP client will return an opaque error if it - // tries to follow a 301/302 response missing the location header. - switch resp.StatusCode { - case 301, 302: - if v := resp.Header.Get("Location"); len(v) == 0 { - resp.Header.Set("Location", badHTTPRedirectLocation) - } - } - - return resp, err -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/content_type.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/content_type.go deleted file mode 100644 index 556f54a7f..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/content_type.go +++ /dev/null @@ -1,42 +0,0 @@ -package http - -import ( - "context" - "fmt" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// removeContentTypeHeader is a build middleware that removes -// content type header if content-length header is unset or -// is set to zero, -type removeContentTypeHeader struct { -} - -// ID the name of the middleware. -func (m *removeContentTypeHeader) ID() string { - return "RemoveContentTypeHeader" -} - -// HandleBuild adds or appends the constructed user agent to the request. -func (m *removeContentTypeHeader) HandleBuild(ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler) ( - out middleware.BuildOutput, metadata middleware.Metadata, err error, -) { - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in) - } - - // remove contentTypeHeader when content-length is zero - if req.ContentLength == 0 { - req.Header.Del("content-type") - } - - return next.HandleBuild(ctx, in) -} - -// RemoveContentTypeHeader removes content-type header if -// content length is unset or equal to zero. -func RemoveContentTypeHeader(stack *middleware.Stack) error { - return stack.Build.Add(&removeContentTypeHeader{}, middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/response_error.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/response_error.go deleted file mode 100644 index 44651c990..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/response_error.go +++ /dev/null @@ -1,33 +0,0 @@ -package http - -import ( - "errors" - "fmt" - - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// ResponseError provides the HTTP centric error type wrapping the underlying error -// with the HTTP response value and the deserialized RequestID. -type ResponseError struct { - *smithyhttp.ResponseError - - // RequestID associated with response error - RequestID string -} - -// ServiceRequestID returns the request id associated with Response Error -func (e *ResponseError) ServiceRequestID() string { return e.RequestID } - -// Error returns the formatted error -func (e *ResponseError) Error() string { - return fmt.Sprintf( - "https response error StatusCode: %d, RequestID: %s, %v", - e.Response.StatusCode, e.RequestID, e.Err) -} - -// As populates target and returns true if the type of target is a error type that -// the ResponseError embeds, (e.g.AWS HTTP ResponseError) -func (e *ResponseError) As(target interface{}) bool { - return errors.As(e.ResponseError, target) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/response_error_middleware.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/response_error_middleware.go deleted file mode 100644 index 8fd14cecd..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/response_error_middleware.go +++ /dev/null @@ -1,54 +0,0 @@ -package http - -import ( - "context" - - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// AddResponseErrorMiddleware adds response error wrapper middleware -func AddResponseErrorMiddleware(stack *middleware.Stack) error { - // add error wrapper middleware before request id retriever middleware so that it can wrap the error response - // returned by operation deserializers - return stack.Deserialize.Insert(&responseErrorWrapper{}, "RequestIDRetriever", middleware.Before) -} - -type responseErrorWrapper struct { -} - -// ID returns the middleware identifier -func (m *responseErrorWrapper) ID() string { - return "ResponseErrorWrapper" -} - -func (m *responseErrorWrapper) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( - out middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err = next.HandleDeserialize(ctx, in) - if err == nil { - // Nothing to do when there is no error. - return out, metadata, err - } - - resp, ok := out.RawResponse.(*smithyhttp.Response) - if !ok { - // No raw response to wrap with. - return out, metadata, err - } - - // look for request id in metadata - reqID, _ := awsmiddleware.GetRequestIDMetadata(metadata) - - // Wrap the returned smithy error with the request id retrieved from the metadata - err = &ResponseError{ - ResponseError: &smithyhttp.ResponseError{ - Response: resp, - Err: err, - }, - RequestID: reqID, - } - - return out, metadata, err -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/timeout_read_closer.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/timeout_read_closer.go deleted file mode 100644 index 993929bd9..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/timeout_read_closer.go +++ /dev/null @@ -1,104 +0,0 @@ -package http - -import ( - "context" - "fmt" - "io" - "time" - - "github.com/aws/smithy-go" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -type readResult struct { - n int - err error -} - -// ResponseTimeoutError is an error when the reads from the response are -// delayed longer than the timeout the read was configured for. -type ResponseTimeoutError struct { - TimeoutDur time.Duration -} - -// Timeout returns that the error is was caused by a timeout, and can be -// retried. -func (*ResponseTimeoutError) Timeout() bool { return true } - -func (e *ResponseTimeoutError) Error() string { - return fmt.Sprintf("read on body reach timeout limit, %v", e.TimeoutDur) -} - -// timeoutReadCloser will handle body reads that take too long. -// We will return a ErrReadTimeout error if a timeout occurs. -type timeoutReadCloser struct { - reader io.ReadCloser - duration time.Duration -} - -// Read will spin off a goroutine to call the reader's Read method. We will -// select on the timer's channel or the read's channel. Whoever completes first -// will be returned. -func (r *timeoutReadCloser) Read(b []byte) (int, error) { - timer := time.NewTimer(r.duration) - c := make(chan readResult, 1) - - go func() { - n, err := r.reader.Read(b) - timer.Stop() - c <- readResult{n: n, err: err} - }() - - select { - case data := <-c: - return data.n, data.err - case <-timer.C: - return 0, &ResponseTimeoutError{TimeoutDur: r.duration} - } -} - -func (r *timeoutReadCloser) Close() error { - return r.reader.Close() -} - -// AddResponseReadTimeoutMiddleware adds a middleware to the stack that wraps the -// response body so that a read that takes too long will return an error. -func AddResponseReadTimeoutMiddleware(stack *middleware.Stack, duration time.Duration) error { - return stack.Deserialize.Add(&readTimeout{duration: duration}, middleware.After) -} - -// readTimeout wraps the response body with a timeoutReadCloser -type readTimeout struct { - duration time.Duration -} - -// ID returns the id of the middleware -func (*readTimeout) ID() string { - return "ReadResponseTimeout" -} - -// HandleDeserialize implements the DeserializeMiddleware interface -func (m *readTimeout) HandleDeserialize( - ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler, -) ( - out middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err = next.HandleDeserialize(ctx, in) - if err != nil { - return out, metadata, err - } - - response, ok := out.RawResponse.(*smithyhttp.Response) - if !ok { - return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} - } - - response.Body = &timeoutReadCloser{ - reader: response.Body, - duration: m.duration, - } - out.RawResponse = response - - return out, metadata, err -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/types.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/types.go deleted file mode 100644 index cc3ae8114..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/types.go +++ /dev/null @@ -1,42 +0,0 @@ -package aws - -import ( - "fmt" -) - -// Ternary is an enum allowing an unknown or none state in addition to a bool's -// true and false. -type Ternary int - -func (t Ternary) String() string { - switch t { - case UnknownTernary: - return "unknown" - case FalseTernary: - return "false" - case TrueTernary: - return "true" - default: - return fmt.Sprintf("unknown value, %d", int(t)) - } -} - -// Bool returns true if the value is TrueTernary, false otherwise. -func (t Ternary) Bool() bool { - return t == TrueTernary -} - -// Enumerations for the values of the Ternary type. -const ( - UnknownTernary Ternary = iota - FalseTernary - TrueTernary -) - -// BoolTernary returns a true or false Ternary value for the bool provided. -func BoolTernary(v bool) Ternary { - if v { - return TrueTernary - } - return FalseTernary -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/version.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/version.go deleted file mode 100644 index 5f729d45e..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/version.go +++ /dev/null @@ -1,8 +0,0 @@ -// Package aws provides core functionality for making requests to AWS services. -package aws - -// SDKName is the name of this AWS SDK -const SDKName = "aws-sdk-go-v2" - -// SDKVersion is the version of this SDK -const SDKVersion = goModuleVersion diff --git a/vendor/github.com/aws/aws-sdk-go-v2/buildspec.yml b/vendor/github.com/aws/aws-sdk-go-v2/buildspec.yml deleted file mode 100644 index b11df5082..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/buildspec.yml +++ /dev/null @@ -1,12 +0,0 @@ -version: 0.2 - -phases: - build: - commands: - - echo Build started on `date` - - export GOPATH=/go - - export SDK_CODEBUILD_ROOT=`pwd` - - make ci-test-no-generate - post_build: - commands: - - echo Build completed on `date` diff --git a/vendor/github.com/aws/aws-sdk-go-v2/ci-find-smithy-go.sh b/vendor/github.com/aws/aws-sdk-go-v2/ci-find-smithy-go.sh deleted file mode 100644 index 9b8f3a3d2..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/ci-find-smithy-go.sh +++ /dev/null @@ -1,58 +0,0 @@ -#!/bin/bash - -# looks for (and modreplaces if existing) a smithy-go branch matching the -# current branch name -# -# the loop will unfurl -*s off of the branch, e.g. sdk branch -# 'feat-foo-bar-baz' will match any of the following (in order): -# - feat-foo-bar-baz -# - feat-foo-bar -# - feat-foo - -if [ -z "$SMITHY_GO_REPOSITORY" ]; then - SMITHY_GO_REPOSITORY=aws/smithy-go -fi - -if [ -z "$RUNNER_TMPDIR" ]; then - echo env RUNNER_TMPDIR is required - exit 1 -fi - -branch=`git branch --show-current` -if [ "$branch" == main ]; then - echo aws-sdk-go-v2 is on branch main, stop - exit 0 -fi - -# For PR workflows, only the triggering ref is checked out, which in isolation -# is not recognized as a branch by git. Use the specific workflow env instead. -if [ -z "$branch" ]; then - branch=$GITHUB_HEAD_REF -fi - -if [ -n "$GIT_PAT" ]; then - repository=https://$GIT_PAT@github.com/$SMITHY_GO_REPOSITORY -else - repository=https://github.com/$SMITHY_GO_REPOSITORY -fi - -echo on branch \"$branch\" -while [ -n "$branch" ] && [[ "$branch" == *-* ]]; do - echo looking for $branch... - git ls-remote --exit-code --heads $repository refs/heads/$branch - if [ "$?" == 0 ]; then - echo found $branch - matched_branch=$branch - break - fi - - branch=${branch%-*} -done - -if [ -z "$matched_branch" ]; then - echo found no matching smithy-go branch, stop - exit 0 -fi - -git clone -b $matched_branch $repository $RUNNER_TMPDIR/smithy-go -SMITHY_GO_SRC=$RUNNER_TMPDIR/smithy-go make gen-mod-replace-smithy-. diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/config/CHANGELOG.md deleted file mode 100644 index 774040216..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/CHANGELOG.md +++ /dev/null @@ -1,399 +0,0 @@ -# v1.18.37 (2023-08-23) - -* No change notes available for this release. - -# v1.18.36 (2023-08-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.35 (2023-08-18) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.34 (2023-08-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.33 (2023-08-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.32 (2023-08-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.31 (2023-07-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.30 (2023-07-28) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.29 (2023-07-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.28 (2023-07-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.27 (2023-06-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.26 (2023-06-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.25 (2023-05-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.24 (2023-05-08) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.23 (2023-05-04) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.22 (2023-04-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.21 (2023-04-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.20 (2023-04-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.19 (2023-03-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.18 (2023-03-16) - -* **Bug Fix**: Allow RoleARN to be set as functional option on STS WebIdentityRoleOptions. Fixes aws/aws-sdk-go-v2#2015. - -# v1.18.17 (2023-03-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.16 (2023-03-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.15 (2023-02-22) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.14 (2023-02-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.13 (2023-02-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.12 (2023-02-03) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.11 (2023-02-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.10 (2023-01-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.9 (2023-01-23) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.8 (2023-01-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.7 (2022-12-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.6 (2022-12-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.5 (2022-12-15) - -* **Bug Fix**: Unify logic between shared config and in finding home directory -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.4 (2022-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.3 (2022-11-22) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.2 (2022-11-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.1 (2022-11-16) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.0 (2022-11-11) - -* **Announcement**: When using the SSOTokenProvider, a previous implementation incorrectly compensated for invalid SSOTokenProvider configurations in the shared profile. This has been fixed via PR #1903 and tracked in issue #1846 -* **Feature**: Adds token refresh support (via SSOTokenProvider) when using the SSOCredentialProvider -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.11 (2022-11-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.10 (2022-10-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.9 (2022-10-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.8 (2022-09-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.7 (2022-09-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.6 (2022-09-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.5 (2022-09-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.4 (2022-08-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.3 (2022-08-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.2 (2022-08-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.1 (2022-08-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.0 (2022-08-14) - -* **Feature**: Add alternative mechanism for determning the users `$HOME` or `%USERPROFILE%` location when the environment variables are not present. - -# v1.16.1 (2022-08-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.0 (2022-08-10) - -* **Feature**: Adds support for the following settings in the `~/.aws/credentials` file: `sso_account_id`, `sso_region`, `sso_role_name`, `sso_start_url`, and `ca_bundle`. - -# v1.15.17 (2022-08-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.16 (2022-08-08) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.15 (2022-08-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.14 (2022-07-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.13 (2022-07-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.12 (2022-06-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.11 (2022-06-16) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.10 (2022-06-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.9 (2022-05-26) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.8 (2022-05-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.7 (2022-05-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.6 (2022-05-16) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.5 (2022-05-09) - -* **Bug Fix**: Fixes a bug in LoadDefaultConfig to correctly assign ConfigSources so all config resolvers have access to the config sources. This fixes the feature/ec2/imds client not having configuration applied via config.LoadOptions such as EC2IMDSClientEnableState. PR [#1682](https://github.com/aws/aws-sdk-go-v2/pull/1682) - -# v1.15.4 (2022-04-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.3 (2022-03-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.2 (2022-03-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.1 (2022-03-23) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.0 (2022-03-08) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.0 (2022-02-24) - -* **Feature**: Adds support for loading RetryMaxAttempts and RetryMod from the environment and shared configuration files. These parameters drive how the SDK's API client will initialize its default retryer, if custome retryer has not been specified. See [config](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/config) module and [aws.Config](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/aws#Config) for more information about and how to use these new options. -* **Feature**: Adds support for the `ca_bundle` parameter in shared config and credentials files. The usage of the file is the same as environment variable, `AWS_CA_BUNDLE`, but sourced from shared config. Fixes [#1589](https://github.com/aws/aws-sdk-go-v2/issues/1589) -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.1 (2022-01-28) - -* **Bug Fix**: Fixes LoadDefaultConfig handling of errors returned by passed in functional options. Previously errors returned from the LoadOptions passed into LoadDefaultConfig were incorrectly ignored. [#1562](https://github.com/aws/aws-sdk-go-v2/pull/1562). Thanks to [Pinglei Guo](https://github.com/pingleig) for submitting this PR. -* **Bug Fix**: Fixes the SDK's handling of `duration_sections` in the shared credentials file or specified in multiple shared config and shared credentials files under the same profile. [#1568](https://github.com/aws/aws-sdk-go-v2/pull/1568). Thanks to [Amir Szekely](https://github.com/kichik) for help reproduce this bug. -* **Bug Fix**: Updates `config` module to use os.UserHomeDir instead of hard coded environment variable for OS. [#1563](https://github.com/aws/aws-sdk-go-v2/pull/1563) -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.0 (2022-01-14) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.0 (2022-01-07) - -* **Feature**: Add load option for CredentialCache. Adds a new member to the LoadOptions struct, CredentialsCacheOptions. This member allows specifying a function that will be used to configure the CredentialsCache. The CredentialsCacheOptions will only be used if the configuration loader will wrap the underlying credential provider in the CredentialsCache. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.1 (2021-12-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.0 (2021-12-02) - -* **Feature**: Add support for specifying `EndpointResolverWithOptions` on `LoadOptions`, and associated `WithEndpointResolverWithOptions`. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.3 (2021-11-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.2 (2021-11-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.1 (2021-11-12) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.0 (2021-11-06) - -* **Feature**: The SDK now supports configuration of FIPS and DualStack endpoints using environment variables, shared configuration, or programmatically. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.0 (2021-10-21) - -* **Feature**: Updated to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.3 (2021-10-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.2 (2021-09-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.1 (2021-09-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.0 (2021-09-02) - -* **Feature**: Add support for S3 Multi-Region Access Point ARNs. - -# v1.7.0 (2021-08-27) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.1 (2021-08-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.0 (2021-08-04) - -* **Feature**: adds error handling for defered close calls -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.5.0 (2021-07-15) - -* **Feature**: Support has been added for EC2 IPv6-enabled Instance Metadata Service Endpoints. -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.1 (2021-07-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.0 (2021-06-25) - -* **Feature**: Adds configuration setting for enabling endpoint discovery. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.0 (2021-05-20) - -* **Feature**: SSO credentials can now be defined alongside other credential providers within the same configuration profile. -* **Bug Fix**: Profile names were incorrectly normalized to lower-case, which could result in unexpected profile configurations. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.0 (2021-05-14) - -* **Feature**: Constant has been added to modules to enable runtime version inspection for reporting. -* **Dependency Update**: Updated to the latest SDK module versions - diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/config/LICENSE.txt deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/LICENSE.txt +++ /dev/null @@ -1,202 +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/aws/aws-sdk-go-v2/config/config.go b/vendor/github.com/aws/aws-sdk-go-v2/config/config.go deleted file mode 100644 index 138f8e76d..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/config.go +++ /dev/null @@ -1,204 +0,0 @@ -package config - -import ( - "context" - - "github.com/aws/aws-sdk-go-v2/aws" -) - -// defaultLoaders are a slice of functions that will read external configuration -// sources for configuration values. These values are read by the AWSConfigResolvers -// using interfaces to extract specific information from the external configuration. -var defaultLoaders = []loader{ - loadEnvConfig, - loadSharedConfigIgnoreNotExist, -} - -// defaultAWSConfigResolvers are a slice of functions that will resolve external -// configuration values into AWS configuration values. -// -// This will setup the AWS configuration's Region, -var defaultAWSConfigResolvers = []awsConfigResolver{ - // Resolves the default configuration the SDK's aws.Config will be - // initialized with. - resolveDefaultAWSConfig, - - // Sets the logger to be used. Could be user provided logger, and client - // logging mode. - resolveLogger, - resolveClientLogMode, - - // Sets the HTTP client and configuration to use for making requests using - // the HTTP transport. - resolveHTTPClient, - resolveCustomCABundle, - - // Sets the endpoint resolving behavior the API Clients will use for making - // requests to. Clients default to their own clients this allows overrides - // to be specified. The resolveEndpointResolver option is deprecated, but - // we still need to set it for backwards compatibility on config - // construction. - resolveEndpointResolver, - resolveEndpointResolverWithOptions, - - // Sets the retry behavior API clients will use within their retry attempt - // middleware. Defaults to unset, allowing API clients to define their own - // retry behavior. - resolveRetryer, - - // Sets the region the API Clients should use for making requests to. - resolveRegion, - resolveEC2IMDSRegion, - resolveDefaultRegion, - - // Sets the additional set of middleware stack mutators that will custom - // API client request pipeline middleware. - resolveAPIOptions, - - // Resolves the DefaultsMode that should be used by SDK clients. If this - // mode is set to DefaultsModeAuto. - // - // Comes after HTTPClient and CustomCABundle to ensure the HTTP client is - // configured if provided before invoking IMDS if mode is auto. Comes - // before resolving credentials so that those subsequent clients use the - // configured auto mode. - resolveDefaultsModeOptions, - - // Sets the resolved credentials the API clients will use for - // authentication. Provides the SDK's default credential chain. - // - // Should probably be the last step in the resolve chain to ensure that all - // other configurations are resolved first in case downstream credentials - // implementations depend on or can be configured with earlier resolved - // configuration options. - resolveCredentials, - - // Sets the resolved bearer authentication token API clients will use for - // httpBearerAuth authentication scheme. - resolveBearerAuthToken, - - // Sets the sdk app ID if present in shared config profile - resolveAppID, -} - -// A Config represents a generic configuration value or set of values. This type -// will be used by the AWSConfigResolvers to extract -// -// General the Config type will use type assertion against the Provider interfaces -// to extract specific data from the Config. -type Config interface{} - -// A loader is used to load external configuration data and returns it as -// a generic Config type. -// -// The loader should return an error if it fails to load the external configuration -// or the configuration data is malformed, or required components missing. -type loader func(context.Context, configs) (Config, error) - -// An awsConfigResolver will extract configuration data from the configs slice -// using the provider interfaces to extract specific functionality. The extracted -// configuration values will be written to the AWS Config value. -// -// The resolver should return an error if it it fails to extract the data, the -// data is malformed, or incomplete. -type awsConfigResolver func(ctx context.Context, cfg *aws.Config, configs configs) error - -// configs is a slice of Config values. These values will be used by the -// AWSConfigResolvers to extract external configuration values to populate the -// AWS Config type. -// -// Use AppendFromLoaders to add additional external Config values that are -// loaded from external sources. -// -// Use ResolveAWSConfig after external Config values have been added or loaded -// to extract the loaded configuration values into the AWS Config. -type configs []Config - -// AppendFromLoaders iterates over the slice of loaders passed in calling each -// loader function in order. The external config value returned by the loader -// will be added to the returned configs slice. -// -// If a loader returns an error this method will stop iterating and return -// that error. -func (cs configs) AppendFromLoaders(ctx context.Context, loaders []loader) (configs, error) { - for _, fn := range loaders { - cfg, err := fn(ctx, cs) - if err != nil { - return nil, err - } - - cs = append(cs, cfg) - } - - return cs, nil -} - -// ResolveAWSConfig returns a AWS configuration populated with values by calling -// the resolvers slice passed in. Each resolver is called in order. Any resolver -// may overwrite the AWS Configuration value of a previous resolver. -// -// If an resolver returns an error this method will return that error, and stop -// iterating over the resolvers. -func (cs configs) ResolveAWSConfig(ctx context.Context, resolvers []awsConfigResolver) (aws.Config, error) { - var cfg aws.Config - - for _, fn := range resolvers { - if err := fn(ctx, &cfg, cs); err != nil { - return aws.Config{}, err - } - } - - return cfg, nil -} - -// ResolveConfig calls the provide function passing slice of configuration sources. -// This implements the aws.ConfigResolver interface. -func (cs configs) ResolveConfig(f func(configs []interface{}) error) error { - var cfgs []interface{} - for i := range cs { - cfgs = append(cfgs, cs[i]) - } - return f(cfgs) -} - -// LoadDefaultConfig reads the SDK's default external configurations, and -// populates an AWS Config with the values from the external configurations. -// -// An optional variadic set of additional Config values can be provided as input -// that will be prepended to the configs slice. Use this to add custom configuration. -// The custom configurations must satisfy the respective providers for their data -// or the custom data will be ignored by the resolvers and config loaders. -// -// cfg, err := config.LoadDefaultConfig( context.TODO(), -// WithSharedConfigProfile("test-profile"), -// ) -// if err != nil { -// panic(fmt.Sprintf("failed loading config, %v", err)) -// } -// -// The default configuration sources are: -// * Environment Variables -// * Shared Configuration and Shared Credentials files. -func LoadDefaultConfig(ctx context.Context, optFns ...func(*LoadOptions) error) (cfg aws.Config, err error) { - var options LoadOptions - for _, optFn := range optFns { - if err := optFn(&options); err != nil { - return aws.Config{}, err - } - } - - // assign Load Options to configs - var cfgCpy = configs{options} - - cfgCpy, err = cfgCpy.AppendFromLoaders(ctx, defaultLoaders) - if err != nil { - return aws.Config{}, err - } - - cfg, err = cfgCpy.ResolveAWSConfig(ctx, defaultAWSConfigResolvers) - if err != nil { - return aws.Config{}, err - } - - return cfg, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/defaultsmode.go b/vendor/github.com/aws/aws-sdk-go-v2/config/defaultsmode.go deleted file mode 100644 index 20b66367f..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/defaultsmode.go +++ /dev/null @@ -1,47 +0,0 @@ -package config - -import ( - "context" - "os" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/feature/ec2/imds" -) - -const execEnvVar = "AWS_EXECUTION_ENV" - -// DefaultsModeOptions is the set of options that are used to configure -type DefaultsModeOptions struct { - // The SDK configuration defaults mode. Defaults to legacy if not specified. - // - // Supported modes are: auto, cross-region, in-region, legacy, mobile, standard - Mode aws.DefaultsMode - - // The EC2 Instance Metadata Client that should be used when performing environment - // discovery when aws.DefaultsModeAuto is set. - // - // If not specified the SDK will construct a client if the instance metadata service has not been disabled by - // the AWS_EC2_METADATA_DISABLED environment variable. - IMDSClient *imds.Client -} - -func resolveDefaultsModeRuntimeEnvironment(ctx context.Context, envConfig *EnvConfig, client *imds.Client) (aws.RuntimeEnvironment, error) { - getRegionOutput, err := client.GetRegion(ctx, &imds.GetRegionInput{}) - // honor context timeouts, but if we couldn't talk to IMDS don't fail runtime environment introspection. - select { - case <-ctx.Done(): - return aws.RuntimeEnvironment{}, err - default: - } - - var imdsRegion string - if err == nil { - imdsRegion = getRegionOutput.Region - } - - return aws.RuntimeEnvironment{ - EnvironmentIdentifier: aws.ExecutionEnvironmentID(os.Getenv(execEnvVar)), - Region: envConfig.Region, - EC2InstanceMetadataRegion: imdsRegion, - }, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/config/doc.go deleted file mode 100644 index aab7164e2..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -// Package config provides utilities for loading configuration from multiple -// sources that can be used to configure the SDK's API clients, and utilities. -// -// The config package will load configuration from environment variables, AWS -// shared configuration file (~/.aws/config), and AWS shared credentials file -// (~/.aws/credentials). -// -// Use the LoadDefaultConfig to load configuration from all the SDK's supported -// sources, and resolve credentials using the SDK's default credential chain. -// -// LoadDefaultConfig allows for a variadic list of additional Config sources that can -// provide one or more configuration values which can be used to programmatically control the resolution -// of a specific value, or allow for broader range of additional configuration sources not supported by the SDK. -// A Config source implements one or more provider interfaces defined in this package. Config sources passed in will -// take precedence over the default environment and shared config sources used by the SDK. If one or more Config sources -// implement the same provider interface, priority will be handled by the order in which the sources were passed in. -// -// A number of helpers (prefixed by “With“) are provided in this package that implement their respective provider -// interface. These helpers should be used for overriding configuration programmatically at runtime. -package config diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/env_config.go b/vendor/github.com/aws/aws-sdk-go-v2/config/env_config.go deleted file mode 100644 index 63ecd02b3..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/env_config.go +++ /dev/null @@ -1,665 +0,0 @@ -package config - -import ( - "bytes" - "context" - "fmt" - "io" - "io/ioutil" - "os" - "strconv" - "strings" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/feature/ec2/imds" -) - -// CredentialsSourceName provides a name of the provider when config is -// loaded from environment. -const CredentialsSourceName = "EnvConfigCredentials" - -// Environment variables that will be read for configuration values. -const ( - awsAccessKeyIDEnvVar = "AWS_ACCESS_KEY_ID" - awsAccessKeyEnvVar = "AWS_ACCESS_KEY" - - awsSecretAccessKeyEnvVar = "AWS_SECRET_ACCESS_KEY" - awsSecretKeyEnvVar = "AWS_SECRET_KEY" - - awsSessionTokenEnvVar = "AWS_SESSION_TOKEN" - - awsContainerCredentialsEndpointEnvVar = "AWS_CONTAINER_CREDENTIALS_FULL_URI" - awsContainerCredentialsRelativePathEnvVar = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" - awsContainerPProviderAuthorizationEnvVar = "AWS_CONTAINER_AUTHORIZATION_TOKEN" - - awsRegionEnvVar = "AWS_REGION" - awsDefaultRegionEnvVar = "AWS_DEFAULT_REGION" - - awsProfileEnvVar = "AWS_PROFILE" - awsDefaultProfileEnvVar = "AWS_DEFAULT_PROFILE" - - awsSharedCredentialsFileEnvVar = "AWS_SHARED_CREDENTIALS_FILE" - - awsConfigFileEnvVar = "AWS_CONFIG_FILE" - - awsCustomCABundleEnvVar = "AWS_CA_BUNDLE" - - awsWebIdentityTokenFilePathEnvVar = "AWS_WEB_IDENTITY_TOKEN_FILE" - - awsRoleARNEnvVar = "AWS_ROLE_ARN" - awsRoleSessionNameEnvVar = "AWS_ROLE_SESSION_NAME" - - awsEnableEndpointDiscoveryEnvVar = "AWS_ENABLE_ENDPOINT_DISCOVERY" - - awsS3UseARNRegionEnvVar = "AWS_S3_USE_ARN_REGION" - - awsEc2MetadataServiceEndpointModeEnvVar = "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE" - - awsEc2MetadataServiceEndpointEnvVar = "AWS_EC2_METADATA_SERVICE_ENDPOINT" - - awsEc2MetadataDisabled = "AWS_EC2_METADATA_DISABLED" - - awsS3DisableMultiRegionAccessPointEnvVar = "AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS" - - awsUseDualStackEndpoint = "AWS_USE_DUALSTACK_ENDPOINT" - - awsUseFIPSEndpoint = "AWS_USE_FIPS_ENDPOINT" - - awsDefaultMode = "AWS_DEFAULTS_MODE" - - awsRetryMaxAttempts = "AWS_MAX_ATTEMPTS" - awsRetryMode = "AWS_RETRY_MODE" -) - -var ( - credAccessEnvKeys = []string{ - awsAccessKeyIDEnvVar, - awsAccessKeyEnvVar, - } - credSecretEnvKeys = []string{ - awsSecretAccessKeyEnvVar, - awsSecretKeyEnvVar, - } - regionEnvKeys = []string{ - awsRegionEnvVar, - awsDefaultRegionEnvVar, - } - profileEnvKeys = []string{ - awsProfileEnvVar, - awsDefaultProfileEnvVar, - } -) - -// EnvConfig is a collection of environment values the SDK will read -// setup config from. All environment values are optional. But some values -// such as credentials require multiple values to be complete or the values -// will be ignored. -type EnvConfig struct { - // Environment configuration values. If set both Access Key ID and Secret Access - // Key must be provided. Session Token and optionally also be provided, but is - // not required. - // - // # Access Key ID - // AWS_ACCESS_KEY_ID=AKID - // AWS_ACCESS_KEY=AKID # only read if AWS_ACCESS_KEY_ID is not set. - // - // # Secret Access Key - // AWS_SECRET_ACCESS_KEY=SECRET - // AWS_SECRET_KEY=SECRET # only read if AWS_SECRET_ACCESS_KEY is not set. - // - // # Session Token - // AWS_SESSION_TOKEN=TOKEN - Credentials aws.Credentials - - // ContainerCredentialsEndpoint value is the HTTP enabled endpoint to retrieve credentials - // using the endpointcreds.Provider - ContainerCredentialsEndpoint string - - // ContainerCredentialsRelativePath is the relative URI path that will be used when attempting to retrieve - // credentials from the container endpoint. - ContainerCredentialsRelativePath string - - // ContainerAuthorizationToken is the authorization token that will be included in the HTTP Authorization - // header when attempting to retrieve credentials from the container credentials endpoint. - ContainerAuthorizationToken string - - // Region value will instruct the SDK where to make service API requests to. If is - // not provided in the environment the region must be provided before a service - // client request is made. - // - // AWS_REGION=us-west-2 - // AWS_DEFAULT_REGION=us-west-2 - Region string - - // Profile name the SDK should load use when loading shared configuration from the - // shared configuration files. If not provided "default" will be used as the - // profile name. - // - // AWS_PROFILE=my_profile - // AWS_DEFAULT_PROFILE=my_profile - SharedConfigProfile string - - // Shared credentials file path can be set to instruct the SDK to use an alternate - // file for the shared credentials. If not set the file will be loaded from - // $HOME/.aws/credentials on Linux/Unix based systems, and - // %USERPROFILE%\.aws\credentials on Windows. - // - // AWS_SHARED_CREDENTIALS_FILE=$HOME/my_shared_credentials - SharedCredentialsFile string - - // Shared config file path can be set to instruct the SDK to use an alternate - // file for the shared config. If not set the file will be loaded from - // $HOME/.aws/config on Linux/Unix based systems, and - // %USERPROFILE%\.aws\config on Windows. - // - // AWS_CONFIG_FILE=$HOME/my_shared_config - SharedConfigFile string - - // Sets the path to a custom Credentials Authority (CA) Bundle PEM file - // that the SDK will use instead of the system's root CA bundle. - // Only use this if you want to configure the SDK to use a custom set - // of CAs. - // - // Enabling this option will attempt to merge the Transport - // into the SDK's HTTP client. If the client's Transport is - // not a http.Transport an error will be returned. If the - // Transport's TLS config is set this option will cause the - // SDK to overwrite the Transport's TLS config's RootCAs value. - // - // Setting a custom HTTPClient in the aws.Config options will override this setting. - // To use this option and custom HTTP client, the HTTP client needs to be provided - // when creating the config. Not the service client. - // - // AWS_CA_BUNDLE=$HOME/my_custom_ca_bundle - CustomCABundle string - - // Enables endpoint discovery via environment variables. - // - // AWS_ENABLE_ENDPOINT_DISCOVERY=true - EnableEndpointDiscovery aws.EndpointDiscoveryEnableState - - // Specifies the WebIdentity token the SDK should use to assume a role - // with. - // - // AWS_WEB_IDENTITY_TOKEN_FILE=file_path - WebIdentityTokenFilePath string - - // Specifies the IAM role arn to use when assuming an role. - // - // AWS_ROLE_ARN=role_arn - RoleARN string - - // Specifies the IAM role session name to use when assuming a role. - // - // AWS_ROLE_SESSION_NAME=session_name - RoleSessionName string - - // Specifies if the S3 service should allow ARNs to direct the region - // the client's requests are sent to. - // - // AWS_S3_USE_ARN_REGION=true - S3UseARNRegion *bool - - // Specifies if the EC2 IMDS service client is enabled. - // - // AWS_EC2_METADATA_DISABLED=true - EC2IMDSClientEnableState imds.ClientEnableState - - // Specifies the EC2 Instance Metadata Service default endpoint selection mode (IPv4 or IPv6) - // - // AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE=IPv6 - EC2IMDSEndpointMode imds.EndpointModeState - - // Specifies the EC2 Instance Metadata Service endpoint to use. If specified it overrides EC2IMDSEndpointMode. - // - // AWS_EC2_METADATA_SERVICE_ENDPOINT=http://fd00:ec2::254 - EC2IMDSEndpoint string - - // Specifies if the S3 service should disable multi-region access points - // support. - // - // AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS=true - S3DisableMultiRegionAccessPoints *bool - - // Specifies that SDK clients must resolve a dual-stack endpoint for - // services. - // - // AWS_USE_DUALSTACK_ENDPOINT=true - UseDualStackEndpoint aws.DualStackEndpointState - - // Specifies that SDK clients must resolve a FIPS endpoint for - // services. - // - // AWS_USE_FIPS_ENDPOINT=true - UseFIPSEndpoint aws.FIPSEndpointState - - // Specifies the SDK Defaults Mode used by services. - // - // AWS_DEFAULTS_MODE=standard - DefaultsMode aws.DefaultsMode - - // Specifies the maximum number attempts an API client will call an - // operation that fails with a retryable error. - // - // AWS_MAX_ATTEMPTS=3 - RetryMaxAttempts int - - // Specifies the retry model the API client will be created with. - // - // aws_retry_mode=standard - RetryMode aws.RetryMode -} - -// loadEnvConfig reads configuration values from the OS's environment variables. -// Returning the a Config typed EnvConfig to satisfy the ConfigLoader func type. -func loadEnvConfig(ctx context.Context, cfgs configs) (Config, error) { - return NewEnvConfig() -} - -// NewEnvConfig retrieves the SDK's environment configuration. -// See `EnvConfig` for the values that will be retrieved. -func NewEnvConfig() (EnvConfig, error) { - var cfg EnvConfig - - creds := aws.Credentials{ - Source: CredentialsSourceName, - } - setStringFromEnvVal(&creds.AccessKeyID, credAccessEnvKeys) - setStringFromEnvVal(&creds.SecretAccessKey, credSecretEnvKeys) - if creds.HasKeys() { - creds.SessionToken = os.Getenv(awsSessionTokenEnvVar) - cfg.Credentials = creds - } - - cfg.ContainerCredentialsEndpoint = os.Getenv(awsContainerCredentialsEndpointEnvVar) - cfg.ContainerCredentialsRelativePath = os.Getenv(awsContainerCredentialsRelativePathEnvVar) - cfg.ContainerAuthorizationToken = os.Getenv(awsContainerPProviderAuthorizationEnvVar) - - setStringFromEnvVal(&cfg.Region, regionEnvKeys) - setStringFromEnvVal(&cfg.SharedConfigProfile, profileEnvKeys) - - cfg.SharedCredentialsFile = os.Getenv(awsSharedCredentialsFileEnvVar) - cfg.SharedConfigFile = os.Getenv(awsConfigFileEnvVar) - - cfg.CustomCABundle = os.Getenv(awsCustomCABundleEnvVar) - - cfg.WebIdentityTokenFilePath = os.Getenv(awsWebIdentityTokenFilePathEnvVar) - - cfg.RoleARN = os.Getenv(awsRoleARNEnvVar) - cfg.RoleSessionName = os.Getenv(awsRoleSessionNameEnvVar) - - if err := setEndpointDiscoveryTypeFromEnvVal(&cfg.EnableEndpointDiscovery, []string{awsEnableEndpointDiscoveryEnvVar}); err != nil { - return cfg, err - } - - if err := setBoolPtrFromEnvVal(&cfg.S3UseARNRegion, []string{awsS3UseARNRegionEnvVar}); err != nil { - return cfg, err - } - - setEC2IMDSClientEnableState(&cfg.EC2IMDSClientEnableState, []string{awsEc2MetadataDisabled}) - if err := setEC2IMDSEndpointMode(&cfg.EC2IMDSEndpointMode, []string{awsEc2MetadataServiceEndpointModeEnvVar}); err != nil { - return cfg, err - } - cfg.EC2IMDSEndpoint = os.Getenv(awsEc2MetadataServiceEndpointEnvVar) - - if err := setBoolPtrFromEnvVal(&cfg.S3DisableMultiRegionAccessPoints, []string{awsS3DisableMultiRegionAccessPointEnvVar}); err != nil { - return cfg, err - } - - if err := setUseDualStackEndpointFromEnvVal(&cfg.UseDualStackEndpoint, []string{awsUseDualStackEndpoint}); err != nil { - return cfg, err - } - - if err := setUseFIPSEndpointFromEnvVal(&cfg.UseFIPSEndpoint, []string{awsUseFIPSEndpoint}); err != nil { - return cfg, err - } - - if err := setDefaultsModeFromEnvVal(&cfg.DefaultsMode, []string{awsDefaultMode}); err != nil { - return cfg, err - } - - if err := setIntFromEnvVal(&cfg.RetryMaxAttempts, []string{awsRetryMaxAttempts}); err != nil { - return cfg, err - } - if err := setRetryModeFromEnvVal(&cfg.RetryMode, []string{awsRetryMode}); err != nil { - return cfg, err - } - - return cfg, nil -} - -func (c EnvConfig) getDefaultsMode(ctx context.Context) (aws.DefaultsMode, bool, error) { - if len(c.DefaultsMode) == 0 { - return "", false, nil - } - return c.DefaultsMode, true, nil -} - -// GetRetryMaxAttempts returns the value of AWS_MAX_ATTEMPTS if was specified, -// and not 0. -func (c EnvConfig) GetRetryMaxAttempts(ctx context.Context) (int, bool, error) { - if c.RetryMaxAttempts == 0 { - return 0, false, nil - } - return c.RetryMaxAttempts, true, nil -} - -// GetRetryMode returns the RetryMode of AWS_RETRY_MODE if was specified, and a -// valid value. -func (c EnvConfig) GetRetryMode(ctx context.Context) (aws.RetryMode, bool, error) { - if len(c.RetryMode) == 0 { - return "", false, nil - } - return c.RetryMode, true, nil -} - -func setEC2IMDSClientEnableState(state *imds.ClientEnableState, keys []string) { - for _, k := range keys { - value := os.Getenv(k) - if len(value) == 0 { - continue - } - switch { - case strings.EqualFold(value, "true"): - *state = imds.ClientDisabled - case strings.EqualFold(value, "false"): - *state = imds.ClientEnabled - default: - continue - } - break - } -} - -func setDefaultsModeFromEnvVal(mode *aws.DefaultsMode, keys []string) error { - for _, k := range keys { - if value := os.Getenv(k); len(value) > 0 { - if ok := mode.SetFromString(value); !ok { - return fmt.Errorf("invalid %s value: %s", k, value) - } - break - } - } - return nil -} - -func setRetryModeFromEnvVal(mode *aws.RetryMode, keys []string) (err error) { - for _, k := range keys { - if value := os.Getenv(k); len(value) > 0 { - *mode, err = aws.ParseRetryMode(value) - if err != nil { - return fmt.Errorf("invalid %s value, %w", k, err) - } - break - } - } - return nil -} - -func setEC2IMDSEndpointMode(mode *imds.EndpointModeState, keys []string) error { - for _, k := range keys { - value := os.Getenv(k) - if len(value) == 0 { - continue - } - if err := mode.SetFromString(value); err != nil { - return fmt.Errorf("invalid value for environment variable, %s=%s, %v", k, value, err) - } - } - return nil -} - -// GetRegion returns the AWS Region if set in the environment. Returns an empty -// string if not set. -func (c EnvConfig) getRegion(ctx context.Context) (string, bool, error) { - if len(c.Region) == 0 { - return "", false, nil - } - return c.Region, true, nil -} - -// GetSharedConfigProfile returns the shared config profile if set in the -// environment. Returns an empty string if not set. -func (c EnvConfig) getSharedConfigProfile(ctx context.Context) (string, bool, error) { - if len(c.SharedConfigProfile) == 0 { - return "", false, nil - } - - return c.SharedConfigProfile, true, nil -} - -// getSharedConfigFiles returns a slice of filenames set in the environment. -// -// Will return the filenames in the order of: -// * Shared Config -func (c EnvConfig) getSharedConfigFiles(context.Context) ([]string, bool, error) { - var files []string - if v := c.SharedConfigFile; len(v) > 0 { - files = append(files, v) - } - - if len(files) == 0 { - return nil, false, nil - } - return files, true, nil -} - -// getSharedCredentialsFiles returns a slice of filenames set in the environment. -// -// Will return the filenames in the order of: -// * Shared Credentials -func (c EnvConfig) getSharedCredentialsFiles(context.Context) ([]string, bool, error) { - var files []string - if v := c.SharedCredentialsFile; len(v) > 0 { - files = append(files, v) - } - if len(files) == 0 { - return nil, false, nil - } - return files, true, nil -} - -// GetCustomCABundle returns the custom CA bundle's PEM bytes if the file was -func (c EnvConfig) getCustomCABundle(context.Context) (io.Reader, bool, error) { - if len(c.CustomCABundle) == 0 { - return nil, false, nil - } - - b, err := ioutil.ReadFile(c.CustomCABundle) - if err != nil { - return nil, false, err - } - return bytes.NewReader(b), true, nil -} - -// GetS3UseARNRegion returns whether to allow ARNs to direct the region -// the S3 client's requests are sent to. -func (c EnvConfig) GetS3UseARNRegion(ctx context.Context) (value, ok bool, err error) { - if c.S3UseARNRegion == nil { - return false, false, nil - } - - return *c.S3UseARNRegion, true, nil -} - -// GetS3DisableMultiRegionAccessPoints returns whether to disable multi-region access point -// support for the S3 client. -func (c EnvConfig) GetS3DisableMultiRegionAccessPoints(ctx context.Context) (value, ok bool, err error) { - if c.S3DisableMultiRegionAccessPoints == nil { - return false, false, nil - } - - return *c.S3DisableMultiRegionAccessPoints, true, nil -} - -// GetUseDualStackEndpoint returns whether the service's dual-stack endpoint should be -// used for requests. -func (c EnvConfig) GetUseDualStackEndpoint(ctx context.Context) (value aws.DualStackEndpointState, found bool, err error) { - if c.UseDualStackEndpoint == aws.DualStackEndpointStateUnset { - return aws.DualStackEndpointStateUnset, false, nil - } - - return c.UseDualStackEndpoint, true, nil -} - -// GetUseFIPSEndpoint returns whether the service's FIPS endpoint should be -// used for requests. -func (c EnvConfig) GetUseFIPSEndpoint(ctx context.Context) (value aws.FIPSEndpointState, found bool, err error) { - if c.UseFIPSEndpoint == aws.FIPSEndpointStateUnset { - return aws.FIPSEndpointStateUnset, false, nil - } - - return c.UseFIPSEndpoint, true, nil -} - -func setStringFromEnvVal(dst *string, keys []string) { - for _, k := range keys { - if v := os.Getenv(k); len(v) > 0 { - *dst = v - break - } - } -} - -func setIntFromEnvVal(dst *int, keys []string) error { - for _, k := range keys { - if v := os.Getenv(k); len(v) > 0 { - i, err := strconv.ParseInt(v, 10, 64) - if err != nil { - return fmt.Errorf("invalid value %s=%s, %w", k, v, err) - } - *dst = int(i) - break - } - } - - return nil -} - -func setBoolPtrFromEnvVal(dst **bool, keys []string) error { - for _, k := range keys { - value := os.Getenv(k) - if len(value) == 0 { - continue - } - - if *dst == nil { - *dst = new(bool) - } - - switch { - case strings.EqualFold(value, "false"): - **dst = false - case strings.EqualFold(value, "true"): - **dst = true - default: - return fmt.Errorf( - "invalid value for environment variable, %s=%s, need true or false", - k, value) - } - break - } - - return nil -} - -func setEndpointDiscoveryTypeFromEnvVal(dst *aws.EndpointDiscoveryEnableState, keys []string) error { - for _, k := range keys { - value := os.Getenv(k) - if len(value) == 0 { - continue // skip if empty - } - - switch { - case strings.EqualFold(value, endpointDiscoveryDisabled): - *dst = aws.EndpointDiscoveryDisabled - case strings.EqualFold(value, endpointDiscoveryEnabled): - *dst = aws.EndpointDiscoveryEnabled - case strings.EqualFold(value, endpointDiscoveryAuto): - *dst = aws.EndpointDiscoveryAuto - default: - return fmt.Errorf( - "invalid value for environment variable, %s=%s, need true, false or auto", - k, value) - } - } - return nil -} - -func setUseDualStackEndpointFromEnvVal(dst *aws.DualStackEndpointState, keys []string) error { - for _, k := range keys { - value := os.Getenv(k) - if len(value) == 0 { - continue // skip if empty - } - - switch { - case strings.EqualFold(value, "true"): - *dst = aws.DualStackEndpointStateEnabled - case strings.EqualFold(value, "false"): - *dst = aws.DualStackEndpointStateDisabled - default: - return fmt.Errorf( - "invalid value for environment variable, %s=%s, need true, false", - k, value) - } - } - return nil -} - -func setUseFIPSEndpointFromEnvVal(dst *aws.FIPSEndpointState, keys []string) error { - for _, k := range keys { - value := os.Getenv(k) - if len(value) == 0 { - continue // skip if empty - } - - switch { - case strings.EqualFold(value, "true"): - *dst = aws.FIPSEndpointStateEnabled - case strings.EqualFold(value, "false"): - *dst = aws.FIPSEndpointStateDisabled - default: - return fmt.Errorf( - "invalid value for environment variable, %s=%s, need true, false", - k, value) - } - } - return nil -} - -// GetEnableEndpointDiscovery returns resolved value for EnableEndpointDiscovery env variable setting. -func (c EnvConfig) GetEnableEndpointDiscovery(ctx context.Context) (value aws.EndpointDiscoveryEnableState, found bool, err error) { - if c.EnableEndpointDiscovery == aws.EndpointDiscoveryUnset { - return aws.EndpointDiscoveryUnset, false, nil - } - - return c.EnableEndpointDiscovery, true, nil -} - -// GetEC2IMDSClientEnableState implements a EC2IMDSClientEnableState options resolver interface. -func (c EnvConfig) GetEC2IMDSClientEnableState() (imds.ClientEnableState, bool, error) { - if c.EC2IMDSClientEnableState == imds.ClientDefaultEnableState { - return imds.ClientDefaultEnableState, false, nil - } - - return c.EC2IMDSClientEnableState, true, nil -} - -// GetEC2IMDSEndpointMode implements a EC2IMDSEndpointMode option resolver interface. -func (c EnvConfig) GetEC2IMDSEndpointMode() (imds.EndpointModeState, bool, error) { - if c.EC2IMDSEndpointMode == imds.EndpointModeStateUnset { - return imds.EndpointModeStateUnset, false, nil - } - - return c.EC2IMDSEndpointMode, true, nil -} - -// GetEC2IMDSEndpoint implements a EC2IMDSEndpoint option resolver interface. -func (c EnvConfig) GetEC2IMDSEndpoint() (string, bool, error) { - if len(c.EC2IMDSEndpoint) == 0 { - return "", false, nil - } - - return c.EC2IMDSEndpoint, true, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/generate.go b/vendor/github.com/aws/aws-sdk-go-v2/config/generate.go deleted file mode 100644 index 654a7a77f..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/generate.go +++ /dev/null @@ -1,4 +0,0 @@ -package config - -//go:generate go run -tags codegen ./codegen -output=provider_assert_test.go -//go:generate gofmt -s -w ./ diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/config/go_module_metadata.go deleted file mode 100644 index c973bb552..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/go_module_metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. - -package config - -// goModuleVersion is the tagged release for this module -const goModuleVersion = "1.18.37" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/load_options.go b/vendor/github.com/aws/aws-sdk-go-v2/config/load_options.go deleted file mode 100644 index 7480bb45e..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/load_options.go +++ /dev/null @@ -1,1046 +0,0 @@ -package config - -import ( - "context" - "io" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/credentials/ec2rolecreds" - "github.com/aws/aws-sdk-go-v2/credentials/endpointcreds" - "github.com/aws/aws-sdk-go-v2/credentials/processcreds" - "github.com/aws/aws-sdk-go-v2/credentials/ssocreds" - "github.com/aws/aws-sdk-go-v2/credentials/stscreds" - "github.com/aws/aws-sdk-go-v2/feature/ec2/imds" - smithybearer "github.com/aws/smithy-go/auth/bearer" - "github.com/aws/smithy-go/logging" - "github.com/aws/smithy-go/middleware" -) - -// LoadOptionsFunc is a type alias for LoadOptions functional option -type LoadOptionsFunc func(*LoadOptions) error - -// LoadOptions are discrete set of options that are valid for loading the -// configuration -type LoadOptions struct { - - // Region is the region to send requests to. - Region string - - // Credentials object to use when signing requests. - Credentials aws.CredentialsProvider - - // Token provider for authentication operations with bearer authentication. - BearerAuthTokenProvider smithybearer.TokenProvider - - // HTTPClient the SDK's API clients will use to invoke HTTP requests. - HTTPClient HTTPClient - - // EndpointResolver that can be used to provide or override an endpoint for - // the given service and region. - // - // See the `aws.EndpointResolver` documentation on usage. - // - // Deprecated: See EndpointResolverWithOptions - EndpointResolver aws.EndpointResolver - - // EndpointResolverWithOptions that can be used to provide or override an - // endpoint for the given service and region. - // - // See the `aws.EndpointResolverWithOptions` documentation on usage. - EndpointResolverWithOptions aws.EndpointResolverWithOptions - - // RetryMaxAttempts specifies the maximum number attempts an API client - // will call an operation that fails with a retryable error. - // - // This value will only be used if Retryer option is nil. - RetryMaxAttempts int - - // RetryMode specifies the retry model the API client will be created with. - // - // This value will only be used if Retryer option is nil. - RetryMode aws.RetryMode - - // Retryer is a function that provides a Retryer implementation. A Retryer - // guides how HTTP requests should be retried in case of recoverable - // failures. - // - // If not nil, RetryMaxAttempts, and RetryMode will be ignored. - Retryer func() aws.Retryer - - // APIOptions provides the set of middleware mutations modify how the API - // client requests will be handled. This is useful for adding additional - // tracing data to a request, or changing behavior of the SDK's client. - APIOptions []func(*middleware.Stack) error - - // Logger writer interface to write logging messages to. - Logger logging.Logger - - // ClientLogMode is used to configure the events that will be sent to the - // configured logger. This can be used to configure the logging of signing, - // retries, request, and responses of the SDK clients. - // - // See the ClientLogMode type documentation for the complete set of logging - // modes and available configuration. - ClientLogMode *aws.ClientLogMode - - // SharedConfigProfile is the profile to be used when loading the SharedConfig - SharedConfigProfile string - - // SharedConfigFiles is the slice of custom shared config files to use when - // loading the SharedConfig. A non-default profile used within config file - // must have name defined with prefix 'profile '. eg [profile xyz] - // indicates a profile with name 'xyz'. To read more on the format of the - // config file, please refer the documentation at - // https://docs.aws.amazon.com/credref/latest/refdocs/file-format.html#file-format-config - // - // If duplicate profiles are provided within the same, or across multiple - // shared config files, the next parsed profile will override only the - // properties that conflict with the previously defined profile. Note that - // if duplicate profiles are provided within the SharedCredentialsFiles and - // SharedConfigFiles, the properties defined in shared credentials file - // take precedence. - SharedConfigFiles []string - - // SharedCredentialsFile is the slice of custom shared credentials files to - // use when loading the SharedConfig. The profile name used within - // credentials file must not prefix 'profile '. eg [xyz] indicates a - // profile with name 'xyz'. Profile declared as [profile xyz] will be - // ignored. To read more on the format of the credentials file, please - // refer the documentation at - // https://docs.aws.amazon.com/credref/latest/refdocs/file-format.html#file-format-creds - // - // If duplicate profiles are provided with a same, or across multiple - // shared credentials files, the next parsed profile will override only - // properties that conflict with the previously defined profile. Note that - // if duplicate profiles are provided within the SharedCredentialsFiles and - // SharedConfigFiles, the properties defined in shared credentials file - // take precedence. - SharedCredentialsFiles []string - - // CustomCABundle is CA bundle PEM bytes reader - CustomCABundle io.Reader - - // DefaultRegion is the fall back region, used if a region was not resolved - // from other sources - DefaultRegion string - - // UseEC2IMDSRegion indicates if SDK should retrieve the region - // from the EC2 Metadata service - UseEC2IMDSRegion *UseEC2IMDSRegion - - // CredentialsCacheOptions is a function for setting the - // aws.CredentialsCacheOptions - CredentialsCacheOptions func(*aws.CredentialsCacheOptions) - - // BearerAuthTokenCacheOptions is a function for setting the smithy-go - // auth/bearer#TokenCacheOptions - BearerAuthTokenCacheOptions func(*smithybearer.TokenCacheOptions) - - // SSOTokenProviderOptions is a function for setting the - // credentials/ssocreds.SSOTokenProviderOptions - SSOTokenProviderOptions func(*ssocreds.SSOTokenProviderOptions) - - // ProcessCredentialOptions is a function for setting - // the processcreds.Options - ProcessCredentialOptions func(*processcreds.Options) - - // EC2RoleCredentialOptions is a function for setting - // the ec2rolecreds.Options - EC2RoleCredentialOptions func(*ec2rolecreds.Options) - - // EndpointCredentialOptions is a function for setting - // the endpointcreds.Options - EndpointCredentialOptions func(*endpointcreds.Options) - - // WebIdentityRoleCredentialOptions is a function for setting - // the stscreds.WebIdentityRoleOptions - WebIdentityRoleCredentialOptions func(*stscreds.WebIdentityRoleOptions) - - // AssumeRoleCredentialOptions is a function for setting the - // stscreds.AssumeRoleOptions - AssumeRoleCredentialOptions func(*stscreds.AssumeRoleOptions) - - // SSOProviderOptions is a function for setting - // the ssocreds.Options - SSOProviderOptions func(options *ssocreds.Options) - - // LogConfigurationWarnings when set to true, enables logging - // configuration warnings - LogConfigurationWarnings *bool - - // S3UseARNRegion specifies if the S3 service should allow ARNs to direct - // the region, the client's requests are sent to. - S3UseARNRegion *bool - - // S3DisableMultiRegionAccessPoints specifies if the S3 service should disable - // the S3 Multi-Region access points feature. - S3DisableMultiRegionAccessPoints *bool - - // EnableEndpointDiscovery specifies if endpoint discovery is enable for - // the client. - EnableEndpointDiscovery aws.EndpointDiscoveryEnableState - - // Specifies if the EC2 IMDS service client is enabled. - // - // AWS_EC2_METADATA_DISABLED=true - EC2IMDSClientEnableState imds.ClientEnableState - - // Specifies the EC2 Instance Metadata Service default endpoint selection - // mode (IPv4 or IPv6) - EC2IMDSEndpointMode imds.EndpointModeState - - // Specifies the EC2 Instance Metadata Service endpoint to use. If - // specified it overrides EC2IMDSEndpointMode. - EC2IMDSEndpoint string - - // Specifies that SDK clients must resolve a dual-stack endpoint for - // services. - UseDualStackEndpoint aws.DualStackEndpointState - - // Specifies that SDK clients must resolve a FIPS endpoint for - // services. - UseFIPSEndpoint aws.FIPSEndpointState - - // Specifies the SDK configuration mode for defaults. - DefaultsModeOptions DefaultsModeOptions - - // The sdk app ID retrieved from env var or shared config to be added to request user agent header - AppID string -} - -func (o LoadOptions) getDefaultsMode(ctx context.Context) (aws.DefaultsMode, bool, error) { - if len(o.DefaultsModeOptions.Mode) == 0 { - return "", false, nil - } - return o.DefaultsModeOptions.Mode, true, nil -} - -// GetRetryMaxAttempts returns the RetryMaxAttempts if specified in the -// LoadOptions and not 0. -func (o LoadOptions) GetRetryMaxAttempts(ctx context.Context) (int, bool, error) { - if o.RetryMaxAttempts == 0 { - return 0, false, nil - } - return o.RetryMaxAttempts, true, nil -} - -// GetRetryMode returns the RetryMode specified in the LoadOptions. -func (o LoadOptions) GetRetryMode(ctx context.Context) (aws.RetryMode, bool, error) { - if len(o.RetryMode) == 0 { - return "", false, nil - } - return o.RetryMode, true, nil -} - -func (o LoadOptions) getDefaultsModeIMDSClient(ctx context.Context) (*imds.Client, bool, error) { - if o.DefaultsModeOptions.IMDSClient == nil { - return nil, false, nil - } - return o.DefaultsModeOptions.IMDSClient, true, nil -} - -// getRegion returns Region from config's LoadOptions -func (o LoadOptions) getRegion(ctx context.Context) (string, bool, error) { - if len(o.Region) == 0 { - return "", false, nil - } - - return o.Region, true, nil -} - -// getAppID returns AppID from config's LoadOptions -func (o LoadOptions) getAppID(ctx context.Context) (string, bool, error) { - return o.AppID, len(o.AppID) > 0, nil -} - -// WithRegion is a helper function to construct functional options -// that sets Region on config's LoadOptions. Setting the region to -// an empty string, will result in the region value being ignored. -// If multiple WithRegion calls are made, the last call overrides -// the previous call values. -func WithRegion(v string) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.Region = v - return nil - } -} - -// WithAppID is a helper function to construct functional options -// that sets AppID on config's LoadOptions. -func WithAppID(ID string) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.AppID = ID - return nil - } -} - -// getDefaultRegion returns DefaultRegion from config's LoadOptions -func (o LoadOptions) getDefaultRegion(ctx context.Context) (string, bool, error) { - if len(o.DefaultRegion) == 0 { - return "", false, nil - } - - return o.DefaultRegion, true, nil -} - -// WithDefaultRegion is a helper function to construct functional options -// that sets a DefaultRegion on config's LoadOptions. Setting the default -// region to an empty string, will result in the default region value -// being ignored. If multiple WithDefaultRegion calls are made, the last -// call overrides the previous call values. Note that both WithRegion and -// WithEC2IMDSRegion call takes precedence over WithDefaultRegion call -// when resolving region. -func WithDefaultRegion(v string) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.DefaultRegion = v - return nil - } -} - -// getSharedConfigProfile returns SharedConfigProfile from config's LoadOptions -func (o LoadOptions) getSharedConfigProfile(ctx context.Context) (string, bool, error) { - if len(o.SharedConfigProfile) == 0 { - return "", false, nil - } - - return o.SharedConfigProfile, true, nil -} - -// WithSharedConfigProfile is a helper function to construct functional options -// that sets SharedConfigProfile on config's LoadOptions. Setting the shared -// config profile to an empty string, will result in the shared config profile -// value being ignored. -// If multiple WithSharedConfigProfile calls are made, the last call overrides -// the previous call values. -func WithSharedConfigProfile(v string) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.SharedConfigProfile = v - return nil - } -} - -// getSharedConfigFiles returns SharedConfigFiles set on config's LoadOptions -func (o LoadOptions) getSharedConfigFiles(ctx context.Context) ([]string, bool, error) { - if o.SharedConfigFiles == nil { - return nil, false, nil - } - - return o.SharedConfigFiles, true, nil -} - -// WithSharedConfigFiles is a helper function to construct functional options -// that sets slice of SharedConfigFiles on config's LoadOptions. -// Setting the shared config files to an nil string slice, will result in the -// shared config files value being ignored. -// If multiple WithSharedConfigFiles calls are made, the last call overrides -// the previous call values. -func WithSharedConfigFiles(v []string) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.SharedConfigFiles = v - return nil - } -} - -// getSharedCredentialsFiles returns SharedCredentialsFiles set on config's LoadOptions -func (o LoadOptions) getSharedCredentialsFiles(ctx context.Context) ([]string, bool, error) { - if o.SharedCredentialsFiles == nil { - return nil, false, nil - } - - return o.SharedCredentialsFiles, true, nil -} - -// WithSharedCredentialsFiles is a helper function to construct functional options -// that sets slice of SharedCredentialsFiles on config's LoadOptions. -// Setting the shared credentials files to an nil string slice, will result in the -// shared credentials files value being ignored. -// If multiple WithSharedCredentialsFiles calls are made, the last call overrides -// the previous call values. -func WithSharedCredentialsFiles(v []string) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.SharedCredentialsFiles = v - return nil - } -} - -// getCustomCABundle returns CustomCABundle from LoadOptions -func (o LoadOptions) getCustomCABundle(ctx context.Context) (io.Reader, bool, error) { - if o.CustomCABundle == nil { - return nil, false, nil - } - - return o.CustomCABundle, true, nil -} - -// WithCustomCABundle is a helper function to construct functional options -// that sets CustomCABundle on config's LoadOptions. Setting the custom CA Bundle -// to nil will result in custom CA Bundle value being ignored. -// If multiple WithCustomCABundle calls are made, the last call overrides the -// previous call values. -func WithCustomCABundle(v io.Reader) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.CustomCABundle = v - return nil - } -} - -// UseEC2IMDSRegion provides a regionProvider that retrieves the region -// from the EC2 Metadata service. -type UseEC2IMDSRegion struct { - // If unset will default to generic EC2 IMDS client. - Client *imds.Client -} - -// getRegion attempts to retrieve the region from EC2 Metadata service. -func (p *UseEC2IMDSRegion) getRegion(ctx context.Context) (string, bool, error) { - if ctx == nil { - ctx = context.Background() - } - - client := p.Client - if client == nil { - client = imds.New(imds.Options{}) - } - - result, err := client.GetRegion(ctx, nil) - if err != nil { - return "", false, err - } - if len(result.Region) != 0 { - return result.Region, true, nil - } - return "", false, nil -} - -// getEC2IMDSRegion returns the value of EC2 IMDS region. -func (o LoadOptions) getEC2IMDSRegion(ctx context.Context) (string, bool, error) { - if o.UseEC2IMDSRegion == nil { - return "", false, nil - } - - return o.UseEC2IMDSRegion.getRegion(ctx) -} - -// WithEC2IMDSRegion is a helper function to construct functional options -// that enables resolving EC2IMDS region. The function takes -// in a UseEC2IMDSRegion functional option, and can be used to set the -// EC2IMDS client which will be used to resolve EC2IMDSRegion. -// If no functional option is provided, an EC2IMDS client is built and used -// by the resolver. If multiple WithEC2IMDSRegion calls are made, the last -// call overrides the previous call values. Note that the WithRegion calls takes -// precedence over WithEC2IMDSRegion when resolving region. -func WithEC2IMDSRegion(fnOpts ...func(o *UseEC2IMDSRegion)) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.UseEC2IMDSRegion = &UseEC2IMDSRegion{} - - for _, fn := range fnOpts { - fn(o.UseEC2IMDSRegion) - } - return nil - } -} - -// getCredentialsProvider returns the credentials value -func (o LoadOptions) getCredentialsProvider(ctx context.Context) (aws.CredentialsProvider, bool, error) { - if o.Credentials == nil { - return nil, false, nil - } - - return o.Credentials, true, nil -} - -// WithCredentialsProvider is a helper function to construct functional options -// that sets Credential provider value on config's LoadOptions. If credentials -// provider is set to nil, the credentials provider value will be ignored. -// If multiple WithCredentialsProvider calls are made, the last call overrides -// the previous call values. -func WithCredentialsProvider(v aws.CredentialsProvider) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.Credentials = v - return nil - } -} - -// getCredentialsCacheOptionsProvider returns the wrapped function to set aws.CredentialsCacheOptions -func (o LoadOptions) getCredentialsCacheOptions(ctx context.Context) (func(*aws.CredentialsCacheOptions), bool, error) { - if o.CredentialsCacheOptions == nil { - return nil, false, nil - } - - return o.CredentialsCacheOptions, true, nil -} - -// WithCredentialsCacheOptions is a helper function to construct functional -// options that sets a function to modify the aws.CredentialsCacheOptions the -// aws.CredentialsCache will be configured with, if the CredentialsCache is used -// by the configuration loader. -// -// If multiple WithCredentialsCacheOptions calls are made, the last call -// overrides the previous call values. -func WithCredentialsCacheOptions(v func(*aws.CredentialsCacheOptions)) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.CredentialsCacheOptions = v - return nil - } -} - -// getBearerAuthTokenProvider returns the credentials value -func (o LoadOptions) getBearerAuthTokenProvider(ctx context.Context) (smithybearer.TokenProvider, bool, error) { - if o.BearerAuthTokenProvider == nil { - return nil, false, nil - } - - return o.BearerAuthTokenProvider, true, nil -} - -// WithBearerAuthTokenProvider is a helper function to construct functional options -// that sets Credential provider value on config's LoadOptions. If credentials -// provider is set to nil, the credentials provider value will be ignored. -// If multiple WithBearerAuthTokenProvider calls are made, the last call overrides -// the previous call values. -func WithBearerAuthTokenProvider(v smithybearer.TokenProvider) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.BearerAuthTokenProvider = v - return nil - } -} - -// getBearerAuthTokenCacheOptionsProvider returns the wrapped function to set smithybearer.TokenCacheOptions -func (o LoadOptions) getBearerAuthTokenCacheOptions(ctx context.Context) (func(*smithybearer.TokenCacheOptions), bool, error) { - if o.BearerAuthTokenCacheOptions == nil { - return nil, false, nil - } - - return o.BearerAuthTokenCacheOptions, true, nil -} - -// WithBearerAuthTokenCacheOptions is a helper function to construct functional options -// that sets a function to modify the TokenCacheOptions the smithy-go -// auth/bearer#TokenCache will be configured with, if the TokenCache is used by -// the configuration loader. -// -// If multiple WithBearerAuthTokenCacheOptions calls are made, the last call overrides -// the previous call values. -func WithBearerAuthTokenCacheOptions(v func(*smithybearer.TokenCacheOptions)) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.BearerAuthTokenCacheOptions = v - return nil - } -} - -// getSSOTokenProviderOptionsProvider returns the wrapped function to set smithybearer.TokenCacheOptions -func (o LoadOptions) getSSOTokenProviderOptions(ctx context.Context) (func(*ssocreds.SSOTokenProviderOptions), bool, error) { - if o.SSOTokenProviderOptions == nil { - return nil, false, nil - } - - return o.SSOTokenProviderOptions, true, nil -} - -// WithSSOTokenProviderOptions is a helper function to construct functional -// options that sets a function to modify the SSOtokenProviderOptions the SDK's -// credentials/ssocreds#SSOProvider will be configured with, if the -// SSOTokenProvider is used by the configuration loader. -// -// If multiple WithSSOTokenProviderOptions calls are made, the last call overrides -// the previous call values. -func WithSSOTokenProviderOptions(v func(*ssocreds.SSOTokenProviderOptions)) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.SSOTokenProviderOptions = v - return nil - } -} - -// getProcessCredentialOptions returns the wrapped function to set processcreds.Options -func (o LoadOptions) getProcessCredentialOptions(ctx context.Context) (func(*processcreds.Options), bool, error) { - if o.ProcessCredentialOptions == nil { - return nil, false, nil - } - - return o.ProcessCredentialOptions, true, nil -} - -// WithProcessCredentialOptions is a helper function to construct functional options -// that sets a function to use processcreds.Options on config's LoadOptions. -// If process credential options is set to nil, the process credential value will -// be ignored. If multiple WithProcessCredentialOptions calls are made, the last call -// overrides the previous call values. -func WithProcessCredentialOptions(v func(*processcreds.Options)) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.ProcessCredentialOptions = v - return nil - } -} - -// getEC2RoleCredentialOptions returns the wrapped function to set the ec2rolecreds.Options -func (o LoadOptions) getEC2RoleCredentialOptions(ctx context.Context) (func(*ec2rolecreds.Options), bool, error) { - if o.EC2RoleCredentialOptions == nil { - return nil, false, nil - } - - return o.EC2RoleCredentialOptions, true, nil -} - -// WithEC2RoleCredentialOptions is a helper function to construct functional options -// that sets a function to use ec2rolecreds.Options on config's LoadOptions. If -// EC2 role credential options is set to nil, the EC2 role credential options value -// will be ignored. If multiple WithEC2RoleCredentialOptions calls are made, -// the last call overrides the previous call values. -func WithEC2RoleCredentialOptions(v func(*ec2rolecreds.Options)) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.EC2RoleCredentialOptions = v - return nil - } -} - -// getEndpointCredentialOptions returns the wrapped function to set endpointcreds.Options -func (o LoadOptions) getEndpointCredentialOptions(context.Context) (func(*endpointcreds.Options), bool, error) { - if o.EndpointCredentialOptions == nil { - return nil, false, nil - } - - return o.EndpointCredentialOptions, true, nil -} - -// WithEndpointCredentialOptions is a helper function to construct functional options -// that sets a function to use endpointcreds.Options on config's LoadOptions. If -// endpoint credential options is set to nil, the endpoint credential options -// value will be ignored. If multiple WithEndpointCredentialOptions calls are made, -// the last call overrides the previous call values. -func WithEndpointCredentialOptions(v func(*endpointcreds.Options)) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.EndpointCredentialOptions = v - return nil - } -} - -// getWebIdentityRoleCredentialOptions returns the wrapped function -func (o LoadOptions) getWebIdentityRoleCredentialOptions(context.Context) (func(*stscreds.WebIdentityRoleOptions), bool, error) { - if o.WebIdentityRoleCredentialOptions == nil { - return nil, false, nil - } - - return o.WebIdentityRoleCredentialOptions, true, nil -} - -// WithWebIdentityRoleCredentialOptions is a helper function to construct -// functional options that sets a function to use stscreds.WebIdentityRoleOptions -// on config's LoadOptions. If web identity role credentials options is set to nil, -// the web identity role credentials value will be ignored. If multiple -// WithWebIdentityRoleCredentialOptions calls are made, the last call -// overrides the previous call values. -func WithWebIdentityRoleCredentialOptions(v func(*stscreds.WebIdentityRoleOptions)) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.WebIdentityRoleCredentialOptions = v - return nil - } -} - -// getAssumeRoleCredentialOptions returns AssumeRoleCredentialOptions from LoadOptions -func (o LoadOptions) getAssumeRoleCredentialOptions(context.Context) (func(options *stscreds.AssumeRoleOptions), bool, error) { - if o.AssumeRoleCredentialOptions == nil { - return nil, false, nil - } - - return o.AssumeRoleCredentialOptions, true, nil -} - -// WithAssumeRoleCredentialOptions is a helper function to construct -// functional options that sets a function to use stscreds.AssumeRoleOptions -// on config's LoadOptions. If assume role credentials options is set to nil, -// the assume role credentials value will be ignored. If multiple -// WithAssumeRoleCredentialOptions calls are made, the last call overrides -// the previous call values. -func WithAssumeRoleCredentialOptions(v func(*stscreds.AssumeRoleOptions)) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.AssumeRoleCredentialOptions = v - return nil - } -} - -func (o LoadOptions) getHTTPClient(ctx context.Context) (HTTPClient, bool, error) { - if o.HTTPClient == nil { - return nil, false, nil - } - - return o.HTTPClient, true, nil -} - -// WithHTTPClient is a helper function to construct functional options -// that sets HTTPClient on LoadOptions. If HTTPClient is set to nil, -// the HTTPClient value will be ignored. -// If multiple WithHTTPClient calls are made, the last call overrides -// the previous call values. -func WithHTTPClient(v HTTPClient) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.HTTPClient = v - return nil - } -} - -func (o LoadOptions) getAPIOptions(ctx context.Context) ([]func(*middleware.Stack) error, bool, error) { - if o.APIOptions == nil { - return nil, false, nil - } - - return o.APIOptions, true, nil -} - -// WithAPIOptions is a helper function to construct functional options -// that sets APIOptions on LoadOptions. If APIOptions is set to nil, the -// APIOptions value is ignored. If multiple WithAPIOptions calls are -// made, the last call overrides the previous call values. -func WithAPIOptions(v []func(*middleware.Stack) error) LoadOptionsFunc { - return func(o *LoadOptions) error { - if v == nil { - return nil - } - - o.APIOptions = append(o.APIOptions, v...) - return nil - } -} - -func (o LoadOptions) getRetryMaxAttempts(ctx context.Context) (int, bool, error) { - if o.RetryMaxAttempts == 0 { - return 0, false, nil - } - - return o.RetryMaxAttempts, true, nil -} - -// WithRetryMaxAttempts is a helper function to construct functional options that sets -// RetryMaxAttempts on LoadOptions. If RetryMaxAttempts is unset, the RetryMaxAttempts value is -// ignored. If multiple WithRetryMaxAttempts calls are made, the last call overrides -// the previous call values. -// -// Will be ignored of LoadOptions.Retryer or WithRetryer are used. -func WithRetryMaxAttempts(v int) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.RetryMaxAttempts = v - return nil - } -} - -func (o LoadOptions) getRetryMode(ctx context.Context) (aws.RetryMode, bool, error) { - if o.RetryMode == "" { - return "", false, nil - } - - return o.RetryMode, true, nil -} - -// WithRetryMode is a helper function to construct functional options that sets -// RetryMode on LoadOptions. If RetryMode is unset, the RetryMode value is -// ignored. If multiple WithRetryMode calls are made, the last call overrides -// the previous call values. -// -// Will be ignored of LoadOptions.Retryer or WithRetryer are used. -func WithRetryMode(v aws.RetryMode) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.RetryMode = v - return nil - } -} - -func (o LoadOptions) getRetryer(ctx context.Context) (func() aws.Retryer, bool, error) { - if o.Retryer == nil { - return nil, false, nil - } - - return o.Retryer, true, nil -} - -// WithRetryer is a helper function to construct functional options -// that sets Retryer on LoadOptions. If Retryer is set to nil, the -// Retryer value is ignored. If multiple WithRetryer calls are -// made, the last call overrides the previous call values. -func WithRetryer(v func() aws.Retryer) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.Retryer = v - return nil - } -} - -func (o LoadOptions) getEndpointResolver(ctx context.Context) (aws.EndpointResolver, bool, error) { - if o.EndpointResolver == nil { - return nil, false, nil - } - - return o.EndpointResolver, true, nil -} - -// WithEndpointResolver is a helper function to construct functional options -// that sets the EndpointResolver on LoadOptions. If the EndpointResolver is set to nil, -// the EndpointResolver value is ignored. If multiple WithEndpointResolver calls -// are made, the last call overrides the previous call values. -// -// Deprecated: See WithEndpointResolverWithOptions -func WithEndpointResolver(v aws.EndpointResolver) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.EndpointResolver = v - return nil - } -} - -func (o LoadOptions) getEndpointResolverWithOptions(ctx context.Context) (aws.EndpointResolverWithOptions, bool, error) { - if o.EndpointResolverWithOptions == nil { - return nil, false, nil - } - - return o.EndpointResolverWithOptions, true, nil -} - -// WithEndpointResolverWithOptions is a helper function to construct functional options -// that sets the EndpointResolverWithOptions on LoadOptions. If the EndpointResolverWithOptions is set to nil, -// the EndpointResolver value is ignored. If multiple WithEndpointResolver calls -// are made, the last call overrides the previous call values. -func WithEndpointResolverWithOptions(v aws.EndpointResolverWithOptions) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.EndpointResolverWithOptions = v - return nil - } -} - -func (o LoadOptions) getLogger(ctx context.Context) (logging.Logger, bool, error) { - if o.Logger == nil { - return nil, false, nil - } - - return o.Logger, true, nil -} - -// WithLogger is a helper function to construct functional options -// that sets Logger on LoadOptions. If Logger is set to nil, the -// Logger value will be ignored. If multiple WithLogger calls are made, -// the last call overrides the previous call values. -func WithLogger(v logging.Logger) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.Logger = v - return nil - } -} - -func (o LoadOptions) getClientLogMode(ctx context.Context) (aws.ClientLogMode, bool, error) { - if o.ClientLogMode == nil { - return 0, false, nil - } - - return *o.ClientLogMode, true, nil -} - -// WithClientLogMode is a helper function to construct functional options -// that sets client log mode on LoadOptions. If client log mode is set to nil, -// the client log mode value will be ignored. If multiple WithClientLogMode calls are made, -// the last call overrides the previous call values. -func WithClientLogMode(v aws.ClientLogMode) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.ClientLogMode = &v - return nil - } -} - -func (o LoadOptions) getLogConfigurationWarnings(ctx context.Context) (v bool, found bool, err error) { - if o.LogConfigurationWarnings == nil { - return false, false, nil - } - return *o.LogConfigurationWarnings, true, nil -} - -// WithLogConfigurationWarnings is a helper function to construct -// functional options that can be used to set LogConfigurationWarnings -// on LoadOptions. -// -// If multiple WithLogConfigurationWarnings calls are made, the last call -// overrides the previous call values. -func WithLogConfigurationWarnings(v bool) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.LogConfigurationWarnings = &v - return nil - } -} - -// GetS3UseARNRegion returns whether to allow ARNs to direct the region -// the S3 client's requests are sent to. -func (o LoadOptions) GetS3UseARNRegion(ctx context.Context) (v bool, found bool, err error) { - if o.S3UseARNRegion == nil { - return false, false, nil - } - return *o.S3UseARNRegion, true, nil -} - -// WithS3UseARNRegion is a helper function to construct functional options -// that can be used to set S3UseARNRegion on LoadOptions. -// If multiple WithS3UseARNRegion calls are made, the last call overrides -// the previous call values. -func WithS3UseARNRegion(v bool) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.S3UseARNRegion = &v - return nil - } -} - -// GetS3DisableMultiRegionAccessPoints returns whether to disable -// the S3 multi-region access points feature. -func (o LoadOptions) GetS3DisableMultiRegionAccessPoints(ctx context.Context) (v bool, found bool, err error) { - if o.S3DisableMultiRegionAccessPoints == nil { - return false, false, nil - } - return *o.S3DisableMultiRegionAccessPoints, true, nil -} - -// WithS3DisableMultiRegionAccessPoints is a helper function to construct functional options -// that can be used to set S3DisableMultiRegionAccessPoints on LoadOptions. -// If multiple WithS3DisableMultiRegionAccessPoints calls are made, the last call overrides -// the previous call values. -func WithS3DisableMultiRegionAccessPoints(v bool) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.S3DisableMultiRegionAccessPoints = &v - return nil - } -} - -// GetEnableEndpointDiscovery returns if the EnableEndpointDiscovery flag is set. -func (o LoadOptions) GetEnableEndpointDiscovery(ctx context.Context) (value aws.EndpointDiscoveryEnableState, ok bool, err error) { - if o.EnableEndpointDiscovery == aws.EndpointDiscoveryUnset { - return aws.EndpointDiscoveryUnset, false, nil - } - return o.EnableEndpointDiscovery, true, nil -} - -// WithEndpointDiscovery is a helper function to construct functional options -// that can be used to enable endpoint discovery on LoadOptions for supported clients. -// If multiple WithEndpointDiscovery calls are made, the last call overrides -// the previous call values. -func WithEndpointDiscovery(v aws.EndpointDiscoveryEnableState) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.EnableEndpointDiscovery = v - return nil - } -} - -// getSSOProviderOptions returns AssumeRoleCredentialOptions from LoadOptions -func (o LoadOptions) getSSOProviderOptions(context.Context) (func(options *ssocreds.Options), bool, error) { - if o.SSOProviderOptions == nil { - return nil, false, nil - } - - return o.SSOProviderOptions, true, nil -} - -// WithSSOProviderOptions is a helper function to construct -// functional options that sets a function to use ssocreds.Options -// on config's LoadOptions. If the SSO credential provider options is set to nil, -// the sso provider options value will be ignored. If multiple -// WithSSOProviderOptions calls are made, the last call overrides -// the previous call values. -func WithSSOProviderOptions(v func(*ssocreds.Options)) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.SSOProviderOptions = v - return nil - } -} - -// GetEC2IMDSClientEnableState implements a EC2IMDSClientEnableState options resolver interface. -func (o LoadOptions) GetEC2IMDSClientEnableState() (imds.ClientEnableState, bool, error) { - if o.EC2IMDSClientEnableState == imds.ClientDefaultEnableState { - return imds.ClientDefaultEnableState, false, nil - } - - return o.EC2IMDSClientEnableState, true, nil -} - -// GetEC2IMDSEndpointMode implements a EC2IMDSEndpointMode option resolver interface. -func (o LoadOptions) GetEC2IMDSEndpointMode() (imds.EndpointModeState, bool, error) { - if o.EC2IMDSEndpointMode == imds.EndpointModeStateUnset { - return imds.EndpointModeStateUnset, false, nil - } - - return o.EC2IMDSEndpointMode, true, nil -} - -// GetEC2IMDSEndpoint implements a EC2IMDSEndpoint option resolver interface. -func (o LoadOptions) GetEC2IMDSEndpoint() (string, bool, error) { - if len(o.EC2IMDSEndpoint) == 0 { - return "", false, nil - } - - return o.EC2IMDSEndpoint, true, nil -} - -// WithEC2IMDSClientEnableState is a helper function to construct functional options that sets the EC2IMDSClientEnableState. -func WithEC2IMDSClientEnableState(v imds.ClientEnableState) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.EC2IMDSClientEnableState = v - return nil - } -} - -// WithEC2IMDSEndpointMode is a helper function to construct functional options that sets the EC2IMDSEndpointMode. -func WithEC2IMDSEndpointMode(v imds.EndpointModeState) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.EC2IMDSEndpointMode = v - return nil - } -} - -// WithEC2IMDSEndpoint is a helper function to construct functional options that sets the EC2IMDSEndpoint. -func WithEC2IMDSEndpoint(v string) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.EC2IMDSEndpoint = v - return nil - } -} - -// WithUseDualStackEndpoint is a helper function to construct -// functional options that can be used to set UseDualStackEndpoint on LoadOptions. -func WithUseDualStackEndpoint(v aws.DualStackEndpointState) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.UseDualStackEndpoint = v - return nil - } -} - -// GetUseDualStackEndpoint returns whether the service's dual-stack endpoint should be -// used for requests. -func (o LoadOptions) GetUseDualStackEndpoint(ctx context.Context) (value aws.DualStackEndpointState, found bool, err error) { - if o.UseDualStackEndpoint == aws.DualStackEndpointStateUnset { - return aws.DualStackEndpointStateUnset, false, nil - } - return o.UseDualStackEndpoint, true, nil -} - -// WithUseFIPSEndpoint is a helper function to construct -// functional options that can be used to set UseFIPSEndpoint on LoadOptions. -func WithUseFIPSEndpoint(v aws.FIPSEndpointState) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.UseFIPSEndpoint = v - return nil - } -} - -// GetUseFIPSEndpoint returns whether the service's FIPS endpoint should be -// used for requests. -func (o LoadOptions) GetUseFIPSEndpoint(ctx context.Context) (value aws.FIPSEndpointState, found bool, err error) { - if o.UseFIPSEndpoint == aws.FIPSEndpointStateUnset { - return aws.FIPSEndpointStateUnset, false, nil - } - return o.UseFIPSEndpoint, true, nil -} - -// WithDefaultsMode sets the SDK defaults configuration mode to the value provided. -// -// Zero or more functional options can be provided to provide configuration options for performing -// environment discovery when using aws.DefaultsModeAuto. -func WithDefaultsMode(mode aws.DefaultsMode, optFns ...func(options *DefaultsModeOptions)) LoadOptionsFunc { - do := DefaultsModeOptions{ - Mode: mode, - } - for _, fn := range optFns { - fn(&do) - } - return func(options *LoadOptions) error { - options.DefaultsModeOptions = do - return nil - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/local.go b/vendor/github.com/aws/aws-sdk-go-v2/config/local.go deleted file mode 100644 index b629137c8..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/local.go +++ /dev/null @@ -1,51 +0,0 @@ -package config - -import ( - "fmt" - "net" - "net/url" -) - -var lookupHostFn = net.LookupHost - -func isLoopbackHost(host string) (bool, error) { - ip := net.ParseIP(host) - if ip != nil { - return ip.IsLoopback(), nil - } - - // Host is not an ip, perform lookup - addrs, err := lookupHostFn(host) - if err != nil { - return false, err - } - if len(addrs) == 0 { - return false, fmt.Errorf("no addrs found for host, %s", host) - } - - for _, addr := range addrs { - if !net.ParseIP(addr).IsLoopback() { - return false, nil - } - } - - return true, nil -} - -func validateLocalURL(v string) error { - u, err := url.Parse(v) - if err != nil { - return err - } - - host := u.Hostname() - if len(host) == 0 { - return fmt.Errorf("unable to parse host from local HTTP cred provider URL") - } else if isLoopback, err := isLoopbackHost(host); err != nil { - return fmt.Errorf("failed to resolve host %q, %v", host, err) - } else if !isLoopback { - return fmt.Errorf("invalid endpoint host, %q, only host resolving to loopback addresses are allowed", host) - } - - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/provider.go b/vendor/github.com/aws/aws-sdk-go-v2/config/provider.go deleted file mode 100644 index 69e54b77f..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/provider.go +++ /dev/null @@ -1,618 +0,0 @@ -package config - -import ( - "context" - "io" - "net/http" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/credentials/ec2rolecreds" - "github.com/aws/aws-sdk-go-v2/credentials/endpointcreds" - "github.com/aws/aws-sdk-go-v2/credentials/processcreds" - "github.com/aws/aws-sdk-go-v2/credentials/ssocreds" - "github.com/aws/aws-sdk-go-v2/credentials/stscreds" - "github.com/aws/aws-sdk-go-v2/feature/ec2/imds" - smithybearer "github.com/aws/smithy-go/auth/bearer" - "github.com/aws/smithy-go/logging" - "github.com/aws/smithy-go/middleware" -) - -// sharedConfigProfileProvider provides access to the shared config profile -// name external configuration value. -type sharedConfigProfileProvider interface { - getSharedConfigProfile(ctx context.Context) (string, bool, error) -} - -// getSharedConfigProfile searches the configs for a sharedConfigProfileProvider -// and returns the value if found. Returns an error if a provider fails before a -// value is found. -func getSharedConfigProfile(ctx context.Context, configs configs) (value string, found bool, err error) { - for _, cfg := range configs { - if p, ok := cfg.(sharedConfigProfileProvider); ok { - value, found, err = p.getSharedConfigProfile(ctx) - if err != nil || found { - break - } - } - } - return -} - -// sharedConfigFilesProvider provides access to the shared config filesnames -// external configuration value. -type sharedConfigFilesProvider interface { - getSharedConfigFiles(ctx context.Context) ([]string, bool, error) -} - -// getSharedConfigFiles searches the configs for a sharedConfigFilesProvider -// and returns the value if found. Returns an error if a provider fails before a -// value is found. -func getSharedConfigFiles(ctx context.Context, configs configs) (value []string, found bool, err error) { - for _, cfg := range configs { - if p, ok := cfg.(sharedConfigFilesProvider); ok { - value, found, err = p.getSharedConfigFiles(ctx) - if err != nil || found { - break - } - } - } - - return -} - -// sharedCredentialsFilesProvider provides access to the shared credentials filesnames -// external configuration value. -type sharedCredentialsFilesProvider interface { - getSharedCredentialsFiles(ctx context.Context) ([]string, bool, error) -} - -// getSharedCredentialsFiles searches the configs for a sharedCredentialsFilesProvider -// and returns the value if found. Returns an error if a provider fails before a -// value is found. -func getSharedCredentialsFiles(ctx context.Context, configs configs) (value []string, found bool, err error) { - for _, cfg := range configs { - if p, ok := cfg.(sharedCredentialsFilesProvider); ok { - value, found, err = p.getSharedCredentialsFiles(ctx) - if err != nil || found { - break - } - } - } - - return -} - -// customCABundleProvider provides access to the custom CA bundle PEM bytes. -type customCABundleProvider interface { - getCustomCABundle(ctx context.Context) (io.Reader, bool, error) -} - -// getCustomCABundle searches the configs for a customCABundleProvider -// and returns the value if found. Returns an error if a provider fails before a -// value is found. -func getCustomCABundle(ctx context.Context, configs configs) (value io.Reader, found bool, err error) { - for _, cfg := range configs { - if p, ok := cfg.(customCABundleProvider); ok { - value, found, err = p.getCustomCABundle(ctx) - if err != nil || found { - break - } - } - } - - return -} - -// regionProvider provides access to the region external configuration value. -type regionProvider interface { - getRegion(ctx context.Context) (string, bool, error) -} - -// getRegion searches the configs for a regionProvider and returns the value -// if found. Returns an error if a provider fails before a value is found. -func getRegion(ctx context.Context, configs configs) (value string, found bool, err error) { - for _, cfg := range configs { - if p, ok := cfg.(regionProvider); ok { - value, found, err = p.getRegion(ctx) - if err != nil || found { - break - } - } - } - return -} - -// appIDProvider provides access to the sdk app ID value -type appIDProvider interface { - getAppID(ctx context.Context) (string, bool, error) -} - -func getAppID(ctx context.Context, configs configs) (value string, found bool, err error) { - for _, cfg := range configs { - if p, ok := cfg.(appIDProvider); ok { - value, found, err = p.getAppID(ctx) - if err != nil || found { - break - } - } - } - return -} - -// ec2IMDSRegionProvider provides access to the ec2 imds region -// configuration value -type ec2IMDSRegionProvider interface { - getEC2IMDSRegion(ctx context.Context) (string, bool, error) -} - -// getEC2IMDSRegion searches the configs for a ec2IMDSRegionProvider and -// returns the value if found. Returns an error if a provider fails before -// a value is found. -func getEC2IMDSRegion(ctx context.Context, configs configs) (region string, found bool, err error) { - for _, cfg := range configs { - if provider, ok := cfg.(ec2IMDSRegionProvider); ok { - region, found, err = provider.getEC2IMDSRegion(ctx) - if err != nil || found { - break - } - } - } - return -} - -// credentialsProviderProvider provides access to the credentials external -// configuration value. -type credentialsProviderProvider interface { - getCredentialsProvider(ctx context.Context) (aws.CredentialsProvider, bool, error) -} - -// getCredentialsProvider searches the configs for a credentialsProviderProvider -// and returns the value if found. Returns an error if a provider fails before a -// value is found. -func getCredentialsProvider(ctx context.Context, configs configs) (p aws.CredentialsProvider, found bool, err error) { - for _, cfg := range configs { - if provider, ok := cfg.(credentialsProviderProvider); ok { - p, found, err = provider.getCredentialsProvider(ctx) - if err != nil || found { - break - } - } - } - return -} - -// credentialsCacheOptionsProvider is an interface for retrieving a function for setting -// the aws.CredentialsCacheOptions. -type credentialsCacheOptionsProvider interface { - getCredentialsCacheOptions(ctx context.Context) (func(*aws.CredentialsCacheOptions), bool, error) -} - -// getCredentialsCacheOptionsProvider is an interface for retrieving a function for setting -// the aws.CredentialsCacheOptions. -func getCredentialsCacheOptionsProvider(ctx context.Context, configs configs) ( - f func(*aws.CredentialsCacheOptions), found bool, err error, -) { - for _, config := range configs { - if p, ok := config.(credentialsCacheOptionsProvider); ok { - f, found, err = p.getCredentialsCacheOptions(ctx) - if err != nil || found { - break - } - } - } - return -} - -// bearerAuthTokenProviderProvider provides access to the bearer authentication -// token external configuration value. -type bearerAuthTokenProviderProvider interface { - getBearerAuthTokenProvider(context.Context) (smithybearer.TokenProvider, bool, error) -} - -// getBearerAuthTokenProvider searches the config sources for a -// bearerAuthTokenProviderProvider and returns the value if found. Returns an -// error if a provider fails before a value is found. -func getBearerAuthTokenProvider(ctx context.Context, configs configs) (p smithybearer.TokenProvider, found bool, err error) { - for _, cfg := range configs { - if provider, ok := cfg.(bearerAuthTokenProviderProvider); ok { - p, found, err = provider.getBearerAuthTokenProvider(ctx) - if err != nil || found { - break - } - } - } - return -} - -// bearerAuthTokenCacheOptionsProvider is an interface for retrieving a function for -// setting the smithy-go auth/bearer#TokenCacheOptions. -type bearerAuthTokenCacheOptionsProvider interface { - getBearerAuthTokenCacheOptions(context.Context) (func(*smithybearer.TokenCacheOptions), bool, error) -} - -// getBearerAuthTokenCacheOptionsProvider is an interface for retrieving a function for -// setting the smithy-go auth/bearer#TokenCacheOptions. -func getBearerAuthTokenCacheOptions(ctx context.Context, configs configs) ( - f func(*smithybearer.TokenCacheOptions), found bool, err error, -) { - for _, config := range configs { - if p, ok := config.(bearerAuthTokenCacheOptionsProvider); ok { - f, found, err = p.getBearerAuthTokenCacheOptions(ctx) - if err != nil || found { - break - } - } - } - return -} - -// ssoTokenProviderOptionsProvider is an interface for retrieving a function for -// setting the SDK's credentials/ssocreds#SSOTokenProviderOptions. -type ssoTokenProviderOptionsProvider interface { - getSSOTokenProviderOptions(context.Context) (func(*ssocreds.SSOTokenProviderOptions), bool, error) -} - -// getSSOTokenProviderOptions is an interface for retrieving a function for -// setting the SDK's credentials/ssocreds#SSOTokenProviderOptions. -func getSSOTokenProviderOptions(ctx context.Context, configs configs) ( - f func(*ssocreds.SSOTokenProviderOptions), found bool, err error, -) { - for _, config := range configs { - if p, ok := config.(ssoTokenProviderOptionsProvider); ok { - f, found, err = p.getSSOTokenProviderOptions(ctx) - if err != nil || found { - break - } - } - } - return -} - -// ssoTokenProviderOptionsProvider - -// processCredentialOptions is an interface for retrieving a function for setting -// the processcreds.Options. -type processCredentialOptions interface { - getProcessCredentialOptions(ctx context.Context) (func(*processcreds.Options), bool, error) -} - -// getProcessCredentialOptions searches the slice of configs and returns the first function found -func getProcessCredentialOptions(ctx context.Context, configs configs) (f func(*processcreds.Options), found bool, err error) { - for _, config := range configs { - if p, ok := config.(processCredentialOptions); ok { - f, found, err = p.getProcessCredentialOptions(ctx) - if err != nil || found { - break - } - } - } - return -} - -// ec2RoleCredentialOptionsProvider is an interface for retrieving a function -// for setting the ec2rolecreds.Provider options. -type ec2RoleCredentialOptionsProvider interface { - getEC2RoleCredentialOptions(ctx context.Context) (func(*ec2rolecreds.Options), bool, error) -} - -// getEC2RoleCredentialProviderOptions searches the slice of configs and returns the first function found -func getEC2RoleCredentialProviderOptions(ctx context.Context, configs configs) (f func(*ec2rolecreds.Options), found bool, err error) { - for _, config := range configs { - if p, ok := config.(ec2RoleCredentialOptionsProvider); ok { - f, found, err = p.getEC2RoleCredentialOptions(ctx) - if err != nil || found { - break - } - } - } - return -} - -// defaultRegionProvider is an interface for retrieving a default region if a region was not resolved from other sources -type defaultRegionProvider interface { - getDefaultRegion(ctx context.Context) (string, bool, error) -} - -// getDefaultRegion searches the slice of configs and returns the first fallback region found -func getDefaultRegion(ctx context.Context, configs configs) (value string, found bool, err error) { - for _, config := range configs { - if p, ok := config.(defaultRegionProvider); ok { - value, found, err = p.getDefaultRegion(ctx) - if err != nil || found { - break - } - } - } - return -} - -// endpointCredentialOptionsProvider is an interface for retrieving a function for setting -// the endpointcreds.ProviderOptions. -type endpointCredentialOptionsProvider interface { - getEndpointCredentialOptions(ctx context.Context) (func(*endpointcreds.Options), bool, error) -} - -// getEndpointCredentialProviderOptions searches the slice of configs and returns the first function found -func getEndpointCredentialProviderOptions(ctx context.Context, configs configs) (f func(*endpointcreds.Options), found bool, err error) { - for _, config := range configs { - if p, ok := config.(endpointCredentialOptionsProvider); ok { - f, found, err = p.getEndpointCredentialOptions(ctx) - if err != nil || found { - break - } - } - } - return -} - -// webIdentityRoleCredentialOptionsProvider is an interface for retrieving a function for setting -// the stscreds.WebIdentityRoleProvider. -type webIdentityRoleCredentialOptionsProvider interface { - getWebIdentityRoleCredentialOptions(ctx context.Context) (func(*stscreds.WebIdentityRoleOptions), bool, error) -} - -// getWebIdentityCredentialProviderOptions searches the slice of configs and returns the first function found -func getWebIdentityCredentialProviderOptions(ctx context.Context, configs configs) (f func(*stscreds.WebIdentityRoleOptions), found bool, err error) { - for _, config := range configs { - if p, ok := config.(webIdentityRoleCredentialOptionsProvider); ok { - f, found, err = p.getWebIdentityRoleCredentialOptions(ctx) - if err != nil || found { - break - } - } - } - return -} - -// assumeRoleCredentialOptionsProvider is an interface for retrieving a function for setting -// the stscreds.AssumeRoleOptions. -type assumeRoleCredentialOptionsProvider interface { - getAssumeRoleCredentialOptions(ctx context.Context) (func(*stscreds.AssumeRoleOptions), bool, error) -} - -// getAssumeRoleCredentialProviderOptions searches the slice of configs and returns the first function found -func getAssumeRoleCredentialProviderOptions(ctx context.Context, configs configs) (f func(*stscreds.AssumeRoleOptions), found bool, err error) { - for _, config := range configs { - if p, ok := config.(assumeRoleCredentialOptionsProvider); ok { - f, found, err = p.getAssumeRoleCredentialOptions(ctx) - if err != nil || found { - break - } - } - } - return -} - -// HTTPClient is an HTTP client implementation -type HTTPClient interface { - Do(*http.Request) (*http.Response, error) -} - -// httpClientProvider is an interface for retrieving HTTPClient -type httpClientProvider interface { - getHTTPClient(ctx context.Context) (HTTPClient, bool, error) -} - -// getHTTPClient searches the slice of configs and returns the HTTPClient set on configs -func getHTTPClient(ctx context.Context, configs configs) (client HTTPClient, found bool, err error) { - for _, config := range configs { - if p, ok := config.(httpClientProvider); ok { - client, found, err = p.getHTTPClient(ctx) - if err != nil || found { - break - } - } - } - return -} - -// apiOptionsProvider is an interface for retrieving APIOptions -type apiOptionsProvider interface { - getAPIOptions(ctx context.Context) ([]func(*middleware.Stack) error, bool, error) -} - -// getAPIOptions searches the slice of configs and returns the APIOptions set on configs -func getAPIOptions(ctx context.Context, configs configs) (apiOptions []func(*middleware.Stack) error, found bool, err error) { - for _, config := range configs { - if p, ok := config.(apiOptionsProvider); ok { - // retrieve APIOptions from configs and set it on cfg - apiOptions, found, err = p.getAPIOptions(ctx) - if err != nil || found { - break - } - } - } - return -} - -// endpointResolverProvider is an interface for retrieving an aws.EndpointResolver from a configuration source -type endpointResolverProvider interface { - getEndpointResolver(ctx context.Context) (aws.EndpointResolver, bool, error) -} - -// getEndpointResolver searches the provided config sources for a EndpointResolverFunc that can be used -// to configure the aws.Config.EndpointResolver value. -func getEndpointResolver(ctx context.Context, configs configs) (f aws.EndpointResolver, found bool, err error) { - for _, c := range configs { - if p, ok := c.(endpointResolverProvider); ok { - f, found, err = p.getEndpointResolver(ctx) - if err != nil || found { - break - } - } - } - return -} - -// endpointResolverWithOptionsProvider is an interface for retrieving an aws.EndpointResolverWithOptions from a configuration source -type endpointResolverWithOptionsProvider interface { - getEndpointResolverWithOptions(ctx context.Context) (aws.EndpointResolverWithOptions, bool, error) -} - -// getEndpointResolver searches the provided config sources for a EndpointResolverFunc that can be used -// to configure the aws.Config.EndpointResolver value. -func getEndpointResolverWithOptions(ctx context.Context, configs configs) (f aws.EndpointResolverWithOptions, found bool, err error) { - for _, c := range configs { - if p, ok := c.(endpointResolverWithOptionsProvider); ok { - f, found, err = p.getEndpointResolverWithOptions(ctx) - if err != nil || found { - break - } - } - } - return -} - -// loggerProvider is an interface for retrieving a logging.Logger from a configuration source. -type loggerProvider interface { - getLogger(ctx context.Context) (logging.Logger, bool, error) -} - -// getLogger searches the provided config sources for a logging.Logger that can be used -// to configure the aws.Config.Logger value. -func getLogger(ctx context.Context, configs configs) (l logging.Logger, found bool, err error) { - for _, c := range configs { - if p, ok := c.(loggerProvider); ok { - l, found, err = p.getLogger(ctx) - if err != nil || found { - break - } - } - } - return -} - -// clientLogModeProvider is an interface for retrieving the aws.ClientLogMode from a configuration source. -type clientLogModeProvider interface { - getClientLogMode(ctx context.Context) (aws.ClientLogMode, bool, error) -} - -func getClientLogMode(ctx context.Context, configs configs) (m aws.ClientLogMode, found bool, err error) { - for _, c := range configs { - if p, ok := c.(clientLogModeProvider); ok { - m, found, err = p.getClientLogMode(ctx) - if err != nil || found { - break - } - } - } - return -} - -// retryProvider is an configuration provider for custom Retryer. -type retryProvider interface { - getRetryer(ctx context.Context) (func() aws.Retryer, bool, error) -} - -func getRetryer(ctx context.Context, configs configs) (v func() aws.Retryer, found bool, err error) { - for _, c := range configs { - if p, ok := c.(retryProvider); ok { - v, found, err = p.getRetryer(ctx) - if err != nil || found { - break - } - } - } - return -} - -// logConfigurationWarningsProvider is an configuration provider for -// retrieving a boolean indicating whether configuration issues should -// be logged when loading from config sources -type logConfigurationWarningsProvider interface { - getLogConfigurationWarnings(ctx context.Context) (bool, bool, error) -} - -func getLogConfigurationWarnings(ctx context.Context, configs configs) (v bool, found bool, err error) { - for _, c := range configs { - if p, ok := c.(logConfigurationWarningsProvider); ok { - v, found, err = p.getLogConfigurationWarnings(ctx) - if err != nil || found { - break - } - } - } - return -} - -// ssoCredentialOptionsProvider is an interface for retrieving a function for setting -// the ssocreds.Options. -type ssoCredentialOptionsProvider interface { - getSSOProviderOptions(context.Context) (func(*ssocreds.Options), bool, error) -} - -func getSSOProviderOptions(ctx context.Context, configs configs) (v func(options *ssocreds.Options), found bool, err error) { - for _, c := range configs { - if p, ok := c.(ssoCredentialOptionsProvider); ok { - v, found, err = p.getSSOProviderOptions(ctx) - if err != nil || found { - break - } - } - } - return v, found, err -} - -type defaultsModeIMDSClientProvider interface { - getDefaultsModeIMDSClient(context.Context) (*imds.Client, bool, error) -} - -func getDefaultsModeIMDSClient(ctx context.Context, configs configs) (v *imds.Client, found bool, err error) { - for _, c := range configs { - if p, ok := c.(defaultsModeIMDSClientProvider); ok { - v, found, err = p.getDefaultsModeIMDSClient(ctx) - if err != nil || found { - break - } - } - } - return v, found, err -} - -type defaultsModeProvider interface { - getDefaultsMode(context.Context) (aws.DefaultsMode, bool, error) -} - -func getDefaultsMode(ctx context.Context, configs configs) (v aws.DefaultsMode, found bool, err error) { - for _, c := range configs { - if p, ok := c.(defaultsModeProvider); ok { - v, found, err = p.getDefaultsMode(ctx) - if err != nil || found { - break - } - } - } - return v, found, err -} - -type retryMaxAttemptsProvider interface { - GetRetryMaxAttempts(context.Context) (int, bool, error) -} - -func getRetryMaxAttempts(ctx context.Context, configs configs) (v int, found bool, err error) { - for _, c := range configs { - if p, ok := c.(retryMaxAttemptsProvider); ok { - v, found, err = p.GetRetryMaxAttempts(ctx) - if err != nil || found { - break - } - } - } - return v, found, err -} - -type retryModeProvider interface { - GetRetryMode(context.Context) (aws.RetryMode, bool, error) -} - -func getRetryMode(ctx context.Context, configs configs) (v aws.RetryMode, found bool, err error) { - for _, c := range configs { - if p, ok := c.(retryModeProvider); ok { - v, found, err = p.GetRetryMode(ctx) - if err != nil || found { - break - } - } - } - return v, found, err -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/resolve.go b/vendor/github.com/aws/aws-sdk-go-v2/config/resolve.go deleted file mode 100644 index b03705350..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/resolve.go +++ /dev/null @@ -1,322 +0,0 @@ -package config - -import ( - "context" - "crypto/tls" - "crypto/x509" - "fmt" - "io/ioutil" - "net/http" - "os" - - "github.com/aws/aws-sdk-go-v2/aws" - awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" - "github.com/aws/aws-sdk-go-v2/feature/ec2/imds" - "github.com/aws/smithy-go/logging" -) - -// resolveDefaultAWSConfig will write default configuration values into the cfg -// value. It will write the default values, overwriting any previous value. -// -// This should be used as the first resolver in the slice of resolvers when -// resolving external configuration. -func resolveDefaultAWSConfig(ctx context.Context, cfg *aws.Config, cfgs configs) error { - var sources []interface{} - for _, s := range cfgs { - sources = append(sources, s) - } - - *cfg = aws.Config{ - Credentials: aws.AnonymousCredentials{}, - Logger: logging.NewStandardLogger(os.Stderr), - ConfigSources: sources, - } - return nil -} - -// resolveCustomCABundle extracts the first instance of a custom CA bundle filename -// from the external configurations. It will update the HTTP Client's builder -// to be configured with the custom CA bundle. -// -// Config provider used: -// * customCABundleProvider -func resolveCustomCABundle(ctx context.Context, cfg *aws.Config, cfgs configs) error { - pemCerts, found, err := getCustomCABundle(ctx, cfgs) - if err != nil { - // TODO error handling, What is the best way to handle this? - // capture previous errors continue. error out if all errors - return err - } - if !found { - return nil - } - - if cfg.HTTPClient == nil { - cfg.HTTPClient = awshttp.NewBuildableClient() - } - - trOpts, ok := cfg.HTTPClient.(*awshttp.BuildableClient) - if !ok { - return fmt.Errorf("unable to add custom RootCAs HTTPClient, "+ - "has no WithTransportOptions, %T", cfg.HTTPClient) - } - - var appendErr error - client := trOpts.WithTransportOptions(func(tr *http.Transport) { - if tr.TLSClientConfig == nil { - tr.TLSClientConfig = &tls.Config{} - } - if tr.TLSClientConfig.RootCAs == nil { - tr.TLSClientConfig.RootCAs = x509.NewCertPool() - } - - b, err := ioutil.ReadAll(pemCerts) - if err != nil { - appendErr = fmt.Errorf("failed to read custom CA bundle PEM file") - } - - if !tr.TLSClientConfig.RootCAs.AppendCertsFromPEM(b) { - appendErr = fmt.Errorf("failed to load custom CA bundle PEM file") - } - }) - if appendErr != nil { - return appendErr - } - - cfg.HTTPClient = client - return err -} - -// resolveRegion extracts the first instance of a Region from the configs slice. -// -// Config providers used: -// * regionProvider -func resolveRegion(ctx context.Context, cfg *aws.Config, configs configs) error { - v, found, err := getRegion(ctx, configs) - if err != nil { - // TODO error handling, What is the best way to handle this? - // capture previous errors continue. error out if all errors - return err - } - if !found { - return nil - } - - cfg.Region = v - return nil -} - -// resolveAppID extracts the sdk app ID from the configs slice's SharedConfig or env var -func resolveAppID(ctx context.Context, cfg *aws.Config, configs configs) error { - ID, _, err := getAppID(ctx, configs) - if err != nil { - return err - } - - // if app ID is set in env var, it should precedence shared config value - if appID := os.Getenv(`AWS_SDK_UA_APP_ID`); len(appID) > 0 { - ID = appID - } - cfg.AppID = ID - return nil -} - -// resolveDefaultRegion extracts the first instance of a default region and sets `aws.Config.Region` to the default -// region if region had not been resolved from other sources. -func resolveDefaultRegion(ctx context.Context, cfg *aws.Config, configs configs) error { - if len(cfg.Region) > 0 { - return nil - } - - v, found, err := getDefaultRegion(ctx, configs) - if err != nil { - return err - } - if !found { - return nil - } - - cfg.Region = v - - return nil -} - -// resolveHTTPClient extracts the first instance of a HTTPClient and sets `aws.Config.HTTPClient` to the HTTPClient instance -// if one has not been resolved from other sources. -func resolveHTTPClient(ctx context.Context, cfg *aws.Config, configs configs) error { - c, found, err := getHTTPClient(ctx, configs) - if err != nil { - return err - } - if !found { - return nil - } - - cfg.HTTPClient = c - return nil -} - -// resolveAPIOptions extracts the first instance of APIOptions and sets `aws.Config.APIOptions` to the resolved API options -// if one has not been resolved from other sources. -func resolveAPIOptions(ctx context.Context, cfg *aws.Config, configs configs) error { - o, found, err := getAPIOptions(ctx, configs) - if err != nil { - return err - } - if !found { - return nil - } - - cfg.APIOptions = o - - return nil -} - -// resolveEndpointResolver extracts the first instance of a EndpointResolverFunc from the config slice -// and sets the functions result on the aws.Config.EndpointResolver -func resolveEndpointResolver(ctx context.Context, cfg *aws.Config, configs configs) error { - endpointResolver, found, err := getEndpointResolver(ctx, configs) - if err != nil { - return err - } - if !found { - return nil - } - - cfg.EndpointResolver = endpointResolver - - return nil -} - -// resolveEndpointResolver extracts the first instance of a EndpointResolverFunc from the config slice -// and sets the functions result on the aws.Config.EndpointResolver -func resolveEndpointResolverWithOptions(ctx context.Context, cfg *aws.Config, configs configs) error { - endpointResolver, found, err := getEndpointResolverWithOptions(ctx, configs) - if err != nil { - return err - } - if !found { - return nil - } - - cfg.EndpointResolverWithOptions = endpointResolver - - return nil -} - -func resolveLogger(ctx context.Context, cfg *aws.Config, configs configs) error { - logger, found, err := getLogger(ctx, configs) - if err != nil { - return err - } - if !found { - return nil - } - - cfg.Logger = logger - - return nil -} - -func resolveClientLogMode(ctx context.Context, cfg *aws.Config, configs configs) error { - mode, found, err := getClientLogMode(ctx, configs) - if err != nil { - return err - } - if !found { - return nil - } - - cfg.ClientLogMode = mode - - return nil -} - -func resolveRetryer(ctx context.Context, cfg *aws.Config, configs configs) error { - retryer, found, err := getRetryer(ctx, configs) - if err != nil { - return err - } - - if found { - cfg.Retryer = retryer - return nil - } - - // Only load the retry options if a custom retryer has not be specified. - if err = resolveRetryMaxAttempts(ctx, cfg, configs); err != nil { - return err - } - return resolveRetryMode(ctx, cfg, configs) -} - -func resolveEC2IMDSRegion(ctx context.Context, cfg *aws.Config, configs configs) error { - if len(cfg.Region) > 0 { - return nil - } - - region, found, err := getEC2IMDSRegion(ctx, configs) - if err != nil { - return err - } - if !found { - return nil - } - - cfg.Region = region - - return nil -} - -func resolveDefaultsModeOptions(ctx context.Context, cfg *aws.Config, configs configs) error { - defaultsMode, found, err := getDefaultsMode(ctx, configs) - if err != nil { - return err - } - if !found { - defaultsMode = aws.DefaultsModeLegacy - } - - var environment aws.RuntimeEnvironment - if defaultsMode == aws.DefaultsModeAuto { - envConfig, _, _ := getAWSConfigSources(configs) - - client, found, err := getDefaultsModeIMDSClient(ctx, configs) - if err != nil { - return err - } - if !found { - client = imds.NewFromConfig(*cfg) - } - - environment, err = resolveDefaultsModeRuntimeEnvironment(ctx, envConfig, client) - if err != nil { - return err - } - } - - cfg.DefaultsMode = defaultsMode - cfg.RuntimeEnvironment = environment - - return nil -} - -func resolveRetryMaxAttempts(ctx context.Context, cfg *aws.Config, configs configs) error { - maxAttempts, found, err := getRetryMaxAttempts(ctx, configs) - if err != nil || !found { - return err - } - cfg.RetryMaxAttempts = maxAttempts - - return nil -} - -func resolveRetryMode(ctx context.Context, cfg *aws.Config, configs configs) error { - retryMode, found, err := getRetryMode(ctx, configs) - if err != nil || !found { - return err - } - cfg.RetryMode = retryMode - - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/resolve_bearer_token.go b/vendor/github.com/aws/aws-sdk-go-v2/config/resolve_bearer_token.go deleted file mode 100644 index a8ebb3c0a..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/resolve_bearer_token.go +++ /dev/null @@ -1,122 +0,0 @@ -package config - -import ( - "context" - "fmt" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/credentials/ssocreds" - "github.com/aws/aws-sdk-go-v2/service/ssooidc" - smithybearer "github.com/aws/smithy-go/auth/bearer" -) - -// resolveBearerAuthToken extracts a token provider from the config sources. -// -// If an explicit bearer authentication token provider is not found the -// resolver will fallback to resolving token provider via other config sources -// such as SharedConfig. -func resolveBearerAuthToken(ctx context.Context, cfg *aws.Config, configs configs) error { - found, err := resolveBearerAuthTokenProvider(ctx, cfg, configs) - if found || err != nil { - return err - } - - return resolveBearerAuthTokenProviderChain(ctx, cfg, configs) -} - -// resolveBearerAuthTokenProvider extracts the first instance of -// BearerAuthTokenProvider from the config sources. -// -// The resolved BearerAuthTokenProvider will be wrapped in a cache to ensure -// the Token is only refreshed when needed. This also protects the -// TokenProvider so it can be used concurrently. -// -// Config providers used: -// * bearerAuthTokenProviderProvider -func resolveBearerAuthTokenProvider(ctx context.Context, cfg *aws.Config, configs configs) (bool, error) { - tokenProvider, found, err := getBearerAuthTokenProvider(ctx, configs) - if !found || err != nil { - return false, err - } - - cfg.BearerAuthTokenProvider, err = wrapWithBearerAuthTokenCache( - ctx, configs, tokenProvider) - if err != nil { - return false, err - } - - return true, nil -} - -func resolveBearerAuthTokenProviderChain(ctx context.Context, cfg *aws.Config, configs configs) (err error) { - _, sharedConfig, _ := getAWSConfigSources(configs) - - var provider smithybearer.TokenProvider - - if sharedConfig.SSOSession != nil { - provider, err = resolveBearerAuthSSOTokenProvider( - ctx, cfg, sharedConfig.SSOSession, configs) - } - - if err == nil && provider != nil { - cfg.BearerAuthTokenProvider, err = wrapWithBearerAuthTokenCache( - ctx, configs, provider) - } - - return err -} - -func resolveBearerAuthSSOTokenProvider(ctx context.Context, cfg *aws.Config, session *SSOSession, configs configs) (*ssocreds.SSOTokenProvider, error) { - ssoTokenProviderOptionsFn, found, err := getSSOTokenProviderOptions(ctx, configs) - if err != nil { - return nil, fmt.Errorf("failed to get SSOTokenProviderOptions from config sources, %w", err) - } - - var optFns []func(*ssocreds.SSOTokenProviderOptions) - if found { - optFns = append(optFns, ssoTokenProviderOptionsFn) - } - - cachePath, err := ssocreds.StandardCachedTokenFilepath(session.Name) - if err != nil { - return nil, fmt.Errorf("failed to get SSOTokenProvider's cache path, %w", err) - } - - client := ssooidc.NewFromConfig(*cfg) - provider := ssocreds.NewSSOTokenProvider(client, cachePath, optFns...) - - return provider, nil -} - -// wrapWithBearerAuthTokenCache will wrap provider with an smithy-go -// bearer/auth#TokenCache with the provided options if the provider is not -// already a TokenCache. -func wrapWithBearerAuthTokenCache( - ctx context.Context, - cfgs configs, - provider smithybearer.TokenProvider, - optFns ...func(*smithybearer.TokenCacheOptions), -) (smithybearer.TokenProvider, error) { - _, ok := provider.(*smithybearer.TokenCache) - if ok { - return provider, nil - } - - tokenCacheConfigOptions, optionsFound, err := getBearerAuthTokenCacheOptions(ctx, cfgs) - if err != nil { - return nil, err - } - - opts := make([]func(*smithybearer.TokenCacheOptions), 0, 2+len(optFns)) - opts = append(opts, func(o *smithybearer.TokenCacheOptions) { - o.RefreshBeforeExpires = 5 * time.Minute - o.RetrieveBearerTokenTimeout = 30 * time.Second - }) - opts = append(opts, optFns...) - if optionsFound { - opts = append(opts, tokenCacheConfigOptions) - } - - return smithybearer.NewTokenCache(provider, opts...), nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/resolve_credentials.go b/vendor/github.com/aws/aws-sdk-go-v2/config/resolve_credentials.go deleted file mode 100644 index b21cd3080..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/resolve_credentials.go +++ /dev/null @@ -1,499 +0,0 @@ -package config - -import ( - "context" - "fmt" - "net/url" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/credentials" - "github.com/aws/aws-sdk-go-v2/credentials/ec2rolecreds" - "github.com/aws/aws-sdk-go-v2/credentials/endpointcreds" - "github.com/aws/aws-sdk-go-v2/credentials/processcreds" - "github.com/aws/aws-sdk-go-v2/credentials/ssocreds" - "github.com/aws/aws-sdk-go-v2/credentials/stscreds" - "github.com/aws/aws-sdk-go-v2/feature/ec2/imds" - "github.com/aws/aws-sdk-go-v2/service/sso" - "github.com/aws/aws-sdk-go-v2/service/ssooidc" - "github.com/aws/aws-sdk-go-v2/service/sts" -) - -const ( - // valid credential source values - credSourceEc2Metadata = "Ec2InstanceMetadata" - credSourceEnvironment = "Environment" - credSourceECSContainer = "EcsContainer" -) - -var ( - ecsContainerEndpoint = "http://169.254.170.2" // not constant to allow for swapping during unit-testing -) - -// resolveCredentials extracts a credential provider from slice of config -// sources. -// -// If an explicit credential provider is not found the resolver will fallback -// to resolving credentials by extracting a credential provider from EnvConfig -// and SharedConfig. -func resolveCredentials(ctx context.Context, cfg *aws.Config, configs configs) error { - found, err := resolveCredentialProvider(ctx, cfg, configs) - if found || err != nil { - return err - } - - return resolveCredentialChain(ctx, cfg, configs) -} - -// resolveCredentialProvider extracts the first instance of Credentials from the -// config slices. -// -// The resolved CredentialProvider will be wrapped in a cache to ensure the -// credentials are only refreshed when needed. This also protects the -// credential provider to be used concurrently. -// -// Config providers used: -// * credentialsProviderProvider -func resolveCredentialProvider(ctx context.Context, cfg *aws.Config, configs configs) (bool, error) { - credProvider, found, err := getCredentialsProvider(ctx, configs) - if !found || err != nil { - return false, err - } - - cfg.Credentials, err = wrapWithCredentialsCache(ctx, configs, credProvider) - if err != nil { - return false, err - } - - return true, nil -} - -// resolveCredentialChain resolves a credential provider chain using EnvConfig -// and SharedConfig if present in the slice of provided configs. -// -// The resolved CredentialProvider will be wrapped in a cache to ensure the -// credentials are only refreshed when needed. This also protects the -// credential provider to be used concurrently. -func resolveCredentialChain(ctx context.Context, cfg *aws.Config, configs configs) (err error) { - envConfig, sharedConfig, other := getAWSConfigSources(configs) - - // When checking if a profile was specified programmatically we should only consider the "other" - // configuration sources that have been provided. This ensures we correctly honor the expected credential - // hierarchy. - _, sharedProfileSet, err := getSharedConfigProfile(ctx, other) - if err != nil { - return err - } - - switch { - case sharedProfileSet: - err = resolveCredsFromProfile(ctx, cfg, envConfig, sharedConfig, other) - case envConfig.Credentials.HasKeys(): - cfg.Credentials = credentials.StaticCredentialsProvider{Value: envConfig.Credentials} - case len(envConfig.WebIdentityTokenFilePath) > 0: - err = assumeWebIdentity(ctx, cfg, envConfig.WebIdentityTokenFilePath, envConfig.RoleARN, envConfig.RoleSessionName, configs) - default: - err = resolveCredsFromProfile(ctx, cfg, envConfig, sharedConfig, other) - } - if err != nil { - return err - } - - // Wrap the resolved provider in a cache so the SDK will cache credentials. - cfg.Credentials, err = wrapWithCredentialsCache(ctx, configs, cfg.Credentials) - if err != nil { - return err - } - - return nil -} - -func resolveCredsFromProfile(ctx context.Context, cfg *aws.Config, envConfig *EnvConfig, sharedConfig *SharedConfig, configs configs) (err error) { - - switch { - case sharedConfig.Source != nil: - // Assume IAM role with credentials source from a different profile. - err = resolveCredsFromProfile(ctx, cfg, envConfig, sharedConfig.Source, configs) - - case sharedConfig.Credentials.HasKeys(): - // Static Credentials from Shared Config/Credentials file. - cfg.Credentials = credentials.StaticCredentialsProvider{ - Value: sharedConfig.Credentials, - } - - case len(sharedConfig.CredentialSource) != 0: - err = resolveCredsFromSource(ctx, cfg, envConfig, sharedConfig, configs) - - case len(sharedConfig.WebIdentityTokenFile) != 0: - // Credentials from Assume Web Identity token require an IAM Role, and - // that roll will be assumed. May be wrapped with another assume role - // via SourceProfile. - return assumeWebIdentity(ctx, cfg, sharedConfig.WebIdentityTokenFile, sharedConfig.RoleARN, sharedConfig.RoleSessionName, configs) - - case sharedConfig.hasSSOConfiguration(): - err = resolveSSOCredentials(ctx, cfg, sharedConfig, configs) - - case len(sharedConfig.CredentialProcess) != 0: - // Get credentials from CredentialProcess - err = processCredentials(ctx, cfg, sharedConfig, configs) - - case len(envConfig.ContainerCredentialsEndpoint) != 0: - err = resolveLocalHTTPCredProvider(ctx, cfg, envConfig.ContainerCredentialsEndpoint, envConfig.ContainerAuthorizationToken, configs) - - case len(envConfig.ContainerCredentialsRelativePath) != 0: - err = resolveHTTPCredProvider(ctx, cfg, ecsContainerURI(envConfig.ContainerCredentialsRelativePath), envConfig.ContainerAuthorizationToken, configs) - - default: - err = resolveEC2RoleCredentials(ctx, cfg, configs) - } - if err != nil { - return err - } - - if len(sharedConfig.RoleARN) > 0 { - return credsFromAssumeRole(ctx, cfg, sharedConfig, configs) - } - - return nil -} - -func resolveSSOCredentials(ctx context.Context, cfg *aws.Config, sharedConfig *SharedConfig, configs configs) error { - if err := sharedConfig.validateSSOConfiguration(); err != nil { - return err - } - - var options []func(*ssocreds.Options) - v, found, err := getSSOProviderOptions(ctx, configs) - if err != nil { - return err - } - if found { - options = append(options, v) - } - - cfgCopy := cfg.Copy() - - if sharedConfig.SSOSession != nil { - ssoTokenProviderOptionsFn, found, err := getSSOTokenProviderOptions(ctx, configs) - if err != nil { - return fmt.Errorf("failed to get SSOTokenProviderOptions from config sources, %w", err) - } - var optFns []func(*ssocreds.SSOTokenProviderOptions) - if found { - optFns = append(optFns, ssoTokenProviderOptionsFn) - } - cfgCopy.Region = sharedConfig.SSOSession.SSORegion - cachedPath, err := ssocreds.StandardCachedTokenFilepath(sharedConfig.SSOSession.Name) - if err != nil { - return err - } - oidcClient := ssooidc.NewFromConfig(cfgCopy) - tokenProvider := ssocreds.NewSSOTokenProvider(oidcClient, cachedPath, optFns...) - options = append(options, func(o *ssocreds.Options) { - o.SSOTokenProvider = tokenProvider - o.CachedTokenFilepath = cachedPath - }) - } else { - cfgCopy.Region = sharedConfig.SSORegion - } - - cfg.Credentials = ssocreds.New(sso.NewFromConfig(cfgCopy), sharedConfig.SSOAccountID, sharedConfig.SSORoleName, sharedConfig.SSOStartURL, options...) - - return nil -} - -func ecsContainerURI(path string) string { - return fmt.Sprintf("%s%s", ecsContainerEndpoint, path) -} - -func processCredentials(ctx context.Context, cfg *aws.Config, sharedConfig *SharedConfig, configs configs) error { - var opts []func(*processcreds.Options) - - options, found, err := getProcessCredentialOptions(ctx, configs) - if err != nil { - return err - } - if found { - opts = append(opts, options) - } - - cfg.Credentials = processcreds.NewProvider(sharedConfig.CredentialProcess, opts...) - - return nil -} - -func resolveLocalHTTPCredProvider(ctx context.Context, cfg *aws.Config, endpointURL, authToken string, configs configs) error { - var resolveErr error - - parsed, err := url.Parse(endpointURL) - if err != nil { - resolveErr = fmt.Errorf("invalid URL, %w", err) - } else { - host := parsed.Hostname() - if len(host) == 0 { - resolveErr = fmt.Errorf("unable to parse host from local HTTP cred provider URL") - } else if isLoopback, loopbackErr := isLoopbackHost(host); loopbackErr != nil { - resolveErr = fmt.Errorf("failed to resolve host %q, %v", host, loopbackErr) - } else if !isLoopback { - resolveErr = fmt.Errorf("invalid endpoint host, %q, only loopback hosts are allowed", host) - } - } - - if resolveErr != nil { - return resolveErr - } - - return resolveHTTPCredProvider(ctx, cfg, endpointURL, authToken, configs) -} - -func resolveHTTPCredProvider(ctx context.Context, cfg *aws.Config, url, authToken string, configs configs) error { - optFns := []func(*endpointcreds.Options){ - func(options *endpointcreds.Options) { - if len(authToken) != 0 { - options.AuthorizationToken = authToken - } - options.APIOptions = cfg.APIOptions - if cfg.Retryer != nil { - options.Retryer = cfg.Retryer() - } - }, - } - - optFn, found, err := getEndpointCredentialProviderOptions(ctx, configs) - if err != nil { - return err - } - if found { - optFns = append(optFns, optFn) - } - - provider := endpointcreds.New(url, optFns...) - - cfg.Credentials, err = wrapWithCredentialsCache(ctx, configs, provider, func(options *aws.CredentialsCacheOptions) { - options.ExpiryWindow = 5 * time.Minute - }) - if err != nil { - return err - } - - return nil -} - -func resolveCredsFromSource(ctx context.Context, cfg *aws.Config, envConfig *EnvConfig, sharedCfg *SharedConfig, configs configs) (err error) { - switch sharedCfg.CredentialSource { - case credSourceEc2Metadata: - return resolveEC2RoleCredentials(ctx, cfg, configs) - - case credSourceEnvironment: - cfg.Credentials = credentials.StaticCredentialsProvider{Value: envConfig.Credentials} - - case credSourceECSContainer: - if len(envConfig.ContainerCredentialsRelativePath) == 0 { - return fmt.Errorf("EcsContainer was specified as the credential_source, but 'AWS_CONTAINER_CREDENTIALS_RELATIVE_URI' was not set") - } - return resolveHTTPCredProvider(ctx, cfg, ecsContainerURI(envConfig.ContainerCredentialsRelativePath), envConfig.ContainerAuthorizationToken, configs) - - default: - return fmt.Errorf("credential_source values must be EcsContainer, Ec2InstanceMetadata, or Environment") - } - - return nil -} - -func resolveEC2RoleCredentials(ctx context.Context, cfg *aws.Config, configs configs) error { - optFns := make([]func(*ec2rolecreds.Options), 0, 2) - - optFn, found, err := getEC2RoleCredentialProviderOptions(ctx, configs) - if err != nil { - return err - } - if found { - optFns = append(optFns, optFn) - } - - optFns = append(optFns, func(o *ec2rolecreds.Options) { - // Only define a client from config if not already defined. - if o.Client == nil { - o.Client = imds.NewFromConfig(*cfg) - } - }) - - provider := ec2rolecreds.New(optFns...) - - cfg.Credentials, err = wrapWithCredentialsCache(ctx, configs, provider) - if err != nil { - return err - } - - return nil -} - -func getAWSConfigSources(cfgs configs) (*EnvConfig, *SharedConfig, configs) { - var ( - envConfig *EnvConfig - sharedConfig *SharedConfig - other configs - ) - - for i := range cfgs { - switch c := cfgs[i].(type) { - case EnvConfig: - if envConfig == nil { - envConfig = &c - } - case *EnvConfig: - if envConfig == nil { - envConfig = c - } - case SharedConfig: - if sharedConfig == nil { - sharedConfig = &c - } - case *SharedConfig: - if envConfig == nil { - sharedConfig = c - } - default: - other = append(other, c) - } - } - - if envConfig == nil { - envConfig = &EnvConfig{} - } - - if sharedConfig == nil { - sharedConfig = &SharedConfig{} - } - - return envConfig, sharedConfig, other -} - -// AssumeRoleTokenProviderNotSetError is an error returned when creating a -// session when the MFAToken option is not set when shared config is configured -// load assume a role with an MFA token. -type AssumeRoleTokenProviderNotSetError struct{} - -// Error is the error message -func (e AssumeRoleTokenProviderNotSetError) Error() string { - return fmt.Sprintf("assume role with MFA enabled, but AssumeRoleTokenProvider session option not set.") -} - -func assumeWebIdentity(ctx context.Context, cfg *aws.Config, filepath string, roleARN, sessionName string, configs configs) error { - if len(filepath) == 0 { - return fmt.Errorf("token file path is not set") - } - - optFns := []func(*stscreds.WebIdentityRoleOptions){ - func(options *stscreds.WebIdentityRoleOptions) { - options.RoleSessionName = sessionName - }, - } - - optFn, found, err := getWebIdentityCredentialProviderOptions(ctx, configs) - if err != nil { - return err - } - - if found { - optFns = append(optFns, optFn) - } - - opts := stscreds.WebIdentityRoleOptions{ - RoleARN: roleARN, - } - - for _, fn := range optFns { - fn(&opts) - } - - if len(opts.RoleARN) == 0 { - return fmt.Errorf("role ARN is not set") - } - - client := opts.Client - if client == nil { - client = sts.NewFromConfig(*cfg) - } - - provider := stscreds.NewWebIdentityRoleProvider(client, roleARN, stscreds.IdentityTokenFile(filepath), optFns...) - - cfg.Credentials = provider - - return nil -} - -func credsFromAssumeRole(ctx context.Context, cfg *aws.Config, sharedCfg *SharedConfig, configs configs) (err error) { - optFns := []func(*stscreds.AssumeRoleOptions){ - func(options *stscreds.AssumeRoleOptions) { - options.RoleSessionName = sharedCfg.RoleSessionName - if sharedCfg.RoleDurationSeconds != nil { - if *sharedCfg.RoleDurationSeconds/time.Minute > 15 { - options.Duration = *sharedCfg.RoleDurationSeconds - } - } - // Assume role with external ID - if len(sharedCfg.ExternalID) > 0 { - options.ExternalID = aws.String(sharedCfg.ExternalID) - } - - // Assume role with MFA - if len(sharedCfg.MFASerial) != 0 { - options.SerialNumber = aws.String(sharedCfg.MFASerial) - } - }, - } - - optFn, found, err := getAssumeRoleCredentialProviderOptions(ctx, configs) - if err != nil { - return err - } - if found { - optFns = append(optFns, optFn) - } - - { - // Synthesize options early to validate configuration errors sooner to ensure a token provider - // is present if the SerialNumber was set. - var o stscreds.AssumeRoleOptions - for _, fn := range optFns { - fn(&o) - } - if o.TokenProvider == nil && o.SerialNumber != nil { - return AssumeRoleTokenProviderNotSetError{} - } - } - - cfg.Credentials = stscreds.NewAssumeRoleProvider(sts.NewFromConfig(*cfg), sharedCfg.RoleARN, optFns...) - - return nil -} - -// wrapWithCredentialsCache will wrap provider with an aws.CredentialsCache -// with the provided options if the provider is not already a -// aws.CredentialsCache. -func wrapWithCredentialsCache( - ctx context.Context, - cfgs configs, - provider aws.CredentialsProvider, - optFns ...func(options *aws.CredentialsCacheOptions), -) (aws.CredentialsProvider, error) { - _, ok := provider.(*aws.CredentialsCache) - if ok { - return provider, nil - } - - credCacheOptions, optionsFound, err := getCredentialsCacheOptionsProvider(ctx, cfgs) - if err != nil { - return nil, err - } - - // force allocation of a new slice if the additional options are - // needed, to prevent overwriting the passed in slice of options. - optFns = optFns[:len(optFns):len(optFns)] - if optionsFound { - optFns = append(optFns, credCacheOptions) - } - - return aws.NewCredentialsCache(provider, optFns...), nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/shared_config.go b/vendor/github.com/aws/aws-sdk-go-v2/config/shared_config.go deleted file mode 100644 index e699194d3..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/shared_config.go +++ /dev/null @@ -1,1397 +0,0 @@ -package config - -import ( - "bytes" - "context" - "errors" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "strings" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/feature/ec2/imds" - "github.com/aws/aws-sdk-go-v2/internal/ini" - "github.com/aws/aws-sdk-go-v2/internal/shareddefaults" - "github.com/aws/smithy-go/logging" -) - -const ( - // Prefix to use for filtering profiles. The profile prefix should only - // exist in the shared config file, not the credentials file. - profilePrefix = `profile ` - - // Prefix to be used for SSO sections. These are supposed to only exist in - // the shared config file, not the credentials file. - ssoSectionPrefix = `sso-session ` - - // string equivalent for boolean - endpointDiscoveryDisabled = `false` - endpointDiscoveryEnabled = `true` - endpointDiscoveryAuto = `auto` - - // Static Credentials group - accessKeyIDKey = `aws_access_key_id` // group required - secretAccessKey = `aws_secret_access_key` // group required - sessionTokenKey = `aws_session_token` // optional - - // Assume Role Credentials group - roleArnKey = `role_arn` // group required - sourceProfileKey = `source_profile` // group required - credentialSourceKey = `credential_source` // group required (or source_profile) - externalIDKey = `external_id` // optional - mfaSerialKey = `mfa_serial` // optional - roleSessionNameKey = `role_session_name` // optional - roleDurationSecondsKey = "duration_seconds" // optional - - // AWS Single Sign-On (AWS SSO) group - ssoSessionNameKey = "sso_session" - - ssoRegionKey = "sso_region" - ssoStartURLKey = "sso_start_url" - - ssoAccountIDKey = "sso_account_id" - ssoRoleNameKey = "sso_role_name" - - // Additional Config fields - regionKey = `region` - - // endpoint discovery group - enableEndpointDiscoveryKey = `endpoint_discovery_enabled` // optional - - // External Credential process - credentialProcessKey = `credential_process` // optional - - // Web Identity Token File - webIdentityTokenFileKey = `web_identity_token_file` // optional - - // S3 ARN Region Usage - s3UseARNRegionKey = "s3_use_arn_region" - - ec2MetadataServiceEndpointModeKey = "ec2_metadata_service_endpoint_mode" - - ec2MetadataServiceEndpointKey = "ec2_metadata_service_endpoint" - - // Use DualStack Endpoint Resolution - useDualStackEndpoint = "use_dualstack_endpoint" - - // DefaultSharedConfigProfile is the default profile to be used when - // loading configuration from the config files if another profile name - // is not provided. - DefaultSharedConfigProfile = `default` - - // S3 Disable Multi-Region AccessPoints - s3DisableMultiRegionAccessPointsKey = `s3_disable_multiregion_access_points` - - useFIPSEndpointKey = "use_fips_endpoint" - - defaultsModeKey = "defaults_mode" - - // Retry options - retryMaxAttemptsKey = "max_attempts" - retryModeKey = "retry_mode" - - caBundleKey = "ca_bundle" - - sdkAppID = "sdk_ua_app_id" -) - -// defaultSharedConfigProfile allows for swapping the default profile for testing -var defaultSharedConfigProfile = DefaultSharedConfigProfile - -// DefaultSharedCredentialsFilename returns the SDK's default file path -// for the shared credentials file. -// -// Builds the shared config file path based on the OS's platform. -// -// - Linux/Unix: $HOME/.aws/credentials -// - Windows: %USERPROFILE%\.aws\credentials -func DefaultSharedCredentialsFilename() string { - return filepath.Join(shareddefaults.UserHomeDir(), ".aws", "credentials") -} - -// DefaultSharedConfigFilename returns the SDK's default file path for -// the shared config file. -// -// Builds the shared config file path based on the OS's platform. -// -// - Linux/Unix: $HOME/.aws/config -// - Windows: %USERPROFILE%\.aws\config -func DefaultSharedConfigFilename() string { - return filepath.Join(shareddefaults.UserHomeDir(), ".aws", "config") -} - -// DefaultSharedConfigFiles is a slice of the default shared config files that -// the will be used in order to load the SharedConfig. -var DefaultSharedConfigFiles = []string{ - DefaultSharedConfigFilename(), -} - -// DefaultSharedCredentialsFiles is a slice of the default shared credentials -// files that the will be used in order to load the SharedConfig. -var DefaultSharedCredentialsFiles = []string{ - DefaultSharedCredentialsFilename(), -} - -// SSOSession provides the shared configuration parameters of the sso-session -// section. -type SSOSession struct { - Name string - SSORegion string - SSOStartURL string -} - -func (s *SSOSession) setFromIniSection(section ini.Section) { - updateString(&s.Name, section, ssoSessionNameKey) - updateString(&s.SSORegion, section, ssoRegionKey) - updateString(&s.SSOStartURL, section, ssoStartURLKey) -} - -// SharedConfig represents the configuration fields of the SDK config files. -type SharedConfig struct { - Profile string - - // Credentials values from the config file. Both aws_access_key_id - // and aws_secret_access_key must be provided together in the same file - // to be considered valid. The values will be ignored if not a complete group. - // aws_session_token is an optional field that can be provided if both of the - // other two fields are also provided. - // - // aws_access_key_id - // aws_secret_access_key - // aws_session_token - Credentials aws.Credentials - - CredentialSource string - CredentialProcess string - WebIdentityTokenFile string - - // SSO session options - SSOSessionName string - SSOSession *SSOSession - - // Legacy SSO session options - SSORegion string - SSOStartURL string - - // SSO fields not used - SSOAccountID string - SSORoleName string - - RoleARN string - ExternalID string - MFASerial string - RoleSessionName string - RoleDurationSeconds *time.Duration - - SourceProfileName string - Source *SharedConfig - - // Region is the region the SDK should use for looking up AWS service endpoints - // and signing requests. - // - // region = us-west-2 - Region string - - // EnableEndpointDiscovery can be enabled or disabled in the shared config - // by setting endpoint_discovery_enabled to true, or false respectively. - // - // endpoint_discovery_enabled = true - EnableEndpointDiscovery aws.EndpointDiscoveryEnableState - - // Specifies if the S3 service should allow ARNs to direct the region - // the client's requests are sent to. - // - // s3_use_arn_region=true - S3UseARNRegion *bool - - // Specifies the EC2 Instance Metadata Service default endpoint selection - // mode (IPv4 or IPv6) - // - // ec2_metadata_service_endpoint_mode=IPv6 - EC2IMDSEndpointMode imds.EndpointModeState - - // Specifies the EC2 Instance Metadata Service endpoint to use. If - // specified it overrides EC2IMDSEndpointMode. - // - // ec2_metadata_service_endpoint=http://fd00:ec2::254 - EC2IMDSEndpoint string - - // Specifies if the S3 service should disable support for Multi-Region - // access-points - // - // s3_disable_multiregion_access_points=true - S3DisableMultiRegionAccessPoints *bool - - // Specifies that SDK clients must resolve a dual-stack endpoint for - // services. - // - // use_dualstack_endpoint=true - UseDualStackEndpoint aws.DualStackEndpointState - - // Specifies that SDK clients must resolve a FIPS endpoint for - // services. - // - // use_fips_endpoint=true - UseFIPSEndpoint aws.FIPSEndpointState - - // Specifies which defaults mode should be used by services. - // - // defaults_mode=standard - DefaultsMode aws.DefaultsMode - - // Specifies the maximum number attempts an API client will call an - // operation that fails with a retryable error. - // - // max_attempts=3 - RetryMaxAttempts int - - // Specifies the retry model the API client will be created with. - // - // retry_mode=standard - RetryMode aws.RetryMode - - // Sets the path to a custom Credentials Authority (CA) Bundle PEM file - // that the SDK will use instead of the system's root CA bundle. Only use - // this if you want to configure the SDK to use a custom set of CAs. - // - // Enabling this option will attempt to merge the Transport into the SDK's - // HTTP client. If the client's Transport is not a http.Transport an error - // will be returned. If the Transport's TLS config is set this option will - // cause the SDK to overwrite the Transport's TLS config's RootCAs value. - // - // Setting a custom HTTPClient in the aws.Config options will override this - // setting. To use this option and custom HTTP client, the HTTP client - // needs to be provided when creating the config. Not the service client. - // - // ca_bundle=$HOME/my_custom_ca_bundle - CustomCABundle string - - // aws sdk app ID that can be added to user agent header string - AppID string -} - -func (c SharedConfig) getDefaultsMode(ctx context.Context) (value aws.DefaultsMode, ok bool, err error) { - if len(c.DefaultsMode) == 0 { - return "", false, nil - } - - return c.DefaultsMode, true, nil -} - -// GetRetryMaxAttempts returns the maximum number of attempts an API client -// created Retryer should attempt an operation call before failing. -func (c SharedConfig) GetRetryMaxAttempts(ctx context.Context) (value int, ok bool, err error) { - if c.RetryMaxAttempts == 0 { - return 0, false, nil - } - - return c.RetryMaxAttempts, true, nil -} - -// GetRetryMode returns the model the API client should create its Retryer in. -func (c SharedConfig) GetRetryMode(ctx context.Context) (value aws.RetryMode, ok bool, err error) { - if len(c.RetryMode) == 0 { - return "", false, nil - } - - return c.RetryMode, true, nil -} - -// GetS3UseARNRegion returns if the S3 service should allow ARNs to direct the region -// the client's requests are sent to. -func (c SharedConfig) GetS3UseARNRegion(ctx context.Context) (value, ok bool, err error) { - if c.S3UseARNRegion == nil { - return false, false, nil - } - - return *c.S3UseARNRegion, true, nil -} - -// GetEnableEndpointDiscovery returns if the enable_endpoint_discovery is set. -func (c SharedConfig) GetEnableEndpointDiscovery(ctx context.Context) (value aws.EndpointDiscoveryEnableState, ok bool, err error) { - if c.EnableEndpointDiscovery == aws.EndpointDiscoveryUnset { - return aws.EndpointDiscoveryUnset, false, nil - } - - return c.EnableEndpointDiscovery, true, nil -} - -// GetS3DisableMultiRegionAccessPoints returns if the S3 service should disable support for Multi-Region -// access-points. -func (c SharedConfig) GetS3DisableMultiRegionAccessPoints(ctx context.Context) (value, ok bool, err error) { - if c.S3DisableMultiRegionAccessPoints == nil { - return false, false, nil - } - - return *c.S3DisableMultiRegionAccessPoints, true, nil -} - -// GetRegion returns the region for the profile if a region is set. -func (c SharedConfig) getRegion(ctx context.Context) (string, bool, error) { - if len(c.Region) == 0 { - return "", false, nil - } - return c.Region, true, nil -} - -// GetCredentialsProvider returns the credentials for a profile if they were set. -func (c SharedConfig) getCredentialsProvider() (aws.Credentials, bool, error) { - return c.Credentials, true, nil -} - -// GetEC2IMDSEndpointMode implements a EC2IMDSEndpointMode option resolver interface. -func (c SharedConfig) GetEC2IMDSEndpointMode() (imds.EndpointModeState, bool, error) { - if c.EC2IMDSEndpointMode == imds.EndpointModeStateUnset { - return imds.EndpointModeStateUnset, false, nil - } - - return c.EC2IMDSEndpointMode, true, nil -} - -// GetEC2IMDSEndpoint implements a EC2IMDSEndpoint option resolver interface. -func (c SharedConfig) GetEC2IMDSEndpoint() (string, bool, error) { - if len(c.EC2IMDSEndpoint) == 0 { - return "", false, nil - } - - return c.EC2IMDSEndpoint, true, nil -} - -// GetUseDualStackEndpoint returns whether the service's dual-stack endpoint should be -// used for requests. -func (c SharedConfig) GetUseDualStackEndpoint(ctx context.Context) (value aws.DualStackEndpointState, found bool, err error) { - if c.UseDualStackEndpoint == aws.DualStackEndpointStateUnset { - return aws.DualStackEndpointStateUnset, false, nil - } - - return c.UseDualStackEndpoint, true, nil -} - -// GetUseFIPSEndpoint returns whether the service's FIPS endpoint should be -// used for requests. -func (c SharedConfig) GetUseFIPSEndpoint(ctx context.Context) (value aws.FIPSEndpointState, found bool, err error) { - if c.UseFIPSEndpoint == aws.FIPSEndpointStateUnset { - return aws.FIPSEndpointStateUnset, false, nil - } - - return c.UseFIPSEndpoint, true, nil -} - -// GetCustomCABundle returns the custom CA bundle's PEM bytes if the file was -func (c SharedConfig) getCustomCABundle(context.Context) (io.Reader, bool, error) { - if len(c.CustomCABundle) == 0 { - return nil, false, nil - } - - b, err := ioutil.ReadFile(c.CustomCABundle) - if err != nil { - return nil, false, err - } - return bytes.NewReader(b), true, nil -} - -// getAppID returns the sdk app ID if set in shared config profile -func (c SharedConfig) getAppID(context.Context) (string, bool, error) { - return c.AppID, len(c.AppID) > 0, nil -} - -// loadSharedConfigIgnoreNotExist is an alias for loadSharedConfig with the -// addition of ignoring when none of the files exist or when the profile -// is not found in any of the files. -func loadSharedConfigIgnoreNotExist(ctx context.Context, configs configs) (Config, error) { - cfg, err := loadSharedConfig(ctx, configs) - if err != nil { - if _, ok := err.(SharedConfigProfileNotExistError); ok { - return SharedConfig{}, nil - } - return nil, err - } - - return cfg, nil -} - -// loadSharedConfig uses the configs passed in to load the SharedConfig from file -// The file names and profile name are sourced from the configs. -// -// If profile name is not provided DefaultSharedConfigProfile (default) will -// be used. -// -// If shared config filenames are not provided DefaultSharedConfigFiles will -// be used. -// -// Config providers used: -// * sharedConfigProfileProvider -// * sharedConfigFilesProvider -func loadSharedConfig(ctx context.Context, configs configs) (Config, error) { - var profile string - var configFiles []string - var credentialsFiles []string - var ok bool - var err error - - profile, ok, err = getSharedConfigProfile(ctx, configs) - if err != nil { - return nil, err - } - if !ok { - profile = defaultSharedConfigProfile - } - - configFiles, ok, err = getSharedConfigFiles(ctx, configs) - if err != nil { - return nil, err - } - - credentialsFiles, ok, err = getSharedCredentialsFiles(ctx, configs) - if err != nil { - return nil, err - } - - // setup logger if log configuration warning is seti - var logger logging.Logger - logWarnings, found, err := getLogConfigurationWarnings(ctx, configs) - if err != nil { - return SharedConfig{}, err - } - if found && logWarnings { - logger, found, err = getLogger(ctx, configs) - if err != nil { - return SharedConfig{}, err - } - if !found { - logger = logging.NewStandardLogger(os.Stderr) - } - } - - return LoadSharedConfigProfile(ctx, profile, - func(o *LoadSharedConfigOptions) { - o.Logger = logger - o.ConfigFiles = configFiles - o.CredentialsFiles = credentialsFiles - }, - ) -} - -// LoadSharedConfigOptions struct contains optional values that can be used to load the config. -type LoadSharedConfigOptions struct { - - // CredentialsFiles are the shared credentials files - CredentialsFiles []string - - // ConfigFiles are the shared config files - ConfigFiles []string - - // Logger is the logger used to log shared config behavior - Logger logging.Logger -} - -// LoadSharedConfigProfile retrieves the configuration from the list of files -// using the profile provided. The order the files are listed will determine -// precedence. Values in subsequent files will overwrite values defined in -// earlier files. -// -// For example, given two files A and B. Both define credentials. If the order -// of the files are A then B, B's credential values will be used instead of A's. -// -// If config files are not set, SDK will default to using a file at location `.aws/config` if present. -// If credentials files are not set, SDK will default to using a file at location `.aws/credentials` if present. -// No default files are set, if files set to an empty slice. -// -// You can read more about shared config and credentials file location at -// https://docs.aws.amazon.com/credref/latest/refdocs/file-location.html#file-location -func LoadSharedConfigProfile(ctx context.Context, profile string, optFns ...func(*LoadSharedConfigOptions)) (SharedConfig, error) { - var option LoadSharedConfigOptions - for _, fn := range optFns { - fn(&option) - } - - if option.ConfigFiles == nil { - option.ConfigFiles = DefaultSharedConfigFiles - } - - if option.CredentialsFiles == nil { - option.CredentialsFiles = DefaultSharedCredentialsFiles - } - - // load shared configuration sections from shared configuration INI options - configSections, err := loadIniFiles(option.ConfigFiles) - if err != nil { - return SharedConfig{}, err - } - - // check for profile prefix and drop duplicates or invalid profiles - err = processConfigSections(ctx, &configSections, option.Logger) - if err != nil { - return SharedConfig{}, err - } - - // load shared credentials sections from shared credentials INI options - credentialsSections, err := loadIniFiles(option.CredentialsFiles) - if err != nil { - return SharedConfig{}, err - } - - // check for profile prefix and drop duplicates or invalid profiles - err = processCredentialsSections(ctx, &credentialsSections, option.Logger) - if err != nil { - return SharedConfig{}, err - } - - err = mergeSections(&configSections, credentialsSections) - if err != nil { - return SharedConfig{}, err - } - - cfg := SharedConfig{} - profiles := map[string]struct{}{} - if err = cfg.setFromIniSections(profiles, profile, configSections, option.Logger); err != nil { - return SharedConfig{}, err - } - - return cfg, nil -} - -func processConfigSections(ctx context.Context, sections *ini.Sections, logger logging.Logger) error { - skipSections := map[string]struct{}{} - - for _, section := range sections.List() { - if _, ok := skipSections[section]; ok { - continue - } - - // drop sections from config file that do not have expected prefixes. - switch { - case strings.HasPrefix(section, profilePrefix): - // Rename sections to remove "profile " prefixing to match with - // credentials file. If default is already present, it will be - // dropped. - newName, err := renameProfileSection(section, sections, logger) - if err != nil { - return fmt.Errorf("failed to rename profile section, %w", err) - } - skipSections[newName] = struct{}{} - - case strings.HasPrefix(section, ssoSectionPrefix): - case strings.EqualFold(section, "default"): - default: - // drop this section, as invalid profile name - sections.DeleteSection(section) - - if logger != nil { - logger.Logf(logging.Debug, "A profile defined with name `%v` is ignored. "+ - "For use within a shared configuration file, "+ - "a non-default profile must have `profile ` "+ - "prefixed to the profile name.", - section, - ) - } - } - } - return nil -} - -func renameProfileSection(section string, sections *ini.Sections, logger logging.Logger) (string, error) { - v, ok := sections.GetSection(section) - if !ok { - return "", fmt.Errorf("error processing profiles within the shared configuration files") - } - - // delete section with profile as prefix - sections.DeleteSection(section) - - // set the value to non-prefixed name in sections. - section = strings.TrimPrefix(section, profilePrefix) - if sections.HasSection(section) { - oldSection, _ := sections.GetSection(section) - v.Logs = append(v.Logs, - fmt.Sprintf("A non-default profile not prefixed with `profile ` found in %s, "+ - "overriding non-default profile from %s", - v.SourceFile, oldSection.SourceFile)) - sections.DeleteSection(section) - } - - // assign non-prefixed name to section - v.Name = section - sections.SetSection(section, v) - - return section, nil -} - -func processCredentialsSections(ctx context.Context, sections *ini.Sections, logger logging.Logger) error { - for _, section := range sections.List() { - // drop profiles with prefix for credential files - if strings.HasPrefix(section, profilePrefix) { - // drop this section, as invalid profile name - sections.DeleteSection(section) - - if logger != nil { - logger.Logf(logging.Debug, - "The profile defined with name `%v` is ignored. A profile with the `profile ` prefix is invalid "+ - "for the shared credentials file.\n", - section, - ) - } - } - } - return nil -} - -func loadIniFiles(filenames []string) (ini.Sections, error) { - mergedSections := ini.NewSections() - - for _, filename := range filenames { - sections, err := ini.OpenFile(filename) - var v *ini.UnableToReadFile - if ok := errors.As(err, &v); ok { - // Skip files which can't be opened and read for whatever reason. - // We treat such files as empty, and do not fall back to other locations. - continue - } else if err != nil { - return ini.Sections{}, SharedConfigLoadError{Filename: filename, Err: err} - } - - // mergeSections into mergedSections - err = mergeSections(&mergedSections, sections) - if err != nil { - return ini.Sections{}, SharedConfigLoadError{Filename: filename, Err: err} - } - } - - return mergedSections, nil -} - -// mergeSections merges source section properties into destination section properties -func mergeSections(dst *ini.Sections, src ini.Sections) error { - for _, sectionName := range src.List() { - srcSection, _ := src.GetSection(sectionName) - - if (!srcSection.Has(accessKeyIDKey) && srcSection.Has(secretAccessKey)) || - (srcSection.Has(accessKeyIDKey) && !srcSection.Has(secretAccessKey)) { - srcSection.Errors = append(srcSection.Errors, - fmt.Errorf("partial credentials found for profile %v", sectionName)) - } - - if !dst.HasSection(sectionName) { - dst.SetSection(sectionName, srcSection) - continue - } - - // merge with destination srcSection - dstSection, _ := dst.GetSection(sectionName) - - // errors should be overriden if any - dstSection.Errors = srcSection.Errors - - // Access key id update - if srcSection.Has(accessKeyIDKey) && srcSection.Has(secretAccessKey) { - accessKey := srcSection.String(accessKeyIDKey) - secretKey := srcSection.String(secretAccessKey) - - if dstSection.Has(accessKeyIDKey) { - dstSection.Logs = append(dstSection.Logs, newMergeKeyLogMessage(sectionName, accessKeyIDKey, - dstSection.SourceFile[accessKeyIDKey], srcSection.SourceFile[accessKeyIDKey])) - } - - // update access key - v, err := ini.NewStringValue(accessKey) - if err != nil { - return fmt.Errorf("error merging access key, %w", err) - } - dstSection.UpdateValue(accessKeyIDKey, v) - - // update secret key - v, err = ini.NewStringValue(secretKey) - if err != nil { - return fmt.Errorf("error merging secret key, %w", err) - } - dstSection.UpdateValue(secretAccessKey, v) - - // update session token - if err = mergeStringKey(&srcSection, &dstSection, sectionName, sessionTokenKey); err != nil { - return err - } - - // update source file to reflect where the static creds came from - dstSection.UpdateSourceFile(accessKeyIDKey, srcSection.SourceFile[accessKeyIDKey]) - dstSection.UpdateSourceFile(secretAccessKey, srcSection.SourceFile[secretAccessKey]) - } - - stringKeys := []string{ - roleArnKey, - sourceProfileKey, - credentialSourceKey, - externalIDKey, - mfaSerialKey, - roleSessionNameKey, - regionKey, - enableEndpointDiscoveryKey, - credentialProcessKey, - webIdentityTokenFileKey, - s3UseARNRegionKey, - s3DisableMultiRegionAccessPointsKey, - ec2MetadataServiceEndpointModeKey, - ec2MetadataServiceEndpointKey, - useDualStackEndpoint, - useFIPSEndpointKey, - defaultsModeKey, - retryModeKey, - caBundleKey, - - ssoSessionNameKey, - ssoAccountIDKey, - ssoRegionKey, - ssoRoleNameKey, - ssoStartURLKey, - } - for i := range stringKeys { - if err := mergeStringKey(&srcSection, &dstSection, sectionName, stringKeys[i]); err != nil { - return err - } - } - - intKeys := []string{ - roleDurationSecondsKey, - retryMaxAttemptsKey, - } - for i := range intKeys { - if err := mergeIntKey(&srcSection, &dstSection, sectionName, intKeys[i]); err != nil { - return err - } - } - - // set srcSection on dst srcSection - *dst = dst.SetSection(sectionName, dstSection) - } - - return nil -} - -func mergeStringKey(srcSection *ini.Section, dstSection *ini.Section, sectionName, key string) error { - if srcSection.Has(key) { - srcValue := srcSection.String(key) - val, err := ini.NewStringValue(srcValue) - if err != nil { - return fmt.Errorf("error merging %s, %w", key, err) - } - - if dstSection.Has(key) { - dstSection.Logs = append(dstSection.Logs, newMergeKeyLogMessage(sectionName, key, - dstSection.SourceFile[key], srcSection.SourceFile[key])) - } - - dstSection.UpdateValue(key, val) - dstSection.UpdateSourceFile(key, srcSection.SourceFile[key]) - } - return nil -} - -func mergeIntKey(srcSection *ini.Section, dstSection *ini.Section, sectionName, key string) error { - if srcSection.Has(key) { - srcValue := srcSection.Int(key) - v, err := ini.NewIntValue(srcValue) - if err != nil { - return fmt.Errorf("error merging %s, %w", key, err) - } - - if dstSection.Has(key) { - dstSection.Logs = append(dstSection.Logs, newMergeKeyLogMessage(sectionName, key, - dstSection.SourceFile[key], srcSection.SourceFile[key])) - - } - - dstSection.UpdateValue(key, v) - dstSection.UpdateSourceFile(key, srcSection.SourceFile[key]) - } - return nil -} - -func newMergeKeyLogMessage(sectionName, key, dstSourceFile, srcSourceFile string) string { - return fmt.Sprintf("For profile: %v, overriding %v value, defined in %v "+ - "with a %v value found in a duplicate profile defined at file %v. \n", - sectionName, key, dstSourceFile, key, srcSourceFile) -} - -// Returns an error if all of the files fail to load. If at least one file is -// successfully loaded and contains the profile, no error will be returned. -func (c *SharedConfig) setFromIniSections(profiles map[string]struct{}, profile string, - sections ini.Sections, logger logging.Logger) error { - c.Profile = profile - - section, ok := sections.GetSection(profile) - if !ok { - return SharedConfigProfileNotExistError{ - Profile: profile, - } - } - - // if logs are appended to the section, log them - if section.Logs != nil && logger != nil { - for _, log := range section.Logs { - logger.Logf(logging.Debug, log) - } - } - - // set config from the provided INI section - err := c.setFromIniSection(profile, section) - if err != nil { - return fmt.Errorf("error fetching config from profile, %v, %w", profile, err) - } - - if _, ok := profiles[profile]; ok { - // if this is the second instance of the profile the Assume Role - // options must be cleared because they are only valid for the - // first reference of a profile. The self linked instance of the - // profile only have credential provider options. - c.clearAssumeRoleOptions() - } else { - // First time a profile has been seen. Assert if the credential type - // requires a role ARN, the ARN is also set - if err := c.validateCredentialsConfig(profile); err != nil { - return err - } - } - - // if not top level profile and has credentials, return with credentials. - if len(profiles) != 0 && c.Credentials.HasKeys() { - return nil - } - - profiles[profile] = struct{}{} - - // validate no colliding credentials type are present - if err := c.validateCredentialType(); err != nil { - return err - } - - // Link source profiles for assume roles - if len(c.SourceProfileName) != 0 { - // Linked profile via source_profile ignore credential provider - // options, the source profile must provide the credentials. - c.clearCredentialOptions() - - srcCfg := &SharedConfig{} - err := srcCfg.setFromIniSections(profiles, c.SourceProfileName, sections, logger) - if err != nil { - // SourceProfileName that doesn't exist is an error in configuration. - if _, ok := err.(SharedConfigProfileNotExistError); ok { - err = SharedConfigAssumeRoleError{ - RoleARN: c.RoleARN, - Profile: c.SourceProfileName, - Err: err, - } - } - return err - } - - if !srcCfg.hasCredentials() { - return SharedConfigAssumeRoleError{ - RoleARN: c.RoleARN, - Profile: c.SourceProfileName, - } - } - - c.Source = srcCfg - } - - // If the profile contains an SSO session parameter, the session MUST exist - // as a section in the config file. Load the SSO session using the name - // provided. If the session section is not found or incomplete an error - // will be returned. - if c.hasSSOTokenProviderConfiguration() { - section, ok := sections.GetSection(ssoSectionPrefix + strings.TrimSpace(c.SSOSessionName)) - if !ok { - return fmt.Errorf("failed to find SSO session section, %v", c.SSOSessionName) - } - var ssoSession SSOSession - ssoSession.setFromIniSection(section) - ssoSession.Name = c.SSOSessionName - c.SSOSession = &ssoSession - } - - return nil -} - -// setFromIniSection loads the configuration from the profile section defined in -// the provided INI file. A SharedConfig pointer type value is used so that -// multiple config file loadings can be chained. -// -// Only loads complete logically grouped values, and will not set fields in cfg -// for incomplete grouped values in the config. Such as credentials. For example -// if a config file only includes aws_access_key_id but no aws_secret_access_key -// the aws_access_key_id will be ignored. -func (c *SharedConfig) setFromIniSection(profile string, section ini.Section) error { - if len(section.Name) == 0 { - sources := make([]string, 0) - for _, v := range section.SourceFile { - sources = append(sources, v) - } - - return fmt.Errorf("parsing error : could not find profile section name after processing files: %v", sources) - } - - if len(section.Errors) != 0 { - var errStatement string - for i, e := range section.Errors { - errStatement = fmt.Sprintf("%d, %v\n", i+1, e.Error()) - } - return fmt.Errorf("Error using profile: \n %v", errStatement) - } - - // Assume Role - updateString(&c.RoleARN, section, roleArnKey) - updateString(&c.ExternalID, section, externalIDKey) - updateString(&c.MFASerial, section, mfaSerialKey) - updateString(&c.RoleSessionName, section, roleSessionNameKey) - updateString(&c.SourceProfileName, section, sourceProfileKey) - updateString(&c.CredentialSource, section, credentialSourceKey) - updateString(&c.Region, section, regionKey) - - // AWS Single Sign-On (AWS SSO) - // SSO session options - updateString(&c.SSOSessionName, section, ssoSessionNameKey) - - // Legacy SSO session options - updateString(&c.SSORegion, section, ssoRegionKey) - updateString(&c.SSOStartURL, section, ssoStartURLKey) - - // SSO fields not used - updateString(&c.SSOAccountID, section, ssoAccountIDKey) - updateString(&c.SSORoleName, section, ssoRoleNameKey) - - if section.Has(roleDurationSecondsKey) { - d := time.Duration(section.Int(roleDurationSecondsKey)) * time.Second - c.RoleDurationSeconds = &d - } - - updateString(&c.CredentialProcess, section, credentialProcessKey) - updateString(&c.WebIdentityTokenFile, section, webIdentityTokenFileKey) - - updateEndpointDiscoveryType(&c.EnableEndpointDiscovery, section, enableEndpointDiscoveryKey) - updateBoolPtr(&c.S3UseARNRegion, section, s3UseARNRegionKey) - updateBoolPtr(&c.S3DisableMultiRegionAccessPoints, section, s3DisableMultiRegionAccessPointsKey) - - if err := updateEC2MetadataServiceEndpointMode(&c.EC2IMDSEndpointMode, section, ec2MetadataServiceEndpointModeKey); err != nil { - return fmt.Errorf("failed to load %s from shared config, %v", ec2MetadataServiceEndpointModeKey, err) - } - updateString(&c.EC2IMDSEndpoint, section, ec2MetadataServiceEndpointKey) - - updateUseDualStackEndpoint(&c.UseDualStackEndpoint, section, useDualStackEndpoint) - updateUseFIPSEndpoint(&c.UseFIPSEndpoint, section, useFIPSEndpointKey) - - if err := updateDefaultsMode(&c.DefaultsMode, section, defaultsModeKey); err != nil { - return fmt.Errorf("failed to load %s from shared config, %w", defaultsModeKey, err) - } - - if err := updateInt(&c.RetryMaxAttempts, section, retryMaxAttemptsKey); err != nil { - return fmt.Errorf("failed to load %s from shared config, %w", retryMaxAttemptsKey, err) - } - if err := updateRetryMode(&c.RetryMode, section, retryModeKey); err != nil { - return fmt.Errorf("failed to load %s from shared config, %w", retryModeKey, err) - } - - updateString(&c.CustomCABundle, section, caBundleKey) - - // user agent app ID added to request User-Agent header - updateString(&c.AppID, section, sdkAppID) - - // Shared Credentials - creds := aws.Credentials{ - AccessKeyID: section.String(accessKeyIDKey), - SecretAccessKey: section.String(secretAccessKey), - SessionToken: section.String(sessionTokenKey), - Source: fmt.Sprintf("SharedConfigCredentials: %s", section.SourceFile[accessKeyIDKey]), - } - - if creds.HasKeys() { - c.Credentials = creds - } - - return nil -} - -func updateDefaultsMode(mode *aws.DefaultsMode, section ini.Section, key string) error { - if !section.Has(key) { - return nil - } - value := section.String(key) - if ok := mode.SetFromString(value); !ok { - return fmt.Errorf("invalid value: %s", value) - } - return nil -} - -func updateRetryMode(mode *aws.RetryMode, section ini.Section, key string) (err error) { - if !section.Has(key) { - return nil - } - value := section.String(key) - if *mode, err = aws.ParseRetryMode(value); err != nil { - return err - } - return nil -} - -func updateEC2MetadataServiceEndpointMode(endpointMode *imds.EndpointModeState, section ini.Section, key string) error { - if !section.Has(key) { - return nil - } - value := section.String(key) - return endpointMode.SetFromString(value) -} - -func (c *SharedConfig) validateCredentialsConfig(profile string) error { - if err := c.validateCredentialsRequireARN(profile); err != nil { - return err - } - - return nil -} - -func (c *SharedConfig) validateCredentialsRequireARN(profile string) error { - var credSource string - - switch { - case len(c.SourceProfileName) != 0: - credSource = sourceProfileKey - case len(c.CredentialSource) != 0: - credSource = credentialSourceKey - case len(c.WebIdentityTokenFile) != 0: - credSource = webIdentityTokenFileKey - } - - if len(credSource) != 0 && len(c.RoleARN) == 0 { - return CredentialRequiresARNError{ - Type: credSource, - Profile: profile, - } - } - - return nil -} - -func (c *SharedConfig) validateCredentialType() error { - // Only one or no credential type can be defined. - if !oneOrNone( - len(c.SourceProfileName) != 0, - len(c.CredentialSource) != 0, - len(c.CredentialProcess) != 0, - len(c.WebIdentityTokenFile) != 0, - ) { - return fmt.Errorf("only one credential type may be specified per profile: source profile, credential source, credential process, web identity token") - } - - return nil -} - -func (c *SharedConfig) validateSSOConfiguration() error { - if c.hasSSOTokenProviderConfiguration() { - err := c.validateSSOTokenProviderConfiguration() - if err != nil { - return err - } - return nil - } - - if c.hasLegacySSOConfiguration() { - err := c.validateLegacySSOConfiguration() - if err != nil { - return err - } - } - return nil -} - -func (c *SharedConfig) validateSSOTokenProviderConfiguration() error { - var missing []string - - if len(c.SSOSessionName) == 0 { - missing = append(missing, ssoSessionNameKey) - } - - if c.SSOSession == nil { - missing = append(missing, ssoSectionPrefix) - } else { - if len(c.SSOSession.SSORegion) == 0 { - missing = append(missing, ssoRegionKey) - } - - if len(c.SSOSession.SSOStartURL) == 0 { - missing = append(missing, ssoStartURLKey) - } - } - - if len(missing) > 0 { - return fmt.Errorf("profile %q is configured to use SSO but is missing required configuration: %s", - c.Profile, strings.Join(missing, ", ")) - } - - if len(c.SSORegion) > 0 && c.SSORegion != c.SSOSession.SSORegion { - return fmt.Errorf("%s in profile %q must match %s in %s", ssoRegionKey, c.Profile, ssoRegionKey, ssoSectionPrefix) - } - - if len(c.SSOStartURL) > 0 && c.SSOStartURL != c.SSOSession.SSOStartURL { - return fmt.Errorf("%s in profile %q must match %s in %s", ssoStartURLKey, c.Profile, ssoStartURLKey, ssoSectionPrefix) - } - - return nil -} - -func (c *SharedConfig) validateLegacySSOConfiguration() error { - var missing []string - - if len(c.SSORegion) == 0 { - missing = append(missing, ssoRegionKey) - } - - if len(c.SSOStartURL) == 0 { - missing = append(missing, ssoStartURLKey) - } - - if len(c.SSOAccountID) == 0 { - missing = append(missing, ssoAccountIDKey) - } - - if len(c.SSORoleName) == 0 { - missing = append(missing, ssoRoleNameKey) - } - - if len(missing) > 0 { - return fmt.Errorf("profile %q is configured to use SSO but is missing required configuration: %s", - c.Profile, strings.Join(missing, ", ")) - } - return nil -} - -func (c *SharedConfig) hasCredentials() bool { - switch { - case len(c.SourceProfileName) != 0: - case len(c.CredentialSource) != 0: - case len(c.CredentialProcess) != 0: - case len(c.WebIdentityTokenFile) != 0: - case c.hasSSOConfiguration(): - case c.Credentials.HasKeys(): - default: - return false - } - - return true -} - -func (c *SharedConfig) hasSSOConfiguration() bool { - return c.hasSSOTokenProviderConfiguration() || c.hasLegacySSOConfiguration() -} - -func (c *SharedConfig) hasSSOTokenProviderConfiguration() bool { - return len(c.SSOSessionName) > 0 -} - -func (c *SharedConfig) hasLegacySSOConfiguration() bool { - return len(c.SSORegion) > 0 || len(c.SSOAccountID) > 0 || len(c.SSOStartURL) > 0 || len(c.SSORoleName) > 0 -} - -func (c *SharedConfig) clearAssumeRoleOptions() { - c.RoleARN = "" - c.ExternalID = "" - c.MFASerial = "" - c.RoleSessionName = "" - c.SourceProfileName = "" -} - -func (c *SharedConfig) clearCredentialOptions() { - c.CredentialSource = "" - c.CredentialProcess = "" - c.WebIdentityTokenFile = "" - c.Credentials = aws.Credentials{} - c.SSOAccountID = "" - c.SSORegion = "" - c.SSORoleName = "" - c.SSOStartURL = "" -} - -// SharedConfigLoadError is an error for the shared config file failed to load. -type SharedConfigLoadError struct { - Filename string - Err error -} - -// Unwrap returns the underlying error that caused the failure. -func (e SharedConfigLoadError) Unwrap() error { - return e.Err -} - -func (e SharedConfigLoadError) Error() string { - return fmt.Sprintf("failed to load shared config file, %s, %v", e.Filename, e.Err) -} - -// SharedConfigProfileNotExistError is an error for the shared config when -// the profile was not find in the config file. -type SharedConfigProfileNotExistError struct { - Filename []string - Profile string - Err error -} - -// Unwrap returns the underlying error that caused the failure. -func (e SharedConfigProfileNotExistError) Unwrap() error { - return e.Err -} - -func (e SharedConfigProfileNotExistError) Error() string { - return fmt.Sprintf("failed to get shared config profile, %s", e.Profile) -} - -// SharedConfigAssumeRoleError is an error for the shared config when the -// profile contains assume role information, but that information is invalid -// or not complete. -type SharedConfigAssumeRoleError struct { - Profile string - RoleARN string - Err error -} - -// Unwrap returns the underlying error that caused the failure. -func (e SharedConfigAssumeRoleError) Unwrap() error { - return e.Err -} - -func (e SharedConfigAssumeRoleError) Error() string { - return fmt.Sprintf("failed to load assume role %s, of profile %s, %v", - e.RoleARN, e.Profile, e.Err) -} - -// CredentialRequiresARNError provides the error for shared config credentials -// that are incorrectly configured in the shared config or credentials file. -type CredentialRequiresARNError struct { - // type of credentials that were configured. - Type string - - // Profile name the credentials were in. - Profile string -} - -// Error satisfies the error interface. -func (e CredentialRequiresARNError) Error() string { - return fmt.Sprintf( - "credential type %s requires role_arn, profile %s", - e.Type, e.Profile, - ) -} - -func oneOrNone(bs ...bool) bool { - var count int - - for _, b := range bs { - if b { - count++ - if count > 1 { - return false - } - } - } - - return true -} - -// updateString will only update the dst with the value in the section key, key -// is present in the section. -func updateString(dst *string, section ini.Section, key string) { - if !section.Has(key) { - return - } - *dst = section.String(key) -} - -// updateInt will only update the dst with the value in the section key, key -// is present in the section. -// -// Down casts the INI integer value from a int64 to an int, which could be -// different bit size depending on platform. -func updateInt(dst *int, section ini.Section, key string) error { - if !section.Has(key) { - return nil - } - if vt, _ := section.ValueType(key); vt != ini.IntegerType { - return fmt.Errorf("invalid value %s=%s, expect integer", - key, section.String(key)) - - } - *dst = int(section.Int(key)) - return nil -} - -// updateBool will only update the dst with the value in the section key, key -// is present in the section. -func updateBool(dst *bool, section ini.Section, key string) { - if !section.Has(key) { - return - } - *dst = section.Bool(key) -} - -// updateBoolPtr will only update the dst with the value in the section key, -// key is present in the section. -func updateBoolPtr(dst **bool, section ini.Section, key string) { - if !section.Has(key) { - return - } - *dst = new(bool) - **dst = section.Bool(key) -} - -// updateEndpointDiscoveryType will only update the dst with the value in the section, if -// a valid key and corresponding EndpointDiscoveryType is found. -func updateEndpointDiscoveryType(dst *aws.EndpointDiscoveryEnableState, section ini.Section, key string) { - if !section.Has(key) { - return - } - - value := section.String(key) - if len(value) == 0 { - return - } - - switch { - case strings.EqualFold(value, endpointDiscoveryDisabled): - *dst = aws.EndpointDiscoveryDisabled - case strings.EqualFold(value, endpointDiscoveryEnabled): - *dst = aws.EndpointDiscoveryEnabled - case strings.EqualFold(value, endpointDiscoveryAuto): - *dst = aws.EndpointDiscoveryAuto - } -} - -// updateEndpointDiscoveryType will only update the dst with the value in the section, if -// a valid key and corresponding EndpointDiscoveryType is found. -func updateUseDualStackEndpoint(dst *aws.DualStackEndpointState, section ini.Section, key string) { - if !section.Has(key) { - return - } - - if section.Bool(key) { - *dst = aws.DualStackEndpointStateEnabled - } else { - *dst = aws.DualStackEndpointStateDisabled - } - - return -} - -// updateEndpointDiscoveryType will only update the dst with the value in the section, if -// a valid key and corresponding EndpointDiscoveryType is found. -func updateUseFIPSEndpoint(dst *aws.FIPSEndpointState, section ini.Section, key string) { - if !section.Has(key) { - return - } - - if section.Bool(key) { - *dst = aws.FIPSEndpointStateEnabled - } else { - *dst = aws.FIPSEndpointStateDisabled - } - - return -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/credentials/CHANGELOG.md deleted file mode 100644 index ef2dd4b2d..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/CHANGELOG.md +++ /dev/null @@ -1,359 +0,0 @@ -# v1.13.35 (2023-08-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.34 (2023-08-18) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.33 (2023-08-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.32 (2023-08-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.31 (2023-08-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.30 (2023-07-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.29 (2023-07-28) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.28 (2023-07-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.27 (2023-07-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.26 (2023-06-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.25 (2023-06-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.24 (2023-05-09) - -* No change notes available for this release. - -# v1.13.23 (2023-05-08) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.22 (2023-05-04) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.21 (2023-04-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.20 (2023-04-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.19 (2023-04-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.18 (2023-03-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.17 (2023-03-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.16 (2023-03-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.15 (2023-02-22) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.14 (2023-02-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.13 (2023-02-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.12 (2023-02-03) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.11 (2023-02-01) - -* No change notes available for this release. - -# v1.13.10 (2023-01-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.9 (2023-01-23) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.8 (2023-01-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.7 (2022-12-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.6 (2022-12-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.5 (2022-12-15) - -* **Bug Fix**: Unify logic between shared config and in finding home directory -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.4 (2022-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.3 (2022-11-22) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.2 (2022-11-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.1 (2022-11-16) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.0 (2022-11-11) - -* **Announcement**: When using the SSOTokenProvider, a previous implementation incorrectly compensated for invalid SSOTokenProvider configurations in the shared profile. This has been fixed via PR #1903 and tracked in issue #1846 -* **Feature**: Adds token refresh support (via SSOTokenProvider) when using the SSOCredentialProvider - -# v1.12.24 (2022-11-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.23 (2022-10-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.22 (2022-10-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.21 (2022-09-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.20 (2022-09-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.19 (2022-09-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.18 (2022-09-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.17 (2022-08-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.16 (2022-08-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.15 (2022-08-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.14 (2022-08-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.13 (2022-08-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.12 (2022-08-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.11 (2022-08-08) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.10 (2022-08-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.9 (2022-07-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.8 (2022-07-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.7 (2022-06-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.6 (2022-06-16) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.5 (2022-06-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.4 (2022-05-26) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.3 (2022-05-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.2 (2022-05-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.1 (2022-05-16) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.0 (2022-04-25) - -* **Feature**: Adds Duration and Policy options that can be used when creating stscreds.WebIdentityRoleProvider credentials provider. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.2 (2022-03-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.1 (2022-03-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.0 (2022-03-23) - -* **Feature**: Update `ec2rolecreds` package's `Provider` to implememnt support for CredentialsCache new optional caching strategy interfaces, HandleFailRefreshCredentialsCacheStrategy and AdjustExpiresByCredentialsCacheStrategy. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.0 (2022-03-08) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.0 (2022-02-24) - -* **Feature**: Adds support for `SourceIdentity` to `stscreds.AssumeRoleProvider` [#1588](https://github.com/aws/aws-sdk-go-v2/pull/1588). Fixes [#1575](https://github.com/aws/aws-sdk-go-v2/issues/1575) -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.0 (2022-01-14) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.7.0 (2022-01-07) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.5 (2021-12-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.4 (2021-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.3 (2021-11-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.2 (2021-11-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.1 (2021-11-12) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.0 (2021-11-06) - -* **Feature**: The SDK now supports configuration of FIPS and DualStack endpoints using environment variables, shared configuration, or programmatically. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.5.0 (2021-10-21) - -* **Feature**: Updated to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.3 (2021-10-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.2 (2021-09-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.1 (2021-09-10) - -* **Documentation**: Fixes the AssumeRoleProvider's documentation for using custom TokenProviders. - -# v1.4.0 (2021-08-27) - -* **Feature**: Adds support for Tags and TransitiveTagKeys to stscreds.AssumeRoleProvider. Closes https://github.com/aws/aws-sdk-go-v2/issues/723 -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.3 (2021-08-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.2 (2021-08-04) - -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.1 (2021-07-15) - -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.0 (2021-06-25) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Bug Fix**: Fixed example usages of aws.CredentialsCache ([#1275](https://github.com/aws/aws-sdk-go-v2/pull/1275)) -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.1 (2021-05-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.0 (2021-05-14) - -* **Feature**: Constant has been added to modules to enable runtime version inspection for reporting. -* **Dependency Update**: Updated to the latest SDK module versions - diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/credentials/LICENSE.txt deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/LICENSE.txt +++ /dev/null @@ -1,202 +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/aws/aws-sdk-go-v2/credentials/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/doc.go deleted file mode 100644 index f6e2873ab..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -/* -Package credentials provides types for retrieving credentials from credentials sources. -*/ -package credentials diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/ec2rolecreds/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/ec2rolecreds/doc.go deleted file mode 100644 index 6ed71b42b..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/ec2rolecreds/doc.go +++ /dev/null @@ -1,58 +0,0 @@ -// Package ec2rolecreds provides the credentials provider implementation for -// retrieving AWS credentials from Amazon EC2 Instance Roles via Amazon EC2 IMDS. -// -// # Concurrency and caching -// -// The Provider is not safe to be used concurrently, and does not provide any -// caching of credentials retrieved. You should wrap the Provider with a -// `aws.CredentialsCache` to provide concurrency safety, and caching of -// credentials. -// -// # Loading credentials with the SDK's AWS Config -// -// The EC2 Instance role credentials provider will automatically be the resolved -// credential provider in the credential chain if no other credential provider is -// resolved first. -// -// To explicitly instruct the SDK's credentials resolving to use the EC2 Instance -// role for credentials, you specify a `credentials_source` property in the config -// profile the SDK will load. -// -// [default] -// credential_source = Ec2InstanceMetadata -// -// # Loading credentials with the Provider directly -// -// Another way to use the EC2 Instance role credentials provider is to create it -// directly and assign it as the credentials provider for an API client. -// -// The following example creates a credentials provider for a command, and wraps -// it with the CredentialsCache before assigning the provider to the Amazon S3 API -// client's Credentials option. -// -// provider := imds.New(imds.Options{}) -// -// // Create the service client value configured for credentials. -// svc := s3.New(s3.Options{ -// Credentials: aws.NewCredentialsCache(provider), -// }) -// -// If you need more control, you can set the configuration options on the -// credentials provider using the imds.Options type to configure the EC2 IMDS -// API Client and ExpiryWindow of the retrieved credentials. -// -// provider := imds.New(imds.Options{ -// // See imds.Options type's documentation for more options available. -// Client: imds.New(Options{ -// HTTPClient: customHTTPClient, -// }), -// -// // Modify how soon credentials expire prior to their original expiry time. -// ExpiryWindow: 5 * time.Minute, -// }) -// -// # EC2 IMDS API Client -// -// See the github.com/aws/aws-sdk-go-v2/feature/ec2/imds module for more details on -// configuring the client, and options available. -package ec2rolecreds diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/ec2rolecreds/provider.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/ec2rolecreds/provider.go deleted file mode 100644 index 5c699f166..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/ec2rolecreds/provider.go +++ /dev/null @@ -1,229 +0,0 @@ -package ec2rolecreds - -import ( - "bufio" - "context" - "encoding/json" - "fmt" - "math" - "path" - "strings" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/feature/ec2/imds" - sdkrand "github.com/aws/aws-sdk-go-v2/internal/rand" - "github.com/aws/aws-sdk-go-v2/internal/sdk" - "github.com/aws/smithy-go" - "github.com/aws/smithy-go/logging" - "github.com/aws/smithy-go/middleware" -) - -// ProviderName provides a name of EC2Role provider -const ProviderName = "EC2RoleProvider" - -// GetMetadataAPIClient provides the interface for an EC2 IMDS API client for the -// GetMetadata operation. -type GetMetadataAPIClient interface { - GetMetadata(context.Context, *imds.GetMetadataInput, ...func(*imds.Options)) (*imds.GetMetadataOutput, error) -} - -// A Provider retrieves credentials from the EC2 service, and keeps track if -// those credentials are expired. -// -// The New function must be used to create the with a custom EC2 IMDS client. -// -// p := &ec2rolecreds.New(func(o *ec2rolecreds.Options{ -// o.Client = imds.New(imds.Options{/* custom options */}) -// }) -type Provider struct { - options Options -} - -// Options is a list of user settable options for setting the behavior of the Provider. -type Options struct { - // The API client that will be used by the provider to make GetMetadata API - // calls to EC2 IMDS. - // - // If nil, the provider will default to the EC2 IMDS client. - Client GetMetadataAPIClient -} - -// New returns an initialized Provider value configured to retrieve -// credentials from EC2 Instance Metadata service. -func New(optFns ...func(*Options)) *Provider { - options := Options{} - - for _, fn := range optFns { - fn(&options) - } - - if options.Client == nil { - options.Client = imds.New(imds.Options{}) - } - - return &Provider{ - options: options, - } -} - -// Retrieve retrieves credentials from the EC2 service. Error will be returned -// if the request fails, or unable to extract the desired credentials. -func (p *Provider) Retrieve(ctx context.Context) (aws.Credentials, error) { - credsList, err := requestCredList(ctx, p.options.Client) - if err != nil { - return aws.Credentials{Source: ProviderName}, err - } - - if len(credsList) == 0 { - return aws.Credentials{Source: ProviderName}, - fmt.Errorf("unexpected empty EC2 IMDS role list") - } - credsName := credsList[0] - - roleCreds, err := requestCred(ctx, p.options.Client, credsName) - if err != nil { - return aws.Credentials{Source: ProviderName}, err - } - - creds := aws.Credentials{ - AccessKeyID: roleCreds.AccessKeyID, - SecretAccessKey: roleCreds.SecretAccessKey, - SessionToken: roleCreds.Token, - Source: ProviderName, - - CanExpire: true, - Expires: roleCreds.Expiration, - } - - // Cap role credentials Expires to 1 hour so they can be refreshed more - // often. Jitter will be applied credentials cache if being used. - if anHour := sdk.NowTime().Add(1 * time.Hour); creds.Expires.After(anHour) { - creds.Expires = anHour - } - - return creds, nil -} - -// HandleFailToRefresh will extend the credentials Expires time if it it is -// expired. If the credentials will not expire within the minimum time, they -// will be returned. -// -// If the credentials cannot expire, the original error will be returned. -func (p *Provider) HandleFailToRefresh(ctx context.Context, prevCreds aws.Credentials, err error) ( - aws.Credentials, error, -) { - if !prevCreds.CanExpire { - return aws.Credentials{}, err - } - - if prevCreds.Expires.After(sdk.NowTime().Add(5 * time.Minute)) { - return prevCreds, nil - } - - newCreds := prevCreds - randFloat64, err := sdkrand.CryptoRandFloat64() - if err != nil { - return aws.Credentials{}, fmt.Errorf("failed to get random float, %w", err) - } - - // Random distribution of [5,15) minutes. - expireOffset := time.Duration(randFloat64*float64(10*time.Minute)) + 5*time.Minute - newCreds.Expires = sdk.NowTime().Add(expireOffset) - - logger := middleware.GetLogger(ctx) - logger.Logf(logging.Warn, "Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted again in %v minutes.", math.Floor(expireOffset.Minutes())) - - return newCreds, nil -} - -// AdjustExpiresBy will adds the passed in duration to the passed in -// credential's Expires time, unless the time until Expires is less than 15 -// minutes. Returns the credentials, even if not updated. -func (p *Provider) AdjustExpiresBy(creds aws.Credentials, dur time.Duration) ( - aws.Credentials, error, -) { - if !creds.CanExpire { - return creds, nil - } - if creds.Expires.Before(sdk.NowTime().Add(15 * time.Minute)) { - return creds, nil - } - - creds.Expires = creds.Expires.Add(dur) - return creds, nil -} - -// ec2RoleCredRespBody provides the shape for unmarshaling credential -// request responses. -type ec2RoleCredRespBody struct { - // Success State - Expiration time.Time - AccessKeyID string - SecretAccessKey string - Token string - - // Error state - Code string - Message string -} - -const iamSecurityCredsPath = "/iam/security-credentials/" - -// requestCredList requests a list of credentials from the EC2 service. If -// there are no credentials, or there is an error making or receiving the -// request -func requestCredList(ctx context.Context, client GetMetadataAPIClient) ([]string, error) { - resp, err := client.GetMetadata(ctx, &imds.GetMetadataInput{ - Path: iamSecurityCredsPath, - }) - if err != nil { - return nil, fmt.Errorf("no EC2 IMDS role found, %w", err) - } - defer resp.Content.Close() - - credsList := []string{} - s := bufio.NewScanner(resp.Content) - for s.Scan() { - credsList = append(credsList, s.Text()) - } - - if err := s.Err(); err != nil { - return nil, fmt.Errorf("failed to read EC2 IMDS role, %w", err) - } - - return credsList, nil -} - -// requestCred requests the credentials for a specific credentials from the EC2 service. -// -// If the credentials cannot be found, or there is an error reading the response -// and error will be returned. -func requestCred(ctx context.Context, client GetMetadataAPIClient, credsName string) (ec2RoleCredRespBody, error) { - resp, err := client.GetMetadata(ctx, &imds.GetMetadataInput{ - Path: path.Join(iamSecurityCredsPath, credsName), - }) - if err != nil { - return ec2RoleCredRespBody{}, - fmt.Errorf("failed to get %s EC2 IMDS role credentials, %w", - credsName, err) - } - defer resp.Content.Close() - - var respCreds ec2RoleCredRespBody - if err := json.NewDecoder(resp.Content).Decode(&respCreds); err != nil { - return ec2RoleCredRespBody{}, - fmt.Errorf("failed to decode %s EC2 IMDS role credentials, %w", - credsName, err) - } - - if !strings.EqualFold(respCreds.Code, "Success") { - // If an error code was returned something failed requesting the role. - return ec2RoleCredRespBody{}, - fmt.Errorf("failed to get %s EC2 IMDS role credentials, %w", - credsName, - &smithy.GenericAPIError{Code: respCreds.Code, Message: respCreds.Message}) - } - - return respCreds, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/internal/client/client.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/internal/client/client.go deleted file mode 100644 index 60b8298f8..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/internal/client/client.go +++ /dev/null @@ -1,148 +0,0 @@ -package client - -import ( - "context" - "fmt" - "net/http" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/retry" - awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" - "github.com/aws/smithy-go" - smithymiddleware "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// ServiceID is the client identifer -const ServiceID = "endpoint-credentials" - -// HTTPClient is a client for sending HTTP requests -type HTTPClient interface { - Do(*http.Request) (*http.Response, error) -} - -// Options is the endpoint client configurable options -type Options struct { - // The endpoint to retrieve credentials from - Endpoint string - - // The HTTP client to invoke API calls with. Defaults to client's default HTTP - // implementation if nil. - HTTPClient HTTPClient - - // Retryer guides how HTTP requests should be retried in case of recoverable - // failures. When nil the API client will use a default retryer. - Retryer aws.Retryer - - // Set of options to modify how the credentials operation is invoked. - APIOptions []func(*smithymiddleware.Stack) error -} - -// Copy creates a copy of the API options. -func (o Options) Copy() Options { - to := o - to.APIOptions = make([]func(*smithymiddleware.Stack) error, len(o.APIOptions)) - copy(to.APIOptions, o.APIOptions) - return to -} - -// Client is an client for retrieving AWS credentials from an endpoint -type Client struct { - options Options -} - -// New constructs a new Client from the given options -func New(options Options, optFns ...func(*Options)) *Client { - options = options.Copy() - - if options.HTTPClient == nil { - options.HTTPClient = awshttp.NewBuildableClient() - } - - if options.Retryer == nil { - options.Retryer = retry.NewStandard() - } - - for _, fn := range optFns { - fn(&options) - } - - client := &Client{ - options: options, - } - - return client -} - -// GetCredentialsInput is the input to send with the endpoint service to receive credentials. -type GetCredentialsInput struct { - AuthorizationToken string -} - -// GetCredentials retrieves credentials from credential endpoint -func (c *Client) GetCredentials(ctx context.Context, params *GetCredentialsInput, optFns ...func(*Options)) (*GetCredentialsOutput, error) { - stack := smithymiddleware.NewStack("GetCredentials", smithyhttp.NewStackRequest) - options := c.options.Copy() - for _, fn := range optFns { - fn(&options) - } - - stack.Serialize.Add(&serializeOpGetCredential{}, smithymiddleware.After) - stack.Build.Add(&buildEndpoint{Endpoint: options.Endpoint}, smithymiddleware.After) - stack.Deserialize.Add(&deserializeOpGetCredential{}, smithymiddleware.After) - retry.AddRetryMiddlewares(stack, retry.AddRetryMiddlewaresOptions{Retryer: options.Retryer}) - middleware.AddSDKAgentKey(middleware.FeatureMetadata, ServiceID) - smithyhttp.AddErrorCloseResponseBodyMiddleware(stack) - smithyhttp.AddCloseResponseBodyMiddleware(stack) - - for _, fn := range options.APIOptions { - if err := fn(stack); err != nil { - return nil, err - } - } - - handler := smithymiddleware.DecorateHandler(smithyhttp.NewClientHandler(options.HTTPClient), stack) - result, _, err := handler.Handle(ctx, params) - if err != nil { - return nil, err - } - - return result.(*GetCredentialsOutput), err -} - -// GetCredentialsOutput is the response from the credential endpoint -type GetCredentialsOutput struct { - Expiration *time.Time - AccessKeyID string - SecretAccessKey string - Token string -} - -// EndpointError is an error returned from the endpoint service -type EndpointError struct { - Code string `json:"code"` - Message string `json:"message"` - Fault smithy.ErrorFault `json:"-"` -} - -// Error is the error mesage string -func (e *EndpointError) Error() string { - return fmt.Sprintf("%s: %s", e.Code, e.Message) -} - -// ErrorCode is the error code returned by the endpoint -func (e *EndpointError) ErrorCode() string { - return e.Code -} - -// ErrorMessage is the error message returned by the endpoint -func (e *EndpointError) ErrorMessage() string { - return e.Message -} - -// ErrorFault indicates error fault classification -func (e *EndpointError) ErrorFault() smithy.ErrorFault { - return e.Fault -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/internal/client/middleware.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/internal/client/middleware.go deleted file mode 100644 index 40747a53c..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/internal/client/middleware.go +++ /dev/null @@ -1,120 +0,0 @@ -package client - -import ( - "context" - "encoding/json" - "fmt" - "net/url" - - "github.com/aws/smithy-go" - smithymiddleware "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -type buildEndpoint struct { - Endpoint string -} - -func (b *buildEndpoint) ID() string { - return "BuildEndpoint" -} - -func (b *buildEndpoint) HandleBuild(ctx context.Context, in smithymiddleware.BuildInput, next smithymiddleware.BuildHandler) ( - out smithymiddleware.BuildOutput, metadata smithymiddleware.Metadata, err error, -) { - request, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport, %T", in.Request) - } - - if len(b.Endpoint) == 0 { - return out, metadata, fmt.Errorf("endpoint not provided") - } - - parsed, err := url.Parse(b.Endpoint) - if err != nil { - return out, metadata, fmt.Errorf("failed to parse endpoint, %w", err) - } - - request.URL = parsed - - return next.HandleBuild(ctx, in) -} - -type serializeOpGetCredential struct{} - -func (s *serializeOpGetCredential) ID() string { - return "OperationSerializer" -} - -func (s *serializeOpGetCredential) HandleSerialize(ctx context.Context, in smithymiddleware.SerializeInput, next smithymiddleware.SerializeHandler) ( - out smithymiddleware.SerializeOutput, metadata smithymiddleware.Metadata, err error, -) { - request, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type, %T", in.Request) - } - - params, ok := in.Parameters.(*GetCredentialsInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters, %T", in.Parameters) - } - - const acceptHeader = "Accept" - request.Header[acceptHeader] = append(request.Header[acceptHeader][:0], "application/json") - - if len(params.AuthorizationToken) > 0 { - const authHeader = "Authorization" - request.Header[authHeader] = append(request.Header[authHeader][:0], params.AuthorizationToken) - } - - return next.HandleSerialize(ctx, in) -} - -type deserializeOpGetCredential struct{} - -func (d *deserializeOpGetCredential) ID() string { - return "OperationDeserializer" -} - -func (d *deserializeOpGetCredential) HandleDeserialize(ctx context.Context, in smithymiddleware.DeserializeInput, next smithymiddleware.DeserializeHandler) ( - out smithymiddleware.DeserializeOutput, metadata smithymiddleware.Metadata, err error, -) { - out, metadata, err = next.HandleDeserialize(ctx, in) - if err != nil { - return out, metadata, err - } - - response, ok := out.RawResponse.(*smithyhttp.Response) - if !ok { - return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} - } - - if response.StatusCode < 200 || response.StatusCode >= 300 { - return out, metadata, deserializeError(response) - } - - var shape *GetCredentialsOutput - if err = json.NewDecoder(response.Body).Decode(&shape); err != nil { - return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("failed to deserialize json response, %w", err)} - } - - out.Result = shape - return out, metadata, err -} - -func deserializeError(response *smithyhttp.Response) error { - var errShape *EndpointError - err := json.NewDecoder(response.Body).Decode(&errShape) - if err != nil { - return &smithy.DeserializationError{Err: fmt.Errorf("failed to decode error message, %w", err)} - } - - if response.StatusCode >= 500 { - errShape.Fault = smithy.FaultServer - } else { - errShape.Fault = smithy.FaultClient - } - - return errShape -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/provider.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/provider.go deleted file mode 100644 index adc7fc6b0..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/provider.go +++ /dev/null @@ -1,136 +0,0 @@ -// Package endpointcreds provides support for retrieving credentials from an -// arbitrary HTTP endpoint. -// -// The credentials endpoint Provider can receive both static and refreshable -// credentials that will expire. Credentials are static when an "Expiration" -// value is not provided in the endpoint's response. -// -// Static credentials will never expire once they have been retrieved. The format -// of the static credentials response: -// -// { -// "AccessKeyId" : "MUA...", -// "SecretAccessKey" : "/7PC5om....", -// } -// -// Refreshable credentials will expire within the "ExpiryWindow" of the Expiration -// value in the response. The format of the refreshable credentials response: -// -// { -// "AccessKeyId" : "MUA...", -// "SecretAccessKey" : "/7PC5om....", -// "Token" : "AQoDY....=", -// "Expiration" : "2016-02-25T06:03:31Z" -// } -// -// Errors should be returned in the following format and only returned with 400 -// or 500 HTTP status codes. -// -// { -// "code": "ErrorCode", -// "message": "Helpful error message." -// } -package endpointcreds - -import ( - "context" - "fmt" - "net/http" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/internal/client" - "github.com/aws/smithy-go/middleware" -) - -// ProviderName is the name of the credentials provider. -const ProviderName = `CredentialsEndpointProvider` - -type getCredentialsAPIClient interface { - GetCredentials(context.Context, *client.GetCredentialsInput, ...func(*client.Options)) (*client.GetCredentialsOutput, error) -} - -// Provider satisfies the aws.CredentialsProvider interface, and is a client to -// retrieve credentials from an arbitrary endpoint. -type Provider struct { - // The AWS Client to make HTTP requests to the endpoint with. The endpoint - // the request will be made to is provided by the aws.Config's - // EndpointResolver. - client getCredentialsAPIClient - - options Options -} - -// HTTPClient is a client for sending HTTP requests -type HTTPClient interface { - Do(*http.Request) (*http.Response, error) -} - -// Options is structure of configurable options for Provider -type Options struct { - // Endpoint to retrieve credentials from. Required - Endpoint string - - // HTTPClient to handle sending HTTP requests to the target endpoint. - HTTPClient HTTPClient - - // Set of options to modify how the credentials operation is invoked. - APIOptions []func(*middleware.Stack) error - - // The Retryer to be used for determining whether a failed requested should be retried - Retryer aws.Retryer - - // Optional authorization token value if set will be used as the value of - // the Authorization header of the endpoint credential request. - AuthorizationToken string -} - -// New returns a credentials Provider for retrieving AWS credentials -// from arbitrary endpoint. -func New(endpoint string, optFns ...func(*Options)) *Provider { - o := Options{ - Endpoint: endpoint, - } - - for _, fn := range optFns { - fn(&o) - } - - p := &Provider{ - client: client.New(client.Options{ - HTTPClient: o.HTTPClient, - Endpoint: o.Endpoint, - APIOptions: o.APIOptions, - Retryer: o.Retryer, - }), - options: o, - } - - return p -} - -// Retrieve will attempt to request the credentials from the endpoint the Provider -// was configured for. And error will be returned if the retrieval fails. -func (p *Provider) Retrieve(ctx context.Context) (aws.Credentials, error) { - resp, err := p.getCredentials(ctx) - if err != nil { - return aws.Credentials{}, fmt.Errorf("failed to load credentials, %w", err) - } - - creds := aws.Credentials{ - AccessKeyID: resp.AccessKeyID, - SecretAccessKey: resp.SecretAccessKey, - SessionToken: resp.Token, - Source: ProviderName, - } - - if resp.Expiration != nil { - creds.CanExpire = true - creds.Expires = *resp.Expiration - } - - return creds, nil -} - -func (p *Provider) getCredentials(ctx context.Context) (*client.GetCredentialsOutput, error) { - return p.client.GetCredentials(ctx, &client.GetCredentialsInput{AuthorizationToken: p.options.AuthorizationToken}) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/go_module_metadata.go deleted file mode 100644 index eb75bb481..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/go_module_metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. - -package credentials - -// goModuleVersion is the tagged release for this module -const goModuleVersion = "1.13.35" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/processcreds/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/processcreds/doc.go deleted file mode 100644 index a3137b8fa..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/processcreds/doc.go +++ /dev/null @@ -1,92 +0,0 @@ -// Package processcreds is a credentials provider to retrieve credentials from a -// external CLI invoked process. -// -// WARNING: The following describes a method of sourcing credentials from an external -// process. This can potentially be dangerous, so proceed with caution. Other -// credential providers should be preferred if at all possible. If using this -// option, you should make sure that the config file is as locked down as possible -// using security best practices for your operating system. -// -// # Concurrency and caching -// -// The Provider is not safe to be used concurrently, and does not provide any -// caching of credentials retrieved. You should wrap the Provider with a -// `aws.CredentialsCache` to provide concurrency safety, and caching of -// credentials. -// -// # Loading credentials with the SDKs AWS Config -// -// You can use credentials from a AWS shared config `credential_process` in a -// variety of ways. -// -// One way is to setup your shared config file, located in the default -// location, with the `credential_process` key and the command you want to be -// called. You also need to set the AWS_SDK_LOAD_CONFIG environment variable -// (e.g., `export AWS_SDK_LOAD_CONFIG=1`) to use the shared config file. -// -// [default] -// credential_process = /command/to/call -// -// Loading configuration using external will use the credential process to -// retrieve credentials. NOTE: If there are credentials in the profile you are -// using, the credential process will not be used. -// -// // Initialize a session to load credentials. -// cfg, _ := config.LoadDefaultConfig(context.TODO()) -// -// // Create S3 service client to use the credentials. -// svc := s3.NewFromConfig(cfg) -// -// # Loading credentials with the Provider directly -// -// Another way to use the credentials process provider is by using the -// `NewProvider` constructor to create the provider and providing a it with a -// command to be executed to retrieve credentials. -// -// The following example creates a credentials provider for a command, and wraps -// it with the CredentialsCache before assigning the provider to the Amazon S3 API -// client's Credentials option. -// -// // Create credentials using the Provider. -// provider := processcreds.NewProvider("/path/to/command") -// -// // Create the service client value configured for credentials. -// svc := s3.New(s3.Options{ -// Credentials: aws.NewCredentialsCache(provider), -// }) -// -// If you need more control, you can set any configurable options in the -// credentials using one or more option functions. -// -// provider := processcreds.NewProvider("/path/to/command", -// func(o *processcreds.Options) { -// // Override the provider's default timeout -// o.Timeout = 2 * time.Minute -// }) -// -// You can also use your own `exec.Cmd` value by satisfying a value that satisfies -// the `NewCommandBuilder` interface and use the `NewProviderCommand` constructor. -// -// // Create an exec.Cmd -// cmdBuilder := processcreds.NewCommandBuilderFunc( -// func(ctx context.Context) (*exec.Cmd, error) { -// cmd := exec.CommandContext(ctx, -// "customCLICommand", -// "-a", "argument", -// ) -// cmd.Env = []string{ -// "ENV_VAR_FOO=value", -// "ENV_VAR_BAR=other_value", -// } -// -// return cmd, nil -// }, -// ) -// -// // Create credentials using your exec.Cmd and custom timeout -// provider := processcreds.NewProviderCommand(cmdBuilder, -// func(opt *processcreds.Provider) { -// // optionally override the provider's default timeout -// opt.Timeout = 1 * time.Second -// }) -package processcreds diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/processcreds/provider.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/processcreds/provider.go deleted file mode 100644 index fe9345e28..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/processcreds/provider.go +++ /dev/null @@ -1,281 +0,0 @@ -package processcreds - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "os" - "os/exec" - "runtime" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/internal/sdkio" -) - -const ( - // ProviderName is the name this credentials provider will label any - // returned credentials Value with. - ProviderName = `ProcessProvider` - - // DefaultTimeout default limit on time a process can run. - DefaultTimeout = time.Duration(1) * time.Minute -) - -// ProviderError is an error indicating failure initializing or executing the -// process credentials provider -type ProviderError struct { - Err error -} - -// Error returns the error message. -func (e *ProviderError) Error() string { - return fmt.Sprintf("process provider error: %v", e.Err) -} - -// Unwrap returns the underlying error the provider error wraps. -func (e *ProviderError) Unwrap() error { - return e.Err -} - -// Provider satisfies the credentials.Provider interface, and is a -// client to retrieve credentials from a process. -type Provider struct { - // Provides a constructor for exec.Cmd that are invoked by the provider for - // retrieving credentials. Use this to provide custom creation of exec.Cmd - // with things like environment variables, or other configuration. - // - // The provider defaults to the DefaultNewCommand function. - commandBuilder NewCommandBuilder - - options Options -} - -// Options is the configuration options for configuring the Provider. -type Options struct { - // Timeout limits the time a process can run. - Timeout time.Duration -} - -// NewCommandBuilder provides the interface for specifying how command will be -// created that the Provider will use to retrieve credentials with. -type NewCommandBuilder interface { - NewCommand(context.Context) (*exec.Cmd, error) -} - -// NewCommandBuilderFunc provides a wrapper type around a function pointer to -// satisfy the NewCommandBuilder interface. -type NewCommandBuilderFunc func(context.Context) (*exec.Cmd, error) - -// NewCommand calls the underlying function pointer the builder was initialized with. -func (fn NewCommandBuilderFunc) NewCommand(ctx context.Context) (*exec.Cmd, error) { - return fn(ctx) -} - -// DefaultNewCommandBuilder provides the default NewCommandBuilder -// implementation used by the provider. It takes a command and arguments to -// invoke. The command will also be initialized with the current process -// environment variables, stderr, and stdin pipes. -type DefaultNewCommandBuilder struct { - Args []string -} - -// NewCommand returns an initialized exec.Cmd with the builder's initialized -// Args. The command is also initialized current process environment variables, -// stderr, and stdin pipes. -func (b DefaultNewCommandBuilder) NewCommand(ctx context.Context) (*exec.Cmd, error) { - var cmdArgs []string - if runtime.GOOS == "windows" { - cmdArgs = []string{"cmd.exe", "/C"} - } else { - cmdArgs = []string{"sh", "-c"} - } - - if len(b.Args) == 0 { - return nil, &ProviderError{ - Err: fmt.Errorf("failed to prepare command: command must not be empty"), - } - } - - cmdArgs = append(cmdArgs, b.Args...) - cmd := exec.CommandContext(ctx, cmdArgs[0], cmdArgs[1:]...) - cmd.Env = os.Environ() - - cmd.Stderr = os.Stderr // display stderr on console for MFA - cmd.Stdin = os.Stdin // enable stdin for MFA - - return cmd, nil -} - -// NewProvider returns a pointer to a new Credentials object wrapping the -// Provider. -// -// The provider defaults to the DefaultNewCommandBuilder for creating command -// the Provider will use to retrieve credentials with. -func NewProvider(command string, options ...func(*Options)) *Provider { - var args []string - - // Ensure that the command arguments are not set if the provided command is - // empty. This will error out when the command is executed since no - // arguments are specified. - if len(command) > 0 { - args = []string{command} - } - - commanBuilder := DefaultNewCommandBuilder{ - Args: args, - } - return NewProviderCommand(commanBuilder, options...) -} - -// NewProviderCommand returns a pointer to a new Credentials object with the -// specified command, and default timeout duration. Use this to provide custom -// creation of exec.Cmd for options like environment variables, or other -// configuration. -func NewProviderCommand(builder NewCommandBuilder, options ...func(*Options)) *Provider { - p := &Provider{ - commandBuilder: builder, - options: Options{ - Timeout: DefaultTimeout, - }, - } - - for _, option := range options { - option(&p.options) - } - - return p -} - -// A CredentialProcessResponse is the AWS credentials format that must be -// returned when executing an external credential_process. -type CredentialProcessResponse struct { - // As of this writing, the Version key must be set to 1. This might - // increment over time as the structure evolves. - Version int - - // The access key ID that identifies the temporary security credentials. - AccessKeyID string `json:"AccessKeyId"` - - // The secret access key that can be used to sign requests. - SecretAccessKey string - - // The token that users must pass to the service API to use the temporary credentials. - SessionToken string - - // The date on which the current credentials expire. - Expiration *time.Time -} - -// Retrieve executes the credential process command and returns the -// credentials, or error if the command fails. -func (p *Provider) Retrieve(ctx context.Context) (aws.Credentials, error) { - out, err := p.executeCredentialProcess(ctx) - if err != nil { - return aws.Credentials{Source: ProviderName}, err - } - - // Serialize and validate response - resp := &CredentialProcessResponse{} - if err = json.Unmarshal(out, resp); err != nil { - return aws.Credentials{Source: ProviderName}, &ProviderError{ - Err: fmt.Errorf("parse failed of process output: %s, error: %w", out, err), - } - } - - if resp.Version != 1 { - return aws.Credentials{Source: ProviderName}, &ProviderError{ - Err: fmt.Errorf("wrong version in process output (not 1)"), - } - } - - if len(resp.AccessKeyID) == 0 { - return aws.Credentials{Source: ProviderName}, &ProviderError{ - Err: fmt.Errorf("missing AccessKeyId in process output"), - } - } - - if len(resp.SecretAccessKey) == 0 { - return aws.Credentials{Source: ProviderName}, &ProviderError{ - Err: fmt.Errorf("missing SecretAccessKey in process output"), - } - } - - creds := aws.Credentials{ - Source: ProviderName, - AccessKeyID: resp.AccessKeyID, - SecretAccessKey: resp.SecretAccessKey, - SessionToken: resp.SessionToken, - } - - // Handle expiration - if resp.Expiration != nil { - creds.CanExpire = true - creds.Expires = *resp.Expiration - } - - return creds, nil -} - -// executeCredentialProcess starts the credential process on the OS and -// returns the results or an error. -func (p *Provider) executeCredentialProcess(ctx context.Context) ([]byte, error) { - if p.options.Timeout >= 0 { - var cancelFunc func() - ctx, cancelFunc = context.WithTimeout(ctx, p.options.Timeout) - defer cancelFunc() - } - - cmd, err := p.commandBuilder.NewCommand(ctx) - if err != nil { - return nil, err - } - - // get creds json on process's stdout - output := bytes.NewBuffer(make([]byte, 0, int(8*sdkio.KibiByte))) - if cmd.Stdout != nil { - cmd.Stdout = io.MultiWriter(cmd.Stdout, output) - } else { - cmd.Stdout = output - } - - execCh := make(chan error, 1) - go executeCommand(cmd, execCh) - - select { - case execError := <-execCh: - if execError == nil { - break - } - select { - case <-ctx.Done(): - return output.Bytes(), &ProviderError{ - Err: fmt.Errorf("credential process timed out: %w", execError), - } - default: - return output.Bytes(), &ProviderError{ - Err: fmt.Errorf("error in credential_process: %w", execError), - } - } - } - - out := output.Bytes() - if runtime.GOOS == "windows" { - // windows adds slashes to quotes - out = bytes.ReplaceAll(out, []byte(`\"`), []byte(`"`)) - } - - return out, nil -} - -func executeCommand(cmd *exec.Cmd, exec chan error) { - // Start the command - err := cmd.Start() - if err == nil { - err = cmd.Wait() - } - - exec <- err -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/ssocreds/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/ssocreds/doc.go deleted file mode 100644 index ece1e65f7..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/ssocreds/doc.go +++ /dev/null @@ -1,81 +0,0 @@ -// Package ssocreds provides a credential provider for retrieving temporary AWS -// credentials using an SSO access token. -// -// IMPORTANT: The provider in this package does not initiate or perform the AWS -// SSO login flow. The SDK provider expects that you have already performed the -// SSO login flow using AWS CLI using the "aws sso login" command, or by some -// other mechanism. The provider must find a valid non-expired access token for -// the AWS SSO user portal URL in ~/.aws/sso/cache. If a cached token is not -// found, it is expired, or the file is malformed an error will be returned. -// -// # Loading AWS SSO credentials with the AWS shared configuration file -// -// You can use configure AWS SSO credentials from the AWS shared configuration file by -// specifying the required keys in the profile and referencing an sso-session: -// -// sso_session -// sso_account_id -// sso_role_name -// -// For example, the following defines a profile "devsso" and specifies the AWS -// SSO parameters that defines the target account, role, sign-on portal, and -// the region where the user portal is located. Note: all SSO arguments must be -// provided, or an error will be returned. -// -// [profile devsso] -// sso_session = dev-session -// sso_role_name = SSOReadOnlyRole -// sso_account_id = 123456789012 -// -// [sso-session dev-session] -// sso_start_url = https://my-sso-portal.awsapps.com/start -// sso_region = us-east-1 -// sso_registration_scopes = sso:account:access -// -// Using the config module, you can load the AWS SDK shared configuration, and -// specify that this profile be used to retrieve credentials. For example: -// -// config, err := config.LoadDefaultConfig(context.TODO(), config.WithSharedConfigProfile("devsso")) -// if err != nil { -// return err -// } -// -// # Programmatically loading AWS SSO credentials directly -// -// You can programmatically construct the AWS SSO Provider in your application, -// and provide the necessary information to load and retrieve temporary -// credentials using an access token from ~/.aws/sso/cache. -// -// ssoClient := sso.NewFromConfig(cfg) -// ssoOidcClient := ssooidc.NewFromConfig(cfg) -// tokenPath, err := ssocreds.StandardCachedTokenFilepath("dev-session") -// if err != nil { -// return err -// } -// -// var provider aws.CredentialsProvider -// provider = ssocreds.New(ssoClient, "123456789012", "SSOReadOnlyRole", "https://my-sso-portal.awsapps.com/start", func(options *ssocreds.Options) { -// options.SSOTokenProvider = ssocreds.NewSSOTokenProvider(ssoOidcClient, tokenPath) -// }) -// -// // Wrap the provider with aws.CredentialsCache to cache the credentials until their expire time -// provider = aws.NewCredentialsCache(provider) -// -// credentials, err := provider.Retrieve(context.TODO()) -// if err != nil { -// return err -// } -// -// It is important that you wrap the Provider with aws.CredentialsCache if you -// are programmatically constructing the provider directly. This prevents your -// application from accessing the cached access token and requesting new -// credentials each time the credentials are used. -// -// # Additional Resources -// -// Configuring the AWS CLI to use AWS Single Sign-On: -// https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html -// -// AWS Single Sign-On User Guide: -// https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html -package ssocreds diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/ssocreds/sso_cached_token.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/ssocreds/sso_cached_token.go deleted file mode 100644 index 3b97e6dd4..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/ssocreds/sso_cached_token.go +++ /dev/null @@ -1,233 +0,0 @@ -package ssocreds - -import ( - "crypto/sha1" - "encoding/hex" - "encoding/json" - "fmt" - "io/ioutil" - "os" - "path/filepath" - "strconv" - "strings" - "time" - - "github.com/aws/aws-sdk-go-v2/internal/sdk" - "github.com/aws/aws-sdk-go-v2/internal/shareddefaults" -) - -var osUserHomeDur = shareddefaults.UserHomeDir - -// StandardCachedTokenFilepath returns the filepath for the cached SSO token file, or -// error if unable get derive the path. Key that will be used to compute a SHA1 -// value that is hex encoded. -// -// Derives the filepath using the Key as: -// -// ~/.aws/sso/cache/.json -func StandardCachedTokenFilepath(key string) (string, error) { - homeDir := osUserHomeDur() - if len(homeDir) == 0 { - return "", fmt.Errorf("unable to get USER's home directory for cached token") - } - hash := sha1.New() - if _, err := hash.Write([]byte(key)); err != nil { - return "", fmt.Errorf("unable to compute cached token filepath key SHA1 hash, %w", err) - } - - cacheFilename := strings.ToLower(hex.EncodeToString(hash.Sum(nil))) + ".json" - - return filepath.Join(homeDir, ".aws", "sso", "cache", cacheFilename), nil -} - -type tokenKnownFields struct { - AccessToken string `json:"accessToken,omitempty"` - ExpiresAt *rfc3339 `json:"expiresAt,omitempty"` - - RefreshToken string `json:"refreshToken,omitempty"` - ClientID string `json:"clientId,omitempty"` - ClientSecret string `json:"clientSecret,omitempty"` -} - -type token struct { - tokenKnownFields - UnknownFields map[string]interface{} `json:"-"` -} - -func (t token) MarshalJSON() ([]byte, error) { - fields := map[string]interface{}{} - - setTokenFieldString(fields, "accessToken", t.AccessToken) - setTokenFieldRFC3339(fields, "expiresAt", t.ExpiresAt) - - setTokenFieldString(fields, "refreshToken", t.RefreshToken) - setTokenFieldString(fields, "clientId", t.ClientID) - setTokenFieldString(fields, "clientSecret", t.ClientSecret) - - for k, v := range t.UnknownFields { - if _, ok := fields[k]; ok { - return nil, fmt.Errorf("unknown token field %v, duplicates known field", k) - } - fields[k] = v - } - - return json.Marshal(fields) -} - -func setTokenFieldString(fields map[string]interface{}, key, value string) { - if value == "" { - return - } - fields[key] = value -} -func setTokenFieldRFC3339(fields map[string]interface{}, key string, value *rfc3339) { - if value == nil { - return - } - fields[key] = value -} - -func (t *token) UnmarshalJSON(b []byte) error { - var fields map[string]interface{} - if err := json.Unmarshal(b, &fields); err != nil { - return nil - } - - t.UnknownFields = map[string]interface{}{} - - for k, v := range fields { - var err error - switch k { - case "accessToken": - err = getTokenFieldString(v, &t.AccessToken) - case "expiresAt": - err = getTokenFieldRFC3339(v, &t.ExpiresAt) - case "refreshToken": - err = getTokenFieldString(v, &t.RefreshToken) - case "clientId": - err = getTokenFieldString(v, &t.ClientID) - case "clientSecret": - err = getTokenFieldString(v, &t.ClientSecret) - default: - t.UnknownFields[k] = v - } - - if err != nil { - return fmt.Errorf("field %q, %w", k, err) - } - } - - return nil -} - -func getTokenFieldString(v interface{}, value *string) error { - var ok bool - *value, ok = v.(string) - if !ok { - return fmt.Errorf("expect value to be string, got %T", v) - } - return nil -} - -func getTokenFieldRFC3339(v interface{}, value **rfc3339) error { - var stringValue string - if err := getTokenFieldString(v, &stringValue); err != nil { - return err - } - - timeValue, err := parseRFC3339(stringValue) - if err != nil { - return err - } - - *value = &timeValue - return nil -} - -func loadCachedToken(filename string) (token, error) { - fileBytes, err := ioutil.ReadFile(filename) - if err != nil { - return token{}, fmt.Errorf("failed to read cached SSO token file, %w", err) - } - - var t token - if err := json.Unmarshal(fileBytes, &t); err != nil { - return token{}, fmt.Errorf("failed to parse cached SSO token file, %w", err) - } - - if len(t.AccessToken) == 0 || t.ExpiresAt == nil || time.Time(*t.ExpiresAt).IsZero() { - return token{}, fmt.Errorf( - "cached SSO token must contain accessToken and expiresAt fields") - } - - return t, nil -} - -func storeCachedToken(filename string, t token, fileMode os.FileMode) (err error) { - tmpFilename := filename + ".tmp-" + strconv.FormatInt(sdk.NowTime().UnixNano(), 10) - if err := writeCacheFile(tmpFilename, fileMode, t); err != nil { - return err - } - - if err := os.Rename(tmpFilename, filename); err != nil { - return fmt.Errorf("failed to replace old cached SSO token file, %w", err) - } - - return nil -} - -func writeCacheFile(filename string, fileMode os.FileMode, t token) (err error) { - var f *os.File - f, err = os.OpenFile(filename, os.O_CREATE|os.O_TRUNC|os.O_RDWR, fileMode) - if err != nil { - return fmt.Errorf("failed to create cached SSO token file %w", err) - } - - defer func() { - closeErr := f.Close() - if err == nil && closeErr != nil { - err = fmt.Errorf("failed to close cached SSO token file, %w", closeErr) - } - }() - - encoder := json.NewEncoder(f) - - if err = encoder.Encode(t); err != nil { - return fmt.Errorf("failed to serialize cached SSO token, %w", err) - } - - return nil -} - -type rfc3339 time.Time - -func parseRFC3339(v string) (rfc3339, error) { - parsed, err := time.Parse(time.RFC3339, v) - if err != nil { - return rfc3339{}, fmt.Errorf("expected RFC3339 timestamp: %w", err) - } - - return rfc3339(parsed), nil -} - -func (r *rfc3339) UnmarshalJSON(bytes []byte) (err error) { - var value string - - // Use JSON unmarshal to unescape the quoted value making use of JSON's - // unquoting rules. - if err = json.Unmarshal(bytes, &value); err != nil { - return err - } - - *r, err = parseRFC3339(value) - - return nil -} - -func (r *rfc3339) MarshalJSON() ([]byte, error) { - value := time.Time(*r).Format(time.RFC3339) - - // Use JSON unmarshal to unescape the quoted value making use of JSON's - // quoting rules. - return json.Marshal(value) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/ssocreds/sso_credentials_provider.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/ssocreds/sso_credentials_provider.go deleted file mode 100644 index b3cf7853e..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/ssocreds/sso_credentials_provider.go +++ /dev/null @@ -1,152 +0,0 @@ -package ssocreds - -import ( - "context" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/internal/sdk" - "github.com/aws/aws-sdk-go-v2/service/sso" -) - -// ProviderName is the name of the provider used to specify the source of -// credentials. -const ProviderName = "SSOProvider" - -// GetRoleCredentialsAPIClient is a API client that implements the -// GetRoleCredentials operation. -type GetRoleCredentialsAPIClient interface { - GetRoleCredentials(context.Context, *sso.GetRoleCredentialsInput, ...func(*sso.Options)) ( - *sso.GetRoleCredentialsOutput, error, - ) -} - -// Options is the Provider options structure. -type Options struct { - // The Client which is configured for the AWS Region where the AWS SSO user - // portal is located. - Client GetRoleCredentialsAPIClient - - // The AWS account that is assigned to the user. - AccountID string - - // The role name that is assigned to the user. - RoleName string - - // The URL that points to the organization's AWS Single Sign-On (AWS SSO) - // user portal. - StartURL string - - // The filepath the cached token will be retrieved from. If unset Provider will - // use the startURL to determine the filepath at. - // - // ~/.aws/sso/cache/.json - // - // If custom cached token filepath is used, the Provider's startUrl - // parameter will be ignored. - CachedTokenFilepath string - - // Used by the SSOCredentialProvider if a token configuration - // profile is used in the shared config - SSOTokenProvider *SSOTokenProvider -} - -// Provider is an AWS credential provider that retrieves temporary AWS -// credentials by exchanging an SSO login token. -type Provider struct { - options Options - - cachedTokenFilepath string -} - -// New returns a new AWS Single Sign-On (AWS SSO) credential provider. The -// provided client is expected to be configured for the AWS Region where the -// AWS SSO user portal is located. -func New(client GetRoleCredentialsAPIClient, accountID, roleName, startURL string, optFns ...func(options *Options)) *Provider { - options := Options{ - Client: client, - AccountID: accountID, - RoleName: roleName, - StartURL: startURL, - } - - for _, fn := range optFns { - fn(&options) - } - - return &Provider{ - options: options, - cachedTokenFilepath: options.CachedTokenFilepath, - } -} - -// Retrieve retrieves temporary AWS credentials from the configured Amazon -// Single Sign-On (AWS SSO) user portal by exchanging the accessToken present -// in ~/.aws/sso/cache. However, if a token provider configuration exists -// in the shared config, then we ought to use the token provider rather then -// direct access on the cached token. -func (p *Provider) Retrieve(ctx context.Context) (aws.Credentials, error) { - var accessToken *string - if p.options.SSOTokenProvider != nil { - token, err := p.options.SSOTokenProvider.RetrieveBearerToken(ctx) - if err != nil { - return aws.Credentials{}, err - } - accessToken = &token.Value - } else { - if p.cachedTokenFilepath == "" { - cachedTokenFilepath, err := StandardCachedTokenFilepath(p.options.StartURL) - if err != nil { - return aws.Credentials{}, &InvalidTokenError{Err: err} - } - p.cachedTokenFilepath = cachedTokenFilepath - } - - tokenFile, err := loadCachedToken(p.cachedTokenFilepath) - if err != nil { - return aws.Credentials{}, &InvalidTokenError{Err: err} - } - - if tokenFile.ExpiresAt == nil || sdk.NowTime().After(time.Time(*tokenFile.ExpiresAt)) { - return aws.Credentials{}, &InvalidTokenError{} - } - accessToken = &tokenFile.AccessToken - } - - output, err := p.options.Client.GetRoleCredentials(ctx, &sso.GetRoleCredentialsInput{ - AccessToken: accessToken, - AccountId: &p.options.AccountID, - RoleName: &p.options.RoleName, - }) - if err != nil { - return aws.Credentials{}, err - } - - return aws.Credentials{ - AccessKeyID: aws.ToString(output.RoleCredentials.AccessKeyId), - SecretAccessKey: aws.ToString(output.RoleCredentials.SecretAccessKey), - SessionToken: aws.ToString(output.RoleCredentials.SessionToken), - CanExpire: true, - Expires: time.Unix(0, output.RoleCredentials.Expiration*int64(time.Millisecond)).UTC(), - Source: ProviderName, - }, nil -} - -// InvalidTokenError is the error type that is returned if loaded token has -// expired or is otherwise invalid. To refresh the SSO session run AWS SSO -// login with the corresponding profile. -type InvalidTokenError struct { - Err error -} - -func (i *InvalidTokenError) Unwrap() error { - return i.Err -} - -func (i *InvalidTokenError) Error() string { - const msg = "the SSO session has expired or is invalid" - if i.Err == nil { - return msg - } - return msg + ": " + i.Err.Error() -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/ssocreds/sso_token_provider.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/ssocreds/sso_token_provider.go deleted file mode 100644 index 7f4fc5467..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/ssocreds/sso_token_provider.go +++ /dev/null @@ -1,147 +0,0 @@ -package ssocreds - -import ( - "context" - "fmt" - "os" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/internal/sdk" - "github.com/aws/aws-sdk-go-v2/service/ssooidc" - "github.com/aws/smithy-go/auth/bearer" -) - -// CreateTokenAPIClient provides the interface for the SSOTokenProvider's API -// client for calling CreateToken operation to refresh the SSO token. -type CreateTokenAPIClient interface { - CreateToken(context.Context, *ssooidc.CreateTokenInput, ...func(*ssooidc.Options)) ( - *ssooidc.CreateTokenOutput, error, - ) -} - -// SSOTokenProviderOptions provides the options for configuring the -// SSOTokenProvider. -type SSOTokenProviderOptions struct { - // Client that can be overridden - Client CreateTokenAPIClient - - // The set of API Client options to be applied when invoking the - // CreateToken operation. - ClientOptions []func(*ssooidc.Options) - - // The path the file containing the cached SSO token will be read from. - // Initialized the NewSSOTokenProvider's cachedTokenFilepath parameter. - CachedTokenFilepath string -} - -// SSOTokenProvider provides an utility for refreshing SSO AccessTokens for -// Bearer Authentication. The SSOTokenProvider can only be used to refresh -// already cached SSO Tokens. This utility cannot perform the initial SSO -// create token. -// -// The SSOTokenProvider is not safe to use concurrently. It must be wrapped in -// a utility such as smithy-go's auth/bearer#TokenCache. The SDK's -// config.LoadDefaultConfig will automatically wrap the SSOTokenProvider with -// the smithy-go TokenCache, if the external configuration loaded configured -// for an SSO session. -// -// The initial SSO create token should be preformed with the AWS CLI before the -// Go application using the SSOTokenProvider will need to retrieve the SSO -// token. If the AWS CLI has not created the token cache file, this provider -// will return an error when attempting to retrieve the cached token. -// -// This provider will attempt to refresh the cached SSO token periodically if -// needed when RetrieveBearerToken is called. -// -// A utility such as the AWS CLI must be used to initially create the SSO -// session and cached token file. -// https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html -type SSOTokenProvider struct { - options SSOTokenProviderOptions -} - -var _ bearer.TokenProvider = (*SSOTokenProvider)(nil) - -// NewSSOTokenProvider returns an initialized SSOTokenProvider that will -// periodically refresh the SSO token cached stored in the cachedTokenFilepath. -// The cachedTokenFilepath file's content will be rewritten by the token -// provider when the token is refreshed. -// -// The client must be configured for the AWS region the SSO token was created for. -func NewSSOTokenProvider(client CreateTokenAPIClient, cachedTokenFilepath string, optFns ...func(o *SSOTokenProviderOptions)) *SSOTokenProvider { - options := SSOTokenProviderOptions{ - Client: client, - CachedTokenFilepath: cachedTokenFilepath, - } - for _, fn := range optFns { - fn(&options) - } - - provider := &SSOTokenProvider{ - options: options, - } - - return provider -} - -// RetrieveBearerToken returns the SSO token stored in the cachedTokenFilepath -// the SSOTokenProvider was created with. If the token has expired -// RetrieveBearerToken will attempt to refresh it. If the token cannot be -// refreshed or is not present an error will be returned. -// -// A utility such as the AWS CLI must be used to initially create the SSO -// session and cached token file. https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html -func (p SSOTokenProvider) RetrieveBearerToken(ctx context.Context) (bearer.Token, error) { - cachedToken, err := loadCachedToken(p.options.CachedTokenFilepath) - if err != nil { - return bearer.Token{}, err - } - - if cachedToken.ExpiresAt != nil && sdk.NowTime().After(time.Time(*cachedToken.ExpiresAt)) { - cachedToken, err = p.refreshToken(ctx, cachedToken) - if err != nil { - return bearer.Token{}, fmt.Errorf("refresh cached SSO token failed, %w", err) - } - } - - expiresAt := aws.ToTime((*time.Time)(cachedToken.ExpiresAt)) - return bearer.Token{ - Value: cachedToken.AccessToken, - CanExpire: !expiresAt.IsZero(), - Expires: expiresAt, - }, nil -} - -func (p SSOTokenProvider) refreshToken(ctx context.Context, cachedToken token) (token, error) { - if cachedToken.ClientSecret == "" || cachedToken.ClientID == "" || cachedToken.RefreshToken == "" { - return token{}, fmt.Errorf("cached SSO token is expired, or not present, and cannot be refreshed") - } - - createResult, err := p.options.Client.CreateToken(ctx, &ssooidc.CreateTokenInput{ - ClientId: &cachedToken.ClientID, - ClientSecret: &cachedToken.ClientSecret, - RefreshToken: &cachedToken.RefreshToken, - GrantType: aws.String("refresh_token"), - }, p.options.ClientOptions...) - if err != nil { - return token{}, fmt.Errorf("unable to refresh SSO token, %w", err) - } - - expiresAt := sdk.NowTime().Add(time.Duration(createResult.ExpiresIn) * time.Second) - - cachedToken.AccessToken = aws.ToString(createResult.AccessToken) - cachedToken.ExpiresAt = (*rfc3339)(&expiresAt) - cachedToken.RefreshToken = aws.ToString(createResult.RefreshToken) - - fileInfo, err := os.Stat(p.options.CachedTokenFilepath) - if err != nil { - return token{}, fmt.Errorf("failed to stat cached SSO token file %w", err) - } - - if err = storeCachedToken(p.options.CachedTokenFilepath, cachedToken, fileInfo.Mode()); err != nil { - return token{}, fmt.Errorf("unable to cache refreshed SSO token, %w", err) - } - - return cachedToken, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/static_provider.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/static_provider.go deleted file mode 100644 index d525cac09..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/static_provider.go +++ /dev/null @@ -1,53 +0,0 @@ -package credentials - -import ( - "context" - - "github.com/aws/aws-sdk-go-v2/aws" -) - -const ( - // StaticCredentialsName provides a name of Static provider - StaticCredentialsName = "StaticCredentials" -) - -// StaticCredentialsEmptyError is emitted when static credentials are empty. -type StaticCredentialsEmptyError struct{} - -func (*StaticCredentialsEmptyError) Error() string { - return "static credentials are empty" -} - -// A StaticCredentialsProvider is a set of credentials which are set, and will -// never expire. -type StaticCredentialsProvider struct { - Value aws.Credentials -} - -// NewStaticCredentialsProvider return a StaticCredentialsProvider initialized with the AWS -// credentials passed in. -func NewStaticCredentialsProvider(key, secret, session string) StaticCredentialsProvider { - return StaticCredentialsProvider{ - Value: aws.Credentials{ - AccessKeyID: key, - SecretAccessKey: secret, - SessionToken: session, - }, - } -} - -// Retrieve returns the credentials or error if the credentials are invalid. -func (s StaticCredentialsProvider) Retrieve(_ context.Context) (aws.Credentials, error) { - v := s.Value - if v.AccessKeyID == "" || v.SecretAccessKey == "" { - return aws.Credentials{ - Source: StaticCredentialsName, - }, &StaticCredentialsEmptyError{} - } - - if len(v.Source) == 0 { - v.Source = StaticCredentialsName - } - - return v, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/stscreds/assume_role_provider.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/stscreds/assume_role_provider.go deleted file mode 100644 index 289707b6d..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/stscreds/assume_role_provider.go +++ /dev/null @@ -1,320 +0,0 @@ -// Package stscreds are credential Providers to retrieve STS AWS credentials. -// -// STS provides multiple ways to retrieve credentials which can be used when making -// future AWS service API operation calls. -// -// The SDK will ensure that per instance of credentials.Credentials all requests -// to refresh the credentials will be synchronized. But, the SDK is unable to -// ensure synchronous usage of the AssumeRoleProvider if the value is shared -// between multiple Credentials or service clients. -// -// # Assume Role -// -// To assume an IAM role using STS with the SDK you can create a new Credentials -// with the SDKs's stscreds package. -// -// // Initial credentials loaded from SDK's default credential chain. Such as -// // the environment, shared credentials (~/.aws/credentials), or EC2 Instance -// // Role. These credentials will be used to to make the STS Assume Role API. -// cfg, err := config.LoadDefaultConfig(context.TODO()) -// if err != nil { -// panic(err) -// } -// -// // Create the credentials from AssumeRoleProvider to assume the role -// // referenced by the "myRoleARN" ARN. -// stsSvc := sts.NewFromConfig(cfg) -// creds := stscreds.NewAssumeRoleProvider(stsSvc, "myRoleArn") -// -// cfg.Credentials = aws.NewCredentialsCache(creds) -// -// // Create service client value configured for credentials -// // from assumed role. -// svc := s3.NewFromConfig(cfg) -// -// # Assume Role with custom MFA Token provider -// -// To assume an IAM role with a MFA token you can either specify a custom MFA -// token provider or use the SDK's built in StdinTokenProvider that will prompt -// the user for a token code each time the credentials need to to be refreshed. -// Specifying a custom token provider allows you to control where the token -// code is retrieved from, and how it is refreshed. -// -// With a custom token provider, the provider is responsible for refreshing the -// token code when called. -// -// cfg, err := config.LoadDefaultConfig(context.TODO()) -// if err != nil { -// panic(err) -// } -// -// staticTokenProvider := func() (string, error) { -// return someTokenCode, nil -// } -// -// // Create the credentials from AssumeRoleProvider to assume the role -// // referenced by the "myRoleARN" ARN using the MFA token code provided. -// creds := stscreds.NewAssumeRoleProvider(sts.NewFromConfig(cfg), "myRoleArn", func(o *stscreds.AssumeRoleOptions) { -// o.SerialNumber = aws.String("myTokenSerialNumber") -// o.TokenProvider = staticTokenProvider -// }) -// -// cfg.Credentials = aws.NewCredentialsCache(creds) -// -// // Create service client value configured for credentials -// // from assumed role. -// svc := s3.NewFromConfig(cfg) -// -// # Assume Role with MFA Token Provider -// -// To assume an IAM role with MFA for longer running tasks where the credentials -// may need to be refreshed setting the TokenProvider field of AssumeRoleProvider -// will allow the credential provider to prompt for new MFA token code when the -// role's credentials need to be refreshed. -// -// The StdinTokenProvider function is available to prompt on stdin to retrieve -// the MFA token code from the user. You can also implement custom prompts by -// satisfying the TokenProvider function signature. -// -// Using StdinTokenProvider with multiple AssumeRoleProviders, or Credentials will -// have undesirable results as the StdinTokenProvider will not be synchronized. A -// single Credentials with an AssumeRoleProvider can be shared safely. -// -// cfg, err := config.LoadDefaultConfig(context.TODO()) -// if err != nil { -// panic(err) -// } -// -// // Create the credentials from AssumeRoleProvider to assume the role -// // referenced by the "myRoleARN" ARN using the MFA token code provided. -// creds := stscreds.NewAssumeRoleProvider(sts.NewFromConfig(cfg), "myRoleArn", func(o *stscreds.AssumeRoleOptions) { -// o.SerialNumber = aws.String("myTokenSerialNumber") -// o.TokenProvider = stscreds.StdinTokenProvider -// }) -// -// cfg.Credentials = aws.NewCredentialsCache(creds) -// -// // Create service client value configured for credentials -// // from assumed role. -// svc := s3.NewFromConfig(cfg) -package stscreds - -import ( - "context" - "fmt" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/sts" - "github.com/aws/aws-sdk-go-v2/service/sts/types" -) - -// StdinTokenProvider will prompt on stdout and read from stdin for a string value. -// An error is returned if reading from stdin fails. -// -// Use this function go read MFA tokens from stdin. The function makes no attempt -// to make atomic prompts from stdin across multiple gorouties. -// -// Using StdinTokenProvider with multiple AssumeRoleProviders, or Credentials will -// have undesirable results as the StdinTokenProvider will not be synchronized. A -// single Credentials with an AssumeRoleProvider can be shared safely -// -// Will wait forever until something is provided on the stdin. -func StdinTokenProvider() (string, error) { - var v string - fmt.Printf("Assume Role MFA token code: ") - _, err := fmt.Scanln(&v) - - return v, err -} - -// ProviderName provides a name of AssumeRole provider -const ProviderName = "AssumeRoleProvider" - -// AssumeRoleAPIClient is a client capable of the STS AssumeRole operation. -type AssumeRoleAPIClient interface { - AssumeRole(ctx context.Context, params *sts.AssumeRoleInput, optFns ...func(*sts.Options)) (*sts.AssumeRoleOutput, error) -} - -// DefaultDuration is the default amount of time in minutes that the -// credentials will be valid for. This value is only used by AssumeRoleProvider -// for specifying the default expiry duration of an assume role. -// -// Other providers such as WebIdentityRoleProvider do not use this value, and -// instead rely on STS API's default parameter handing to assign a default -// value. -var DefaultDuration = time.Duration(15) * time.Minute - -// AssumeRoleProvider retrieves temporary credentials from the STS service, and -// keeps track of their expiration time. -// -// This credential provider will be used by the SDKs default credential change -// when shared configuration is enabled, and the shared config or shared credentials -// file configure assume role. See Session docs for how to do this. -// -// AssumeRoleProvider does not provide any synchronization and it is not safe -// to share this value across multiple Credentials, Sessions, or service clients -// without also sharing the same Credentials instance. -type AssumeRoleProvider struct { - options AssumeRoleOptions -} - -// AssumeRoleOptions is the configurable options for AssumeRoleProvider -type AssumeRoleOptions struct { - // Client implementation of the AssumeRole operation. Required - Client AssumeRoleAPIClient - - // IAM Role ARN to be assumed. Required - RoleARN string - - // Session name, if you wish to uniquely identify this session. - RoleSessionName string - - // Expiry duration of the STS credentials. Defaults to 15 minutes if not set. - Duration time.Duration - - // Optional ExternalID to pass along, defaults to nil if not set. - ExternalID *string - - // The policy plain text must be 2048 bytes or shorter. However, an internal - // conversion compresses it into a packed binary format with a separate limit. - // The PackedPolicySize response element indicates by percentage how close to - // the upper size limit the policy is, with 100% equaling the maximum allowed - // size. - Policy *string - - // The ARNs of IAM managed policies you want to use as managed session policies. - // The policies must exist in the same account as the role. - // - // This parameter is optional. You can provide up to 10 managed policy ARNs. - // However, the plain text that you use for both inline and managed session - // policies can't exceed 2,048 characters. - // - // An AWS conversion compresses the passed session policies and session tags - // into a packed binary format that has a separate limit. Your request can fail - // for this limit even if your plain text meets the other requirements. The - // PackedPolicySize response element indicates by percentage how close the policies - // and tags for your request are to the upper size limit. - // - // Passing policies to this operation returns new temporary credentials. The - // resulting session's permissions are the intersection of the role's identity-based - // policy and the session policies. You can use the role's temporary credentials - // in subsequent AWS API calls to access resources in the account that owns - // the role. You cannot use session policies to grant more permissions than - // those allowed by the identity-based policy of the role that is being assumed. - // For more information, see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // in the IAM User Guide. - PolicyARNs []types.PolicyDescriptorType - - // The identification number of the MFA device that is associated with the user - // who is making the AssumeRole call. Specify this value if the trust policy - // of the role being assumed includes a condition that requires MFA authentication. - // The value is either the serial number for a hardware device (such as GAHT12345678) - // or an Amazon Resource Name (ARN) for a virtual device (such as arn:aws:iam::123456789012:mfa/user). - SerialNumber *string - - // The source identity specified by the principal that is calling the AssumeRole - // operation. You can require users to specify a source identity when they assume a - // role. You do this by using the sts:SourceIdentity condition key in a role trust - // policy. You can use source identity information in CloudTrail logs to determine - // who took actions with a role. You can use the aws:SourceIdentity condition key - // to further control access to Amazon Web Services resources based on the value of - // source identity. For more information about using source identity, see Monitor - // and control actions taken with assumed roles - // (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_monitor.html) - // in the IAM User Guide. - SourceIdentity *string - - // Async method of providing MFA token code for assuming an IAM role with MFA. - // The value returned by the function will be used as the TokenCode in the Retrieve - // call. See StdinTokenProvider for a provider that prompts and reads from stdin. - // - // This token provider will be called when ever the assumed role's - // credentials need to be refreshed when SerialNumber is set. - TokenProvider func() (string, error) - - // A list of session tags that you want to pass. Each session tag consists of a key - // name and an associated value. For more information about session tags, see - // Tagging STS Sessions - // (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) in the - // IAM User Guide. This parameter is optional. You can pass up to 50 session tags. - Tags []types.Tag - - // A list of keys for session tags that you want to set as transitive. If you set a - // tag key as transitive, the corresponding key and value passes to subsequent - // sessions in a role chain. For more information, see Chaining Roles with Session - // Tags - // (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html#id_session-tags_role-chaining) - // in the IAM User Guide. This parameter is optional. - TransitiveTagKeys []string -} - -// NewAssumeRoleProvider constructs and returns a credentials provider that -// will retrieve credentials by assuming a IAM role using STS. -func NewAssumeRoleProvider(client AssumeRoleAPIClient, roleARN string, optFns ...func(*AssumeRoleOptions)) *AssumeRoleProvider { - o := AssumeRoleOptions{ - Client: client, - RoleARN: roleARN, - } - - for _, fn := range optFns { - fn(&o) - } - - return &AssumeRoleProvider{ - options: o, - } -} - -// Retrieve generates a new set of temporary credentials using STS. -func (p *AssumeRoleProvider) Retrieve(ctx context.Context) (aws.Credentials, error) { - // Apply defaults where parameters are not set. - if len(p.options.RoleSessionName) == 0 { - // Try to work out a role name that will hopefully end up unique. - p.options.RoleSessionName = fmt.Sprintf("aws-go-sdk-%d", time.Now().UTC().UnixNano()) - } - if p.options.Duration == 0 { - // Expire as often as AWS permits. - p.options.Duration = DefaultDuration - } - input := &sts.AssumeRoleInput{ - DurationSeconds: aws.Int32(int32(p.options.Duration / time.Second)), - PolicyArns: p.options.PolicyARNs, - RoleArn: aws.String(p.options.RoleARN), - RoleSessionName: aws.String(p.options.RoleSessionName), - ExternalId: p.options.ExternalID, - SourceIdentity: p.options.SourceIdentity, - Tags: p.options.Tags, - TransitiveTagKeys: p.options.TransitiveTagKeys, - } - if p.options.Policy != nil { - input.Policy = p.options.Policy - } - if p.options.SerialNumber != nil { - if p.options.TokenProvider != nil { - input.SerialNumber = p.options.SerialNumber - code, err := p.options.TokenProvider() - if err != nil { - return aws.Credentials{}, err - } - input.TokenCode = aws.String(code) - } else { - return aws.Credentials{}, fmt.Errorf("assume role with MFA enabled, but TokenProvider is not set") - } - } - - resp, err := p.options.Client.AssumeRole(ctx, input) - if err != nil { - return aws.Credentials{Source: ProviderName}, err - } - - return aws.Credentials{ - AccessKeyID: *resp.Credentials.AccessKeyId, - SecretAccessKey: *resp.Credentials.SecretAccessKey, - SessionToken: *resp.Credentials.SessionToken, - Source: ProviderName, - - CanExpire: true, - Expires: *resp.Credentials.Expiration, - }, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/stscreds/web_identity_provider.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/stscreds/web_identity_provider.go deleted file mode 100644 index ddaf6df6c..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/stscreds/web_identity_provider.go +++ /dev/null @@ -1,150 +0,0 @@ -package stscreds - -import ( - "context" - "fmt" - "io/ioutil" - "strconv" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/aws/retry" - "github.com/aws/aws-sdk-go-v2/internal/sdk" - "github.com/aws/aws-sdk-go-v2/service/sts" - "github.com/aws/aws-sdk-go-v2/service/sts/types" -) - -var invalidIdentityTokenExceptionCode = (&types.InvalidIdentityTokenException{}).ErrorCode() - -const ( - // WebIdentityProviderName is the web identity provider name - WebIdentityProviderName = "WebIdentityCredentials" -) - -// AssumeRoleWithWebIdentityAPIClient is a client capable of the STS AssumeRoleWithWebIdentity operation. -type AssumeRoleWithWebIdentityAPIClient interface { - AssumeRoleWithWebIdentity(ctx context.Context, params *sts.AssumeRoleWithWebIdentityInput, optFns ...func(*sts.Options)) (*sts.AssumeRoleWithWebIdentityOutput, error) -} - -// WebIdentityRoleProvider is used to retrieve credentials using -// an OIDC token. -type WebIdentityRoleProvider struct { - options WebIdentityRoleOptions -} - -// WebIdentityRoleOptions is a structure of configurable options for WebIdentityRoleProvider -type WebIdentityRoleOptions struct { - // Client implementation of the AssumeRoleWithWebIdentity operation. Required - Client AssumeRoleWithWebIdentityAPIClient - - // JWT Token Provider. Required - TokenRetriever IdentityTokenRetriever - - // IAM Role ARN to assume. Required - RoleARN string - - // Session name, if you wish to uniquely identify this session. - RoleSessionName string - - // Expiry duration of the STS credentials. STS will assign a default expiry - // duration if this value is unset. This is different from the Duration - // option of AssumeRoleProvider, which automatically assigns 15 minutes if - // Duration is unset. - // - // See the STS AssumeRoleWithWebIdentity API reference guide for more - // information on defaults. - // https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html - Duration time.Duration - - // An IAM policy in JSON format that you want to use as an inline session policy. - Policy *string - - // The Amazon Resource Names (ARNs) of the IAM managed policies that you - // want to use as managed session policies. The policies must exist in the - // same account as the role. - PolicyARNs []types.PolicyDescriptorType -} - -// IdentityTokenRetriever is an interface for retrieving a JWT -type IdentityTokenRetriever interface { - GetIdentityToken() ([]byte, error) -} - -// IdentityTokenFile is for retrieving an identity token from the given file name -type IdentityTokenFile string - -// GetIdentityToken retrieves the JWT token from the file and returns the contents as a []byte -func (j IdentityTokenFile) GetIdentityToken() ([]byte, error) { - b, err := ioutil.ReadFile(string(j)) - if err != nil { - return nil, fmt.Errorf("unable to read file at %s: %v", string(j), err) - } - - return b, nil -} - -// NewWebIdentityRoleProvider will return a new WebIdentityRoleProvider with the -// provided stsiface.ClientAPI -func NewWebIdentityRoleProvider(client AssumeRoleWithWebIdentityAPIClient, roleARN string, tokenRetriever IdentityTokenRetriever, optFns ...func(*WebIdentityRoleOptions)) *WebIdentityRoleProvider { - o := WebIdentityRoleOptions{ - Client: client, - RoleARN: roleARN, - TokenRetriever: tokenRetriever, - } - - for _, fn := range optFns { - fn(&o) - } - - return &WebIdentityRoleProvider{options: o} -} - -// Retrieve will attempt to assume a role from a token which is located at -// 'WebIdentityTokenFilePath' specified destination and if that is empty an -// error will be returned. -func (p *WebIdentityRoleProvider) Retrieve(ctx context.Context) (aws.Credentials, error) { - b, err := p.options.TokenRetriever.GetIdentityToken() - if err != nil { - return aws.Credentials{}, fmt.Errorf("failed to retrieve jwt from provide source, %w", err) - } - - sessionName := p.options.RoleSessionName - if len(sessionName) == 0 { - // session name is used to uniquely identify a session. This simply - // uses unix time in nanoseconds to uniquely identify sessions. - sessionName = strconv.FormatInt(sdk.NowTime().UnixNano(), 10) - } - input := &sts.AssumeRoleWithWebIdentityInput{ - PolicyArns: p.options.PolicyARNs, - RoleArn: &p.options.RoleARN, - RoleSessionName: &sessionName, - WebIdentityToken: aws.String(string(b)), - } - if p.options.Duration != 0 { - // If set use the value, otherwise STS will assign a default expiration duration. - input.DurationSeconds = aws.Int32(int32(p.options.Duration / time.Second)) - } - if p.options.Policy != nil { - input.Policy = p.options.Policy - } - - resp, err := p.options.Client.AssumeRoleWithWebIdentity(ctx, input, func(options *sts.Options) { - options.Retryer = retry.AddWithErrorCodes(options.Retryer, invalidIdentityTokenExceptionCode) - }) - if err != nil { - return aws.Credentials{}, fmt.Errorf("failed to retrieve credentials, %w", err) - } - - // InvalidIdentityToken error is a temporary error that can occur - // when assuming an Role with a JWT web identity token. - - value := aws.Credentials{ - AccessKeyID: aws.ToString(resp.Credentials.AccessKeyId), - SecretAccessKey: aws.ToString(resp.Credentials.SecretAccessKey), - SessionToken: aws.ToString(resp.Credentials.SessionToken), - Source: WebIdentityProviderName, - CanExpire: true, - Expires: *resp.Credentials.Expiration, - } - return value, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/doc.go deleted file mode 100644 index 944feac55..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/doc.go +++ /dev/null @@ -1,58 +0,0 @@ -// Package sdk is the official AWS SDK v2 for the Go programming language. -// -// aws-sdk-go-v2 is the the v2 of the AWS SDK for the Go programming language. -// -// # Getting started -// -// The best way to get started working with the SDK is to use `go get` to add the -// SDK and desired service clients to your Go dependencies explicitly. -// -// go get github.com/aws/aws-sdk-go-v2 -// go get github.com/aws/aws-sdk-go-v2/config -// go get github.com/aws/aws-sdk-go-v2/service/dynamodb -// -// # Hello AWS -// -// This example shows how you can use the v2 SDK to make an API request using the -// SDK's Amazon DynamoDB client. -// -// package main -// -// import ( -// "context" -// "fmt" -// "log" -// -// "github.com/aws/aws-sdk-go-v2/aws" -// "github.com/aws/aws-sdk-go-v2/config" -// "github.com/aws/aws-sdk-go-v2/service/dynamodb" -// ) -// -// func main() { -// // Using the SDK's default configuration, loading additional config -// // and credentials values from the environment variables, shared -// // credentials, and shared configuration files -// cfg, err := config.LoadDefaultConfig(context.TODO(), -// config.WithRegion("us-west-2"), -// ) -// if err != nil { -// log.Fatalf("unable to load SDK config, %v", err) -// } -// -// // Using the Config value, create the DynamoDB client -// svc := dynamodb.NewFromConfig(cfg) -// -// // Build the request with its input parameters -// resp, err := svc.ListTables(context.TODO(), &dynamodb.ListTablesInput{ -// Limit: aws.Int32(5), -// }) -// if err != nil { -// log.Fatalf("failed to list tables, %v", err) -// } -// -// fmt.Println("Tables:") -// for _, tableName := range resp.TableNames { -// fmt.Println(tableName) -// } -// } -package sdk diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/CHANGELOG.md deleted file mode 100644 index 66b3e83c3..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/CHANGELOG.md +++ /dev/null @@ -1,228 +0,0 @@ -# v1.13.11 (2023-08-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.10 (2023-08-18) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.9 (2023-08-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.8 (2023-08-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.7 (2023-07-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.6 (2023-07-28) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.5 (2023-07-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.4 (2023-06-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.3 (2023-04-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.2 (2023-04-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.1 (2023-03-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.0 (2023-03-14) - -* **Feature**: Add flag to disable IMDSv1 fallback - -# v1.12.24 (2023-03-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.23 (2023-02-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.22 (2023-02-03) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.21 (2022-12-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.20 (2022-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.19 (2022-10-24) - -* **Bug Fix**: Fixes an issue that prevented logging of the API request or responses when the respective log modes were enabled. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.18 (2022-10-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.17 (2022-09-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.16 (2022-09-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.15 (2022-09-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.14 (2022-08-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.13 (2022-08-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.12 (2022-08-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.11 (2022-08-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.10 (2022-08-08) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.9 (2022-08-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.8 (2022-07-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.7 (2022-06-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.6 (2022-06-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.5 (2022-05-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.4 (2022-04-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.3 (2022-03-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.2 (2022-03-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.1 (2022-03-23) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.0 (2022-03-08) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.0 (2022-02-24) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.0 (2022-01-14) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.0 (2022-01-07) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.2 (2021-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.1 (2021-11-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.0 (2021-11-06) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.7.0 (2021-10-21) - -* **Feature**: Updated to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.0 (2021-10-11) - -* **Feature**: Respect passed in Context Deadline/Timeout. Updates the IMDS Client operations to not override the passed in Context's Deadline or Timeout options. If an Client operation is called with a Context with a Deadline or Timeout, the client will no longer override it with the client's default timeout. -* **Bug Fix**: Fix IMDS client's response handling and operation timeout race. Fixes #1253 -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.5.1 (2021-09-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.5.0 (2021-08-27) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.1 (2021-08-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.0 (2021-08-04) - -* **Feature**: adds error handling for defered close calls -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.0 (2021-07-15) - -* **Feature**: Support has been added for EC2 IPv6-enabled Instance Metadata Service Endpoints. -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.0 (2021-06-25) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.1 (2021-05-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.0 (2021-05-14) - -* **Feature**: Constant has been added to modules to enable runtime version inspection for reporting. -* **Dependency Update**: Updated to the latest SDK module versions - diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/LICENSE.txt deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/LICENSE.txt +++ /dev/null @@ -1,202 +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/aws/aws-sdk-go-v2/feature/ec2/imds/api_client.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_client.go deleted file mode 100644 index e55edd992..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_client.go +++ /dev/null @@ -1,330 +0,0 @@ -package imds - -import ( - "context" - "fmt" - "net" - "net/http" - "os" - "strings" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/aws/retry" - awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" - internalconfig "github.com/aws/aws-sdk-go-v2/feature/ec2/imds/internal/config" - "github.com/aws/smithy-go" - "github.com/aws/smithy-go/logging" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// ServiceID provides the unique name of this API client -const ServiceID = "ec2imds" - -// Client provides the API client for interacting with the Amazon EC2 Instance -// Metadata Service API. -type Client struct { - options Options -} - -// ClientEnableState provides an enumeration if the client is enabled, -// disabled, or default behavior. -type ClientEnableState = internalconfig.ClientEnableState - -// Enumeration values for ClientEnableState -const ( - ClientDefaultEnableState ClientEnableState = internalconfig.ClientDefaultEnableState // default behavior - ClientDisabled ClientEnableState = internalconfig.ClientDisabled // client disabled - ClientEnabled ClientEnableState = internalconfig.ClientEnabled // client enabled -) - -// EndpointModeState is an enum configuration variable describing the client endpoint mode. -// Not configurable directly, but used when using the NewFromConfig. -type EndpointModeState = internalconfig.EndpointModeState - -// Enumeration values for EndpointModeState -const ( - EndpointModeStateUnset EndpointModeState = internalconfig.EndpointModeStateUnset - EndpointModeStateIPv4 EndpointModeState = internalconfig.EndpointModeStateIPv4 - EndpointModeStateIPv6 EndpointModeState = internalconfig.EndpointModeStateIPv6 -) - -const ( - disableClientEnvVar = "AWS_EC2_METADATA_DISABLED" - - // Client endpoint options - endpointEnvVar = "AWS_EC2_METADATA_SERVICE_ENDPOINT" - - defaultIPv4Endpoint = "http://169.254.169.254" - defaultIPv6Endpoint = "http://[fd00:ec2::254]" -) - -// New returns an initialized Client based on the functional options. Provide -// additional functional options to further configure the behavior of the client, -// such as changing the client's endpoint or adding custom middleware behavior. -func New(options Options, optFns ...func(*Options)) *Client { - options = options.Copy() - - for _, fn := range optFns { - fn(&options) - } - - options.HTTPClient = resolveHTTPClient(options.HTTPClient) - - if options.Retryer == nil { - options.Retryer = retry.NewStandard() - } - options.Retryer = retry.AddWithMaxBackoffDelay(options.Retryer, 1*time.Second) - - if options.ClientEnableState == ClientDefaultEnableState { - if v := os.Getenv(disableClientEnvVar); strings.EqualFold(v, "true") { - options.ClientEnableState = ClientDisabled - } - } - - if len(options.Endpoint) == 0 { - if v := os.Getenv(endpointEnvVar); len(v) != 0 { - options.Endpoint = v - } - } - - client := &Client{ - options: options, - } - - if client.options.tokenProvider == nil && !client.options.disableAPIToken { - client.options.tokenProvider = newTokenProvider(client, defaultTokenTTL) - } - - return client -} - -// NewFromConfig returns an initialized Client based the AWS SDK config, and -// functional options. Provide additional functional options to further -// configure the behavior of the client, such as changing the client's endpoint -// or adding custom middleware behavior. -func NewFromConfig(cfg aws.Config, optFns ...func(*Options)) *Client { - opts := Options{ - APIOptions: append([]func(*middleware.Stack) error{}, cfg.APIOptions...), - HTTPClient: cfg.HTTPClient, - ClientLogMode: cfg.ClientLogMode, - Logger: cfg.Logger, - } - - if cfg.Retryer != nil { - opts.Retryer = cfg.Retryer() - } - - resolveClientEnableState(cfg, &opts) - resolveEndpointConfig(cfg, &opts) - resolveEndpointModeConfig(cfg, &opts) - - return New(opts, optFns...) -} - -// Options provides the fields for configuring the API client's behavior. -type Options struct { - // Set of options to modify how an operation is invoked. These apply to all - // operations invoked for this client. Use functional options on operation - // call to modify this list for per operation behavior. - APIOptions []func(*middleware.Stack) error - - // The endpoint the client will use to retrieve EC2 instance metadata. - // - // Specifies the EC2 Instance Metadata Service endpoint to use. If specified it overrides EndpointMode. - // - // If unset, and the environment variable AWS_EC2_METADATA_SERVICE_ENDPOINT - // has a value the client will use the value of the environment variable as - // the endpoint for operation calls. - // - // AWS_EC2_METADATA_SERVICE_ENDPOINT=http://[::1] - Endpoint string - - // The endpoint selection mode the client will use if no explicit endpoint is provided using the Endpoint field. - // - // Setting EndpointMode to EndpointModeStateIPv4 will configure the client to use the default EC2 IPv4 endpoint. - // Setting EndpointMode to EndpointModeStateIPv6 will configure the client to use the default EC2 IPv6 endpoint. - // - // By default if EndpointMode is not set (EndpointModeStateUnset) than the default endpoint selection mode EndpointModeStateIPv4. - EndpointMode EndpointModeState - - // The HTTP client to invoke API calls with. Defaults to client's default - // HTTP implementation if nil. - HTTPClient HTTPClient - - // Retryer guides how HTTP requests should be retried in case of recoverable - // failures. When nil the API client will use a default retryer. - Retryer aws.Retryer - - // Changes if the EC2 Instance Metadata client is enabled or not. Client - // will default to enabled if not set to ClientDisabled. When the client is - // disabled it will return an error for all operation calls. - // - // If ClientEnableState value is ClientDefaultEnableState (default value), - // and the environment variable "AWS_EC2_METADATA_DISABLED" is set to - // "true", the client will be disabled. - // - // AWS_EC2_METADATA_DISABLED=true - ClientEnableState ClientEnableState - - // Configures the events that will be sent to the configured logger. - ClientLogMode aws.ClientLogMode - - // The logger writer interface to write logging messages to. - Logger logging.Logger - - // Configure IMDSv1 fallback behavior. By default, the client will attempt - // to fall back to IMDSv1 as needed for backwards compatibility. When set to [aws.FalseTernary] - // the client will return any errors encountered from attempting to fetch a token - // instead of silently using the insecure data flow of IMDSv1. - // - // See [configuring IMDS] for more information. - // - // [configuring IMDS]: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html - EnableFallback aws.Ternary - - // provides the caching of API tokens used for operation calls. If unset, - // the API token will not be retrieved for the operation. - tokenProvider *tokenProvider - - // option to disable the API token provider for testing. - disableAPIToken bool -} - -// HTTPClient provides the interface for a client making HTTP requests with the -// API. -type HTTPClient interface { - Do(*http.Request) (*http.Response, error) -} - -// Copy creates a copy of the API options. -func (o Options) Copy() Options { - to := o - to.APIOptions = append([]func(*middleware.Stack) error{}, o.APIOptions...) - return to -} - -// WithAPIOptions wraps the API middleware functions, as a functional option -// for the API Client Options. Use this helper to add additional functional -// options to the API client, or operation calls. -func WithAPIOptions(optFns ...func(*middleware.Stack) error) func(*Options) { - return func(o *Options) { - o.APIOptions = append(o.APIOptions, optFns...) - } -} - -func (c *Client) invokeOperation( - ctx context.Context, opID string, params interface{}, optFns []func(*Options), - stackFns ...func(*middleware.Stack, Options) error, -) ( - result interface{}, metadata middleware.Metadata, err error, -) { - stack := middleware.NewStack(opID, smithyhttp.NewStackRequest) - options := c.options.Copy() - for _, fn := range optFns { - fn(&options) - } - - if options.ClientEnableState == ClientDisabled { - return nil, metadata, &smithy.OperationError{ - ServiceID: ServiceID, - OperationName: opID, - Err: fmt.Errorf( - "access disabled to EC2 IMDS via client option, or %q environment variable", - disableClientEnvVar), - } - } - - for _, fn := range stackFns { - if err := fn(stack, options); err != nil { - return nil, metadata, err - } - } - - for _, fn := range options.APIOptions { - if err := fn(stack); err != nil { - return nil, metadata, err - } - } - - handler := middleware.DecorateHandler(smithyhttp.NewClientHandler(options.HTTPClient), stack) - result, metadata, err = handler.Handle(ctx, params) - if err != nil { - return nil, metadata, &smithy.OperationError{ - ServiceID: ServiceID, - OperationName: opID, - Err: err, - } - } - - return result, metadata, err -} - -const ( - // HTTP client constants - defaultDialerTimeout = 250 * time.Millisecond - defaultResponseHeaderTimeout = 500 * time.Millisecond -) - -func resolveHTTPClient(client HTTPClient) HTTPClient { - if client == nil { - client = awshttp.NewBuildableClient() - } - - if c, ok := client.(*awshttp.BuildableClient); ok { - client = c. - WithDialerOptions(func(d *net.Dialer) { - // Use a custom Dial timeout for the EC2 Metadata service to account - // for the possibility the application might not be running in an - // environment with the service present. The client should fail fast in - // this case. - d.Timeout = defaultDialerTimeout - }). - WithTransportOptions(func(tr *http.Transport) { - // Use a custom Transport timeout for the EC2 Metadata service to - // account for the possibility that the application might be running in - // a container, and EC2Metadata service drops the connection after a - // single IP Hop. The client should fail fast in this case. - tr.ResponseHeaderTimeout = defaultResponseHeaderTimeout - }) - } - - return client -} - -func resolveClientEnableState(cfg aws.Config, options *Options) error { - if options.ClientEnableState != ClientDefaultEnableState { - return nil - } - value, found, err := internalconfig.ResolveClientEnableState(cfg.ConfigSources) - if err != nil || !found { - return err - } - options.ClientEnableState = value - return nil -} - -func resolveEndpointModeConfig(cfg aws.Config, options *Options) error { - if options.EndpointMode != EndpointModeStateUnset { - return nil - } - value, found, err := internalconfig.ResolveEndpointModeConfig(cfg.ConfigSources) - if err != nil || !found { - return err - } - options.EndpointMode = value - return nil -} - -func resolveEndpointConfig(cfg aws.Config, options *Options) error { - if len(options.Endpoint) != 0 { - return nil - } - value, found, err := internalconfig.ResolveEndpointConfig(cfg.ConfigSources) - if err != nil || !found { - return err - } - options.Endpoint = value - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetDynamicData.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetDynamicData.go deleted file mode 100644 index 9e3bdb0e6..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetDynamicData.go +++ /dev/null @@ -1,76 +0,0 @@ -package imds - -import ( - "context" - "fmt" - "io" - - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -const getDynamicDataPath = "/latest/dynamic" - -// GetDynamicData uses the path provided to request information from the EC2 -// instance metadata service for dynamic data. The content will be returned -// as a string, or error if the request failed. -func (c *Client) GetDynamicData(ctx context.Context, params *GetDynamicDataInput, optFns ...func(*Options)) (*GetDynamicDataOutput, error) { - if params == nil { - params = &GetDynamicDataInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetDynamicData", params, optFns, - addGetDynamicDataMiddleware, - ) - if err != nil { - return nil, err - } - - out := result.(*GetDynamicDataOutput) - out.ResultMetadata = metadata - return out, nil -} - -// GetDynamicDataInput provides the input parameters for the GetDynamicData -// operation. -type GetDynamicDataInput struct { - // The relative dynamic data path to retrieve. Can be empty string to - // retrieve a response containing a new line separated list of dynamic data - // resources available. - // - // Must not include the dynamic data base path. - // - // May include leading slash. If Path includes trailing slash the trailing - // slash will be included in the request for the resource. - Path string -} - -// GetDynamicDataOutput provides the output parameters for the GetDynamicData -// operation. -type GetDynamicDataOutput struct { - Content io.ReadCloser - - ResultMetadata middleware.Metadata -} - -func addGetDynamicDataMiddleware(stack *middleware.Stack, options Options) error { - return addAPIRequestMiddleware(stack, - options, - buildGetDynamicDataPath, - buildGetDynamicDataOutput) -} - -func buildGetDynamicDataPath(params interface{}) (string, error) { - p, ok := params.(*GetDynamicDataInput) - if !ok { - return "", fmt.Errorf("unknown parameter type %T", params) - } - - return appendURIPath(getDynamicDataPath, p.Path), nil -} - -func buildGetDynamicDataOutput(resp *smithyhttp.Response) (interface{}, error) { - return &GetDynamicDataOutput{ - Content: resp.Body, - }, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetIAMInfo.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetIAMInfo.go deleted file mode 100644 index 24845dccd..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetIAMInfo.go +++ /dev/null @@ -1,102 +0,0 @@ -package imds - -import ( - "context" - "encoding/json" - "fmt" - "io" - "strings" - "time" - - "github.com/aws/smithy-go" - smithyio "github.com/aws/smithy-go/io" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -const getIAMInfoPath = getMetadataPath + "/iam/info" - -// GetIAMInfo retrieves an identity document describing an -// instance. Error is returned if the request fails or is unable to parse -// the response. -func (c *Client) GetIAMInfo( - ctx context.Context, params *GetIAMInfoInput, optFns ...func(*Options), -) ( - *GetIAMInfoOutput, error, -) { - if params == nil { - params = &GetIAMInfoInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetIAMInfo", params, optFns, - addGetIAMInfoMiddleware, - ) - if err != nil { - return nil, err - } - - out := result.(*GetIAMInfoOutput) - out.ResultMetadata = metadata - return out, nil -} - -// GetIAMInfoInput provides the input parameters for GetIAMInfo operation. -type GetIAMInfoInput struct{} - -// GetIAMInfoOutput provides the output parameters for GetIAMInfo operation. -type GetIAMInfoOutput struct { - IAMInfo - - ResultMetadata middleware.Metadata -} - -func addGetIAMInfoMiddleware(stack *middleware.Stack, options Options) error { - return addAPIRequestMiddleware(stack, - options, - buildGetIAMInfoPath, - buildGetIAMInfoOutput, - ) -} - -func buildGetIAMInfoPath(params interface{}) (string, error) { - return getIAMInfoPath, nil -} - -func buildGetIAMInfoOutput(resp *smithyhttp.Response) (v interface{}, err error) { - defer func() { - closeErr := resp.Body.Close() - if err == nil { - err = closeErr - } else if closeErr != nil { - err = fmt.Errorf("response body close error: %v, original error: %w", closeErr, err) - } - }() - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(resp.Body, ringBuffer) - - imdsResult := &GetIAMInfoOutput{} - if err = json.NewDecoder(body).Decode(&imdsResult.IAMInfo); err != nil { - return nil, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode instance identity document, %w", err), - Snapshot: ringBuffer.Bytes(), - } - } - // Any code other success is an error - if !strings.EqualFold(imdsResult.Code, "success") { - return nil, fmt.Errorf("failed to get EC2 IMDS IAM info, %s", - imdsResult.Code) - } - - return imdsResult, nil -} - -// IAMInfo provides the shape for unmarshaling an IAM info from the metadata -// API. -type IAMInfo struct { - Code string - LastUpdated time.Time - InstanceProfileArn string - InstanceProfileID string -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetInstanceIdentityDocument.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetInstanceIdentityDocument.go deleted file mode 100644 index a87758ed3..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetInstanceIdentityDocument.go +++ /dev/null @@ -1,109 +0,0 @@ -package imds - -import ( - "context" - "encoding/json" - "fmt" - "io" - "time" - - "github.com/aws/smithy-go" - smithyio "github.com/aws/smithy-go/io" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -const getInstanceIdentityDocumentPath = getDynamicDataPath + "/instance-identity/document" - -// GetInstanceIdentityDocument retrieves an identity document describing an -// instance. Error is returned if the request fails or is unable to parse -// the response. -func (c *Client) GetInstanceIdentityDocument( - ctx context.Context, params *GetInstanceIdentityDocumentInput, optFns ...func(*Options), -) ( - *GetInstanceIdentityDocumentOutput, error, -) { - if params == nil { - params = &GetInstanceIdentityDocumentInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetInstanceIdentityDocument", params, optFns, - addGetInstanceIdentityDocumentMiddleware, - ) - if err != nil { - return nil, err - } - - out := result.(*GetInstanceIdentityDocumentOutput) - out.ResultMetadata = metadata - return out, nil -} - -// GetInstanceIdentityDocumentInput provides the input parameters for -// GetInstanceIdentityDocument operation. -type GetInstanceIdentityDocumentInput struct{} - -// GetInstanceIdentityDocumentOutput provides the output parameters for -// GetInstanceIdentityDocument operation. -type GetInstanceIdentityDocumentOutput struct { - InstanceIdentityDocument - - ResultMetadata middleware.Metadata -} - -func addGetInstanceIdentityDocumentMiddleware(stack *middleware.Stack, options Options) error { - return addAPIRequestMiddleware(stack, - options, - buildGetInstanceIdentityDocumentPath, - buildGetInstanceIdentityDocumentOutput, - ) -} - -func buildGetInstanceIdentityDocumentPath(params interface{}) (string, error) { - return getInstanceIdentityDocumentPath, nil -} - -func buildGetInstanceIdentityDocumentOutput(resp *smithyhttp.Response) (v interface{}, err error) { - defer func() { - closeErr := resp.Body.Close() - if err == nil { - err = closeErr - } else if closeErr != nil { - err = fmt.Errorf("response body close error: %v, original error: %w", closeErr, err) - } - }() - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(resp.Body, ringBuffer) - - output := &GetInstanceIdentityDocumentOutput{} - if err = json.NewDecoder(body).Decode(&output.InstanceIdentityDocument); err != nil { - return nil, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode instance identity document, %w", err), - Snapshot: ringBuffer.Bytes(), - } - } - - return output, nil -} - -// InstanceIdentityDocument provides the shape for unmarshaling -// an instance identity document -type InstanceIdentityDocument struct { - DevpayProductCodes []string `json:"devpayProductCodes"` - MarketplaceProductCodes []string `json:"marketplaceProductCodes"` - AvailabilityZone string `json:"availabilityZone"` - PrivateIP string `json:"privateIp"` - Version string `json:"version"` - Region string `json:"region"` - InstanceID string `json:"instanceId"` - BillingProducts []string `json:"billingProducts"` - InstanceType string `json:"instanceType"` - AccountID string `json:"accountId"` - PendingTime time.Time `json:"pendingTime"` - ImageID string `json:"imageId"` - KernelID string `json:"kernelId"` - RamdiskID string `json:"ramdiskId"` - Architecture string `json:"architecture"` -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetMetadata.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetMetadata.go deleted file mode 100644 index cb0ce4c00..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetMetadata.go +++ /dev/null @@ -1,76 +0,0 @@ -package imds - -import ( - "context" - "fmt" - "io" - - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -const getMetadataPath = "/latest/meta-data" - -// GetMetadata uses the path provided to request information from the Amazon -// EC2 Instance Metadata Service. The content will be returned as a string, or -// error if the request failed. -func (c *Client) GetMetadata(ctx context.Context, params *GetMetadataInput, optFns ...func(*Options)) (*GetMetadataOutput, error) { - if params == nil { - params = &GetMetadataInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetMetadata", params, optFns, - addGetMetadataMiddleware, - ) - if err != nil { - return nil, err - } - - out := result.(*GetMetadataOutput) - out.ResultMetadata = metadata - return out, nil -} - -// GetMetadataInput provides the input parameters for the GetMetadata -// operation. -type GetMetadataInput struct { - // The relative metadata path to retrieve. Can be empty string to retrieve - // a response containing a new line separated list of metadata resources - // available. - // - // Must not include the metadata base path. - // - // May include leading slash. If Path includes trailing slash the trailing slash - // will be included in the request for the resource. - Path string -} - -// GetMetadataOutput provides the output parameters for the GetMetadata -// operation. -type GetMetadataOutput struct { - Content io.ReadCloser - - ResultMetadata middleware.Metadata -} - -func addGetMetadataMiddleware(stack *middleware.Stack, options Options) error { - return addAPIRequestMiddleware(stack, - options, - buildGetMetadataPath, - buildGetMetadataOutput) -} - -func buildGetMetadataPath(params interface{}) (string, error) { - p, ok := params.(*GetMetadataInput) - if !ok { - return "", fmt.Errorf("unknown parameter type %T", params) - } - - return appendURIPath(getMetadataPath, p.Path), nil -} - -func buildGetMetadataOutput(resp *smithyhttp.Response) (interface{}, error) { - return &GetMetadataOutput{ - Content: resp.Body, - }, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetRegion.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetRegion.go deleted file mode 100644 index 7b9b48912..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetRegion.go +++ /dev/null @@ -1,72 +0,0 @@ -package imds - -import ( - "context" - "fmt" - - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// GetRegion retrieves an identity document describing an -// instance. Error is returned if the request fails or is unable to parse -// the response. -func (c *Client) GetRegion( - ctx context.Context, params *GetRegionInput, optFns ...func(*Options), -) ( - *GetRegionOutput, error, -) { - if params == nil { - params = &GetRegionInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetRegion", params, optFns, - addGetRegionMiddleware, - ) - if err != nil { - return nil, err - } - - out := result.(*GetRegionOutput) - out.ResultMetadata = metadata - return out, nil -} - -// GetRegionInput provides the input parameters for GetRegion operation. -type GetRegionInput struct{} - -// GetRegionOutput provides the output parameters for GetRegion operation. -type GetRegionOutput struct { - Region string - - ResultMetadata middleware.Metadata -} - -func addGetRegionMiddleware(stack *middleware.Stack, options Options) error { - return addAPIRequestMiddleware(stack, - options, - buildGetInstanceIdentityDocumentPath, - buildGetRegionOutput, - ) -} - -func buildGetRegionOutput(resp *smithyhttp.Response) (interface{}, error) { - out, err := buildGetInstanceIdentityDocumentOutput(resp) - if err != nil { - return nil, err - } - - result, ok := out.(*GetInstanceIdentityDocumentOutput) - if !ok { - return nil, fmt.Errorf("unexpected instance identity document type, %T", out) - } - - region := result.Region - if len(region) == 0 { - return "", fmt.Errorf("instance metadata did not return a region value") - } - - return &GetRegionOutput{ - Region: region, - }, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetToken.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetToken.go deleted file mode 100644 index 841f802c1..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetToken.go +++ /dev/null @@ -1,118 +0,0 @@ -package imds - -import ( - "context" - "fmt" - "io" - "strconv" - "strings" - "time" - - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -const getTokenPath = "/latest/api/token" -const tokenTTLHeader = "X-Aws-Ec2-Metadata-Token-Ttl-Seconds" - -// getToken uses the duration to return a token for EC2 IMDS, or an error if -// the request failed. -func (c *Client) getToken(ctx context.Context, params *getTokenInput, optFns ...func(*Options)) (*getTokenOutput, error) { - if params == nil { - params = &getTokenInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "getToken", params, optFns, - addGetTokenMiddleware, - ) - if err != nil { - return nil, err - } - - out := result.(*getTokenOutput) - out.ResultMetadata = metadata - return out, nil -} - -type getTokenInput struct { - TokenTTL time.Duration -} - -type getTokenOutput struct { - Token string - TokenTTL time.Duration - - ResultMetadata middleware.Metadata -} - -func addGetTokenMiddleware(stack *middleware.Stack, options Options) error { - err := addRequestMiddleware(stack, - options, - "PUT", - buildGetTokenPath, - buildGetTokenOutput) - if err != nil { - return err - } - - err = stack.Serialize.Add(&tokenTTLRequestHeader{}, middleware.After) - if err != nil { - return err - } - - return nil -} - -func buildGetTokenPath(interface{}) (string, error) { - return getTokenPath, nil -} - -func buildGetTokenOutput(resp *smithyhttp.Response) (v interface{}, err error) { - defer func() { - closeErr := resp.Body.Close() - if err == nil { - err = closeErr - } else if closeErr != nil { - err = fmt.Errorf("response body close error: %v, original error: %w", closeErr, err) - } - }() - - ttlHeader := resp.Header.Get(tokenTTLHeader) - tokenTTL, err := strconv.ParseInt(ttlHeader, 10, 64) - if err != nil { - return nil, fmt.Errorf("unable to parse API token, %w", err) - } - - var token strings.Builder - if _, err = io.Copy(&token, resp.Body); err != nil { - return nil, fmt.Errorf("unable to read API token, %w", err) - } - - return &getTokenOutput{ - Token: token.String(), - TokenTTL: time.Duration(tokenTTL) * time.Second, - }, nil -} - -type tokenTTLRequestHeader struct{} - -func (*tokenTTLRequestHeader) ID() string { return "tokenTTLRequestHeader" } -func (*tokenTTLRequestHeader) HandleSerialize( - ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler, -) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("expect HTTP transport, got %T", in.Request) - } - - input, ok := in.Parameters.(*getTokenInput) - if !ok { - return out, metadata, fmt.Errorf("expect getTokenInput, got %T", in.Parameters) - } - - req.Header.Set(tokenTTLHeader, strconv.Itoa(int(input.TokenTTL/time.Second))) - - return next.HandleSerialize(ctx, in) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetUserData.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetUserData.go deleted file mode 100644 index 88aa61e9a..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetUserData.go +++ /dev/null @@ -1,60 +0,0 @@ -package imds - -import ( - "context" - "io" - - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -const getUserDataPath = "/latest/user-data" - -// GetUserData uses the path provided to request information from the EC2 -// instance metadata service for dynamic data. The content will be returned -// as a string, or error if the request failed. -func (c *Client) GetUserData(ctx context.Context, params *GetUserDataInput, optFns ...func(*Options)) (*GetUserDataOutput, error) { - if params == nil { - params = &GetUserDataInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetUserData", params, optFns, - addGetUserDataMiddleware, - ) - if err != nil { - return nil, err - } - - out := result.(*GetUserDataOutput) - out.ResultMetadata = metadata - return out, nil -} - -// GetUserDataInput provides the input parameters for the GetUserData -// operation. -type GetUserDataInput struct{} - -// GetUserDataOutput provides the output parameters for the GetUserData -// operation. -type GetUserDataOutput struct { - Content io.ReadCloser - - ResultMetadata middleware.Metadata -} - -func addGetUserDataMiddleware(stack *middleware.Stack, options Options) error { - return addAPIRequestMiddleware(stack, - options, - buildGetUserDataPath, - buildGetUserDataOutput) -} - -func buildGetUserDataPath(params interface{}) (string, error) { - return getUserDataPath, nil -} - -func buildGetUserDataOutput(resp *smithyhttp.Response) (interface{}, error) { - return &GetUserDataOutput{ - Content: resp.Body, - }, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/doc.go deleted file mode 100644 index bacdb5d21..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/doc.go +++ /dev/null @@ -1,11 +0,0 @@ -// Package imds provides the API client for interacting with the Amazon EC2 -// Instance Metadata Service. -// -// All Client operation calls have a default timeout. If the operation is not -// completed before this timeout expires, the operation will be canceled. This -// timeout can be overridden by providing Context with a timeout or deadline -// with calling the client's operations. -// -// See the EC2 IMDS user guide for more information on using the API. -// https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html -package imds diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/go_module_metadata.go deleted file mode 100644 index deb28a237..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/go_module_metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. - -package imds - -// goModuleVersion is the tagged release for this module -const goModuleVersion = "1.13.11" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/internal/config/resolvers.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/internal/config/resolvers.go deleted file mode 100644 index d72fcb562..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/internal/config/resolvers.go +++ /dev/null @@ -1,98 +0,0 @@ -package config - -import ( - "fmt" - "strings" -) - -// ClientEnableState provides an enumeration if the client is enabled, -// disabled, or default behavior. -type ClientEnableState uint - -// Enumeration values for ClientEnableState -const ( - ClientDefaultEnableState ClientEnableState = iota - ClientDisabled - ClientEnabled -) - -// EndpointModeState is the EC2 IMDS Endpoint Configuration Mode -type EndpointModeState uint - -// Enumeration values for ClientEnableState -const ( - EndpointModeStateUnset EndpointModeState = iota - EndpointModeStateIPv4 - EndpointModeStateIPv6 -) - -// SetFromString sets the EndpointModeState based on the provided string value. Unknown values will default to EndpointModeStateUnset -func (e *EndpointModeState) SetFromString(v string) error { - v = strings.TrimSpace(v) - - switch { - case len(v) == 0: - *e = EndpointModeStateUnset - case strings.EqualFold(v, "IPv6"): - *e = EndpointModeStateIPv6 - case strings.EqualFold(v, "IPv4"): - *e = EndpointModeStateIPv4 - default: - return fmt.Errorf("unknown EC2 IMDS endpoint mode, must be either IPv6 or IPv4") - } - return nil -} - -// ClientEnableStateResolver is a config resolver interface for retrieving whether the IMDS client is disabled. -type ClientEnableStateResolver interface { - GetEC2IMDSClientEnableState() (ClientEnableState, bool, error) -} - -// EndpointModeResolver is a config resolver interface for retrieving the EndpointModeState configuration. -type EndpointModeResolver interface { - GetEC2IMDSEndpointMode() (EndpointModeState, bool, error) -} - -// EndpointResolver is a config resolver interface for retrieving the endpoint. -type EndpointResolver interface { - GetEC2IMDSEndpoint() (string, bool, error) -} - -// ResolveClientEnableState resolves the ClientEnableState from a list of configuration sources. -func ResolveClientEnableState(sources []interface{}) (value ClientEnableState, found bool, err error) { - for _, source := range sources { - if resolver, ok := source.(ClientEnableStateResolver); ok { - value, found, err = resolver.GetEC2IMDSClientEnableState() - if err != nil || found { - return value, found, err - } - } - } - return value, found, err -} - -// ResolveEndpointModeConfig resolves the EndpointModeState from a list of configuration sources. -func ResolveEndpointModeConfig(sources []interface{}) (value EndpointModeState, found bool, err error) { - for _, source := range sources { - if resolver, ok := source.(EndpointModeResolver); ok { - value, found, err = resolver.GetEC2IMDSEndpointMode() - if err != nil || found { - return value, found, err - } - } - } - return value, found, err -} - -// ResolveEndpointConfig resolves the endpoint from a list of configuration sources. -func ResolveEndpointConfig(sources []interface{}) (value string, found bool, err error) { - for _, source := range sources { - if resolver, ok := source.(EndpointResolver); ok { - value, found, err = resolver.GetEC2IMDSEndpoint() - if err != nil || found { - return value, found, err - } - } - } - return value, found, err -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/request_middleware.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/request_middleware.go deleted file mode 100644 index c8abd6491..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/request_middleware.go +++ /dev/null @@ -1,285 +0,0 @@ -package imds - -import ( - "bytes" - "context" - "fmt" - "io/ioutil" - "net/url" - "path" - "time" - - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/retry" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -func addAPIRequestMiddleware(stack *middleware.Stack, - options Options, - getPath func(interface{}) (string, error), - getOutput func(*smithyhttp.Response) (interface{}, error), -) (err error) { - err = addRequestMiddleware(stack, options, "GET", getPath, getOutput) - if err != nil { - return err - } - - // Token Serializer build and state management. - if !options.disableAPIToken { - err = stack.Finalize.Insert(options.tokenProvider, (*retry.Attempt)(nil).ID(), middleware.After) - if err != nil { - return err - } - - err = stack.Deserialize.Insert(options.tokenProvider, "OperationDeserializer", middleware.Before) - if err != nil { - return err - } - } - - return nil -} - -func addRequestMiddleware(stack *middleware.Stack, - options Options, - method string, - getPath func(interface{}) (string, error), - getOutput func(*smithyhttp.Response) (interface{}, error), -) (err error) { - err = awsmiddleware.AddSDKAgentKey(awsmiddleware.FeatureMetadata, "ec2-imds")(stack) - if err != nil { - return err - } - - // Operation timeout - err = stack.Initialize.Add(&operationTimeout{ - DefaultTimeout: defaultOperationTimeout, - }, middleware.Before) - if err != nil { - return err - } - - // Operation Serializer - err = stack.Serialize.Add(&serializeRequest{ - GetPath: getPath, - Method: method, - }, middleware.After) - if err != nil { - return err - } - - // Operation endpoint resolver - err = stack.Serialize.Insert(&resolveEndpoint{ - Endpoint: options.Endpoint, - EndpointMode: options.EndpointMode, - }, "OperationSerializer", middleware.Before) - if err != nil { - return err - } - - // Operation Deserializer - err = stack.Deserialize.Add(&deserializeResponse{ - GetOutput: getOutput, - }, middleware.After) - if err != nil { - return err - } - - err = stack.Deserialize.Add(&smithyhttp.RequestResponseLogger{ - LogRequest: options.ClientLogMode.IsRequest(), - LogRequestWithBody: options.ClientLogMode.IsRequestWithBody(), - LogResponse: options.ClientLogMode.IsResponse(), - LogResponseWithBody: options.ClientLogMode.IsResponseWithBody(), - }, middleware.After) - if err != nil { - return err - } - - err = addSetLoggerMiddleware(stack, options) - if err != nil { - return err - } - - // Retry support - return retry.AddRetryMiddlewares(stack, retry.AddRetryMiddlewaresOptions{ - Retryer: options.Retryer, - LogRetryAttempts: options.ClientLogMode.IsRetries(), - }) -} - -func addSetLoggerMiddleware(stack *middleware.Stack, o Options) error { - return middleware.AddSetLoggerMiddleware(stack, o.Logger) -} - -type serializeRequest struct { - GetPath func(interface{}) (string, error) - Method string -} - -func (*serializeRequest) ID() string { - return "OperationSerializer" -} - -func (m *serializeRequest) HandleSerialize( - ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler, -) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - request, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - reqPath, err := m.GetPath(in.Parameters) - if err != nil { - return out, metadata, fmt.Errorf("unable to get request URL path, %w", err) - } - - request.Request.URL.Path = reqPath - request.Request.Method = m.Method - - return next.HandleSerialize(ctx, in) -} - -type deserializeResponse struct { - GetOutput func(*smithyhttp.Response) (interface{}, error) -} - -func (*deserializeResponse) ID() string { - return "OperationDeserializer" -} - -func (m *deserializeResponse) HandleDeserialize( - ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler, -) ( - out middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err = next.HandleDeserialize(ctx, in) - if err != nil { - return out, metadata, err - } - - resp, ok := out.RawResponse.(*smithyhttp.Response) - if !ok { - return out, metadata, fmt.Errorf( - "unexpected transport response type, %T, want %T", out.RawResponse, resp) - } - defer resp.Body.Close() - - // read the full body so that any operation timeouts cleanup will not race - // the body being read. - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return out, metadata, fmt.Errorf("read response body failed, %w", err) - } - resp.Body = ioutil.NopCloser(bytes.NewReader(body)) - - // Anything that's not 200 |< 300 is error - if resp.StatusCode < 200 || resp.StatusCode >= 300 { - return out, metadata, &smithyhttp.ResponseError{ - Response: resp, - Err: fmt.Errorf("request to EC2 IMDS failed"), - } - } - - result, err := m.GetOutput(resp) - if err != nil { - return out, metadata, fmt.Errorf( - "unable to get deserialized result for response, %w", err, - ) - } - out.Result = result - - return out, metadata, err -} - -type resolveEndpoint struct { - Endpoint string - EndpointMode EndpointModeState -} - -func (*resolveEndpoint) ID() string { - return "ResolveEndpoint" -} - -func (m *resolveEndpoint) HandleSerialize( - ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler, -) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - var endpoint string - if len(m.Endpoint) > 0 { - endpoint = m.Endpoint - } else { - switch m.EndpointMode { - case EndpointModeStateIPv6: - endpoint = defaultIPv6Endpoint - case EndpointModeStateIPv4: - fallthrough - case EndpointModeStateUnset: - endpoint = defaultIPv4Endpoint - default: - return out, metadata, fmt.Errorf("unsupported IMDS endpoint mode") - } - } - - req.URL, err = url.Parse(endpoint) - if err != nil { - return out, metadata, fmt.Errorf("failed to parse endpoint URL: %w", err) - } - - return next.HandleSerialize(ctx, in) -} - -const ( - defaultOperationTimeout = 5 * time.Second -) - -// operationTimeout adds a timeout on the middleware stack if the Context the -// stack was called with does not have a deadline. The next middleware must -// complete before the timeout, or the context will be canceled. -// -// If DefaultTimeout is zero, no default timeout will be used if the Context -// does not have a timeout. -// -// The next middleware must also ensure that any resources that are also -// canceled by the stack's context are completely consumed before returning. -// Otherwise the timeout cleanup will race the resource being consumed -// upstream. -type operationTimeout struct { - DefaultTimeout time.Duration -} - -func (*operationTimeout) ID() string { return "OperationTimeout" } - -func (m *operationTimeout) HandleInitialize( - ctx context.Context, input middleware.InitializeInput, next middleware.InitializeHandler, -) ( - output middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - if _, ok := ctx.Deadline(); !ok && m.DefaultTimeout != 0 { - var cancelFn func() - ctx, cancelFn = context.WithTimeout(ctx, m.DefaultTimeout) - defer cancelFn() - } - - return next.HandleInitialize(ctx, input) -} - -// appendURIPath joins a URI path component to the existing path with `/` -// separators between the path components. If the path being added ends with a -// trailing `/` that slash will be maintained. -func appendURIPath(base, add string) string { - reqPath := path.Join(base, add) - if len(add) != 0 && add[len(add)-1] == '/' { - reqPath += "/" - } - return reqPath -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/token_provider.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/token_provider.go deleted file mode 100644 index 5703c6e16..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/token_provider.go +++ /dev/null @@ -1,261 +0,0 @@ -package imds - -import ( - "context" - "errors" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/smithy-go" - "github.com/aws/smithy-go/logging" - "net/http" - "sync" - "sync/atomic" - "time" - - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -const ( - // Headers for Token and TTL - tokenHeader = "x-aws-ec2-metadata-token" - defaultTokenTTL = 5 * time.Minute -) - -type tokenProvider struct { - client *Client - tokenTTL time.Duration - - token *apiToken - tokenMux sync.RWMutex - - disabled uint32 // Atomic updated -} - -func newTokenProvider(client *Client, ttl time.Duration) *tokenProvider { - return &tokenProvider{ - client: client, - tokenTTL: ttl, - } -} - -// apiToken provides the API token used by all operation calls for th EC2 -// Instance metadata service. -type apiToken struct { - token string - expires time.Time -} - -var timeNow = time.Now - -// Expired returns if the token is expired. -func (t *apiToken) Expired() bool { - // Calling Round(0) on the current time will truncate the monotonic reading only. Ensures credential expiry - // time is always based on reported wall-clock time. - return timeNow().Round(0).After(t.expires) -} - -func (t *tokenProvider) ID() string { return "APITokenProvider" } - -// HandleFinalize is the finalize stack middleware, that if the token provider is -// enabled, will attempt to add the cached API token to the request. If the API -// token is not cached, it will be retrieved in a separate API call, getToken. -// -// For retry attempts, handler must be added after attempt retryer. -// -// If request for getToken fails the token provider may be disabled from future -// requests, depending on the response status code. -func (t *tokenProvider) HandleFinalize( - ctx context.Context, input middleware.FinalizeInput, next middleware.FinalizeHandler, -) ( - out middleware.FinalizeOutput, metadata middleware.Metadata, err error, -) { - if t.fallbackEnabled() && !t.enabled() { - // short-circuits to insecure data flow if token provider is disabled. - return next.HandleFinalize(ctx, input) - } - - req, ok := input.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unexpected transport request type %T", input.Request) - } - - tok, err := t.getToken(ctx) - if err != nil { - // If the error allows the token to downgrade to insecure flow allow that. - var bypassErr *bypassTokenRetrievalError - if errors.As(err, &bypassErr) { - return next.HandleFinalize(ctx, input) - } - - return out, metadata, fmt.Errorf("failed to get API token, %w", err) - } - - req.Header.Set(tokenHeader, tok.token) - - return next.HandleFinalize(ctx, input) -} - -// HandleDeserialize is the deserialize stack middleware for determining if the -// operation the token provider is decorating failed because of a 401 -// unauthorized status code. If the operation failed for that reason the token -// provider needs to be re-enabled so that it can start adding the API token to -// operation calls. -func (t *tokenProvider) HandleDeserialize( - ctx context.Context, input middleware.DeserializeInput, next middleware.DeserializeHandler, -) ( - out middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err = next.HandleDeserialize(ctx, input) - if err == nil { - return out, metadata, err - } - - resp, ok := out.RawResponse.(*smithyhttp.Response) - if !ok { - return out, metadata, fmt.Errorf("expect HTTP transport, got %T", out.RawResponse) - } - - if resp.StatusCode == http.StatusUnauthorized { // unauthorized - t.enable() - err = &retryableError{Err: err, isRetryable: true} - } - - return out, metadata, err -} - -func (t *tokenProvider) getToken(ctx context.Context) (tok *apiToken, err error) { - if t.fallbackEnabled() && !t.enabled() { - return nil, &bypassTokenRetrievalError{ - Err: fmt.Errorf("cannot get API token, provider disabled"), - } - } - - t.tokenMux.RLock() - tok = t.token - t.tokenMux.RUnlock() - - if tok != nil && !tok.Expired() { - return tok, nil - } - - tok, err = t.updateToken(ctx) - if err != nil { - return nil, err - } - - return tok, nil -} - -func (t *tokenProvider) updateToken(ctx context.Context) (*apiToken, error) { - t.tokenMux.Lock() - defer t.tokenMux.Unlock() - - // Prevent multiple requests to update retrieving the token. - if t.token != nil && !t.token.Expired() { - tok := t.token - return tok, nil - } - - result, err := t.client.getToken(ctx, &getTokenInput{ - TokenTTL: t.tokenTTL, - }) - if err != nil { - var statusErr interface{ HTTPStatusCode() int } - if errors.As(err, &statusErr) { - switch statusErr.HTTPStatusCode() { - // Disable future get token if failed because of 403, 404, or 405 - case http.StatusForbidden, - http.StatusNotFound, - http.StatusMethodNotAllowed: - - if t.fallbackEnabled() { - logger := middleware.GetLogger(ctx) - logger.Logf(logging.Warn, "falling back to IMDSv1: %v", err) - t.disable() - } - - // 400 errors are terminal, and need to be upstreamed - case http.StatusBadRequest: - return nil, err - } - } - - // Disable if request send failed or timed out getting response - var re *smithyhttp.RequestSendError - var ce *smithy.CanceledError - if errors.As(err, &re) || errors.As(err, &ce) { - atomic.StoreUint32(&t.disabled, 1) - } - - if !t.fallbackEnabled() { - // NOTE: getToken() is an implementation detail of some outer operation - // (e.g. GetMetadata). It has its own retries that have already been exhausted. - // Mark the underlying error as a terminal error. - err = &retryableError{Err: err, isRetryable: false} - return nil, err - } - - // Token couldn't be retrieved, fallback to IMDSv1 insecure flow for this request - // and allow the request to proceed. Future requests _may_ re-attempt fetching a - // token if not disabled. - return nil, &bypassTokenRetrievalError{Err: err} - } - - tok := &apiToken{ - token: result.Token, - expires: timeNow().Add(result.TokenTTL), - } - t.token = tok - - return tok, nil -} - -// enabled returns if the token provider is current enabled or not. -func (t *tokenProvider) enabled() bool { - return atomic.LoadUint32(&t.disabled) == 0 -} - -// fallbackEnabled returns false if EnableFallback is [aws.FalseTernary], true otherwise -func (t *tokenProvider) fallbackEnabled() bool { - switch t.client.options.EnableFallback { - case aws.FalseTernary: - return false - default: - return true - } -} - -// disable disables the token provider and it will no longer attempt to inject -// the token, nor request updates. -func (t *tokenProvider) disable() { - atomic.StoreUint32(&t.disabled, 1) -} - -// enable enables the token provide to start refreshing tokens, and adding them -// to the pending request. -func (t *tokenProvider) enable() { - t.tokenMux.Lock() - t.token = nil - t.tokenMux.Unlock() - atomic.StoreUint32(&t.disabled, 0) -} - -type bypassTokenRetrievalError struct { - Err error -} - -func (e *bypassTokenRetrievalError) Error() string { - return fmt.Sprintf("bypass token retrieval, %v", e.Err) -} - -func (e *bypassTokenRetrievalError) Unwrap() error { return e.Err } - -type retryableError struct { - Err error - isRetryable bool -} - -func (e *retryableError) RetryableError() bool { return e.isRetryable } - -func (e *retryableError) Error() string { return e.Err.Error() } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/auth/scheme.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/auth/scheme.go deleted file mode 100644 index ff229c048..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/auth/scheme.go +++ /dev/null @@ -1,186 +0,0 @@ -package auth - -import ( - "context" - "fmt" - - smithy "github.com/aws/smithy-go" - "github.com/aws/smithy-go/middleware" -) - -// SigV4 is a constant representing -// Authentication Scheme Signature Version 4 -const SigV4 = "sigv4" - -// SigV4A is a constant representing -// Authentication Scheme Signature Version 4A -const SigV4A = "sigv4a" - -// None is a constant representing the -// None Authentication Scheme -const None = "none" - -// SupportedSchemes is a data structure -// that indicates the list of supported AWS -// authentication schemes -var SupportedSchemes = map[string]bool{ - SigV4: true, - SigV4A: true, - None: true, -} - -// AuthenticationScheme is a representation of -// AWS authentication schemes -type AuthenticationScheme interface { - isAuthenticationScheme() -} - -// AuthenticationSchemeV4 is a AWS SigV4 representation -type AuthenticationSchemeV4 struct { - Name string - SigningName *string - SigningRegion *string - DisableDoubleEncoding *bool -} - -func (a *AuthenticationSchemeV4) isAuthenticationScheme() {} - -// AuthenticationSchemeV4A is a AWS SigV4A representation -type AuthenticationSchemeV4A struct { - Name string - SigningName *string - SigningRegionSet []string - DisableDoubleEncoding *bool -} - -func (a *AuthenticationSchemeV4A) isAuthenticationScheme() {} - -// AuthenticationSchemeNone is a representation for the none auth scheme -type AuthenticationSchemeNone struct{} - -func (a *AuthenticationSchemeNone) isAuthenticationScheme() {} - -// NoAuthenticationSchemesFoundError is used in signaling -// that no authentication schemes have been specified. -type NoAuthenticationSchemesFoundError struct{} - -func (e *NoAuthenticationSchemesFoundError) Error() string { - return fmt.Sprint("No authentication schemes specified.") -} - -// UnSupportedAuthenticationSchemeSpecifiedError is used in -// signaling that only unsupported authentication schemes -// were specified. -type UnSupportedAuthenticationSchemeSpecifiedError struct { - UnsupportedSchemes []string -} - -func (e *UnSupportedAuthenticationSchemeSpecifiedError) Error() string { - return fmt.Sprint("Unsupported authentication scheme specified.") -} - -// GetAuthenticationSchemes extracts the relevant authentication scheme data -// into a custom strongly typed Go data structure. -func GetAuthenticationSchemes(p *smithy.Properties) ([]AuthenticationScheme, error) { - var result []AuthenticationScheme - if !p.Has("authSchemes") { - return nil, &NoAuthenticationSchemesFoundError{} - } - - authSchemes, _ := p.Get("authSchemes").([]interface{}) - - var unsupportedSchemes []string - for _, scheme := range authSchemes { - authScheme, _ := scheme.(map[string]interface{}) - - switch authScheme["name"] { - case SigV4: - v4Scheme := AuthenticationSchemeV4{ - Name: SigV4, - SigningName: getSigningName(authScheme), - SigningRegion: getSigningRegion(authScheme), - DisableDoubleEncoding: getDisableDoubleEncoding(authScheme), - } - result = append(result, AuthenticationScheme(&v4Scheme)) - case SigV4A: - v4aScheme := AuthenticationSchemeV4A{ - Name: SigV4A, - SigningName: getSigningName(authScheme), - SigningRegionSet: getSigningRegionSet(authScheme), - DisableDoubleEncoding: getDisableDoubleEncoding(authScheme), - } - result = append(result, AuthenticationScheme(&v4aScheme)) - case None: - noneScheme := AuthenticationSchemeNone{} - result = append(result, AuthenticationScheme(&noneScheme)) - default: - unsupportedSchemes = append(unsupportedSchemes, authScheme["name"].(string)) - continue - } - } - - if len(result) == 0 { - return nil, &UnSupportedAuthenticationSchemeSpecifiedError{ - UnsupportedSchemes: unsupportedSchemes, - } - } - - return result, nil -} - -type disableDoubleEncoding struct{} - -// SetDisableDoubleEncoding sets or modifies the disable double encoding option -// on the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func SetDisableDoubleEncoding(ctx context.Context, value bool) context.Context { - return middleware.WithStackValue(ctx, disableDoubleEncoding{}, value) -} - -// GetDisableDoubleEncoding retrieves the disable double encoding option -// from the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func GetDisableDoubleEncoding(ctx context.Context) (value bool, ok bool) { - value, ok = middleware.GetStackValue(ctx, disableDoubleEncoding{}).(bool) - return value, ok -} - -func getSigningName(authScheme map[string]interface{}) *string { - signingName, ok := authScheme["signingName"].(string) - if !ok || signingName == "" { - return nil - } - return &signingName -} - -func getSigningRegionSet(authScheme map[string]interface{}) []string { - untypedSigningRegionSet, ok := authScheme["signingRegionSet"].([]interface{}) - if !ok { - return nil - } - signingRegionSet := []string{} - for _, item := range untypedSigningRegionSet { - signingRegionSet = append(signingRegionSet, item.(string)) - } - return signingRegionSet -} - -func getSigningRegion(authScheme map[string]interface{}) *string { - signingRegion, ok := authScheme["signingRegion"].(string) - if !ok || signingRegion == "" { - return nil - } - return &signingRegion -} - -func getDisableDoubleEncoding(authScheme map[string]interface{}) *bool { - disableDoubleEncoding, ok := authScheme["disableDoubleEncoding"].(bool) - if !ok { - return nil - } - return &disableDoubleEncoding -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/CHANGELOG.md deleted file mode 100644 index 9826a85e6..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/CHANGELOG.md +++ /dev/null @@ -1,202 +0,0 @@ -# v1.1.41 (2023-08-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.40 (2023-08-18) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.39 (2023-08-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.38 (2023-08-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.37 (2023-07-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.36 (2023-07-28) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.35 (2023-07-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.34 (2023-06-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.33 (2023-04-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.32 (2023-04-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.31 (2023-03-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.30 (2023-03-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.29 (2023-02-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.28 (2023-02-03) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.27 (2022-12-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.26 (2022-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.25 (2022-10-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.24 (2022-10-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.23 (2022-09-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.22 (2022-09-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.21 (2022-09-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.20 (2022-08-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.19 (2022-08-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.18 (2022-08-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.17 (2022-08-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.16 (2022-08-08) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.15 (2022-08-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.14 (2022-07-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.13 (2022-06-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.12 (2022-06-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.11 (2022-05-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.10 (2022-04-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.9 (2022-03-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.8 (2022-03-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.7 (2022-03-23) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.6 (2022-03-08) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.5 (2022-02-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.4 (2022-01-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.3 (2022-01-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.2 (2021-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.1 (2021-11-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.0 (2021-11-06) - -* **Feature**: The SDK now supports configuration of FIPS and DualStack endpoints using environment variables, shared configuration, or programmatically. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.0.7 (2021-10-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.0.6 (2021-10-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.0.5 (2021-09-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.0.4 (2021-08-27) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.0.3 (2021-08-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.0.2 (2021-08-04) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.0.1 (2021-07-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.0.0 (2021-06-25) - -* **Release**: Release new modules -* **Dependency Update**: Updated to the latest SDK module versions - diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/LICENSE.txt deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/LICENSE.txt +++ /dev/null @@ -1,202 +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/aws/aws-sdk-go-v2/internal/configsources/config.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/config.go deleted file mode 100644 index cd4d19b89..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/config.go +++ /dev/null @@ -1,65 +0,0 @@ -package configsources - -import ( - "context" - "github.com/aws/aws-sdk-go-v2/aws" -) - -// EnableEndpointDiscoveryProvider is an interface for retrieving external configuration value -// for Enable Endpoint Discovery -type EnableEndpointDiscoveryProvider interface { - GetEnableEndpointDiscovery(ctx context.Context) (value aws.EndpointDiscoveryEnableState, found bool, err error) -} - -// ResolveEnableEndpointDiscovery extracts the first instance of a EnableEndpointDiscoveryProvider from the config slice. -// Additionally returns a aws.EndpointDiscoveryEnableState to indicate if the value was found in provided configs, -// and error if one is encountered. -func ResolveEnableEndpointDiscovery(ctx context.Context, configs []interface{}) (value aws.EndpointDiscoveryEnableState, found bool, err error) { - for _, cfg := range configs { - if p, ok := cfg.(EnableEndpointDiscoveryProvider); ok { - value, found, err = p.GetEnableEndpointDiscovery(ctx) - if err != nil || found { - break - } - } - } - return -} - -// UseDualStackEndpointProvider is an interface for retrieving external configuration values for UseDualStackEndpoint -type UseDualStackEndpointProvider interface { - GetUseDualStackEndpoint(context.Context) (value aws.DualStackEndpointState, found bool, err error) -} - -// ResolveUseDualStackEndpoint extracts the first instance of a UseDualStackEndpoint from the config slice. -// Additionally returns a boolean to indicate if the value was found in provided configs, and error if one is encountered. -func ResolveUseDualStackEndpoint(ctx context.Context, configs []interface{}) (value aws.DualStackEndpointState, found bool, err error) { - for _, cfg := range configs { - if p, ok := cfg.(UseDualStackEndpointProvider); ok { - value, found, err = p.GetUseDualStackEndpoint(ctx) - if err != nil || found { - break - } - } - } - return -} - -// UseFIPSEndpointProvider is an interface for retrieving external configuration values for UseFIPSEndpoint -type UseFIPSEndpointProvider interface { - GetUseFIPSEndpoint(context.Context) (value aws.FIPSEndpointState, found bool, err error) -} - -// ResolveUseFIPSEndpoint extracts the first instance of a UseFIPSEndpointProvider from the config slice. -// Additionally, returns a boolean to indicate if the value was found in provided configs, and error if one is encountered. -func ResolveUseFIPSEndpoint(ctx context.Context, configs []interface{}) (value aws.FIPSEndpointState, found bool, err error) { - for _, cfg := range configs { - if p, ok := cfg.(UseFIPSEndpointProvider); ok { - value, found, err = p.GetUseFIPSEndpoint(ctx) - if err != nil || found { - break - } - } - } - return -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/go_module_metadata.go deleted file mode 100644 index c7eec1c13..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/go_module_metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. - -package configsources - -// goModuleVersion is the tagged release for this module -const goModuleVersion = "1.1.41" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/arn.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/arn.go deleted file mode 100644 index e6223dd3b..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/arn.go +++ /dev/null @@ -1,94 +0,0 @@ -package awsrulesfn - -import ( - "strings" -) - -// ARN provides AWS ARN components broken out into a data structure. -type ARN struct { - Partition string - Service string - Region string - AccountId string - ResourceId OptionalStringSlice -} - -const ( - arnDelimiters = ":" - resourceDelimiters = "/:" - arnSections = 6 - arnPrefix = "arn:" - - // zero-indexed - sectionPartition = 1 - sectionService = 2 - sectionRegion = 3 - sectionAccountID = 4 - sectionResource = 5 -) - -// ParseARN returns an [ARN] value parsed from the input string provided. If -// the ARN cannot be parsed nil will be returned, and error added to -// [ErrorCollector]. -func ParseARN(input string) *ARN { - if !strings.HasPrefix(input, arnPrefix) { - return nil - } - - sections := strings.SplitN(input, arnDelimiters, arnSections) - if numSections := len(sections); numSections != arnSections { - return nil - } - - if sections[sectionPartition] == "" { - return nil - } - if sections[sectionService] == "" { - return nil - } - if sections[sectionResource] == "" { - return nil - } - - return &ARN{ - Partition: sections[sectionPartition], - Service: sections[sectionService], - Region: sections[sectionRegion], - AccountId: sections[sectionAccountID], - ResourceId: splitResource(sections[sectionResource]), - } -} - -// splitResource splits the resource components by the ARN resource delimiters. -func splitResource(v string) []string { - var parts []string - var offset int - - for offset <= len(v) { - idx := strings.IndexAny(v[offset:], "/:") - if idx < 0 { - parts = append(parts, v[offset:]) - break - } - parts = append(parts, v[offset:idx+offset]) - offset += idx + 1 - } - - return parts -} - -// OptionalStringSlice provides a helper to safely get the index of a string -// slice that may be out of bounds. Returns pointer to string if index is -// valid. Otherwise returns nil. -type OptionalStringSlice []string - -// Get returns a string pointer of the string at index i if the index is valid. -// Otherwise returns nil. -func (s OptionalStringSlice) Get(i int) *string { - if i < 0 || i >= len(s) { - return nil - } - - v := s[i] - return &v -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/doc.go deleted file mode 100644 index d5a365853..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package awsrulesfn provides AWS focused endpoint rule functions for -// evaluating endpoint resolution rules. -package awsrulesfn diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/generate.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/generate.go deleted file mode 100644 index df72da97c..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/generate.go +++ /dev/null @@ -1,7 +0,0 @@ -//go:build codegen -// +build codegen - -package awsrulesfn - -//go:generate go run -tags codegen ./internal/partition/codegen.go -model partitions.json -output partitions.go -//go:generate gofmt -w -s . diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/host.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/host.go deleted file mode 100644 index 637e5fc18..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/host.go +++ /dev/null @@ -1,51 +0,0 @@ -package awsrulesfn - -import ( - "net" - "strings" - - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// IsVirtualHostableS3Bucket returns if the input is a DNS compatible bucket -// name and can be used with Amazon S3 virtual hosted style addressing. Similar -// to [rulesfn.IsValidHostLabel] with the added restriction that the length of label -// must be [3:63] characters long, all lowercase, and not formatted as an IP -// address. -func IsVirtualHostableS3Bucket(input string, allowSubDomains bool) bool { - // input should not be formatted as an IP address - // NOTE: this will technically trip up on IPv6 hosts with zone IDs, but - // validation further down will catch that anyway (it's guaranteed to have - // unfriendly characters % and : if that's the case) - if net.ParseIP(input) != nil { - return false - } - - var labels []string - if allowSubDomains { - labels = strings.Split(input, ".") - } else { - labels = []string{input} - } - - for _, label := range labels { - // validate special length constraints - if l := len(label); l < 3 || l > 63 { - return false - } - - // Validate no capital letters - for _, r := range label { - if r >= 'A' && r <= 'Z' { - return false - } - } - - // Validate valid host label - if !smithyhttp.ValidHostLabel(label) { - return false - } - } - - return true -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partition.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partition.go deleted file mode 100644 index ba6032758..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partition.go +++ /dev/null @@ -1,75 +0,0 @@ -package awsrulesfn - -import "regexp" - -// Partition provides the metadata describing an AWS partition. -type Partition struct { - ID string `json:"id"` - Regions map[string]RegionOverrides `json:"regions"` - RegionRegex string `json:"regionRegex"` - DefaultConfig PartitionConfig `json:"outputs"` -} - -// PartitionConfig provides the endpoint metadata for an AWS region or partition. -type PartitionConfig struct { - Name string `json:"name"` - DnsSuffix string `json:"dnsSuffix"` - DualStackDnsSuffix string `json:"dualStackDnsSuffix"` - SupportsFIPS bool `json:"supportsFIPS"` - SupportsDualStack bool `json:"supportsDualStack"` -} - -type RegionOverrides struct { - Name *string `json:"name"` - DnsSuffix *string `json:"dnsSuffix"` - DualStackDnsSuffix *string `json:"dualStackDnsSuffix"` - SupportsFIPS *bool `json:"supportsFIPS"` - SupportsDualStack *bool `json:"supportsDualStack"` -} - -const defaultPartition = "aws" - -func getPartition(partitions []Partition, region string) *PartitionConfig { - for _, partition := range partitions { - if v, ok := partition.Regions[region]; ok { - p := mergeOverrides(partition.DefaultConfig, v) - return &p - } - } - - for _, partition := range partitions { - regionRegex := regexp.MustCompile(partition.RegionRegex) - if regionRegex.MatchString(region) { - v := partition.DefaultConfig - return &v - } - } - - for _, partition := range partitions { - if partition.ID == defaultPartition { - v := partition.DefaultConfig - return &v - } - } - - return nil -} - -func mergeOverrides(into PartitionConfig, from RegionOverrides) PartitionConfig { - if from.Name != nil { - into.Name = *from.Name - } - if from.DnsSuffix != nil { - into.DnsSuffix = *from.DnsSuffix - } - if from.DualStackDnsSuffix != nil { - into.DualStackDnsSuffix = *from.DualStackDnsSuffix - } - if from.SupportsFIPS != nil { - into.SupportsFIPS = *from.SupportsFIPS - } - if from.SupportsDualStack != nil { - into.SupportsDualStack = *from.SupportsDualStack - } - return into -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partitions.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partitions.go deleted file mode 100644 index 7ea49d4ea..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partitions.go +++ /dev/null @@ -1,343 +0,0 @@ -// Code generated by endpoint/awsrulesfn/internal/partition. DO NOT EDIT. - -package awsrulesfn - -// GetPartition returns an AWS [Partition] for the region provided. If the -// partition cannot be determined nil will be returned. -func GetPartition(region string) *PartitionConfig { - return getPartition(partitions, region) -} - -var partitions = []Partition{ - { - ID: "aws", - RegionRegex: "^(us|eu|ap|sa|ca|me|af)\\-\\w+\\-\\d+$", - DefaultConfig: PartitionConfig{ - Name: "aws", - DnsSuffix: "amazonaws.com", - DualStackDnsSuffix: "api.aws", - SupportsFIPS: true, - SupportsDualStack: true, - }, - Regions: map[string]RegionOverrides{ - "af-south-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "ap-east-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "ap-northeast-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "ap-northeast-2": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "ap-northeast-3": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "ap-south-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "ap-south-2": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "ap-southeast-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "ap-southeast-2": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "ap-southeast-3": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "aws-global": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "ca-central-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "eu-central-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "eu-central-2": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "eu-north-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "eu-south-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "eu-south-2": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "eu-west-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "eu-west-2": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "eu-west-3": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "me-central-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "me-south-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "sa-east-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "us-east-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "us-east-2": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "us-west-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "us-west-2": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - }, - }, - { - ID: "aws-cn", - RegionRegex: "^cn\\-\\w+\\-\\d+$", - DefaultConfig: PartitionConfig{ - Name: "aws-cn", - DnsSuffix: "amazonaws.com.cn", - DualStackDnsSuffix: "api.amazonwebservices.com.cn", - SupportsFIPS: true, - SupportsDualStack: true, - }, - Regions: map[string]RegionOverrides{ - "aws-cn-global": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "cn-north-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "cn-northwest-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - }, - }, - { - ID: "aws-us-gov", - RegionRegex: "^us\\-gov\\-\\w+\\-\\d+$", - DefaultConfig: PartitionConfig{ - Name: "aws-us-gov", - DnsSuffix: "amazonaws.com", - DualStackDnsSuffix: "api.aws", - SupportsFIPS: true, - SupportsDualStack: true, - }, - Regions: map[string]RegionOverrides{ - "aws-us-gov-global": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "us-gov-east-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "us-gov-west-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - }, - }, - { - ID: "aws-iso", - RegionRegex: "^us\\-iso\\-\\w+\\-\\d+$", - DefaultConfig: PartitionConfig{ - Name: "aws-iso", - DnsSuffix: "c2s.ic.gov", - DualStackDnsSuffix: "c2s.ic.gov", - SupportsFIPS: true, - SupportsDualStack: false, - }, - Regions: map[string]RegionOverrides{ - "aws-iso-global": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "us-iso-east-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "us-iso-west-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - }, - }, - { - ID: "aws-iso-b", - RegionRegex: "^us\\-isob\\-\\w+\\-\\d+$", - DefaultConfig: PartitionConfig{ - Name: "aws-iso-b", - DnsSuffix: "sc2s.sgov.gov", - DualStackDnsSuffix: "sc2s.sgov.gov", - SupportsFIPS: true, - SupportsDualStack: false, - }, - Regions: map[string]RegionOverrides{ - "aws-iso-b-global": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "us-isob-east-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - }, - }, -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partitions.json b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partitions.json deleted file mode 100644 index 4e0c6f123..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partitions.json +++ /dev/null @@ -1,206 +0,0 @@ -{ - "partitions" : [ { - "id" : "aws", - "outputs" : { - "dnsSuffix" : "amazonaws.com", - "dualStackDnsSuffix" : "api.aws", - "name" : "aws", - "supportsDualStack" : true, - "supportsFIPS" : true - }, - "regionRegex" : "^(us|eu|ap|sa|ca|me|af|il)\\-\\w+\\-\\d+$", - "regions" : { - "af-south-1" : { - "description" : "Africa (Cape Town)" - }, - "ap-east-1" : { - "description" : "Asia Pacific (Hong Kong)" - }, - "ap-northeast-1" : { - "description" : "Asia Pacific (Tokyo)" - }, - "ap-northeast-2" : { - "description" : "Asia Pacific (Seoul)" - }, - "ap-northeast-3" : { - "description" : "Asia Pacific (Osaka)" - }, - "ap-south-1" : { - "description" : "Asia Pacific (Mumbai)" - }, - "ap-south-2" : { - "description" : "Asia Pacific (Hyderabad)" - }, - "ap-southeast-1" : { - "description" : "Asia Pacific (Singapore)" - }, - "ap-southeast-2" : { - "description" : "Asia Pacific (Sydney)" - }, - "ap-southeast-3" : { - "description" : "Asia Pacific (Jakarta)" - }, - "ap-southeast-4" : { - "description" : "Asia Pacific (Melbourne)" - }, - "aws-global" : { - "description" : "AWS Standard global region" - }, - "ca-central-1" : { - "description" : "Canada (Central)" - }, - "eu-central-1" : { - "description" : "Europe (Frankfurt)" - }, - "eu-central-2" : { - "description" : "Europe (Zurich)" - }, - "eu-north-1" : { - "description" : "Europe (Stockholm)" - }, - "eu-south-1" : { - "description" : "Europe (Milan)" - }, - "eu-south-2" : { - "description" : "Europe (Spain)" - }, - "eu-west-1" : { - "description" : "Europe (Ireland)" - }, - "eu-west-2" : { - "description" : "Europe (London)" - }, - "eu-west-3" : { - "description" : "Europe (Paris)" - }, - "il-central-1" : { - "description" : "Israel (Tel Aviv)" - }, - "me-central-1" : { - "description" : "Middle East (UAE)" - }, - "me-south-1" : { - "description" : "Middle East (Bahrain)" - }, - "sa-east-1" : { - "description" : "South America (Sao Paulo)" - }, - "us-east-1" : { - "description" : "US East (N. Virginia)" - }, - "us-east-2" : { - "description" : "US East (Ohio)" - }, - "us-west-1" : { - "description" : "US West (N. California)" - }, - "us-west-2" : { - "description" : "US West (Oregon)" - } - } - }, { - "id" : "aws-cn", - "outputs" : { - "dnsSuffix" : "amazonaws.com.cn", - "dualStackDnsSuffix" : "api.amazonwebservices.com.cn", - "name" : "aws-cn", - "supportsDualStack" : true, - "supportsFIPS" : true - }, - "regionRegex" : "^cn\\-\\w+\\-\\d+$", - "regions" : { - "aws-cn-global" : { - "description" : "AWS China global region" - }, - "cn-north-1" : { - "description" : "China (Beijing)" - }, - "cn-northwest-1" : { - "description" : "China (Ningxia)" - } - } - }, { - "id" : "aws-us-gov", - "outputs" : { - "dnsSuffix" : "amazonaws.com", - "dualStackDnsSuffix" : "api.aws", - "name" : "aws-us-gov", - "supportsDualStack" : true, - "supportsFIPS" : true - }, - "regionRegex" : "^us\\-gov\\-\\w+\\-\\d+$", - "regions" : { - "aws-us-gov-global" : { - "description" : "AWS GovCloud (US) global region" - }, - "us-gov-east-1" : { - "description" : "AWS GovCloud (US-East)" - }, - "us-gov-west-1" : { - "description" : "AWS GovCloud (US-West)" - } - } - }, { - "id" : "aws-iso", - "outputs" : { - "dnsSuffix" : "c2s.ic.gov", - "dualStackDnsSuffix" : "c2s.ic.gov", - "name" : "aws-iso", - "supportsDualStack" : false, - "supportsFIPS" : true - }, - "regionRegex" : "^us\\-iso\\-\\w+\\-\\d+$", - "regions" : { - "aws-iso-global" : { - "description" : "AWS ISO (US) global region" - }, - "us-iso-east-1" : { - "description" : "US ISO East" - }, - "us-iso-west-1" : { - "description" : "US ISO WEST" - } - } - }, { - "id" : "aws-iso-b", - "outputs" : { - "dnsSuffix" : "sc2s.sgov.gov", - "dualStackDnsSuffix" : "sc2s.sgov.gov", - "name" : "aws-iso-b", - "supportsDualStack" : false, - "supportsFIPS" : true - }, - "regionRegex" : "^us\\-isob\\-\\w+\\-\\d+$", - "regions" : { - "aws-iso-b-global" : { - "description" : "AWS ISOB (US) global region" - }, - "us-isob-east-1" : { - "description" : "US ISOB East (Ohio)" - } - } - }, { - "id" : "aws-iso-e", - "outputs" : { - "dnsSuffix" : "cloud.adc-e.uk", - "dualStackDnsSuffix" : "cloud.adc-e.uk", - "name" : "aws-iso-e", - "supportsDualStack" : false, - "supportsFIPS" : true - }, - "regionRegex" : "^eu\\-isoe\\-\\w+\\-\\d+$", - "regions" : { } - }, { - "id" : "aws-iso-f", - "outputs" : { - "dnsSuffix" : "csp.hci.ic.gov", - "dualStackDnsSuffix" : "csp.hci.ic.gov", - "name" : "aws-iso-f", - "supportsDualStack" : false, - "supportsFIPS" : true - }, - "regionRegex" : "^us\\-isof\\-\\w+\\-\\d+$", - "regions" : { } - } ], - "version" : "1.1" -} \ No newline at end of file diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/CHANGELOG.md deleted file mode 100644 index a470e22de..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/CHANGELOG.md +++ /dev/null @@ -1,175 +0,0 @@ -# v2.4.35 (2023-08-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.34 (2023-08-18) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.33 (2023-08-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.32 (2023-08-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.31 (2023-07-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.30 (2023-07-28) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.29 (2023-07-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.28 (2023-06-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.27 (2023-04-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.26 (2023-04-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.25 (2023-03-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.24 (2023-03-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.23 (2023-02-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.22 (2023-02-03) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.21 (2022-12-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.20 (2022-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.19 (2022-10-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.18 (2022-10-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.17 (2022-09-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.16 (2022-09-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.15 (2022-09-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.14 (2022-08-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.13 (2022-08-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.12 (2022-08-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.11 (2022-08-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.10 (2022-08-08) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.9 (2022-08-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.8 (2022-07-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.7 (2022-06-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.6 (2022-06-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.5 (2022-05-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.4 (2022-04-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.3 (2022-03-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.2 (2022-03-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.1 (2022-03-23) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.0 (2022-03-08) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.3.0 (2022-02-24) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.2.0 (2022-01-14) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.1.0 (2022-01-07) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.0.2 (2021-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.0.1 (2021-11-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.0.0 (2021-11-06) - -* **Release**: Endpoint Variant Model Support -* **Feature**: The SDK now supports configuration of FIPS and DualStack endpoints using environment variables, shared configuration, or programmatically. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/LICENSE.txt deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/LICENSE.txt +++ /dev/null @@ -1,202 +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/aws/aws-sdk-go-v2/internal/endpoints/v2/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/endpoints.go deleted file mode 100644 index 32251a7e3..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/endpoints.go +++ /dev/null @@ -1,302 +0,0 @@ -package endpoints - -import ( - "fmt" - "github.com/aws/smithy-go/logging" - "regexp" - "strings" - - "github.com/aws/aws-sdk-go-v2/aws" -) - -// DefaultKey is a compound map key of a variant and other values. -type DefaultKey struct { - Variant EndpointVariant - ServiceVariant ServiceVariant -} - -// EndpointKey is a compound map key of a region and associated variant value. -type EndpointKey struct { - Region string - Variant EndpointVariant - ServiceVariant ServiceVariant -} - -// EndpointVariant is a bit field to describe the endpoints attributes. -type EndpointVariant uint64 - -const ( - // FIPSVariant indicates that the endpoint is FIPS capable. - FIPSVariant EndpointVariant = 1 << (64 - 1 - iota) - - // DualStackVariant indicates that the endpoint is DualStack capable. - DualStackVariant -) - -// ServiceVariant is a bit field to describe the service endpoint attributes. -type ServiceVariant uint64 - -const ( - defaultProtocol = "https" - defaultSigner = "v4" -) - -var ( - protocolPriority = []string{"https", "http"} - signerPriority = []string{"v4", "s3v4"} -) - -// Options provide configuration needed to direct how endpoints are resolved. -type Options struct { - // Logger is a logging implementation that log events should be sent to. - Logger logging.Logger - - // LogDeprecated indicates that deprecated endpoints should be logged to the provided logger. - LogDeprecated bool - - // ResolvedRegion is the resolved region string. If provided (non-zero length) it takes priority - // over the region name passed to the ResolveEndpoint call. - ResolvedRegion string - - // Disable usage of HTTPS (TLS / SSL) - DisableHTTPS bool - - // Instruct the resolver to use a service endpoint that supports dual-stack. - // If a service does not have a dual-stack endpoint an error will be returned by the resolver. - UseDualStackEndpoint aws.DualStackEndpointState - - // Instruct the resolver to use a service endpoint that supports FIPS. - // If a service does not have a FIPS endpoint an error will be returned by the resolver. - UseFIPSEndpoint aws.FIPSEndpointState - - // ServiceVariant is a bitfield of service specified endpoint variant data. - ServiceVariant ServiceVariant -} - -// GetEndpointVariant returns the EndpointVariant for the variant associated options. -func (o Options) GetEndpointVariant() (v EndpointVariant) { - if o.UseDualStackEndpoint == aws.DualStackEndpointStateEnabled { - v |= DualStackVariant - } - if o.UseFIPSEndpoint == aws.FIPSEndpointStateEnabled { - v |= FIPSVariant - } - return v -} - -// Partitions is a slice of partition -type Partitions []Partition - -// ResolveEndpoint resolves a service endpoint for the given region and options. -func (ps Partitions) ResolveEndpoint(region string, opts Options) (aws.Endpoint, error) { - if len(ps) == 0 { - return aws.Endpoint{}, fmt.Errorf("no partitions found") - } - - if opts.Logger == nil { - opts.Logger = logging.Nop{} - } - - if len(opts.ResolvedRegion) > 0 { - region = opts.ResolvedRegion - } - - for i := 0; i < len(ps); i++ { - if !ps[i].canResolveEndpoint(region, opts) { - continue - } - - return ps[i].ResolveEndpoint(region, opts) - } - - // fallback to first partition format to use when resolving the endpoint. - return ps[0].ResolveEndpoint(region, opts) -} - -// Partition is an AWS partition description for a service and its' region endpoints. -type Partition struct { - ID string - RegionRegex *regexp.Regexp - PartitionEndpoint string - IsRegionalized bool - Defaults map[DefaultKey]Endpoint - Endpoints Endpoints -} - -func (p Partition) canResolveEndpoint(region string, opts Options) bool { - _, ok := p.Endpoints[EndpointKey{ - Region: region, - Variant: opts.GetEndpointVariant(), - }] - return ok || p.RegionRegex.MatchString(region) -} - -// ResolveEndpoint resolves and service endpoint for the given region and options. -func (p Partition) ResolveEndpoint(region string, options Options) (resolved aws.Endpoint, err error) { - if len(region) == 0 && len(p.PartitionEndpoint) != 0 { - region = p.PartitionEndpoint - } - - endpoints := p.Endpoints - - variant := options.GetEndpointVariant() - serviceVariant := options.ServiceVariant - - defaults := p.Defaults[DefaultKey{ - Variant: variant, - ServiceVariant: serviceVariant, - }] - - return p.endpointForRegion(region, variant, serviceVariant, endpoints).resolve(p.ID, region, defaults, options) -} - -func (p Partition) endpointForRegion(region string, variant EndpointVariant, serviceVariant ServiceVariant, endpoints Endpoints) Endpoint { - key := EndpointKey{ - Region: region, - Variant: variant, - } - - if e, ok := endpoints[key]; ok { - return e - } - - if !p.IsRegionalized { - return endpoints[EndpointKey{ - Region: p.PartitionEndpoint, - Variant: variant, - ServiceVariant: serviceVariant, - }] - } - - // Unable to find any matching endpoint, return - // blank that will be used for generic endpoint creation. - return Endpoint{} -} - -// Endpoints is a map of service config regions to endpoints -type Endpoints map[EndpointKey]Endpoint - -// CredentialScope is the credential scope of a region and service -type CredentialScope struct { - Region string - Service string -} - -// Endpoint is a service endpoint description -type Endpoint struct { - // True if the endpoint cannot be resolved for this partition/region/service - Unresolveable aws.Ternary - - Hostname string - Protocols []string - - CredentialScope CredentialScope - - SignatureVersions []string - - // Indicates that this endpoint is deprecated. - Deprecated aws.Ternary -} - -// IsZero returns whether the endpoint structure is an empty (zero) value. -func (e Endpoint) IsZero() bool { - switch { - case e.Unresolveable != aws.UnknownTernary: - return false - case len(e.Hostname) != 0: - return false - case len(e.Protocols) != 0: - return false - case e.CredentialScope != (CredentialScope{}): - return false - case len(e.SignatureVersions) != 0: - return false - } - return true -} - -func (e Endpoint) resolve(partition, region string, def Endpoint, options Options) (aws.Endpoint, error) { - var merged Endpoint - merged.mergeIn(def) - merged.mergeIn(e) - e = merged - - if e.IsZero() { - return aws.Endpoint{}, fmt.Errorf("unable to resolve endpoint for region: %v", region) - } - - var u string - if e.Unresolveable != aws.TrueTernary { - // Only attempt to resolve the endpoint if it can be resolved. - hostname := strings.Replace(e.Hostname, "{region}", region, 1) - - scheme := getEndpointScheme(e.Protocols, options.DisableHTTPS) - u = scheme + "://" + hostname - } - - signingRegion := e.CredentialScope.Region - if len(signingRegion) == 0 { - signingRegion = region - } - signingName := e.CredentialScope.Service - - if e.Deprecated == aws.TrueTernary && options.LogDeprecated { - options.Logger.Logf(logging.Warn, "endpoint identifier %q, url %q marked as deprecated", region, u) - } - - return aws.Endpoint{ - URL: u, - PartitionID: partition, - SigningRegion: signingRegion, - SigningName: signingName, - SigningMethod: getByPriority(e.SignatureVersions, signerPriority, defaultSigner), - }, nil -} - -func (e *Endpoint) mergeIn(other Endpoint) { - if other.Unresolveable != aws.UnknownTernary { - e.Unresolveable = other.Unresolveable - } - if len(other.Hostname) > 0 { - e.Hostname = other.Hostname - } - if len(other.Protocols) > 0 { - e.Protocols = other.Protocols - } - if len(other.CredentialScope.Region) > 0 { - e.CredentialScope.Region = other.CredentialScope.Region - } - if len(other.CredentialScope.Service) > 0 { - e.CredentialScope.Service = other.CredentialScope.Service - } - if len(other.SignatureVersions) > 0 { - e.SignatureVersions = other.SignatureVersions - } - if other.Deprecated != aws.UnknownTernary { - e.Deprecated = other.Deprecated - } -} - -func getEndpointScheme(protocols []string, disableHTTPS bool) string { - if disableHTTPS { - return "http" - } - - return getByPriority(protocols, protocolPriority, defaultProtocol) -} - -func getByPriority(s []string, p []string, def string) string { - if len(s) == 0 { - return def - } - - for i := 0; i < len(p); i++ { - for j := 0; j < len(s); j++ { - if s[j] == p[i] { - return s[j] - } - } - } - - return s[0] -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/go_module_metadata.go deleted file mode 100644 index ac28b313b..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/go_module_metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. - -package endpoints - -// goModuleVersion is the tagged release for this module -const goModuleVersion = "2.4.35" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/CHANGELOG.md deleted file mode 100644 index 74eff6a52..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/CHANGELOG.md +++ /dev/null @@ -1,216 +0,0 @@ -# v1.3.42 (2023-08-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.41 (2023-08-18) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.40 (2023-08-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.39 (2023-08-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.38 (2023-07-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.37 (2023-07-28) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.36 (2023-07-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.35 (2023-06-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.34 (2023-04-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.33 (2023-04-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.32 (2023-03-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.31 (2023-03-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.30 (2023-02-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.29 (2023-02-03) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.28 (2022-12-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.27 (2022-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.26 (2022-10-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.25 (2022-10-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.24 (2022-09-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.23 (2022-09-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.22 (2022-09-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.21 (2022-08-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.20 (2022-08-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.19 (2022-08-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.18 (2022-08-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.17 (2022-08-08) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.16 (2022-08-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.15 (2022-07-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.14 (2022-06-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.13 (2022-06-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.12 (2022-05-17) - -* **Bug Fix**: Removes the fuzz testing files from the module, as they are invalid and not used. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.11 (2022-04-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.10 (2022-03-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.9 (2022-03-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.8 (2022-03-23) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.7 (2022-03-08) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.6 (2022-02-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.5 (2022-01-28) - -* **Bug Fix**: Fixes the SDK's handling of `duration_sections` in the shared credentials file or specified in multiple shared config and shared credentials files under the same profile. [#1568](https://github.com/aws/aws-sdk-go-v2/pull/1568). Thanks to [Amir Szekely](https://github.com/kichik) for help reproduce this bug. - -# v1.3.4 (2022-01-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.3 (2022-01-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.2 (2021-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.1 (2021-11-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.0 (2021-11-06) - -* **Feature**: The SDK now supports configuration of FIPS and DualStack endpoints using environment variables, shared configuration, or programmatically. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.5 (2021-10-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.4 (2021-10-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.3 (2021-09-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.2 (2021-08-27) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.1 (2021-08-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.0 (2021-08-04) - -* **Feature**: adds error handling for defered close calls -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.1 (2021-07-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.0 (2021-07-01) - -* **Feature**: Support for `:`, `=`, `[`, `]` being present in expression values. - -# v1.0.1 (2021-06-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.0.0 (2021-05-20) - -* **Release**: The `github.com/aws/aws-sdk-go-v2/internal/ini` package is now a Go Module. -* **Dependency Update**: Updated to the latest SDK module versions - diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/LICENSE.txt deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/LICENSE.txt +++ /dev/null @@ -1,202 +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/aws/aws-sdk-go-v2/internal/ini/ast.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/ast.go deleted file mode 100644 index e83a99886..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/ast.go +++ /dev/null @@ -1,120 +0,0 @@ -package ini - -// ASTKind represents different states in the parse table -// and the type of AST that is being constructed -type ASTKind int - -// ASTKind* is used in the parse table to transition between -// the different states -const ( - ASTKindNone = ASTKind(iota) - ASTKindStart - ASTKindExpr - ASTKindEqualExpr - ASTKindStatement - ASTKindSkipStatement - ASTKindExprStatement - ASTKindSectionStatement - ASTKindNestedSectionStatement - ASTKindCompletedNestedSectionStatement - ASTKindCommentStatement - ASTKindCompletedSectionStatement -) - -func (k ASTKind) String() string { - switch k { - case ASTKindNone: - return "none" - case ASTKindStart: - return "start" - case ASTKindExpr: - return "expr" - case ASTKindStatement: - return "stmt" - case ASTKindSectionStatement: - return "section_stmt" - case ASTKindExprStatement: - return "expr_stmt" - case ASTKindCommentStatement: - return "comment" - case ASTKindNestedSectionStatement: - return "nested_section_stmt" - case ASTKindCompletedSectionStatement: - return "completed_stmt" - case ASTKindSkipStatement: - return "skip" - default: - return "" - } -} - -// AST interface allows us to determine what kind of node we -// are on and casting may not need to be necessary. -// -// The root is always the first node in Children -type AST struct { - Kind ASTKind - Root Token - RootToken bool - Children []AST -} - -func newAST(kind ASTKind, root AST, children ...AST) AST { - return AST{ - Kind: kind, - Children: append([]AST{root}, children...), - } -} - -func newASTWithRootToken(kind ASTKind, root Token, children ...AST) AST { - return AST{ - Kind: kind, - Root: root, - RootToken: true, - Children: children, - } -} - -// AppendChild will append to the list of children an AST has. -func (a *AST) AppendChild(child AST) { - a.Children = append(a.Children, child) -} - -// GetRoot will return the root AST which can be the first entry -// in the children list or a token. -func (a *AST) GetRoot() AST { - if a.RootToken { - return *a - } - - if len(a.Children) == 0 { - return AST{} - } - - return a.Children[0] -} - -// GetChildren will return the current AST's list of children -func (a *AST) GetChildren() []AST { - if len(a.Children) == 0 { - return []AST{} - } - - if a.RootToken { - return a.Children - } - - return a.Children[1:] -} - -// SetChildren will set and override all children of the AST. -func (a *AST) SetChildren(children []AST) { - if a.RootToken { - a.Children = children - } else { - a.Children = append(a.Children[:1], children...) - } -} - -// Start is used to indicate the starting state of the parse table. -var Start = newAST(ASTKindStart, AST{}) diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/comma_token.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/comma_token.go deleted file mode 100644 index 0895d53cb..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/comma_token.go +++ /dev/null @@ -1,11 +0,0 @@ -package ini - -var commaRunes = []rune(",") - -func isComma(b rune) bool { - return b == ',' -} - -func newCommaToken() Token { - return newToken(TokenComma, commaRunes, NoneType) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/comment_token.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/comment_token.go deleted file mode 100644 index 0b76999ba..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/comment_token.go +++ /dev/null @@ -1,35 +0,0 @@ -package ini - -// isComment will return whether or not the next byte(s) is a -// comment. -func isComment(b []rune) bool { - if len(b) == 0 { - return false - } - - switch b[0] { - case ';': - return true - case '#': - return true - } - - return false -} - -// newCommentToken will create a comment token and -// return how many bytes were read. -func newCommentToken(b []rune) (Token, int, error) { - i := 0 - for ; i < len(b); i++ { - if b[i] == '\n' { - break - } - - if len(b)-i > 2 && b[i] == '\r' && b[i+1] == '\n' { - break - } - } - - return newToken(TokenComment, b[:i], NoneType), i, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/dependency.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/dependency.go deleted file mode 100644 index f5ebe52e1..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/dependency.go +++ /dev/null @@ -1,6 +0,0 @@ -package ini - -import ( - // internal/ini module was carved out of this module - _ "github.com/aws/aws-sdk-go-v2" -) diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/doc.go deleted file mode 100644 index fdd5321b4..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/doc.go +++ /dev/null @@ -1,43 +0,0 @@ -// Package ini is an LL(1) parser for configuration files. -// -// Example: -// sections, err := ini.OpenFile("/path/to/file") -// if err != nil { -// panic(err) -// } -// -// profile := "foo" -// section, ok := sections.GetSection(profile) -// if !ok { -// fmt.Printf("section %q could not be found", profile) -// } -// -// Below is the BNF that describes this parser -// -// Grammar: -// stmt -> section | stmt' -// stmt' -> epsilon | expr -// expr -> value (stmt)* | equal_expr (stmt)* -// equal_expr -> value ( ':' | '=' ) equal_expr' -// equal_expr' -> number | string | quoted_string -// quoted_string -> " quoted_string' -// quoted_string' -> string quoted_string_end -// quoted_string_end -> " -// -// section -> [ section' -// section' -> section_value section_close -// section_value -> number | string_subset | boolean | quoted_string_subset -// quoted_string_subset -> " quoted_string_subset' -// quoted_string_subset' -> string_subset quoted_string_end -// quoted_string_subset -> " -// section_close -> ] -// -// value -> number | string_subset | boolean -// string -> ? UTF-8 Code-Points except '\n' (U+000A) and '\r\n' (U+000D U+000A) ? -// string_subset -> ? Code-points excepted by grammar except ':' (U+003A), '=' (U+003D), '[' (U+005B), and ']' (U+005D) ? -// -// SkipState will skip (NL WS)+ -// -// comment -> # comment' | ; comment' -// comment' -> epsilon | value -package ini diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/empty_token.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/empty_token.go deleted file mode 100644 index 04345a54c..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/empty_token.go +++ /dev/null @@ -1,4 +0,0 @@ -package ini - -// emptyToken is used to satisfy the Token interface -var emptyToken = newToken(TokenNone, []rune{}, NoneType) diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/errors.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/errors.go deleted file mode 100644 index 0f278d55e..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/errors.go +++ /dev/null @@ -1,22 +0,0 @@ -package ini - -import "fmt" - -// UnableToReadFile is an error indicating that a ini file could not be read -type UnableToReadFile struct { - Err error -} - -// Error returns an error message and the underlying error message if present -func (e *UnableToReadFile) Error() string { - base := "unable to read file" - if e.Err == nil { - return base - } - return fmt.Sprintf("%s: %v", base, e.Err) -} - -// Unwrap returns the underlying error -func (e *UnableToReadFile) Unwrap() error { - return e.Err -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/expression.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/expression.go deleted file mode 100644 index 91ba2a59d..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/expression.go +++ /dev/null @@ -1,24 +0,0 @@ -package ini - -// newExpression will return an expression AST. -// Expr represents an expression -// -// grammar: -// expr -> string | number -func newExpression(tok Token) AST { - return newASTWithRootToken(ASTKindExpr, tok) -} - -func newEqualExpr(left AST, tok Token) AST { - return newASTWithRootToken(ASTKindEqualExpr, tok, left) -} - -// EqualExprKey will return a LHS value in the equal expr -func EqualExprKey(ast AST) string { - children := ast.GetChildren() - if len(children) == 0 || ast.Kind != ASTKindEqualExpr { - return "" - } - - return string(children[0].Root.Raw()) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/go_module_metadata.go deleted file mode 100644 index 709294b9e..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/go_module_metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. - -package ini - -// goModuleVersion is the tagged release for this module -const goModuleVersion = "1.3.42" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/ini.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/ini.go deleted file mode 100644 index f74062313..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/ini.go +++ /dev/null @@ -1,58 +0,0 @@ -package ini - -import ( - "fmt" - "io" - "os" -) - -// OpenFile takes a path to a given file, and will open and parse -// that file. -func OpenFile(path string) (sections Sections, err error) { - f, oerr := os.Open(path) - if oerr != nil { - return Sections{}, &UnableToReadFile{Err: oerr} - } - - defer func() { - closeErr := f.Close() - if err == nil { - err = closeErr - } else if closeErr != nil { - err = fmt.Errorf("close error: %v, original error: %w", closeErr, err) - } - }() - - return Parse(f, path) -} - -// Parse will parse the given file using the shared config -// visitor. -func Parse(f io.Reader, path string) (Sections, error) { - tree, err := ParseAST(f) - if err != nil { - return Sections{}, err - } - - v := NewDefaultVisitor(path) - if err = Walk(tree, v); err != nil { - return Sections{}, err - } - - return v.Sections, nil -} - -// ParseBytes will parse the given bytes and return the parsed sections. -func ParseBytes(b []byte) (Sections, error) { - tree, err := ParseASTBytes(b) - if err != nil { - return Sections{}, err - } - - v := NewDefaultVisitor("") - if err = Walk(tree, v); err != nil { - return Sections{}, err - } - - return v.Sections, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/ini_lexer.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/ini_lexer.go deleted file mode 100644 index abf1fb036..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/ini_lexer.go +++ /dev/null @@ -1,157 +0,0 @@ -package ini - -import ( - "bytes" - "io" - "io/ioutil" -) - -// TokenType represents the various different tokens types -type TokenType int - -func (t TokenType) String() string { - switch t { - case TokenNone: - return "none" - case TokenLit: - return "literal" - case TokenSep: - return "sep" - case TokenOp: - return "op" - case TokenWS: - return "ws" - case TokenNL: - return "newline" - case TokenComment: - return "comment" - case TokenComma: - return "comma" - default: - return "" - } -} - -// TokenType enums -const ( - TokenNone = TokenType(iota) - TokenLit - TokenSep - TokenComma - TokenOp - TokenWS - TokenNL - TokenComment -) - -type iniLexer struct{} - -// Tokenize will return a list of tokens during lexical analysis of the -// io.Reader. -func (l *iniLexer) Tokenize(r io.Reader) ([]Token, error) { - b, err := ioutil.ReadAll(r) - if err != nil { - return nil, &UnableToReadFile{Err: err} - } - - return l.tokenize(b) -} - -func (l *iniLexer) tokenize(b []byte) ([]Token, error) { - runes := bytes.Runes(b) - var err error - n := 0 - tokenAmount := countTokens(runes) - tokens := make([]Token, tokenAmount) - count := 0 - - for len(runes) > 0 && count < tokenAmount { - switch { - case isWhitespace(runes[0]): - tokens[count], n, err = newWSToken(runes) - case isComma(runes[0]): - tokens[count], n = newCommaToken(), 1 - case isComment(runes): - tokens[count], n, err = newCommentToken(runes) - case isNewline(runes): - tokens[count], n, err = newNewlineToken(runes) - case isSep(runes): - tokens[count], n, err = newSepToken(runes) - case isOp(runes): - tokens[count], n, err = newOpToken(runes) - default: - tokens[count], n, err = newLitToken(runes) - } - - if err != nil { - return nil, err - } - - count++ - - runes = runes[n:] - } - - return tokens[:count], nil -} - -func countTokens(runes []rune) int { - count, n := 0, 0 - var err error - - for len(runes) > 0 { - switch { - case isWhitespace(runes[0]): - _, n, err = newWSToken(runes) - case isComma(runes[0]): - _, n = newCommaToken(), 1 - case isComment(runes): - _, n, err = newCommentToken(runes) - case isNewline(runes): - _, n, err = newNewlineToken(runes) - case isSep(runes): - _, n, err = newSepToken(runes) - case isOp(runes): - _, n, err = newOpToken(runes) - default: - _, n, err = newLitToken(runes) - } - - if err != nil { - return 0 - } - - count++ - runes = runes[n:] - } - - return count + 1 -} - -// Token indicates a metadata about a given value. -type Token struct { - t TokenType - ValueType ValueType - base int - raw []rune -} - -var emptyValue = Value{} - -func newToken(t TokenType, raw []rune, v ValueType) Token { - return Token{ - t: t, - raw: raw, - ValueType: v, - } -} - -// Raw return the raw runes that were consumed -func (tok Token) Raw() []rune { - return tok.raw -} - -// Type returns the token type -func (tok Token) Type() TokenType { - return tok.t -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/ini_parser.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/ini_parser.go deleted file mode 100644 index 12fc7d5aa..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/ini_parser.go +++ /dev/null @@ -1,349 +0,0 @@ -package ini - -import ( - "fmt" - "io" -) - -// ParseState represents the current state of the parser. -type ParseState uint - -// State enums for the parse table -const ( - InvalidState ParseState = iota - // stmt -> value stmt' - StatementState - // stmt' -> MarkComplete | op stmt - StatementPrimeState - // value -> number | string | boolean | quoted_string - ValueState - // section -> [ section' - OpenScopeState - // section' -> value section_close - SectionState - // section_close -> ] - CloseScopeState - // SkipState will skip (NL WS)+ - SkipState - // SkipTokenState will skip any token and push the previous - // state onto the stack. - SkipTokenState - // comment -> # comment' | ; comment' - // comment' -> MarkComplete | value - CommentState - // MarkComplete state will complete statements and move that - // to the completed AST list - MarkCompleteState - // TerminalState signifies that the tokens have been fully parsed - TerminalState -) - -// parseTable is a state machine to dictate the grammar above. -var parseTable = map[ASTKind]map[TokenType]ParseState{ - ASTKindStart: { - TokenLit: StatementState, - TokenSep: OpenScopeState, - TokenWS: SkipTokenState, - TokenNL: SkipTokenState, - TokenComment: CommentState, - TokenNone: TerminalState, - }, - ASTKindCommentStatement: { - TokenLit: StatementState, - TokenSep: OpenScopeState, - TokenWS: SkipTokenState, - TokenNL: SkipTokenState, - TokenComment: CommentState, - TokenNone: MarkCompleteState, - }, - ASTKindExpr: { - TokenOp: StatementPrimeState, - TokenLit: ValueState, - TokenSep: OpenScopeState, - TokenWS: ValueState, - TokenNL: SkipState, - TokenComment: CommentState, - TokenNone: MarkCompleteState, - }, - ASTKindEqualExpr: { - TokenLit: ValueState, - TokenSep: ValueState, - TokenOp: ValueState, - TokenWS: SkipTokenState, - TokenNL: SkipState, - }, - ASTKindStatement: { - TokenLit: SectionState, - TokenSep: CloseScopeState, - TokenWS: SkipTokenState, - TokenNL: SkipTokenState, - TokenComment: CommentState, - TokenNone: MarkCompleteState, - }, - ASTKindExprStatement: { - TokenLit: ValueState, - TokenSep: ValueState, - TokenOp: ValueState, - TokenWS: ValueState, - TokenNL: MarkCompleteState, - TokenComment: CommentState, - TokenNone: TerminalState, - TokenComma: SkipState, - }, - ASTKindSectionStatement: { - TokenLit: SectionState, - TokenOp: SectionState, - TokenSep: CloseScopeState, - TokenWS: SectionState, - TokenNL: SkipTokenState, - }, - ASTKindCompletedSectionStatement: { - TokenWS: SkipTokenState, - TokenNL: SkipTokenState, - TokenLit: StatementState, - TokenSep: OpenScopeState, - TokenComment: CommentState, - TokenNone: MarkCompleteState, - }, - ASTKindSkipStatement: { - TokenLit: StatementState, - TokenSep: OpenScopeState, - TokenWS: SkipTokenState, - TokenNL: SkipTokenState, - TokenComment: CommentState, - TokenNone: TerminalState, - }, -} - -// ParseAST will parse input from an io.Reader using -// an LL(1) parser. -func ParseAST(r io.Reader) ([]AST, error) { - lexer := iniLexer{} - tokens, err := lexer.Tokenize(r) - if err != nil { - return []AST{}, err - } - - return parse(tokens) -} - -// ParseASTBytes will parse input from a byte slice using -// an LL(1) parser. -func ParseASTBytes(b []byte) ([]AST, error) { - lexer := iniLexer{} - tokens, err := lexer.tokenize(b) - if err != nil { - return []AST{}, err - } - - return parse(tokens) -} - -func parse(tokens []Token) ([]AST, error) { - start := Start - stack := newParseStack(3, len(tokens)) - - stack.Push(start) - s := newSkipper() - -loop: - for stack.Len() > 0 { - k := stack.Pop() - - var tok Token - if len(tokens) == 0 { - // this occurs when all the tokens have been processed - // but reduction of what's left on the stack needs to - // occur. - tok = emptyToken - } else { - tok = tokens[0] - } - - step := parseTable[k.Kind][tok.Type()] - if s.ShouldSkip(tok) { - // being in a skip state with no tokens will break out of - // the parse loop since there is nothing left to process. - if len(tokens) == 0 { - break loop - } - // if should skip is true, we skip the tokens until should skip is set to false. - step = SkipTokenState - } - - switch step { - case TerminalState: - // Finished parsing. Push what should be the last - // statement to the stack. If there is anything left - // on the stack, an error in parsing has occurred. - if k.Kind != ASTKindStart { - stack.MarkComplete(k) - } - break loop - case SkipTokenState: - // When skipping a token, the previous state was popped off the stack. - // To maintain the correct state, the previous state will be pushed - // onto the stack. - stack.Push(k) - case StatementState: - if k.Kind != ASTKindStart { - stack.MarkComplete(k) - } - expr := newExpression(tok) - stack.Push(expr) - case StatementPrimeState: - if tok.Type() != TokenOp { - stack.MarkComplete(k) - continue - } - - if k.Kind != ASTKindExpr { - return nil, NewParseError( - fmt.Sprintf("invalid expression: expected Expr type, but found %T type", k), - ) - } - - k = trimSpaces(k) - expr := newEqualExpr(k, tok) - stack.Push(expr) - case ValueState: - // ValueState requires the previous state to either be an equal expression - // or an expression statement. - switch k.Kind { - case ASTKindEqualExpr: - // assigning a value to some key - k.AppendChild(newExpression(tok)) - stack.Push(newExprStatement(k)) - case ASTKindExpr: - k.Root.raw = append(k.Root.raw, tok.Raw()...) - stack.Push(k) - case ASTKindExprStatement: - root := k.GetRoot() - children := root.GetChildren() - if len(children) == 0 { - return nil, NewParseError( - fmt.Sprintf("invalid expression: AST contains no children %s", k.Kind), - ) - } - - rhs := children[len(children)-1] - - if rhs.Root.ValueType != QuotedStringType { - rhs.Root.ValueType = StringType - rhs.Root.raw = append(rhs.Root.raw, tok.Raw()...) - - } - - children[len(children)-1] = rhs - root.SetChildren(children) - - stack.Push(k) - } - case OpenScopeState: - if !runeCompare(tok.Raw(), openBrace) { - return nil, NewParseError("expected '['") - } - // If OpenScopeState is not at the start, we must mark the previous ast as complete - // - // for example: if previous ast was a skip statement; - // we should mark it as complete before we create a new statement - if k.Kind != ASTKindStart { - stack.MarkComplete(k) - } - - stmt := newStatement() - stack.Push(stmt) - case CloseScopeState: - if !runeCompare(tok.Raw(), closeBrace) { - return nil, NewParseError("expected ']'") - } - - k = trimSpaces(k) - stack.Push(newCompletedSectionStatement(k)) - case SectionState: - var stmt AST - - switch k.Kind { - case ASTKindStatement: - // If there are multiple literals inside of a scope declaration, - // then the current token's raw value will be appended to the Name. - // - // This handles cases like [ profile default ] - // - // k will represent a SectionStatement with the children representing - // the label of the section - stmt = newSectionStatement(tok) - case ASTKindSectionStatement: - k.Root.raw = append(k.Root.raw, tok.Raw()...) - stmt = k - default: - return nil, NewParseError( - fmt.Sprintf("invalid statement: expected statement: %v", k.Kind), - ) - } - - stack.Push(stmt) - case MarkCompleteState: - if k.Kind != ASTKindStart { - stack.MarkComplete(k) - } - - if stack.Len() == 0 { - stack.Push(start) - } - case SkipState: - stack.Push(newSkipStatement(k)) - s.Skip() - case CommentState: - if k.Kind == ASTKindStart { - stack.Push(k) - } else { - stack.MarkComplete(k) - } - - stmt := newCommentStatement(tok) - stack.Push(stmt) - default: - return nil, NewParseError( - fmt.Sprintf("invalid state with ASTKind %v and TokenType %v", - k.Kind, tok.Type())) - } - - if len(tokens) > 0 { - tokens = tokens[1:] - } - } - - // this occurs when a statement has not been completed - if stack.top > 1 { - return nil, NewParseError(fmt.Sprintf("incomplete ini expression")) - } - - // returns a sublist which exludes the start symbol - return stack.List(), nil -} - -// trimSpaces will trim spaces on the left and right hand side of -// the literal. -func trimSpaces(k AST) AST { - // trim left hand side of spaces - for i := 0; i < len(k.Root.raw); i++ { - if !isWhitespace(k.Root.raw[i]) { - break - } - - k.Root.raw = k.Root.raw[1:] - i-- - } - - // trim right hand side of spaces - for i := len(k.Root.raw) - 1; i >= 0; i-- { - if !isWhitespace(k.Root.raw[i]) { - break - } - - k.Root.raw = k.Root.raw[:len(k.Root.raw)-1] - } - - return k -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/literal_tokens.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/literal_tokens.go deleted file mode 100644 index eca42d1b2..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/literal_tokens.go +++ /dev/null @@ -1,336 +0,0 @@ -package ini - -import ( - "fmt" - "strconv" - "strings" - "unicode" -) - -var ( - runesTrue = []rune("true") - runesFalse = []rune("false") -) - -var literalValues = [][]rune{ - runesTrue, - runesFalse, -} - -func isBoolValue(b []rune) bool { - for _, lv := range literalValues { - if isCaselessLitValue(lv, b) { - return true - } - } - return false -} - -func isLitValue(want, have []rune) bool { - if len(have) < len(want) { - return false - } - - for i := 0; i < len(want); i++ { - if want[i] != have[i] { - return false - } - } - - return true -} - -// isCaselessLitValue is a caseless value comparison, assumes want is already lower-cased for efficiency. -func isCaselessLitValue(want, have []rune) bool { - if len(have) < len(want) { - return false - } - - for i := 0; i < len(want); i++ { - if want[i] != unicode.ToLower(have[i]) { - return false - } - } - - return true -} - -// isNumberValue will return whether not the leading characters in -// a byte slice is a number. A number is delimited by whitespace or -// the newline token. -// -// A number is defined to be in a binary, octal, decimal (int | float), hex format, -// or in scientific notation. -func isNumberValue(b []rune) bool { - negativeIndex := 0 - helper := numberHelper{} - needDigit := false - - for i := 0; i < len(b); i++ { - negativeIndex++ - - switch b[i] { - case '-': - if helper.IsNegative() || negativeIndex != 1 { - return false - } - helper.Determine(b[i]) - needDigit = true - continue - case 'e', 'E': - if err := helper.Determine(b[i]); err != nil { - return false - } - negativeIndex = 0 - needDigit = true - continue - case 'b': - if helper.numberFormat == hex { - break - } - fallthrough - case 'o', 'x': - needDigit = true - if i == 0 { - return false - } - - fallthrough - case '.': - if err := helper.Determine(b[i]); err != nil { - return false - } - needDigit = true - continue - } - - if i > 0 && (isNewline(b[i:]) || isWhitespace(b[i])) { - return !needDigit - } - - if !helper.CorrectByte(b[i]) { - return false - } - needDigit = false - } - - return !needDigit -} - -func isValid(b []rune) (bool, int, error) { - if len(b) == 0 { - // TODO: should probably return an error - return false, 0, nil - } - - return isValidRune(b[0]), 1, nil -} - -func isValidRune(r rune) bool { - return r != ':' && r != '=' && r != '[' && r != ']' && r != ' ' && r != '\n' -} - -// ValueType is an enum that will signify what type -// the Value is -type ValueType int - -func (v ValueType) String() string { - switch v { - case NoneType: - return "NONE" - case DecimalType: - return "FLOAT" - case IntegerType: - return "INT" - case StringType: - return "STRING" - case BoolType: - return "BOOL" - } - - return "" -} - -// ValueType enums -const ( - NoneType = ValueType(iota) - DecimalType - IntegerType - StringType - QuotedStringType - BoolType -) - -// Value is a union container -type Value struct { - Type ValueType - raw []rune - - integer int64 - decimal float64 - boolean bool - str string -} - -func newValue(t ValueType, base int, raw []rune) (Value, error) { - v := Value{ - Type: t, - raw: raw, - } - var err error - - switch t { - case DecimalType: - v.decimal, err = strconv.ParseFloat(string(raw), 64) - case IntegerType: - if base != 10 { - raw = raw[2:] - } - - v.integer, err = strconv.ParseInt(string(raw), base, 64) - case StringType: - v.str = string(raw) - case QuotedStringType: - v.str = string(raw[1 : len(raw)-1]) - case BoolType: - v.boolean = isCaselessLitValue(runesTrue, v.raw) - } - - // issue 2253 - // - // if the value trying to be parsed is too large, then we will use - // the 'StringType' and raw value instead. - if nerr, ok := err.(*strconv.NumError); ok && nerr.Err == strconv.ErrRange { - v.Type = StringType - v.str = string(raw) - err = nil - } - - return v, err -} - -// NewStringValue returns a Value type generated using a string input. -func NewStringValue(str string) (Value, error) { - return newValue(StringType, 10, []rune(str)) -} - -// NewIntValue returns a Value type generated using an int64 input. -func NewIntValue(i int64) (Value, error) { - v := strconv.FormatInt(i, 10) - return newValue(IntegerType, 10, []rune(v)) -} - -func (v Value) String() string { - switch v.Type { - case DecimalType: - return fmt.Sprintf("decimal: %f", v.decimal) - case IntegerType: - return fmt.Sprintf("integer: %d", v.integer) - case StringType: - return fmt.Sprintf("string: %s", string(v.raw)) - case QuotedStringType: - return fmt.Sprintf("quoted string: %s", string(v.raw)) - case BoolType: - return fmt.Sprintf("bool: %t", v.boolean) - default: - return "union not set" - } -} - -func newLitToken(b []rune) (Token, int, error) { - n := 0 - var err error - - token := Token{} - if b[0] == '"' { - n, err = getStringValue(b) - if err != nil { - return token, n, err - } - - token = newToken(TokenLit, b[:n], QuotedStringType) - } else if isNumberValue(b) { - var base int - base, n, err = getNumericalValue(b) - if err != nil { - return token, 0, err - } - - value := b[:n] - vType := IntegerType - if contains(value, '.') || hasExponent(value) { - vType = DecimalType - } - token = newToken(TokenLit, value, vType) - token.base = base - } else if isBoolValue(b) { - n, err = getBoolValue(b) - - token = newToken(TokenLit, b[:n], BoolType) - } else { - n, err = getValue(b) - token = newToken(TokenLit, b[:n], StringType) - } - - return token, n, err -} - -// IntValue returns an integer value -func (v Value) IntValue() int64 { - return v.integer -} - -// FloatValue returns a float value -func (v Value) FloatValue() float64 { - return v.decimal -} - -// BoolValue returns a bool value -func (v Value) BoolValue() bool { - return v.boolean -} - -func isTrimmable(r rune) bool { - switch r { - case '\n', ' ': - return true - } - return false -} - -// StringValue returns the string value -func (v Value) StringValue() string { - switch v.Type { - case StringType: - return strings.TrimFunc(string(v.raw), isTrimmable) - case QuotedStringType: - // preserve all characters in the quotes - return string(removeEscapedCharacters(v.raw[1 : len(v.raw)-1])) - default: - return strings.TrimFunc(string(v.raw), isTrimmable) - } -} - -func contains(runes []rune, c rune) bool { - for i := 0; i < len(runes); i++ { - if runes[i] == c { - return true - } - } - - return false -} - -func runeCompare(v1 []rune, v2 []rune) bool { - if len(v1) != len(v2) { - return false - } - - for i := 0; i < len(v1); i++ { - if v1[i] != v2[i] { - return false - } - } - - return true -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/newline_token.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/newline_token.go deleted file mode 100644 index e52ac399f..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/newline_token.go +++ /dev/null @@ -1,30 +0,0 @@ -package ini - -func isNewline(b []rune) bool { - if len(b) == 0 { - return false - } - - if b[0] == '\n' { - return true - } - - if len(b) < 2 { - return false - } - - return b[0] == '\r' && b[1] == '\n' -} - -func newNewlineToken(b []rune) (Token, int, error) { - i := 1 - if b[0] == '\r' && isNewline(b[1:]) { - i++ - } - - if !isNewline([]rune(b[:i])) { - return emptyToken, 0, NewParseError("invalid new line token") - } - - return newToken(TokenNL, b[:i], NoneType), i, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/number_helper.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/number_helper.go deleted file mode 100644 index a45c0bc56..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/number_helper.go +++ /dev/null @@ -1,152 +0,0 @@ -package ini - -import ( - "bytes" - "fmt" - "strconv" -) - -const ( - none = numberFormat(iota) - binary - octal - decimal - hex - exponent -) - -type numberFormat int - -// numberHelper is used to dictate what format a number is in -// and what to do for negative values. Since -1e-4 is a valid -// number, we cannot just simply check for duplicate negatives. -type numberHelper struct { - numberFormat numberFormat - - negative bool - negativeExponent bool -} - -func (b numberHelper) Exists() bool { - return b.numberFormat != none -} - -func (b numberHelper) IsNegative() bool { - return b.negative || b.negativeExponent -} - -func (b *numberHelper) Determine(c rune) error { - if b.Exists() { - return NewParseError(fmt.Sprintf("multiple number formats: 0%v", string(c))) - } - - switch c { - case 'b': - b.numberFormat = binary - case 'o': - b.numberFormat = octal - case 'x': - b.numberFormat = hex - case 'e', 'E': - b.numberFormat = exponent - case '-': - if b.numberFormat != exponent { - b.negative = true - } else { - b.negativeExponent = true - } - case '.': - b.numberFormat = decimal - default: - return NewParseError(fmt.Sprintf("invalid number character: %v", string(c))) - } - - return nil -} - -func (b numberHelper) CorrectByte(c rune) bool { - switch { - case b.numberFormat == binary: - if !isBinaryByte(c) { - return false - } - case b.numberFormat == octal: - if !isOctalByte(c) { - return false - } - case b.numberFormat == hex: - if !isHexByte(c) { - return false - } - case b.numberFormat == decimal: - if !isDigit(c) { - return false - } - case b.numberFormat == exponent: - if !isDigit(c) { - return false - } - case b.negativeExponent: - if !isDigit(c) { - return false - } - case b.negative: - if !isDigit(c) { - return false - } - default: - if !isDigit(c) { - return false - } - } - - return true -} - -func (b numberHelper) Base() int { - switch b.numberFormat { - case binary: - return 2 - case octal: - return 8 - case hex: - return 16 - default: - return 10 - } -} - -func (b numberHelper) String() string { - buf := bytes.Buffer{} - i := 0 - - switch b.numberFormat { - case binary: - i++ - buf.WriteString(strconv.Itoa(i) + ": binary format\n") - case octal: - i++ - buf.WriteString(strconv.Itoa(i) + ": octal format\n") - case hex: - i++ - buf.WriteString(strconv.Itoa(i) + ": hex format\n") - case exponent: - i++ - buf.WriteString(strconv.Itoa(i) + ": exponent format\n") - default: - i++ - buf.WriteString(strconv.Itoa(i) + ": integer format\n") - } - - if b.negative { - i++ - buf.WriteString(strconv.Itoa(i) + ": negative format\n") - } - - if b.negativeExponent { - i++ - buf.WriteString(strconv.Itoa(i) + ": negative exponent format\n") - } - - return buf.String() -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/op_tokens.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/op_tokens.go deleted file mode 100644 index 8a84c7cbe..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/op_tokens.go +++ /dev/null @@ -1,39 +0,0 @@ -package ini - -import ( - "fmt" -) - -var ( - equalOp = []rune("=") - equalColonOp = []rune(":") -) - -func isOp(b []rune) bool { - if len(b) == 0 { - return false - } - - switch b[0] { - case '=': - return true - case ':': - return true - default: - return false - } -} - -func newOpToken(b []rune) (Token, int, error) { - tok := Token{} - - switch b[0] { - case '=': - tok = newToken(TokenOp, equalOp, NoneType) - case ':': - tok = newToken(TokenOp, equalColonOp, NoneType) - default: - return tok, 0, NewParseError(fmt.Sprintf("unexpected op type, %v", b[0])) - } - return tok, 1, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/parse_error.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/parse_error.go deleted file mode 100644 index 30ae0b8f2..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/parse_error.go +++ /dev/null @@ -1,19 +0,0 @@ -package ini - -// ParseError is an error which is returned during any part of -// the parsing process. -type ParseError struct { - msg string -} - -// NewParseError will return a new ParseError where message -// is the description of the error. -func NewParseError(message string) *ParseError { - return &ParseError{ - msg: message, - } -} - -func (err *ParseError) Error() string { - return err.msg -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/parse_stack.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/parse_stack.go deleted file mode 100644 index 7f01cf7c7..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/parse_stack.go +++ /dev/null @@ -1,60 +0,0 @@ -package ini - -import ( - "bytes" - "fmt" -) - -// ParseStack is a stack that contains a container, the stack portion, -// and the list which is the list of ASTs that have been successfully -// parsed. -type ParseStack struct { - top int - container []AST - list []AST - index int -} - -func newParseStack(sizeContainer, sizeList int) ParseStack { - return ParseStack{ - container: make([]AST, sizeContainer), - list: make([]AST, sizeList), - } -} - -// Pop will return and truncate the last container element. -func (s *ParseStack) Pop() AST { - s.top-- - return s.container[s.top] -} - -// Push will add the new AST to the container -func (s *ParseStack) Push(ast AST) { - s.container[s.top] = ast - s.top++ -} - -// MarkComplete will append the AST to the list of completed statements -func (s *ParseStack) MarkComplete(ast AST) { - s.list[s.index] = ast - s.index++ -} - -// List will return the completed statements -func (s ParseStack) List() []AST { - return s.list[:s.index] -} - -// Len will return the length of the container -func (s *ParseStack) Len() int { - return s.top -} - -func (s ParseStack) String() string { - buf := bytes.Buffer{} - for i, node := range s.list { - buf.WriteString(fmt.Sprintf("%d: %v\n", i+1, node)) - } - - return buf.String() -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/sep_tokens.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/sep_tokens.go deleted file mode 100644 index f82095ba2..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/sep_tokens.go +++ /dev/null @@ -1,41 +0,0 @@ -package ini - -import ( - "fmt" -) - -var ( - emptyRunes = []rune{} -) - -func isSep(b []rune) bool { - if len(b) == 0 { - return false - } - - switch b[0] { - case '[', ']': - return true - default: - return false - } -} - -var ( - openBrace = []rune("[") - closeBrace = []rune("]") -) - -func newSepToken(b []rune) (Token, int, error) { - tok := Token{} - - switch b[0] { - case '[': - tok = newToken(TokenSep, openBrace, NoneType) - case ']': - tok = newToken(TokenSep, closeBrace, NoneType) - default: - return tok, 0, NewParseError(fmt.Sprintf("unexpected sep type, %v", b[0])) - } - return tok, 1, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/skipper.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/skipper.go deleted file mode 100644 index 07e90876a..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/skipper.go +++ /dev/null @@ -1,45 +0,0 @@ -package ini - -// skipper is used to skip certain blocks of an ini file. -// Currently skipper is used to skip nested blocks of ini -// files. See example below -// -// [ foo ] -// nested = ; this section will be skipped -// a=b -// c=d -// bar=baz ; this will be included -type skipper struct { - shouldSkip bool - TokenSet bool - prevTok Token -} - -func newSkipper() skipper { - return skipper{ - prevTok: emptyToken, - } -} - -func (s *skipper) ShouldSkip(tok Token) bool { - // should skip state will be modified only if previous token was new line (NL); - // and the current token is not WhiteSpace (WS). - if s.shouldSkip && - s.prevTok.Type() == TokenNL && - tok.Type() != TokenWS { - s.Continue() - return false - } - - s.prevTok = tok - return s.shouldSkip -} - -func (s *skipper) Skip() { - s.shouldSkip = true -} - -func (s *skipper) Continue() { - s.shouldSkip = false - s.prevTok = emptyToken -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/statement.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/statement.go deleted file mode 100644 index ba0af01b5..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/statement.go +++ /dev/null @@ -1,35 +0,0 @@ -package ini - -// Statement is an empty AST mostly used for transitioning states. -func newStatement() AST { - return newAST(ASTKindStatement, AST{}) -} - -// SectionStatement represents a section AST -func newSectionStatement(tok Token) AST { - return newASTWithRootToken(ASTKindSectionStatement, tok) -} - -// ExprStatement represents a completed expression AST -func newExprStatement(ast AST) AST { - return newAST(ASTKindExprStatement, ast) -} - -// CommentStatement represents a comment in the ini defintion. -// -// grammar: -// comment -> #comment' | ;comment' -// comment' -> epsilon | value -func newCommentStatement(tok Token) AST { - return newAST(ASTKindCommentStatement, newExpression(tok)) -} - -// CompletedSectionStatement represents a completed section -func newCompletedSectionStatement(ast AST) AST { - return newAST(ASTKindCompletedSectionStatement, ast) -} - -// SkipStatement is used to skip whole statements -func newSkipStatement(ast AST) AST { - return newAST(ASTKindSkipStatement, ast) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/value_util.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/value_util.go deleted file mode 100644 index b5480fdeb..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/value_util.go +++ /dev/null @@ -1,284 +0,0 @@ -package ini - -import ( - "fmt" -) - -// getStringValue will return a quoted string and the amount -// of bytes read -// -// an error will be returned if the string is not properly formatted -func getStringValue(b []rune) (int, error) { - if b[0] != '"' { - return 0, NewParseError("strings must start with '\"'") - } - - endQuote := false - i := 1 - - for ; i < len(b) && !endQuote; i++ { - if escaped := isEscaped(b[:i], b[i]); b[i] == '"' && !escaped { - endQuote = true - break - } else if escaped { - /*c, err := getEscapedByte(b[i]) - if err != nil { - return 0, err - } - - b[i-1] = c - b = append(b[:i], b[i+1:]...) - i--*/ - - continue - } - } - - if !endQuote { - return 0, NewParseError("missing '\"' in string value") - } - - return i + 1, nil -} - -// getBoolValue will return a boolean and the amount -// of bytes read -// -// an error will be returned if the boolean is not of a correct -// value -func getBoolValue(b []rune) (int, error) { - if len(b) < 4 { - return 0, NewParseError("invalid boolean value") - } - - n := 0 - for _, lv := range literalValues { - if len(lv) > len(b) { - continue - } - - if isCaselessLitValue(lv, b) { - n = len(lv) - } - } - - if n == 0 { - return 0, NewParseError("invalid boolean value") - } - - return n, nil -} - -// getNumericalValue will return a numerical string, the amount -// of bytes read, and the base of the number -// -// an error will be returned if the number is not of a correct -// value -func getNumericalValue(b []rune) (int, int, error) { - if !isDigit(b[0]) { - return 0, 0, NewParseError("invalid digit value") - } - - i := 0 - helper := numberHelper{} - -loop: - for negativeIndex := 0; i < len(b); i++ { - negativeIndex++ - - if !isDigit(b[i]) { - switch b[i] { - case '-': - if helper.IsNegative() || negativeIndex != 1 { - return 0, 0, NewParseError("parse error '-'") - } - - n := getNegativeNumber(b[i:]) - i += (n - 1) - helper.Determine(b[i]) - continue - case '.': - if err := helper.Determine(b[i]); err != nil { - return 0, 0, err - } - case 'e', 'E': - if err := helper.Determine(b[i]); err != nil { - return 0, 0, err - } - - negativeIndex = 0 - case 'b': - if helper.numberFormat == hex { - break - } - fallthrough - case 'o', 'x': - if i == 0 && b[i] != '0' { - return 0, 0, NewParseError("incorrect base format, expected leading '0'") - } - - if i != 1 { - return 0, 0, NewParseError(fmt.Sprintf("incorrect base format found %s at %d index", string(b[i]), i)) - } - - if err := helper.Determine(b[i]); err != nil { - return 0, 0, err - } - default: - if isWhitespace(b[i]) { - break loop - } - - if isNewline(b[i:]) { - break loop - } - - if !(helper.numberFormat == hex && isHexByte(b[i])) { - if i+2 < len(b) && !isNewline(b[i:i+2]) { - return 0, 0, NewParseError("invalid numerical character") - } else if !isNewline([]rune{b[i]}) { - return 0, 0, NewParseError("invalid numerical character") - } - - break loop - } - } - } - } - - return helper.Base(), i, nil -} - -// isDigit will return whether or not something is an integer -func isDigit(b rune) bool { - return b >= '0' && b <= '9' -} - -func hasExponent(v []rune) bool { - return contains(v, 'e') || contains(v, 'E') -} - -func isBinaryByte(b rune) bool { - switch b { - case '0', '1': - return true - default: - return false - } -} - -func isOctalByte(b rune) bool { - switch b { - case '0', '1', '2', '3', '4', '5', '6', '7': - return true - default: - return false - } -} - -func isHexByte(b rune) bool { - if isDigit(b) { - return true - } - return (b >= 'A' && b <= 'F') || - (b >= 'a' && b <= 'f') -} - -func getValue(b []rune) (int, error) { - i := 0 - - for i < len(b) { - if isNewline(b[i:]) { - break - } - - if isOp(b[i:]) { - break - } - - valid, n, err := isValid(b[i:]) - if err != nil { - return 0, err - } - - if !valid { - break - } - - i += n - } - - return i, nil -} - -// getNegativeNumber will return a negative number from a -// byte slice. This will iterate through all characters until -// a non-digit has been found. -func getNegativeNumber(b []rune) int { - if b[0] != '-' { - return 0 - } - - i := 1 - for ; i < len(b); i++ { - if !isDigit(b[i]) { - return i - } - } - - return i -} - -// isEscaped will return whether or not the character is an escaped -// character. -func isEscaped(value []rune, b rune) bool { - if len(value) == 0 { - return false - } - - switch b { - case '\'': // single quote - case '"': // quote - case 'n': // newline - case 't': // tab - case '\\': // backslash - default: - return false - } - - return value[len(value)-1] == '\\' -} - -func getEscapedByte(b rune) (rune, error) { - switch b { - case '\'': // single quote - return '\'', nil - case '"': // quote - return '"', nil - case 'n': // newline - return '\n', nil - case 't': // table - return '\t', nil - case '\\': // backslash - return '\\', nil - default: - return b, NewParseError(fmt.Sprintf("invalid escaped character %c", b)) - } -} - -func removeEscapedCharacters(b []rune) []rune { - for i := 0; i < len(b); i++ { - if isEscaped(b[:i], b[i]) { - c, err := getEscapedByte(b[i]) - if err != nil { - return b - } - - b[i-1] = c - b = append(b[:i], b[i+1:]...) - i-- - } - } - - return b -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/visitor.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/visitor.go deleted file mode 100644 index a07a63738..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/visitor.go +++ /dev/null @@ -1,269 +0,0 @@ -package ini - -import ( - "fmt" - "sort" - "strings" -) - -// Visitor is an interface used by walkers that will -// traverse an array of ASTs. -type Visitor interface { - VisitExpr(AST) error - VisitStatement(AST) error -} - -// DefaultVisitor is used to visit statements and expressions -// and ensure that they are both of the correct format. -// In addition, upon visiting this will build sections and populate -// the Sections field which can be used to retrieve profile -// configuration. -type DefaultVisitor struct { - - // scope is the profile which is being visited - scope string - - // path is the file path which the visitor is visiting - path string - - // Sections defines list of the profile section - Sections Sections -} - -// NewDefaultVisitor returns a DefaultVisitor. It takes in a filepath -// which points to the file it is visiting. -func NewDefaultVisitor(filepath string) *DefaultVisitor { - return &DefaultVisitor{ - Sections: Sections{ - container: map[string]Section{}, - }, - path: filepath, - } -} - -// VisitExpr visits expressions... -func (v *DefaultVisitor) VisitExpr(expr AST) error { - t := v.Sections.container[v.scope] - if t.values == nil { - t.values = values{} - } - if t.SourceFile == nil { - t.SourceFile = make(map[string]string, 0) - } - - switch expr.Kind { - case ASTKindExprStatement: - opExpr := expr.GetRoot() - switch opExpr.Kind { - case ASTKindEqualExpr: - children := opExpr.GetChildren() - if len(children) <= 1 { - return NewParseError("unexpected token type") - } - - rhs := children[1] - - // The right-hand value side the equality expression is allowed to contain '[', ']', ':', '=' in the values. - // If the token is not either a literal or one of the token types that identifies those four additional - // tokens then error. - if !(rhs.Root.Type() == TokenLit || rhs.Root.Type() == TokenOp || rhs.Root.Type() == TokenSep) { - return NewParseError("unexpected token type") - } - - key := EqualExprKey(opExpr) - val, err := newValue(rhs.Root.ValueType, rhs.Root.base, rhs.Root.Raw()) - if err != nil { - return err - } - - // lower case key to standardize - k := strings.ToLower(key) - - // identify if the section already had this key, append log on section - if t.Has(k) { - t.Logs = append(t.Logs, - fmt.Sprintf("For profile: %v, overriding %v value, "+ - "with a %v value found in a duplicate profile defined later in the same file %v. \n", - t.Name, k, k, v.path)) - } - - // assign the value - t.values[k] = val - // update the source file path for region - t.SourceFile[k] = v.path - default: - return NewParseError(fmt.Sprintf("unsupported expression %v", expr)) - } - default: - return NewParseError(fmt.Sprintf("unsupported expression %v", expr)) - } - - v.Sections.container[v.scope] = t - return nil -} - -// VisitStatement visits statements... -func (v *DefaultVisitor) VisitStatement(stmt AST) error { - switch stmt.Kind { - case ASTKindCompletedSectionStatement: - child := stmt.GetRoot() - if child.Kind != ASTKindSectionStatement { - return NewParseError(fmt.Sprintf("unsupported child statement: %T", child)) - } - - name := string(child.Root.Raw()) - - // trim start and end space - name = strings.TrimSpace(name) - - // if has prefix "profile " + [ws+] + "profile-name", - // we standardize by removing the [ws+] between prefix and profile-name. - if strings.HasPrefix(name, "profile ") { - names := strings.SplitN(name, " ", 2) - name = names[0] + " " + strings.TrimLeft(names[1], " ") - } - - // attach profile name on section - if !v.Sections.HasSection(name) { - v.Sections.container[name] = NewSection(name) - } - v.scope = name - default: - return NewParseError(fmt.Sprintf("unsupported statement: %s", stmt.Kind)) - } - - return nil -} - -// Sections is a map of Section structures that represent -// a configuration. -type Sections struct { - container map[string]Section -} - -// NewSections returns empty ini Sections -func NewSections() Sections { - return Sections{ - container: make(map[string]Section, 0), - } -} - -// GetSection will return section p. If section p does not exist, -// false will be returned in the second parameter. -func (t Sections) GetSection(p string) (Section, bool) { - v, ok := t.container[p] - return v, ok -} - -// HasSection denotes if Sections consist of a section with -// provided name. -func (t Sections) HasSection(p string) bool { - _, ok := t.container[p] - return ok -} - -// SetSection sets a section value for provided section name. -func (t Sections) SetSection(p string, v Section) Sections { - t.container[p] = v - return t -} - -// DeleteSection deletes a section entry/value for provided section name./ -func (t Sections) DeleteSection(p string) { - delete(t.container, p) -} - -// values represents a map of union values. -type values map[string]Value - -// List will return a list of all sections that were successfully -// parsed. -func (t Sections) List() []string { - keys := make([]string, len(t.container)) - i := 0 - for k := range t.container { - keys[i] = k - i++ - } - - sort.Strings(keys) - return keys -} - -// Section contains a name and values. This represent -// a sectioned entry in a configuration file. -type Section struct { - // Name is the Section profile name - Name string - - // values are the values within parsed profile - values values - - // Errors is the list of errors - Errors []error - - // Logs is the list of logs - Logs []string - - // SourceFile is the INI Source file from where this section - // was retrieved. They key is the property, value is the - // source file the property was retrieved from. - SourceFile map[string]string -} - -// NewSection returns an initialize section for the name -func NewSection(name string) Section { - return Section{ - Name: name, - values: values{}, - SourceFile: map[string]string{}, - } -} - -// UpdateSourceFile updates source file for a property to provided filepath. -func (t Section) UpdateSourceFile(property string, filepath string) { - t.SourceFile[property] = filepath -} - -// UpdateValue updates value for a provided key with provided value -func (t Section) UpdateValue(k string, v Value) error { - t.values[k] = v - return nil -} - -// Has will return whether or not an entry exists in a given section -func (t Section) Has(k string) bool { - _, ok := t.values[k] - return ok -} - -// ValueType will returned what type the union is set to. If -// k was not found, the NoneType will be returned. -func (t Section) ValueType(k string) (ValueType, bool) { - v, ok := t.values[k] - return v.Type, ok -} - -// Bool returns a bool value at k -func (t Section) Bool(k string) bool { - return t.values[k].BoolValue() -} - -// Int returns an integer value at k -func (t Section) Int(k string) int64 { - return t.values[k].IntValue() -} - -// Float64 returns a float value at k -func (t Section) Float64(k string) float64 { - return t.values[k].FloatValue() -} - -// String returns the string value at k -func (t Section) String(k string) string { - _, ok := t.values[k] - if !ok { - return "" - } - return t.values[k].StringValue() -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/walker.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/walker.go deleted file mode 100644 index 99915f7f7..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/walker.go +++ /dev/null @@ -1,25 +0,0 @@ -package ini - -// Walk will traverse the AST using the v, the Visitor. -func Walk(tree []AST, v Visitor) error { - for _, node := range tree { - switch node.Kind { - case ASTKindExpr, - ASTKindExprStatement: - - if err := v.VisitExpr(node); err != nil { - return err - } - case ASTKindStatement, - ASTKindCompletedSectionStatement, - ASTKindNestedSectionStatement, - ASTKindCompletedNestedSectionStatement: - - if err := v.VisitStatement(node); err != nil { - return err - } - } - } - - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/ws_token.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/ws_token.go deleted file mode 100644 index 7ffb4ae06..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/ws_token.go +++ /dev/null @@ -1,24 +0,0 @@ -package ini - -import ( - "unicode" -) - -// isWhitespace will return whether or not the character is -// a whitespace character. -// -// Whitespace is defined as a space or tab. -func isWhitespace(c rune) bool { - return unicode.IsSpace(c) && c != '\n' && c != '\r' -} - -func newWSToken(b []rune) (Token, int, error) { - i := 0 - for ; i < len(b); i++ { - if !isWhitespace(b[i]) { - break - } - } - - return newToken(TokenWS, b[:i], NoneType), i, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/rand/rand.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/rand/rand.go deleted file mode 100644 index c8484dcd7..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/rand/rand.go +++ /dev/null @@ -1,33 +0,0 @@ -package rand - -import ( - "crypto/rand" - "fmt" - "io" - "math/big" -) - -func init() { - Reader = rand.Reader -} - -// Reader provides a random reader that can reset during testing. -var Reader io.Reader - -var floatMaxBigInt = big.NewInt(1 << 53) - -// Float64 returns a float64 read from an io.Reader source. The returned float will be between [0.0, 1.0). -func Float64(reader io.Reader) (float64, error) { - bi, err := rand.Int(reader, floatMaxBigInt) - if err != nil { - return 0, fmt.Errorf("failed to read random value, %v", err) - } - - return float64(bi.Int64()) / (1 << 53), nil -} - -// CryptoRandFloat64 returns a random float64 obtained from the crypto rand -// source. -func CryptoRandFloat64() (float64, error) { - return Float64(Reader) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/sdk/interfaces.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/sdk/interfaces.go deleted file mode 100644 index 2b42cbe64..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/sdk/interfaces.go +++ /dev/null @@ -1,9 +0,0 @@ -package sdk - -// Invalidator provides access to a type's invalidate method to make it -// invalidate it cache. -// -// e.g aws.SafeCredentialsProvider's Invalidate method. -type Invalidator interface { - Invalidate() -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/sdk/time.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/sdk/time.go deleted file mode 100644 index 8e8dabad5..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/sdk/time.go +++ /dev/null @@ -1,74 +0,0 @@ -package sdk - -import ( - "context" - "time" -) - -func init() { - NowTime = time.Now - Sleep = time.Sleep - SleepWithContext = sleepWithContext -} - -// NowTime is a value for getting the current time. This value can be overridden -// for testing mocking out current time. -var NowTime func() time.Time - -// Sleep is a value for sleeping for a duration. This value can be overridden -// for testing and mocking out sleep duration. -var Sleep func(time.Duration) - -// SleepWithContext will wait for the timer duration to expire, or the context -// is canceled. Which ever happens first. If the context is canceled the Context's -// error will be returned. -// -// This value can be overridden for testing and mocking out sleep duration. -var SleepWithContext func(context.Context, time.Duration) error - -// sleepWithContext will wait for the timer duration to expire, or the context -// is canceled. Which ever happens first. If the context is canceled the -// Context's error will be returned. -func sleepWithContext(ctx context.Context, dur time.Duration) error { - t := time.NewTimer(dur) - defer t.Stop() - - select { - case <-t.C: - break - case <-ctx.Done(): - return ctx.Err() - } - - return nil -} - -// noOpSleepWithContext does nothing, returns immediately. -func noOpSleepWithContext(context.Context, time.Duration) error { - return nil -} - -func noOpSleep(time.Duration) {} - -// TestingUseNopSleep is a utility for disabling sleep across the SDK for -// testing. -func TestingUseNopSleep() func() { - SleepWithContext = noOpSleepWithContext - Sleep = noOpSleep - - return func() { - SleepWithContext = sleepWithContext - Sleep = time.Sleep - } -} - -// TestingUseReferenceTime is a utility for swapping the time function across the SDK to return a specific reference time -// for testing purposes. -func TestingUseReferenceTime(referenceTime time.Time) func() { - NowTime = func() time.Time { - return referenceTime - } - return func() { - NowTime = time.Now - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/sdkio/byte.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/sdkio/byte.go deleted file mode 100644 index 6c443988b..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/sdkio/byte.go +++ /dev/null @@ -1,12 +0,0 @@ -package sdkio - -const ( - // Byte is 8 bits - Byte int64 = 1 - // KibiByte (KiB) is 1024 Bytes - KibiByte = Byte * 1024 - // MebiByte (MiB) is 1024 KiB - MebiByte = KibiByte * 1024 - // GibiByte (GiB) is 1024 MiB - GibiByte = MebiByte * 1024 -) diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/shareddefaults/shared_config.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/shareddefaults/shared_config.go deleted file mode 100644 index c96b717e0..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/shareddefaults/shared_config.go +++ /dev/null @@ -1,47 +0,0 @@ -package shareddefaults - -import ( - "os" - "os/user" - "path/filepath" -) - -// SharedCredentialsFilename returns the SDK's default file path -// for the shared credentials file. -// -// Builds the shared config file path based on the OS's platform. -// -// - Linux/Unix: $HOME/.aws/credentials -// - Windows: %USERPROFILE%\.aws\credentials -func SharedCredentialsFilename() string { - return filepath.Join(UserHomeDir(), ".aws", "credentials") -} - -// SharedConfigFilename returns the SDK's default file path for -// the shared config file. -// -// Builds the shared config file path based on the OS's platform. -// -// - Linux/Unix: $HOME/.aws/config -// - Windows: %USERPROFILE%\.aws\config -func SharedConfigFilename() string { - return filepath.Join(UserHomeDir(), ".aws", "config") -} - -// UserHomeDir returns the home directory for the user the process is -// running under. -func UserHomeDir() string { - // Ignore errors since we only care about Windows and *nix. - home, _ := os.UserHomeDir() - - if len(home) > 0 { - return home - } - - currUser, _ := user.Current() - if currUser != nil { - home = currUser.HomeDir - } - - return home -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/strings/strings.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/strings/strings.go deleted file mode 100644 index d008ae27c..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/strings/strings.go +++ /dev/null @@ -1,11 +0,0 @@ -package strings - -import ( - "strings" -) - -// HasPrefixFold tests whether the string s begins with prefix, interpreted as UTF-8 strings, -// under Unicode case-folding. -func HasPrefixFold(s, prefix string) bool { - return len(s) >= len(prefix) && strings.EqualFold(s[0:len(prefix)], prefix) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/sync/singleflight/LICENSE b/vendor/github.com/aws/aws-sdk-go-v2/internal/sync/singleflight/LICENSE deleted file mode 100644 index fe6a62006..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/sync/singleflight/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright (c) 2009 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 COPYIGHT 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/aws/aws-sdk-go-v2/internal/sync/singleflight/docs.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/sync/singleflight/docs.go deleted file mode 100644 index cb70616e8..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/sync/singleflight/docs.go +++ /dev/null @@ -1,7 +0,0 @@ -// Package singleflight provides a duplicate function call suppression -// mechanism. This package is a fork of the Go golang.org/x/sync/singleflight -// package. The package is forked, because the package a part of the unstable -// and unversioned golang.org/x/sync module. -// -// https://github.com/golang/sync/tree/67f06af15bc961c363a7260195bcd53487529a21/singleflight -package singleflight diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/sync/singleflight/singleflight.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/sync/singleflight/singleflight.go deleted file mode 100644 index e8a1b17d5..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/sync/singleflight/singleflight.go +++ /dev/null @@ -1,210 +0,0 @@ -// 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 singleflight - -import ( - "bytes" - "errors" - "fmt" - "runtime" - "runtime/debug" - "sync" -) - -// errGoexit indicates the runtime.Goexit was called in -// the user given function. -var errGoexit = errors.New("runtime.Goexit was called") - -// A panicError is an arbitrary value recovered from a panic -// with the stack trace during the execution of given function. -type panicError struct { - value interface{} - stack []byte -} - -// Error implements error interface. -func (p *panicError) Error() string { - return fmt.Sprintf("%v\n\n%s", p.value, p.stack) -} - -func newPanicError(v interface{}) error { - stack := debug.Stack() - - // The first line of the stack trace is of the form "goroutine N [status]:" - // but by the time the panic reaches Do the goroutine may no longer exist - // and its status will have changed. Trim out the misleading line. - if line := bytes.IndexByte(stack[:], '\n'); line >= 0 { - stack = stack[line+1:] - } - return &panicError{value: v, stack: stack} -} - -// call is an in-flight or completed singleflight.Do call -type call struct { - wg sync.WaitGroup - - // These fields are written once before the WaitGroup is done - // and are only read after the WaitGroup is done. - val interface{} - err error - - // forgotten indicates whether Forget was called with this call's key - // while the call was still in flight. - forgotten bool - - // These fields are read and written with the singleflight - // mutex held before the WaitGroup is done, and are read but - // not written after the WaitGroup is done. - dups int - chans []chan<- Result -} - -// Group represents a class of work and forms a namespace in -// which units of work can be executed with duplicate suppression. -type Group struct { - mu sync.Mutex // protects m - m map[string]*call // lazily initialized -} - -// Result holds the results of Do, so they can be passed -// on a channel. -type Result struct { - Val interface{} - Err error - Shared bool -} - -// Do executes and returns the results of the given function, making -// sure that only one execution is in-flight for a given key at a -// time. If a duplicate comes in, the duplicate caller waits for the -// original to complete and receives the same results. -// The return value shared indicates whether v was given to multiple callers. -func (g *Group) Do(key string, fn func() (interface{}, error)) (v interface{}, err error, shared bool) { - g.mu.Lock() - if g.m == nil { - g.m = make(map[string]*call) - } - if c, ok := g.m[key]; ok { - c.dups++ - g.mu.Unlock() - c.wg.Wait() - - if e, ok := c.err.(*panicError); ok { - panic(e) - } else if c.err == errGoexit { - runtime.Goexit() - } - return c.val, c.err, true - } - c := new(call) - c.wg.Add(1) - g.m[key] = c - g.mu.Unlock() - - g.doCall(c, key, fn) - return c.val, c.err, c.dups > 0 -} - -// DoChan is like Do but returns a channel that will receive the -// results when they are ready. -// -// The returned channel will not be closed. -func (g *Group) DoChan(key string, fn func() (interface{}, error)) <-chan Result { - ch := make(chan Result, 1) - g.mu.Lock() - if g.m == nil { - g.m = make(map[string]*call) - } - if c, ok := g.m[key]; ok { - c.dups++ - c.chans = append(c.chans, ch) - g.mu.Unlock() - return ch - } - c := &call{chans: []chan<- Result{ch}} - c.wg.Add(1) - g.m[key] = c - g.mu.Unlock() - - go g.doCall(c, key, fn) - - return ch -} - -// doCall handles the single call for a key. -func (g *Group) doCall(c *call, key string, fn func() (interface{}, error)) { - normalReturn := false - recovered := false - - // use double-defer to distinguish panic from runtime.Goexit, - // more details see https://golang.org/cl/134395 - defer func() { - // the given function invoked runtime.Goexit - if !normalReturn && !recovered { - c.err = errGoexit - } - - c.wg.Done() - g.mu.Lock() - defer g.mu.Unlock() - if !c.forgotten { - delete(g.m, key) - } - - if e, ok := c.err.(*panicError); ok { - // In order to prevent the waiting channels from being blocked forever, - // needs to ensure that this panic cannot be recovered. - if len(c.chans) > 0 { - go panic(e) - select {} // Keep this goroutine around so that it will appear in the crash dump. - } else { - panic(e) - } - } else if c.err == errGoexit { - // Already in the process of goexit, no need to call again - } else { - // Normal return - for _, ch := range c.chans { - ch <- Result{c.val, c.err, c.dups > 0} - } - } - }() - - func() { - defer func() { - if !normalReturn { - // Ideally, we would wait to take a stack trace until we've determined - // whether this is a panic or a runtime.Goexit. - // - // Unfortunately, the only way we can distinguish the two is to see - // whether the recover stopped the goroutine from terminating, and by - // the time we know that, the part of the stack trace relevant to the - // panic has been discarded. - if r := recover(); r != nil { - c.err = newPanicError(r) - } - } - }() - - c.val, c.err = fn() - normalReturn = true - }() - - if !normalReturn { - recovered = true - } -} - -// Forget tells the singleflight to forget about a key. Future calls -// to Do for this key will call the function rather than waiting for -// an earlier call to complete. -func (g *Group) Forget(key string) { - g.mu.Lock() - if c, ok := g.m[key]; ok { - c.forgotten = true - } - delete(g.m, key) - g.mu.Unlock() -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/timeconv/duration.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/timeconv/duration.go deleted file mode 100644 index 5d69db5f2..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/timeconv/duration.go +++ /dev/null @@ -1,13 +0,0 @@ -package timeconv - -import "time" - -// FloatSecondsDur converts a fractional seconds to duration. -func FloatSecondsDur(v float64) time.Duration { - return time.Duration(v * float64(time.Second)) -} - -// DurSecondsFloat converts a duration into fractional seconds. -func DurSecondsFloat(d time.Duration) float64 { - return float64(d) / float64(time.Second) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/local-mod-replace.sh b/vendor/github.com/aws/aws-sdk-go-v2/local-mod-replace.sh deleted file mode 100644 index 81a836127..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/local-mod-replace.sh +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env bash - -PROJECT_DIR="" -SDK_SOURCE_DIR=$(cd `dirname $0` && pwd) - -usage() { - echo "Usage: $0 [-s SDK_SOURCE_DIR] [-d PROJECT_DIR]" 1>&2 - exit 1 -} - -while getopts "hs:d:" options; do - case "${options}" in - s) - SDK_SOURCE_DIR=${OPTARG} - if [ "$SDK_SOURCE_DIR" == "" ]; then - echo "path to SDK source directory is required" || exit - usage - fi - ;; - d) - PROJECT_DIR=${OPTARG} - ;; - h) - usage - ;; - *) - usage - ;; - esac -done - -if [ "$PROJECT_DIR" != "" ]; then - cd "$PROJECT_DIR" || exit -fi - -go mod graph | awk '{print $1}' | cut -d '@' -f 1 | sort | uniq | grep "github.com/aws/aws-sdk-go-v2" | while read x; do - repPath=${x/github.com\/aws\/aws-sdk-go-v2/${SDK_SOURCE_DIR}} - echo -replace $x=$repPath -done | xargs go mod edit diff --git a/vendor/github.com/aws/aws-sdk-go-v2/modman.toml b/vendor/github.com/aws/aws-sdk-go-v2/modman.toml deleted file mode 100644 index dad0dfc63..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/modman.toml +++ /dev/null @@ -1,78 +0,0 @@ - -[dependencies] - "github.com/aws/aws-sdk-go" = "v1.44.28" - "github.com/aws/smithy-go" = "v1.14.2" - "github.com/google/go-cmp" = "v0.5.8" - "github.com/jmespath/go-jmespath" = "v0.4.0" - "golang.org/x/net" = "v0.1.0" - -[modules] - - [modules."."] - metadata_package = "aws" - - [modules.codegen] - no_tag = true - - [modules."example/service/dynamodb/createTable"] - no_tag = true - - [modules."example/service/dynamodb/scanItems"] - no_tag = true - - [modules."example/service/s3/listObjects"] - no_tag = true - - [modules."example/service/s3/usingPrivateLink"] - no_tag = true - - [modules."feature/ec2/imds/internal/configtesting"] - no_tag = true - - [modules."internal/codegen"] - no_tag = true - - [modules."internal/configsources/configtesting"] - no_tag = true - - [modules."internal/protocoltest/awsrestjson"] - no_tag = true - - [modules."internal/protocoltest/ec2query"] - no_tag = true - - [modules."internal/protocoltest/jsonrpc"] - no_tag = true - - [modules."internal/protocoltest/jsonrpc10"] - no_tag = true - - [modules."internal/protocoltest/query"] - no_tag = true - - [modules."internal/protocoltest/restxml"] - no_tag = true - - [modules."internal/protocoltest/restxmlwithnamespace"] - no_tag = true - - [modules."internal/repotools"] - no_tag = true - - [modules."internal/repotools/changes"] - no_tag = true - - [modules."service/internal/benchmark"] - no_tag = true - - [modules."service/internal/integrationtest"] - no_tag = true - - [modules."service/kinesis/internal/testing"] - no_tag = true - - [modules."service/s3/internal/configtesting"] - no_tag = true - - [modules."service/transcribestreaming/internal/testing"] - no_tag = true diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/CHANGELOG.md deleted file mode 100644 index e410f3e48..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/CHANGELOG.md +++ /dev/null @@ -1,219 +0,0 @@ -# v1.9.35 (2023-08-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.34 (2023-08-18) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.33 (2023-08-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.32 (2023-08-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.31 (2023-07-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.30 (2023-07-28) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.29 (2023-07-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.28 (2023-06-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.27 (2023-04-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.26 (2023-04-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.25 (2023-03-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.24 (2023-03-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.23 (2023-02-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.22 (2023-02-03) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.21 (2022-12-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.20 (2022-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.19 (2022-10-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.18 (2022-10-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.17 (2022-09-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.16 (2022-09-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.15 (2022-09-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.14 (2022-08-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.13 (2022-08-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.12 (2022-08-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.11 (2022-08-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.10 (2022-08-08) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.9 (2022-08-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.8 (2022-07-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.7 (2022-06-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.6 (2022-06-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.5 (2022-05-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.4 (2022-04-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.3 (2022-03-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.2 (2022-03-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.1 (2022-03-23) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.0 (2022-03-08) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.0 (2022-02-24) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.7.0 (2022-01-14) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.0 (2022-01-07) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.5.2 (2021-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.5.1 (2021-11-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.5.0 (2021-11-06) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.0 (2021-10-21) - -* **Feature**: Updated to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.2 (2021-10-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.1 (2021-09-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.0 (2021-08-27) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.3 (2021-08-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.2 (2021-08-04) - -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.1 (2021-07-15) - -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.0 (2021-06-25) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.1 (2021-05-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.0 (2021-05-14) - -* **Feature**: Constant has been added to modules to enable runtime version inspection for reporting. -* **Dependency Update**: Updated to the latest SDK module versions - diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/LICENSE.txt deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/LICENSE.txt +++ /dev/null @@ -1,202 +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/aws/aws-sdk-go-v2/service/internal/presigned-url/context.go b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/context.go deleted file mode 100644 index cc919701a..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/context.go +++ /dev/null @@ -1,48 +0,0 @@ -package presignedurl - -import ( - "context" - - "github.com/aws/smithy-go/middleware" -) - -// WithIsPresigning adds the isPresigning sentinel value to a context to signal -// that the middleware stack is using the presign flow. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func WithIsPresigning(ctx context.Context) context.Context { - return middleware.WithStackValue(ctx, isPresigningKey{}, true) -} - -// GetIsPresigning returns if the context contains the isPresigning sentinel -// value for presigning flows. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func GetIsPresigning(ctx context.Context) bool { - v, _ := middleware.GetStackValue(ctx, isPresigningKey{}).(bool) - return v -} - -type isPresigningKey struct{} - -// AddAsIsPresigingMiddleware adds a middleware to the head of the stack that -// will update the stack's context to be flagged as being invoked for the -// purpose of presigning. -func AddAsIsPresigingMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(asIsPresigningMiddleware{}, middleware.Before) -} - -type asIsPresigningMiddleware struct{} - -func (asIsPresigningMiddleware) ID() string { return "AsIsPresigningMiddleware" } - -func (asIsPresigningMiddleware) HandleInitialize( - ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler, -) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - ctx = WithIsPresigning(ctx) - return next.HandleInitialize(ctx, in) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/doc.go deleted file mode 100644 index 1b85375cf..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package presignedurl provides the customizations for API clients to fill in -// presigned URLs into input parameters. -package presignedurl diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/go_module_metadata.go deleted file mode 100644 index 9c076b11f..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/go_module_metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. - -package presignedurl - -// goModuleVersion is the tagged release for this module -const goModuleVersion = "1.9.35" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/middleware.go b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/middleware.go deleted file mode 100644 index 1e2f5c812..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/middleware.go +++ /dev/null @@ -1,110 +0,0 @@ -package presignedurl - -import ( - "context" - "fmt" - - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - - "github.com/aws/smithy-go/middleware" -) - -// URLPresigner provides the interface to presign the input parameters in to a -// presigned URL. -type URLPresigner interface { - // PresignURL presigns a URL. - PresignURL(ctx context.Context, srcRegion string, params interface{}) (*v4.PresignedHTTPRequest, error) -} - -// ParameterAccessor provides an collection of accessor to for retrieving and -// setting the values needed to PresignedURL generation -type ParameterAccessor struct { - // GetPresignedURL accessor points to a function that retrieves a presigned url if present - GetPresignedURL func(interface{}) (string, bool, error) - - // GetSourceRegion accessor points to a function that retrieves source region for presigned url - GetSourceRegion func(interface{}) (string, bool, error) - - // CopyInput accessor points to a function that takes in an input, and returns a copy. - CopyInput func(interface{}) (interface{}, error) - - // SetDestinationRegion accessor points to a function that sets destination region on api input struct - SetDestinationRegion func(interface{}, string) error - - // SetPresignedURL accessor points to a function that sets presigned url on api input struct - SetPresignedURL func(interface{}, string) error -} - -// Options provides the set of options needed by the presigned URL middleware. -type Options struct { - // Accessor are the parameter accessors used by this middleware - Accessor ParameterAccessor - - // Presigner is the URLPresigner used by the middleware - Presigner URLPresigner -} - -// AddMiddleware adds the Presign URL middleware to the middleware stack. -func AddMiddleware(stack *middleware.Stack, opts Options) error { - return stack.Initialize.Add(&presign{options: opts}, middleware.Before) -} - -// RemoveMiddleware removes the Presign URL middleware from the stack. -func RemoveMiddleware(stack *middleware.Stack) error { - _, err := stack.Initialize.Remove((*presign)(nil).ID()) - return err -} - -type presign struct { - options Options -} - -func (m *presign) ID() string { return "Presign" } - -func (m *presign) HandleInitialize( - ctx context.Context, input middleware.InitializeInput, next middleware.InitializeHandler, -) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - // If PresignedURL is already set ignore middleware. - if _, ok, err := m.options.Accessor.GetPresignedURL(input.Parameters); err != nil { - return out, metadata, fmt.Errorf("presign middleware failed, %w", err) - } else if ok { - return next.HandleInitialize(ctx, input) - } - - // If have source region is not set ignore middleware. - srcRegion, ok, err := m.options.Accessor.GetSourceRegion(input.Parameters) - if err != nil { - return out, metadata, fmt.Errorf("presign middleware failed, %w", err) - } else if !ok || len(srcRegion) == 0 { - return next.HandleInitialize(ctx, input) - } - - // Create a copy of the original input so the destination region value can - // be added. This ensures that value does not leak into the original - // request parameters. - paramCpy, err := m.options.Accessor.CopyInput(input.Parameters) - if err != nil { - return out, metadata, fmt.Errorf("unable to create presigned URL, %w", err) - } - - // Destination region is the API client's configured region. - dstRegion := awsmiddleware.GetRegion(ctx) - if err = m.options.Accessor.SetDestinationRegion(paramCpy, dstRegion); err != nil { - return out, metadata, fmt.Errorf("presign middleware failed, %w", err) - } - - presignedReq, err := m.options.Presigner.PresignURL(ctx, srcRegion, paramCpy) - if err != nil { - return out, metadata, fmt.Errorf("unable to create presigned URL, %w", err) - } - - // Update the original input with the presigned URL value. - if err = m.options.Accessor.SetPresignedURL(input.Parameters, presignedReq.URL); err != nil { - return out, metadata, fmt.Errorf("presign middleware failed, %w", err) - } - - return next.HandleInitialize(ctx, input) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/CHANGELOG.md deleted file mode 100644 index c7ba9b268..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/CHANGELOG.md +++ /dev/null @@ -1,288 +0,0 @@ -# v1.13.5 (2023-08-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.4 (2023-08-18) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.3 (2023-08-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.2 (2023-08-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.1 (2023-08-01) - -* No change notes available for this release. - -# v1.13.0 (2023-07-31) - -* **Feature**: Adds support for smithy-modeled endpoint resolution. A new rules-based endpoint resolution will be added to the SDK which will supercede and deprecate existing endpoint resolution. Specifically, EndpointResolver will be deprecated while BaseEndpoint and EndpointResolverV2 will take its place. For more information, please see the Endpoints section in our Developer Guide. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.14 (2023-07-28) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.13 (2023-07-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.12 (2023-06-15) - -* No change notes available for this release. - -# v1.12.11 (2023-06-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.10 (2023-05-04) - -* No change notes available for this release. - -# v1.12.9 (2023-04-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.8 (2023-04-10) - -* No change notes available for this release. - -# v1.12.7 (2023-04-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.6 (2023-03-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.5 (2023-03-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.4 (2023-02-22) - -* **Bug Fix**: Prevent nil pointer dereference when retrieving error codes. - -# v1.12.3 (2023-02-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.2 (2023-02-15) - -* **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. -* **Bug Fix**: Correct error type parsing for restJson services. - -# v1.12.1 (2023-02-03) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.0 (2023-01-05) - -* **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). - -# v1.11.28 (2022-12-20) - -* No change notes available for this release. - -# v1.11.27 (2022-12-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.26 (2022-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.25 (2022-10-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.24 (2022-10-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.23 (2022-09-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.22 (2022-09-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.21 (2022-09-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.20 (2022-08-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.19 (2022-08-30) - -* **Documentation**: Documentation updates for the AWS IAM Identity Center Portal CLI Reference. - -# v1.11.18 (2022-08-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.17 (2022-08-15) - -* **Documentation**: Documentation updates to reflect service rename - AWS IAM Identity Center (successor to AWS Single Sign-On) - -# v1.11.16 (2022-08-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.15 (2022-08-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.14 (2022-08-08) - -* **Documentation**: Documentation updates to reflect service rename - AWS IAM Identity Center (successor to AWS Single Sign-On) -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.13 (2022-08-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.12 (2022-07-11) - -* No change notes available for this release. - -# v1.11.11 (2022-07-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.10 (2022-06-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.9 (2022-06-16) - -* No change notes available for this release. - -# v1.11.8 (2022-06-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.7 (2022-05-26) - -* No change notes available for this release. - -# v1.11.6 (2022-05-25) - -* No change notes available for this release. - -# v1.11.5 (2022-05-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.4 (2022-04-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.3 (2022-03-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.2 (2022-03-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.1 (2022-03-23) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.0 (2022-03-08) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.0 (2022-02-24) - -* **Feature**: API client updated -* **Feature**: Adds RetryMaxAttempts and RetryMod to API client Options. This allows the API clients' default Retryer to be configured from the shared configuration files or environment variables. Adding a new Retry mode of `Adaptive`. `Adaptive` retry mode is an experimental mode, adding client rate limiting when throttles reponses are received from an API. See [retry.AdaptiveMode](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/aws/retry#AdaptiveMode) for more details, and configuration options. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.0 (2022-01-14) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Documentation**: Updated API models -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.0 (2022-01-07) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.7.0 (2021-12-21) - -* **Feature**: API Paginators now support specifying the initial starting token, and support stopping on empty string tokens. - -# v1.6.2 (2021-12-02) - -* **Bug Fix**: Fixes a bug that prevented aws.EndpointResolverWithOptions from being used by the service client. ([#1514](https://github.com/aws/aws-sdk-go-v2/pull/1514)) -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.1 (2021-11-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.0 (2021-11-06) - -* **Feature**: The SDK now supports configuration of FIPS and DualStack endpoints using environment variables, shared configuration, or programmatically. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Feature**: Updated service to latest API model. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.5.0 (2021-10-21) - -* **Feature**: Updated to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.2 (2021-10-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.1 (2021-09-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.0 (2021-08-27) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.3 (2021-08-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.2 (2021-08-04) - -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.1 (2021-07-15) - -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.0 (2021-06-25) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.1 (2021-05-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.0 (2021-05-14) - -* **Feature**: Constant has been added to modules to enable runtime version inspection for reporting. -* **Dependency Update**: Updated to the latest SDK module versions - diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/LICENSE.txt deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/LICENSE.txt +++ /dev/null @@ -1,202 +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/aws/aws-sdk-go-v2/service/sso/api_client.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_client.go deleted file mode 100644 index da4e470a6..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_client.go +++ /dev/null @@ -1,525 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sso - -import ( - "context" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/aws/defaults" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/retry" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" - internalConfig "github.com/aws/aws-sdk-go-v2/internal/configsources" - smithy "github.com/aws/smithy-go" - smithydocument "github.com/aws/smithy-go/document" - "github.com/aws/smithy-go/logging" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" - "net" - "net/http" - "time" -) - -const ServiceID = "SSO" -const ServiceAPIVersion = "2019-06-10" - -// Client provides the API client to make operations call for AWS Single Sign-On. -type Client struct { - options Options -} - -// New returns an initialized Client based on the functional options. Provide -// additional functional options to further configure the behavior of the client, -// such as changing the client's endpoint or adding custom middleware behavior. -func New(options Options, optFns ...func(*Options)) *Client { - options = options.Copy() - - resolveDefaultLogger(&options) - - setResolvedDefaultsMode(&options) - - resolveRetryer(&options) - - resolveHTTPClient(&options) - - resolveHTTPSignerV4(&options) - - for _, fn := range optFns { - fn(&options) - } - - client := &Client{ - options: options, - } - - return client -} - -type Options struct { - // Set of options to modify how an operation is invoked. These apply to all - // operations invoked for this client. Use functional options on operation call to - // modify this list for per operation behavior. - APIOptions []func(*middleware.Stack) error - - // The optional application specific identifier appended to the User-Agent header. - AppID string - - // This endpoint will be given as input to an EndpointResolverV2. It is used for - // providing a custom base endpoint that is subject to modifications by the - // processing EndpointResolverV2. - BaseEndpoint *string - - // Configures the events that will be sent to the configured logger. - ClientLogMode aws.ClientLogMode - - // The credentials object to use when signing requests. - Credentials aws.CredentialsProvider - - // The configuration DefaultsMode that the SDK should use when constructing the - // clients initial default settings. - DefaultsMode aws.DefaultsMode - - // The endpoint options to be used when attempting to resolve an endpoint. - EndpointOptions EndpointResolverOptions - - // The service endpoint resolver. - // - // Deprecated: Deprecated: EndpointResolver and WithEndpointResolver. Providing a - // value for this field will likely prevent you from using any endpoint-related - // service features released after the introduction of EndpointResolverV2 and - // BaseEndpoint. To migrate an EndpointResolver implementation that uses a custom - // endpoint, set the client option BaseEndpoint instead. - EndpointResolver EndpointResolver - - // Resolves the endpoint used for a particular service. This should be used over - // the deprecated EndpointResolver - EndpointResolverV2 EndpointResolverV2 - - // Signature Version 4 (SigV4) Signer - HTTPSignerV4 HTTPSignerV4 - - // The logger writer interface to write logging messages to. - Logger logging.Logger - - // The region to send requests to. (Required) - Region string - - // RetryMaxAttempts specifies the maximum number attempts an API client will call - // an operation that fails with a retryable error. A value of 0 is ignored, and - // will not be used to configure the API client created default retryer, or modify - // per operation call's retry max attempts. When creating a new API Clients this - // member will only be used if the Retryer Options member is nil. This value will - // be ignored if Retryer is not nil. If specified in an operation call's functional - // options with a value that is different than the constructed client's Options, - // the Client's Retryer will be wrapped to use the operation's specific - // RetryMaxAttempts value. - RetryMaxAttempts int - - // RetryMode specifies the retry mode the API client will be created with, if - // Retryer option is not also specified. When creating a new API Clients this - // member will only be used if the Retryer Options member is nil. This value will - // be ignored if Retryer is not nil. Currently does not support per operation call - // overrides, may in the future. - RetryMode aws.RetryMode - - // Retryer guides how HTTP requests should be retried in case of recoverable - // failures. When nil the API client will use a default retryer. The kind of - // default retry created by the API client can be changed with the RetryMode - // option. - Retryer aws.Retryer - - // The RuntimeEnvironment configuration, only populated if the DefaultsMode is set - // to DefaultsModeAuto and is initialized using config.LoadDefaultConfig . You - // should not populate this structure programmatically, or rely on the values here - // within your applications. - RuntimeEnvironment aws.RuntimeEnvironment - - // The initial DefaultsMode used when the client options were constructed. If the - // DefaultsMode was set to aws.DefaultsModeAuto this will store what the resolved - // value was at that point in time. Currently does not support per operation call - // overrides, may in the future. - resolvedDefaultsMode aws.DefaultsMode - - // The HTTP client to invoke API calls with. Defaults to client's default HTTP - // implementation if nil. - HTTPClient HTTPClient -} - -// WithAPIOptions returns a functional option for setting the Client's APIOptions -// option. -func WithAPIOptions(optFns ...func(*middleware.Stack) error) func(*Options) { - return func(o *Options) { - o.APIOptions = append(o.APIOptions, optFns...) - } -} - -// Deprecated: EndpointResolver and WithEndpointResolver. Providing a value for -// this field will likely prevent you from using any endpoint-related service -// features released after the introduction of EndpointResolverV2 and BaseEndpoint. -// To migrate an EndpointResolver implementation that uses a custom endpoint, set -// the client option BaseEndpoint instead. -func WithEndpointResolver(v EndpointResolver) func(*Options) { - return func(o *Options) { - o.EndpointResolver = v - } -} - -// WithEndpointResolverV2 returns a functional option for setting the Client's -// EndpointResolverV2 option. -func WithEndpointResolverV2(v EndpointResolverV2) func(*Options) { - return func(o *Options) { - o.EndpointResolverV2 = v - } -} - -type HTTPClient interface { - Do(*http.Request) (*http.Response, error) -} - -// Copy creates a clone where the APIOptions list is deep copied. -func (o Options) Copy() Options { - to := o - to.APIOptions = make([]func(*middleware.Stack) error, len(o.APIOptions)) - copy(to.APIOptions, o.APIOptions) - - return to -} -func (c *Client) invokeOperation(ctx context.Context, opID string, params interface{}, optFns []func(*Options), stackFns ...func(*middleware.Stack, Options) error) (result interface{}, metadata middleware.Metadata, err error) { - ctx = middleware.ClearStackValues(ctx) - stack := middleware.NewStack(opID, smithyhttp.NewStackRequest) - options := c.options.Copy() - resolveEndpointResolverV2(&options) - - for _, fn := range optFns { - fn(&options) - } - - finalizeRetryMaxAttemptOptions(&options, *c) - - finalizeClientEndpointResolverOptions(&options) - - for _, fn := range stackFns { - if err := fn(stack, options); err != nil { - return nil, metadata, err - } - } - - for _, fn := range options.APIOptions { - if err := fn(stack); err != nil { - return nil, metadata, err - } - } - - handler := middleware.DecorateHandler(smithyhttp.NewClientHandler(options.HTTPClient), stack) - result, metadata, err = handler.Handle(ctx, params) - if err != nil { - err = &smithy.OperationError{ - ServiceID: ServiceID, - OperationName: opID, - Err: err, - } - } - return result, metadata, err -} - -type noSmithyDocumentSerde = smithydocument.NoSerde - -type legacyEndpointContextSetter struct { - LegacyResolver EndpointResolver -} - -func (*legacyEndpointContextSetter) ID() string { - return "legacyEndpointContextSetter" -} - -func (m *legacyEndpointContextSetter) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - if m.LegacyResolver != nil { - ctx = awsmiddleware.SetRequiresLegacyEndpoints(ctx, true) - } - - return next.HandleInitialize(ctx, in) - -} -func addlegacyEndpointContextSetter(stack *middleware.Stack, o Options) error { - return stack.Initialize.Add(&legacyEndpointContextSetter{ - LegacyResolver: o.EndpointResolver, - }, middleware.Before) -} - -func resolveDefaultLogger(o *Options) { - if o.Logger != nil { - return - } - o.Logger = logging.Nop{} -} - -func addSetLoggerMiddleware(stack *middleware.Stack, o Options) error { - return middleware.AddSetLoggerMiddleware(stack, o.Logger) -} - -func setResolvedDefaultsMode(o *Options) { - if len(o.resolvedDefaultsMode) > 0 { - return - } - - var mode aws.DefaultsMode - mode.SetFromString(string(o.DefaultsMode)) - - if mode == aws.DefaultsModeAuto { - mode = defaults.ResolveDefaultsModeAuto(o.Region, o.RuntimeEnvironment) - } - - o.resolvedDefaultsMode = mode -} - -// NewFromConfig returns a new client from the provided config. -func NewFromConfig(cfg aws.Config, optFns ...func(*Options)) *Client { - opts := Options{ - Region: cfg.Region, - DefaultsMode: cfg.DefaultsMode, - RuntimeEnvironment: cfg.RuntimeEnvironment, - HTTPClient: cfg.HTTPClient, - Credentials: cfg.Credentials, - APIOptions: cfg.APIOptions, - Logger: cfg.Logger, - ClientLogMode: cfg.ClientLogMode, - AppID: cfg.AppID, - } - resolveAWSRetryerProvider(cfg, &opts) - resolveAWSRetryMaxAttempts(cfg, &opts) - resolveAWSRetryMode(cfg, &opts) - resolveAWSEndpointResolver(cfg, &opts) - resolveUseDualStackEndpoint(cfg, &opts) - resolveUseFIPSEndpoint(cfg, &opts) - return New(opts, optFns...) -} - -func resolveHTTPClient(o *Options) { - var buildable *awshttp.BuildableClient - - if o.HTTPClient != nil { - var ok bool - buildable, ok = o.HTTPClient.(*awshttp.BuildableClient) - if !ok { - return - } - } else { - buildable = awshttp.NewBuildableClient() - } - - modeConfig, err := defaults.GetModeConfiguration(o.resolvedDefaultsMode) - if err == nil { - buildable = buildable.WithDialerOptions(func(dialer *net.Dialer) { - if dialerTimeout, ok := modeConfig.GetConnectTimeout(); ok { - dialer.Timeout = dialerTimeout - } - }) - - buildable = buildable.WithTransportOptions(func(transport *http.Transport) { - if tlsHandshakeTimeout, ok := modeConfig.GetTLSNegotiationTimeout(); ok { - transport.TLSHandshakeTimeout = tlsHandshakeTimeout - } - }) - } - - o.HTTPClient = buildable -} - -func resolveRetryer(o *Options) { - if o.Retryer != nil { - return - } - - if len(o.RetryMode) == 0 { - modeConfig, err := defaults.GetModeConfiguration(o.resolvedDefaultsMode) - if err == nil { - o.RetryMode = modeConfig.RetryMode - } - } - if len(o.RetryMode) == 0 { - o.RetryMode = aws.RetryModeStandard - } - - var standardOptions []func(*retry.StandardOptions) - if v := o.RetryMaxAttempts; v != 0 { - standardOptions = append(standardOptions, func(so *retry.StandardOptions) { - so.MaxAttempts = v - }) - } - - switch o.RetryMode { - case aws.RetryModeAdaptive: - var adaptiveOptions []func(*retry.AdaptiveModeOptions) - if len(standardOptions) != 0 { - adaptiveOptions = append(adaptiveOptions, func(ao *retry.AdaptiveModeOptions) { - ao.StandardOptions = append(ao.StandardOptions, standardOptions...) - }) - } - o.Retryer = retry.NewAdaptiveMode(adaptiveOptions...) - - default: - o.Retryer = retry.NewStandard(standardOptions...) - } -} - -func resolveAWSRetryerProvider(cfg aws.Config, o *Options) { - if cfg.Retryer == nil { - return - } - o.Retryer = cfg.Retryer() -} - -func resolveAWSRetryMode(cfg aws.Config, o *Options) { - if len(cfg.RetryMode) == 0 { - return - } - o.RetryMode = cfg.RetryMode -} -func resolveAWSRetryMaxAttempts(cfg aws.Config, o *Options) { - if cfg.RetryMaxAttempts == 0 { - return - } - o.RetryMaxAttempts = cfg.RetryMaxAttempts -} - -func finalizeRetryMaxAttemptOptions(o *Options, client Client) { - if v := o.RetryMaxAttempts; v == 0 || v == client.options.RetryMaxAttempts { - return - } - - o.Retryer = retry.AddWithMaxAttempts(o.Retryer, o.RetryMaxAttempts) -} - -func resolveAWSEndpointResolver(cfg aws.Config, o *Options) { - if cfg.EndpointResolver == nil && cfg.EndpointResolverWithOptions == nil { - return - } - o.EndpointResolver = withEndpointResolver(cfg.EndpointResolver, cfg.EndpointResolverWithOptions) -} - -func addClientUserAgent(stack *middleware.Stack, options Options) error { - if err := awsmiddleware.AddSDKAgentKeyValue(awsmiddleware.APIMetadata, "sso", goModuleVersion)(stack); err != nil { - return err - } - - if len(options.AppID) > 0 { - return awsmiddleware.AddSDKAgentKey(awsmiddleware.ApplicationIdentifier, options.AppID)(stack) - } - - return nil -} - -func addHTTPSignerV4Middleware(stack *middleware.Stack, o Options) error { - mw := v4.NewSignHTTPRequestMiddleware(v4.SignHTTPRequestMiddlewareOptions{ - CredentialsProvider: o.Credentials, - Signer: o.HTTPSignerV4, - LogSigning: o.ClientLogMode.IsSigning(), - }) - return stack.Finalize.Add(mw, middleware.After) -} - -type HTTPSignerV4 interface { - SignHTTP(ctx context.Context, credentials aws.Credentials, r *http.Request, payloadHash string, service string, region string, signingTime time.Time, optFns ...func(*v4.SignerOptions)) error -} - -func resolveHTTPSignerV4(o *Options) { - if o.HTTPSignerV4 != nil { - return - } - o.HTTPSignerV4 = newDefaultV4Signer(*o) -} - -func newDefaultV4Signer(o Options) *v4.Signer { - return v4.NewSigner(func(so *v4.SignerOptions) { - so.Logger = o.Logger - so.LogSigning = o.ClientLogMode.IsSigning() - }) -} - -func addRetryMiddlewares(stack *middleware.Stack, o Options) error { - mo := retry.AddRetryMiddlewaresOptions{ - Retryer: o.Retryer, - LogRetryAttempts: o.ClientLogMode.IsRetries(), - } - return retry.AddRetryMiddlewares(stack, mo) -} - -// resolves dual-stack endpoint configuration -func resolveUseDualStackEndpoint(cfg aws.Config, o *Options) error { - if len(cfg.ConfigSources) == 0 { - return nil - } - value, found, err := internalConfig.ResolveUseDualStackEndpoint(context.Background(), cfg.ConfigSources) - if err != nil { - return err - } - if found { - o.EndpointOptions.UseDualStackEndpoint = value - } - return nil -} - -// resolves FIPS endpoint configuration -func resolveUseFIPSEndpoint(cfg aws.Config, o *Options) error { - if len(cfg.ConfigSources) == 0 { - return nil - } - value, found, err := internalConfig.ResolveUseFIPSEndpoint(context.Background(), cfg.ConfigSources) - if err != nil { - return err - } - if found { - o.EndpointOptions.UseFIPSEndpoint = value - } - return nil -} - -func addRequestIDRetrieverMiddleware(stack *middleware.Stack) error { - return awsmiddleware.AddRequestIDRetrieverMiddleware(stack) -} - -func addResponseErrorMiddleware(stack *middleware.Stack) error { - return awshttp.AddResponseErrorMiddleware(stack) -} - -func addRequestResponseLogging(stack *middleware.Stack, o Options) error { - return stack.Deserialize.Add(&smithyhttp.RequestResponseLogger{ - LogRequest: o.ClientLogMode.IsRequest(), - LogRequestWithBody: o.ClientLogMode.IsRequestWithBody(), - LogResponse: o.ClientLogMode.IsResponse(), - LogResponseWithBody: o.ClientLogMode.IsResponseWithBody(), - }, middleware.After) -} - -type endpointDisableHTTPSMiddleware struct { - EndpointDisableHTTPS bool -} - -func (*endpointDisableHTTPSMiddleware) ID() string { - return "endpointDisableHTTPSMiddleware" -} - -func (m *endpointDisableHTTPSMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointDisableHTTPS && !smithyhttp.GetHostnameImmutable(ctx) { - req.URL.Scheme = "http" - } - - return next.HandleSerialize(ctx, in) - -} -func addendpointDisableHTTPSMiddleware(stack *middleware.Stack, o Options) error { - return stack.Serialize.Insert(&endpointDisableHTTPSMiddleware{ - EndpointDisableHTTPS: o.EndpointOptions.DisableHTTPS, - }, "OperationSerializer", middleware.Before) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_GetRoleCredentials.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_GetRoleCredentials.go deleted file mode 100644 index 0383bb0bd..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_GetRoleCredentials.go +++ /dev/null @@ -1,266 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sso - -import ( - "context" - "errors" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - "github.com/aws/aws-sdk-go-v2/service/sso/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Returns the STS short-term credentials for a given role name that is assigned -// to the user. -func (c *Client) GetRoleCredentials(ctx context.Context, params *GetRoleCredentialsInput, optFns ...func(*Options)) (*GetRoleCredentialsOutput, error) { - if params == nil { - params = &GetRoleCredentialsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetRoleCredentials", params, optFns, c.addOperationGetRoleCredentialsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetRoleCredentialsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetRoleCredentialsInput struct { - - // The token issued by the CreateToken API call. For more information, see - // CreateToken (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html) - // in the IAM Identity Center OIDC API Reference Guide. - // - // This member is required. - AccessToken *string - - // The identifier for the AWS account that is assigned to the user. - // - // This member is required. - AccountId *string - - // The friendly name of the role that is assigned to the user. - // - // This member is required. - RoleName *string - - noSmithyDocumentSerde -} - -type GetRoleCredentialsOutput struct { - - // The credentials for the role that is assigned to the user. - RoleCredentials *types.RoleCredentials - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetRoleCredentialsMiddlewares(stack *middleware.Stack, options Options) (err error) { - err = stack.Serialize.Add(&awsRestjson1_serializeOpGetRoleCredentials{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsRestjson1_deserializeOpGetRoleCredentials{}, middleware.After) - if err != nil { - return err - } - if err = addlegacyEndpointContextSetter(stack, options); err != nil { - return err - } - if err = addSetLoggerMiddleware(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { - return err - } - if err = addClientUserAgent(stack, options); err != nil { - return err - } - if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = addGetRoleCredentialsResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addOpGetRoleCredentialsValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetRoleCredentials(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { - return err - } - if err = addRequestIDRetrieverMiddleware(stack); err != nil { - return err - } - if err = addResponseErrorMiddleware(stack); err != nil { - return err - } - if err = addRequestResponseLogging(stack, options); err != nil { - return err - } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { - return err - } - return nil -} - -func newServiceMetadataMiddleware_opGetRoleCredentials(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetRoleCredentials", - } -} - -type opGetRoleCredentialsResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opGetRoleCredentialsResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opGetRoleCredentialsResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "awsssoportal" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "awsssoportal" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("awsssoportal") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addGetRoleCredentialsResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opGetRoleCredentialsResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_ListAccountRoles.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_ListAccountRoles.go deleted file mode 100644 index cc28543f8..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_ListAccountRoles.go +++ /dev/null @@ -1,361 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sso - -import ( - "context" - "errors" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - "github.com/aws/aws-sdk-go-v2/service/sso/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Lists all roles that are assigned to the user for a given AWS account. -func (c *Client) ListAccountRoles(ctx context.Context, params *ListAccountRolesInput, optFns ...func(*Options)) (*ListAccountRolesOutput, error) { - if params == nil { - params = &ListAccountRolesInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "ListAccountRoles", params, optFns, c.addOperationListAccountRolesMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*ListAccountRolesOutput) - out.ResultMetadata = metadata - return out, nil -} - -type ListAccountRolesInput struct { - - // The token issued by the CreateToken API call. For more information, see - // CreateToken (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html) - // in the IAM Identity Center OIDC API Reference Guide. - // - // This member is required. - AccessToken *string - - // The identifier for the AWS account that is assigned to the user. - // - // This member is required. - AccountId *string - - // The number of items that clients can request per page. - MaxResults *int32 - - // The page token from the previous response output when you request subsequent - // pages. - NextToken *string - - noSmithyDocumentSerde -} - -type ListAccountRolesOutput struct { - - // The page token client that is used to retrieve the list of accounts. - NextToken *string - - // A paginated response with the list of roles and the next token if more results - // are available. - RoleList []types.RoleInfo - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationListAccountRolesMiddlewares(stack *middleware.Stack, options Options) (err error) { - err = stack.Serialize.Add(&awsRestjson1_serializeOpListAccountRoles{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsRestjson1_deserializeOpListAccountRoles{}, middleware.After) - if err != nil { - return err - } - if err = addlegacyEndpointContextSetter(stack, options); err != nil { - return err - } - if err = addSetLoggerMiddleware(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { - return err - } - if err = addClientUserAgent(stack, options); err != nil { - return err - } - if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = addListAccountRolesResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addOpListAccountRolesValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListAccountRoles(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { - return err - } - if err = addRequestIDRetrieverMiddleware(stack); err != nil { - return err - } - if err = addResponseErrorMiddleware(stack); err != nil { - return err - } - if err = addRequestResponseLogging(stack, options); err != nil { - return err - } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { - return err - } - return nil -} - -// ListAccountRolesAPIClient is a client that implements the ListAccountRoles -// operation. -type ListAccountRolesAPIClient interface { - ListAccountRoles(context.Context, *ListAccountRolesInput, ...func(*Options)) (*ListAccountRolesOutput, error) -} - -var _ ListAccountRolesAPIClient = (*Client)(nil) - -// ListAccountRolesPaginatorOptions is the paginator options for ListAccountRoles -type ListAccountRolesPaginatorOptions struct { - // The number of items that clients can request per page. - Limit int32 - - // Set to true if pagination should stop if the service returns a pagination token - // that matches the most recent token provided to the service. - StopOnDuplicateToken bool -} - -// ListAccountRolesPaginator is a paginator for ListAccountRoles -type ListAccountRolesPaginator struct { - options ListAccountRolesPaginatorOptions - client ListAccountRolesAPIClient - params *ListAccountRolesInput - nextToken *string - firstPage bool -} - -// NewListAccountRolesPaginator returns a new ListAccountRolesPaginator -func NewListAccountRolesPaginator(client ListAccountRolesAPIClient, params *ListAccountRolesInput, optFns ...func(*ListAccountRolesPaginatorOptions)) *ListAccountRolesPaginator { - if params == nil { - params = &ListAccountRolesInput{} - } - - options := ListAccountRolesPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &ListAccountRolesPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *ListAccountRolesPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next ListAccountRoles page. -func (p *ListAccountRolesPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListAccountRolesOutput, error) { - if !p.HasMorePages() { - return nil, fmt.Errorf("no more pages available") - } - - params := *p.params - params.NextToken = p.nextToken - - var limit *int32 - if p.options.Limit > 0 { - limit = &p.options.Limit - } - params.MaxResults = limit - - result, err := p.client.ListAccountRoles(ctx, ¶ms, optFns...) - if err != nil { - return nil, err - } - p.firstPage = false - - prevToken := p.nextToken - p.nextToken = result.NextToken - - if p.options.StopOnDuplicateToken && - prevToken != nil && - p.nextToken != nil && - *prevToken == *p.nextToken { - p.nextToken = nil - } - - return result, nil -} - -func newServiceMetadataMiddleware_opListAccountRoles(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "ListAccountRoles", - } -} - -type opListAccountRolesResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opListAccountRolesResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opListAccountRolesResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "awsssoportal" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "awsssoportal" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("awsssoportal") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addListAccountRolesResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opListAccountRolesResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_ListAccounts.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_ListAccounts.go deleted file mode 100644 index 567f6c669..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_ListAccounts.go +++ /dev/null @@ -1,358 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sso - -import ( - "context" - "errors" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - "github.com/aws/aws-sdk-go-v2/service/sso/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Lists all AWS accounts assigned to the user. These AWS accounts are assigned by -// the administrator of the account. For more information, see Assign User Access (https://docs.aws.amazon.com/singlesignon/latest/userguide/useraccess.html#assignusers) -// in the IAM Identity Center User Guide. This operation returns a paginated -// response. -func (c *Client) ListAccounts(ctx context.Context, params *ListAccountsInput, optFns ...func(*Options)) (*ListAccountsOutput, error) { - if params == nil { - params = &ListAccountsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "ListAccounts", params, optFns, c.addOperationListAccountsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*ListAccountsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type ListAccountsInput struct { - - // The token issued by the CreateToken API call. For more information, see - // CreateToken (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html) - // in the IAM Identity Center OIDC API Reference Guide. - // - // This member is required. - AccessToken *string - - // This is the number of items clients can request per page. - MaxResults *int32 - - // (Optional) When requesting subsequent pages, this is the page token from the - // previous response output. - NextToken *string - - noSmithyDocumentSerde -} - -type ListAccountsOutput struct { - - // A paginated response with the list of account information and the next token if - // more results are available. - AccountList []types.AccountInfo - - // The page token client that is used to retrieve the list of accounts. - NextToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationListAccountsMiddlewares(stack *middleware.Stack, options Options) (err error) { - err = stack.Serialize.Add(&awsRestjson1_serializeOpListAccounts{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsRestjson1_deserializeOpListAccounts{}, middleware.After) - if err != nil { - return err - } - if err = addlegacyEndpointContextSetter(stack, options); err != nil { - return err - } - if err = addSetLoggerMiddleware(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { - return err - } - if err = addClientUserAgent(stack, options); err != nil { - return err - } - if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = addListAccountsResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addOpListAccountsValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListAccounts(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { - return err - } - if err = addRequestIDRetrieverMiddleware(stack); err != nil { - return err - } - if err = addResponseErrorMiddleware(stack); err != nil { - return err - } - if err = addRequestResponseLogging(stack, options); err != nil { - return err - } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { - return err - } - return nil -} - -// ListAccountsAPIClient is a client that implements the ListAccounts operation. -type ListAccountsAPIClient interface { - ListAccounts(context.Context, *ListAccountsInput, ...func(*Options)) (*ListAccountsOutput, error) -} - -var _ ListAccountsAPIClient = (*Client)(nil) - -// ListAccountsPaginatorOptions is the paginator options for ListAccounts -type ListAccountsPaginatorOptions struct { - // This is the number of items clients can request per page. - Limit int32 - - // Set to true if pagination should stop if the service returns a pagination token - // that matches the most recent token provided to the service. - StopOnDuplicateToken bool -} - -// ListAccountsPaginator is a paginator for ListAccounts -type ListAccountsPaginator struct { - options ListAccountsPaginatorOptions - client ListAccountsAPIClient - params *ListAccountsInput - nextToken *string - firstPage bool -} - -// NewListAccountsPaginator returns a new ListAccountsPaginator -func NewListAccountsPaginator(client ListAccountsAPIClient, params *ListAccountsInput, optFns ...func(*ListAccountsPaginatorOptions)) *ListAccountsPaginator { - if params == nil { - params = &ListAccountsInput{} - } - - options := ListAccountsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &ListAccountsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *ListAccountsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next ListAccounts page. -func (p *ListAccountsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListAccountsOutput, error) { - if !p.HasMorePages() { - return nil, fmt.Errorf("no more pages available") - } - - params := *p.params - params.NextToken = p.nextToken - - var limit *int32 - if p.options.Limit > 0 { - limit = &p.options.Limit - } - params.MaxResults = limit - - result, err := p.client.ListAccounts(ctx, ¶ms, optFns...) - if err != nil { - return nil, err - } - p.firstPage = false - - prevToken := p.nextToken - p.nextToken = result.NextToken - - if p.options.StopOnDuplicateToken && - prevToken != nil && - p.nextToken != nil && - *prevToken == *p.nextToken { - p.nextToken = nil - } - - return result, nil -} - -func newServiceMetadataMiddleware_opListAccounts(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "ListAccounts", - } -} - -type opListAccountsResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opListAccountsResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opListAccountsResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "awsssoportal" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "awsssoportal" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("awsssoportal") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addListAccountsResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opListAccountsResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_Logout.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_Logout.go deleted file mode 100644 index c30da0296..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_Logout.go +++ /dev/null @@ -1,261 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sso - -import ( - "context" - "errors" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Removes the locally stored SSO tokens from the client-side cache and sends an -// API call to the IAM Identity Center service to invalidate the corresponding -// server-side IAM Identity Center sign in session. If a user uses IAM Identity -// Center to access the AWS CLI, the user’s IAM Identity Center sign in session is -// used to obtain an IAM session, as specified in the corresponding IAM Identity -// Center permission set. More specifically, IAM Identity Center assumes an IAM -// role in the target account on behalf of the user, and the corresponding -// temporary AWS credentials are returned to the client. After user logout, any -// existing IAM role sessions that were created by using IAM Identity Center -// permission sets continue based on the duration configured in the permission set. -// For more information, see User authentications (https://docs.aws.amazon.com/singlesignon/latest/userguide/authconcept.html) -// in the IAM Identity Center User Guide. -func (c *Client) Logout(ctx context.Context, params *LogoutInput, optFns ...func(*Options)) (*LogoutOutput, error) { - if params == nil { - params = &LogoutInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "Logout", params, optFns, c.addOperationLogoutMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*LogoutOutput) - out.ResultMetadata = metadata - return out, nil -} - -type LogoutInput struct { - - // The token issued by the CreateToken API call. For more information, see - // CreateToken (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html) - // in the IAM Identity Center OIDC API Reference Guide. - // - // This member is required. - AccessToken *string - - noSmithyDocumentSerde -} - -type LogoutOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationLogoutMiddlewares(stack *middleware.Stack, options Options) (err error) { - err = stack.Serialize.Add(&awsRestjson1_serializeOpLogout{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsRestjson1_deserializeOpLogout{}, middleware.After) - if err != nil { - return err - } - if err = addlegacyEndpointContextSetter(stack, options); err != nil { - return err - } - if err = addSetLoggerMiddleware(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { - return err - } - if err = addClientUserAgent(stack, options); err != nil { - return err - } - if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = addLogoutResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addOpLogoutValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opLogout(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { - return err - } - if err = addRequestIDRetrieverMiddleware(stack); err != nil { - return err - } - if err = addResponseErrorMiddleware(stack); err != nil { - return err - } - if err = addRequestResponseLogging(stack, options); err != nil { - return err - } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { - return err - } - return nil -} - -func newServiceMetadataMiddleware_opLogout(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "Logout", - } -} - -type opLogoutResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opLogoutResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opLogoutResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "awsssoportal" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "awsssoportal" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("awsssoportal") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addLogoutResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opLogoutResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/deserializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/deserializers.go deleted file mode 100644 index 8bba205f4..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/deserializers.go +++ /dev/null @@ -1,1151 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sso - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws/protocol/restjson" - "github.com/aws/aws-sdk-go-v2/service/sso/types" - smithy "github.com/aws/smithy-go" - smithyio "github.com/aws/smithy-go/io" - "github.com/aws/smithy-go/middleware" - "github.com/aws/smithy-go/ptr" - smithyhttp "github.com/aws/smithy-go/transport/http" - "io" - "io/ioutil" - "strings" -) - -type awsRestjson1_deserializeOpGetRoleCredentials struct { -} - -func (*awsRestjson1_deserializeOpGetRoleCredentials) ID() string { - return "OperationDeserializer" -} - -func (m *awsRestjson1_deserializeOpGetRoleCredentials) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( - out middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err = next.HandleDeserialize(ctx, in) - if err != nil { - return out, metadata, err - } - - response, ok := out.RawResponse.(*smithyhttp.Response) - if !ok { - return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} - } - - if response.StatusCode < 200 || response.StatusCode >= 300 { - return out, metadata, awsRestjson1_deserializeOpErrorGetRoleCredentials(response, &metadata) - } - output := &GetRoleCredentialsOutput{} - out.Result = output - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(response.Body, ringBuffer) - - decoder := json.NewDecoder(body) - decoder.UseNumber() - var shape interface{} - if err := decoder.Decode(&shape); err != nil && err != io.EOF { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return out, metadata, err - } - - err = awsRestjson1_deserializeOpDocumentGetRoleCredentialsOutput(&output, shape) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return out, metadata, err -} - -func awsRestjson1_deserializeOpErrorGetRoleCredentials(response *smithyhttp.Response, metadata *middleware.Metadata) error { - var errorBuffer bytes.Buffer - if _, err := io.Copy(&errorBuffer, response.Body); err != nil { - return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} - } - errorBody := bytes.NewReader(errorBuffer.Bytes()) - - errorCode := "UnknownError" - errorMessage := errorCode - - headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InvalidRequestException", errorCode): - return awsRestjson1_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("ResourceNotFoundException", errorCode): - return awsRestjson1_deserializeErrorResourceNotFoundException(response, errorBody) - - case strings.EqualFold("TooManyRequestsException", errorCode): - return awsRestjson1_deserializeErrorTooManyRequestsException(response, errorBody) - - case strings.EqualFold("UnauthorizedException", errorCode): - return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -func awsRestjson1_deserializeOpDocumentGetRoleCredentialsOutput(v **GetRoleCredentialsOutput, value interface{}) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - if value == nil { - return nil - } - - shape, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var sv *GetRoleCredentialsOutput - if *v == nil { - sv = &GetRoleCredentialsOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "roleCredentials": - if err := awsRestjson1_deserializeDocumentRoleCredentials(&sv.RoleCredentials, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -type awsRestjson1_deserializeOpListAccountRoles struct { -} - -func (*awsRestjson1_deserializeOpListAccountRoles) ID() string { - return "OperationDeserializer" -} - -func (m *awsRestjson1_deserializeOpListAccountRoles) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( - out middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err = next.HandleDeserialize(ctx, in) - if err != nil { - return out, metadata, err - } - - response, ok := out.RawResponse.(*smithyhttp.Response) - if !ok { - return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} - } - - if response.StatusCode < 200 || response.StatusCode >= 300 { - return out, metadata, awsRestjson1_deserializeOpErrorListAccountRoles(response, &metadata) - } - output := &ListAccountRolesOutput{} - out.Result = output - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(response.Body, ringBuffer) - - decoder := json.NewDecoder(body) - decoder.UseNumber() - var shape interface{} - if err := decoder.Decode(&shape); err != nil && err != io.EOF { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return out, metadata, err - } - - err = awsRestjson1_deserializeOpDocumentListAccountRolesOutput(&output, shape) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return out, metadata, err -} - -func awsRestjson1_deserializeOpErrorListAccountRoles(response *smithyhttp.Response, metadata *middleware.Metadata) error { - var errorBuffer bytes.Buffer - if _, err := io.Copy(&errorBuffer, response.Body); err != nil { - return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} - } - errorBody := bytes.NewReader(errorBuffer.Bytes()) - - errorCode := "UnknownError" - errorMessage := errorCode - - headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InvalidRequestException", errorCode): - return awsRestjson1_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("ResourceNotFoundException", errorCode): - return awsRestjson1_deserializeErrorResourceNotFoundException(response, errorBody) - - case strings.EqualFold("TooManyRequestsException", errorCode): - return awsRestjson1_deserializeErrorTooManyRequestsException(response, errorBody) - - case strings.EqualFold("UnauthorizedException", errorCode): - return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -func awsRestjson1_deserializeOpDocumentListAccountRolesOutput(v **ListAccountRolesOutput, value interface{}) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - if value == nil { - return nil - } - - shape, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var sv *ListAccountRolesOutput - if *v == nil { - sv = &ListAccountRolesOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "nextToken": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected NextTokenType to be of type string, got %T instead", value) - } - sv.NextToken = ptr.String(jtv) - } - - case "roleList": - if err := awsRestjson1_deserializeDocumentRoleListType(&sv.RoleList, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -type awsRestjson1_deserializeOpListAccounts struct { -} - -func (*awsRestjson1_deserializeOpListAccounts) ID() string { - return "OperationDeserializer" -} - -func (m *awsRestjson1_deserializeOpListAccounts) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( - out middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err = next.HandleDeserialize(ctx, in) - if err != nil { - return out, metadata, err - } - - response, ok := out.RawResponse.(*smithyhttp.Response) - if !ok { - return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} - } - - if response.StatusCode < 200 || response.StatusCode >= 300 { - return out, metadata, awsRestjson1_deserializeOpErrorListAccounts(response, &metadata) - } - output := &ListAccountsOutput{} - out.Result = output - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(response.Body, ringBuffer) - - decoder := json.NewDecoder(body) - decoder.UseNumber() - var shape interface{} - if err := decoder.Decode(&shape); err != nil && err != io.EOF { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return out, metadata, err - } - - err = awsRestjson1_deserializeOpDocumentListAccountsOutput(&output, shape) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return out, metadata, err -} - -func awsRestjson1_deserializeOpErrorListAccounts(response *smithyhttp.Response, metadata *middleware.Metadata) error { - var errorBuffer bytes.Buffer - if _, err := io.Copy(&errorBuffer, response.Body); err != nil { - return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} - } - errorBody := bytes.NewReader(errorBuffer.Bytes()) - - errorCode := "UnknownError" - errorMessage := errorCode - - headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InvalidRequestException", errorCode): - return awsRestjson1_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("ResourceNotFoundException", errorCode): - return awsRestjson1_deserializeErrorResourceNotFoundException(response, errorBody) - - case strings.EqualFold("TooManyRequestsException", errorCode): - return awsRestjson1_deserializeErrorTooManyRequestsException(response, errorBody) - - case strings.EqualFold("UnauthorizedException", errorCode): - return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -func awsRestjson1_deserializeOpDocumentListAccountsOutput(v **ListAccountsOutput, value interface{}) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - if value == nil { - return nil - } - - shape, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var sv *ListAccountsOutput - if *v == nil { - sv = &ListAccountsOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "accountList": - if err := awsRestjson1_deserializeDocumentAccountListType(&sv.AccountList, value); err != nil { - return err - } - - case "nextToken": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected NextTokenType to be of type string, got %T instead", value) - } - sv.NextToken = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -type awsRestjson1_deserializeOpLogout struct { -} - -func (*awsRestjson1_deserializeOpLogout) ID() string { - return "OperationDeserializer" -} - -func (m *awsRestjson1_deserializeOpLogout) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( - out middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err = next.HandleDeserialize(ctx, in) - if err != nil { - return out, metadata, err - } - - response, ok := out.RawResponse.(*smithyhttp.Response) - if !ok { - return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} - } - - if response.StatusCode < 200 || response.StatusCode >= 300 { - return out, metadata, awsRestjson1_deserializeOpErrorLogout(response, &metadata) - } - output := &LogoutOutput{} - out.Result = output - - if _, err = io.Copy(ioutil.Discard, response.Body); err != nil { - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to discard response body, %w", err), - } - } - - return out, metadata, err -} - -func awsRestjson1_deserializeOpErrorLogout(response *smithyhttp.Response, metadata *middleware.Metadata) error { - var errorBuffer bytes.Buffer - if _, err := io.Copy(&errorBuffer, response.Body); err != nil { - return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} - } - errorBody := bytes.NewReader(errorBuffer.Bytes()) - - errorCode := "UnknownError" - errorMessage := errorCode - - headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InvalidRequestException", errorCode): - return awsRestjson1_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("TooManyRequestsException", errorCode): - return awsRestjson1_deserializeErrorTooManyRequestsException(response, errorBody) - - case strings.EqualFold("UnauthorizedException", errorCode): - return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -func awsRestjson1_deserializeErrorInvalidRequestException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.InvalidRequestException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - var shape interface{} - if err := decoder.Decode(&shape); err != nil && err != io.EOF { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - err := awsRestjson1_deserializeDocumentInvalidRequestException(&output, shape) - - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - errorBody.Seek(0, io.SeekStart) - - return output -} - -func awsRestjson1_deserializeErrorResourceNotFoundException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.ResourceNotFoundException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - var shape interface{} - if err := decoder.Decode(&shape); err != nil && err != io.EOF { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - err := awsRestjson1_deserializeDocumentResourceNotFoundException(&output, shape) - - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - errorBody.Seek(0, io.SeekStart) - - return output -} - -func awsRestjson1_deserializeErrorTooManyRequestsException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.TooManyRequestsException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - var shape interface{} - if err := decoder.Decode(&shape); err != nil && err != io.EOF { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - err := awsRestjson1_deserializeDocumentTooManyRequestsException(&output, shape) - - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - errorBody.Seek(0, io.SeekStart) - - return output -} - -func awsRestjson1_deserializeErrorUnauthorizedException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.UnauthorizedException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - var shape interface{} - if err := decoder.Decode(&shape); err != nil && err != io.EOF { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - err := awsRestjson1_deserializeDocumentUnauthorizedException(&output, shape) - - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - errorBody.Seek(0, io.SeekStart) - - return output -} - -func awsRestjson1_deserializeDocumentAccountInfo(v **types.AccountInfo, value interface{}) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - if value == nil { - return nil - } - - shape, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var sv *types.AccountInfo - if *v == nil { - sv = &types.AccountInfo{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "accountId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AccountIdType to be of type string, got %T instead", value) - } - sv.AccountId = ptr.String(jtv) - } - - case "accountName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AccountNameType to be of type string, got %T instead", value) - } - sv.AccountName = ptr.String(jtv) - } - - case "emailAddress": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected EmailAddressType to be of type string, got %T instead", value) - } - sv.EmailAddress = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentAccountListType(v *[]types.AccountInfo, value interface{}) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - if value == nil { - return nil - } - - shape, ok := value.([]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var cv []types.AccountInfo - if *v == nil { - cv = []types.AccountInfo{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.AccountInfo - destAddr := &col - if err := awsRestjson1_deserializeDocumentAccountInfo(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsRestjson1_deserializeDocumentInvalidRequestException(v **types.InvalidRequestException, value interface{}) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - if value == nil { - return nil - } - - shape, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var sv *types.InvalidRequestException - if *v == nil { - sv = &types.InvalidRequestException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentResourceNotFoundException(v **types.ResourceNotFoundException, value interface{}) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - if value == nil { - return nil - } - - shape, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var sv *types.ResourceNotFoundException - if *v == nil { - sv = &types.ResourceNotFoundException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentRoleCredentials(v **types.RoleCredentials, value interface{}) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - if value == nil { - return nil - } - - shape, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var sv *types.RoleCredentials - if *v == nil { - sv = &types.RoleCredentials{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "accessKeyId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AccessKeyType to be of type string, got %T instead", value) - } - sv.AccessKeyId = ptr.String(jtv) - } - - case "expiration": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected ExpirationTimestampType to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.Expiration = i64 - } - - case "secretAccessKey": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretAccessKeyType to be of type string, got %T instead", value) - } - sv.SecretAccessKey = ptr.String(jtv) - } - - case "sessionToken": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SessionTokenType to be of type string, got %T instead", value) - } - sv.SessionToken = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentRoleInfo(v **types.RoleInfo, value interface{}) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - if value == nil { - return nil - } - - shape, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var sv *types.RoleInfo - if *v == nil { - sv = &types.RoleInfo{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "accountId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AccountIdType to be of type string, got %T instead", value) - } - sv.AccountId = ptr.String(jtv) - } - - case "roleName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected RoleNameType to be of type string, got %T instead", value) - } - sv.RoleName = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentRoleListType(v *[]types.RoleInfo, value interface{}) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - if value == nil { - return nil - } - - shape, ok := value.([]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var cv []types.RoleInfo - if *v == nil { - cv = []types.RoleInfo{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.RoleInfo - destAddr := &col - if err := awsRestjson1_deserializeDocumentRoleInfo(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsRestjson1_deserializeDocumentTooManyRequestsException(v **types.TooManyRequestsException, value interface{}) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - if value == nil { - return nil - } - - shape, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var sv *types.TooManyRequestsException - if *v == nil { - sv = &types.TooManyRequestsException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentUnauthorizedException(v **types.UnauthorizedException, value interface{}) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - if value == nil { - return nil - } - - shape, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var sv *types.UnauthorizedException - if *v == nil { - sv = &types.UnauthorizedException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/doc.go deleted file mode 100644 index 59456d5dc..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/doc.go +++ /dev/null @@ -1,21 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -// Package sso provides the API client, operations, and parameter types for AWS -// Single Sign-On. -// -// AWS IAM Identity Center (successor to AWS Single Sign-On) Portal is a web -// service that makes it easy for you to assign user access to IAM Identity Center -// resources such as the AWS access portal. Users can get AWS account applications -// and roles assigned to them and get federated into the application. Although AWS -// Single Sign-On was renamed, the sso and identitystore API namespaces will -// continue to retain their original name for backward compatibility purposes. For -// more information, see IAM Identity Center rename (https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html#renamed) -// . This reference guide describes the IAM Identity Center Portal operations that -// you can call programatically and includes detailed information on data types and -// errors. AWS provides SDKs that consist of libraries and sample code for various -// programming languages and platforms, such as Java, Ruby, .Net, iOS, or Android. -// The SDKs provide a convenient way to create programmatic access to IAM Identity -// Center and other AWS services. For more information about the AWS SDKs, -// including how to download and install them, see Tools for Amazon Web Services (http://aws.amazon.com/tools/) -// . -package sso diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/endpoints.go deleted file mode 100644 index 9395e91e2..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/endpoints.go +++ /dev/null @@ -1,753 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sso - -import ( - "context" - "errors" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn" - internalendpoints "github.com/aws/aws-sdk-go-v2/service/sso/internal/endpoints" - smithyendpoints "github.com/aws/smithy-go/endpoints" - "github.com/aws/smithy-go/middleware" - "github.com/aws/smithy-go/ptr" - smithyhttp "github.com/aws/smithy-go/transport/http" - "net/http" - "net/url" - "strings" -) - -// EndpointResolverOptions is the service endpoint resolver options -type EndpointResolverOptions = internalendpoints.Options - -// EndpointResolver interface for resolving service endpoints. -type EndpointResolver interface { - ResolveEndpoint(region string, options EndpointResolverOptions) (aws.Endpoint, error) -} - -var _ EndpointResolver = &internalendpoints.Resolver{} - -// NewDefaultEndpointResolver constructs a new service endpoint resolver -func NewDefaultEndpointResolver() *internalendpoints.Resolver { - return internalendpoints.New() -} - -// EndpointResolverFunc is a helper utility that wraps a function so it satisfies -// the EndpointResolver interface. This is useful when you want to add additional -// endpoint resolving logic, or stub out specific endpoints with custom values. -type EndpointResolverFunc func(region string, options EndpointResolverOptions) (aws.Endpoint, error) - -func (fn EndpointResolverFunc) ResolveEndpoint(region string, options EndpointResolverOptions) (endpoint aws.Endpoint, err error) { - return fn(region, options) -} - -// EndpointResolverFromURL returns an EndpointResolver configured using the -// provided endpoint url. By default, the resolved endpoint resolver uses the -// client region as signing region, and the endpoint source is set to -// EndpointSourceCustom.You can provide functional options to configure endpoint -// values for the resolved endpoint. -func EndpointResolverFromURL(url string, optFns ...func(*aws.Endpoint)) EndpointResolver { - e := aws.Endpoint{URL: url, Source: aws.EndpointSourceCustom} - for _, fn := range optFns { - fn(&e) - } - - return EndpointResolverFunc( - func(region string, options EndpointResolverOptions) (aws.Endpoint, error) { - if len(e.SigningRegion) == 0 { - e.SigningRegion = region - } - return e, nil - }, - ) -} - -type ResolveEndpoint struct { - Resolver EndpointResolver - Options EndpointResolverOptions -} - -func (*ResolveEndpoint) ID() string { - return "ResolveEndpoint" -} - -func (m *ResolveEndpoint) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if !awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.Resolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - eo := m.Options - eo.Logger = middleware.GetLogger(ctx) - - var endpoint aws.Endpoint - endpoint, err = m.Resolver.ResolveEndpoint(awsmiddleware.GetRegion(ctx), eo) - if err != nil { - nf := (&aws.EndpointNotFoundError{}) - if errors.As(err, &nf) { - ctx = awsmiddleware.SetRequiresLegacyEndpoints(ctx, false) - return next.HandleSerialize(ctx, in) - } - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL, err = url.Parse(endpoint.URL) - if err != nil { - return out, metadata, fmt.Errorf("failed to parse endpoint URL: %w", err) - } - - if len(awsmiddleware.GetSigningName(ctx)) == 0 { - signingName := endpoint.SigningName - if len(signingName) == 0 { - signingName = "awsssoportal" - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - } - ctx = awsmiddleware.SetEndpointSource(ctx, endpoint.Source) - ctx = smithyhttp.SetHostnameImmutable(ctx, endpoint.HostnameImmutable) - ctx = awsmiddleware.SetSigningRegion(ctx, endpoint.SigningRegion) - ctx = awsmiddleware.SetPartitionID(ctx, endpoint.PartitionID) - return next.HandleSerialize(ctx, in) -} -func addResolveEndpointMiddleware(stack *middleware.Stack, o Options) error { - return stack.Serialize.Insert(&ResolveEndpoint{ - Resolver: o.EndpointResolver, - Options: o.EndpointOptions, - }, "OperationSerializer", middleware.Before) -} - -func removeResolveEndpointMiddleware(stack *middleware.Stack) error { - _, err := stack.Serialize.Remove((&ResolveEndpoint{}).ID()) - return err -} - -type wrappedEndpointResolver struct { - awsResolver aws.EndpointResolverWithOptions -} - -func (w *wrappedEndpointResolver) ResolveEndpoint(region string, options EndpointResolverOptions) (endpoint aws.Endpoint, err error) { - return w.awsResolver.ResolveEndpoint(ServiceID, region, options) -} - -type awsEndpointResolverAdaptor func(service, region string) (aws.Endpoint, error) - -func (a awsEndpointResolverAdaptor) ResolveEndpoint(service, region string, options ...interface{}) (aws.Endpoint, error) { - return a(service, region) -} - -var _ aws.EndpointResolverWithOptions = awsEndpointResolverAdaptor(nil) - -// withEndpointResolver returns an aws.EndpointResolverWithOptions that first delegates endpoint resolution to the awsResolver. -// If awsResolver returns aws.EndpointNotFoundError error, the v1 resolver middleware will swallow the error, -// and set an appropriate context flag such that fallback will occur when EndpointResolverV2 is invoked -// via its middleware. -// -// If another error (besides aws.EndpointNotFoundError) is returned, then that error will be propagated. -func withEndpointResolver(awsResolver aws.EndpointResolver, awsResolverWithOptions aws.EndpointResolverWithOptions) EndpointResolver { - var resolver aws.EndpointResolverWithOptions - - if awsResolverWithOptions != nil { - resolver = awsResolverWithOptions - } else if awsResolver != nil { - resolver = awsEndpointResolverAdaptor(awsResolver.ResolveEndpoint) - } - - return &wrappedEndpointResolver{ - awsResolver: resolver, - } -} - -func finalizeClientEndpointResolverOptions(options *Options) { - options.EndpointOptions.LogDeprecated = options.ClientLogMode.IsDeprecatedUsage() - - if len(options.EndpointOptions.ResolvedRegion) == 0 { - const fipsInfix = "-fips-" - const fipsPrefix = "fips-" - const fipsSuffix = "-fips" - - if strings.Contains(options.Region, fipsInfix) || - strings.Contains(options.Region, fipsPrefix) || - strings.Contains(options.Region, fipsSuffix) { - options.EndpointOptions.ResolvedRegion = strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll( - options.Region, fipsInfix, "-"), fipsPrefix, ""), fipsSuffix, "") - options.EndpointOptions.UseFIPSEndpoint = aws.FIPSEndpointStateEnabled - } - } - -} - -func resolveEndpointResolverV2(options *Options) { - if options.EndpointResolverV2 == nil { - options.EndpointResolverV2 = NewDefaultEndpointResolverV2() - } -} - -// Utility function to aid with translating pseudo-regions to classical regions -// with the appropriate setting indicated by the pseudo-region -func mapPseudoRegion(pr string) (region string, fips aws.FIPSEndpointState) { - const fipsInfix = "-fips-" - const fipsPrefix = "fips-" - const fipsSuffix = "-fips" - - if strings.Contains(pr, fipsInfix) || - strings.Contains(pr, fipsPrefix) || - strings.Contains(pr, fipsSuffix) { - region = strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll( - pr, fipsInfix, "-"), fipsPrefix, ""), fipsSuffix, "") - fips = aws.FIPSEndpointStateEnabled - } else { - region = pr - } - - return region, fips -} - -// builtInParameterResolver is the interface responsible for resolving BuiltIn -// values during the sourcing of EndpointParameters -type builtInParameterResolver interface { - ResolveBuiltIns(*EndpointParameters) error -} - -// builtInResolver resolves modeled BuiltIn values using only the members defined -// below. -type builtInResolver struct { - // The AWS region used to dispatch the request. - Region string - - // Sourced BuiltIn value in a historical enabled or disabled state. - UseDualStack aws.DualStackEndpointState - - // Sourced BuiltIn value in a historical enabled or disabled state. - UseFIPS aws.FIPSEndpointState - - // Base endpoint that can potentially be modified during Endpoint resolution. - Endpoint *string -} - -// Invoked at runtime to resolve BuiltIn Values. Only resolution code specific to -// each BuiltIn value is generated. -func (b *builtInResolver) ResolveBuiltIns(params *EndpointParameters) error { - - region, _ := mapPseudoRegion(b.Region) - if len(region) == 0 { - return fmt.Errorf("Could not resolve AWS::Region") - } else { - params.Region = aws.String(region) - } - if b.UseDualStack == aws.DualStackEndpointStateEnabled { - params.UseDualStack = aws.Bool(true) - } else { - params.UseDualStack = aws.Bool(false) - } - if b.UseFIPS == aws.FIPSEndpointStateEnabled { - params.UseFIPS = aws.Bool(true) - } else { - params.UseFIPS = aws.Bool(false) - } - params.Endpoint = b.Endpoint - return nil -} - -// EndpointParameters provides the parameters that influence how endpoints are -// resolved. -type EndpointParameters struct { - // The AWS region used to dispatch the request. - // - // Parameter is - // required. - // - // AWS::Region - Region *string - - // When true, use the dual-stack endpoint. If the configured endpoint does not - // support dual-stack, dispatching the request MAY return an error. - // - // Defaults to - // false if no value is provided. - // - // AWS::UseDualStack - UseDualStack *bool - - // When true, send this request to the FIPS-compliant regional endpoint. If the - // configured endpoint does not have a FIPS compliant endpoint, dispatching the - // request will return an error. - // - // Defaults to false if no value is - // provided. - // - // AWS::UseFIPS - UseFIPS *bool - - // Override the endpoint used to send this request - // - // Parameter is - // required. - // - // SDK::Endpoint - Endpoint *string -} - -// ValidateRequired validates required parameters are set. -func (p EndpointParameters) ValidateRequired() error { - if p.UseDualStack == nil { - return fmt.Errorf("parameter UseDualStack is required") - } - - if p.UseFIPS == nil { - return fmt.Errorf("parameter UseFIPS is required") - } - - return nil -} - -// WithDefaults returns a shallow copy of EndpointParameterswith default values -// applied to members where applicable. -func (p EndpointParameters) WithDefaults() EndpointParameters { - if p.UseDualStack == nil { - p.UseDualStack = ptr.Bool(false) - } - - if p.UseFIPS == nil { - p.UseFIPS = ptr.Bool(false) - } - return p -} - -// EndpointResolverV2 provides the interface for resolving service endpoints. -type EndpointResolverV2 interface { - // ResolveEndpoint attempts to resolve the endpoint with the provided options, - // returning the endpoint if found. Otherwise an error is returned. - ResolveEndpoint(ctx context.Context, params EndpointParameters) ( - smithyendpoints.Endpoint, error, - ) -} - -// resolver provides the implementation for resolving endpoints. -type resolver struct{} - -func NewDefaultEndpointResolverV2() EndpointResolverV2 { - return &resolver{} -} - -// ResolveEndpoint attempts to resolve the endpoint with the provided options, -// returning the endpoint if found. Otherwise an error is returned. -func (r *resolver) ResolveEndpoint( - ctx context.Context, params EndpointParameters, -) ( - endpoint smithyendpoints.Endpoint, err error, -) { - params = params.WithDefaults() - if err = params.ValidateRequired(); err != nil { - return endpoint, fmt.Errorf("endpoint parameters are not valid, %w", err) - } - _UseDualStack := *params.UseDualStack - _UseFIPS := *params.UseFIPS - - if exprVal := params.Endpoint; exprVal != nil { - _Endpoint := *exprVal - _ = _Endpoint - if _UseFIPS == true { - return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: FIPS and custom endpoint are not supported") - } - if _UseDualStack == true { - return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: Dualstack and custom endpoint are not supported") - } - uriString := _Endpoint - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if exprVal := params.Region; exprVal != nil { - _Region := *exprVal - _ = _Region - if exprVal := awsrulesfn.GetPartition(_Region); exprVal != nil { - _PartitionResult := *exprVal - _ = _PartitionResult - if _UseFIPS == true { - if _UseDualStack == true { - if true == _PartitionResult.SupportsFIPS { - if true == _PartitionResult.SupportsDualStack { - uriString := func() string { - var out strings.Builder - out.WriteString("https://portal.sso-fips.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DualStackDnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "FIPS and DualStack are enabled, but this partition does not support one or both") - } - } - if _UseFIPS == true { - if true == _PartitionResult.SupportsFIPS { - uriString := func() string { - var out strings.Builder - out.WriteString("https://portal.sso-fips.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "FIPS is enabled but this partition does not support FIPS") - } - if _UseDualStack == true { - if true == _PartitionResult.SupportsDualStack { - uriString := func() string { - var out strings.Builder - out.WriteString("https://portal.sso.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DualStackDnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "DualStack is enabled but this partition does not support DualStack") - } - if _Region == "ap-east-1" { - uriString := "https://portal.sso.ap-east-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "ap-northeast-1" { - uriString := "https://portal.sso.ap-northeast-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "ap-northeast-2" { - uriString := "https://portal.sso.ap-northeast-2.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "ap-northeast-3" { - uriString := "https://portal.sso.ap-northeast-3.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "ap-south-1" { - uriString := "https://portal.sso.ap-south-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "ap-southeast-1" { - uriString := "https://portal.sso.ap-southeast-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "ap-southeast-2" { - uriString := "https://portal.sso.ap-southeast-2.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "ca-central-1" { - uriString := "https://portal.sso.ca-central-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "eu-central-1" { - uriString := "https://portal.sso.eu-central-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "eu-north-1" { - uriString := "https://portal.sso.eu-north-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "eu-south-1" { - uriString := "https://portal.sso.eu-south-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "eu-west-1" { - uriString := "https://portal.sso.eu-west-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "eu-west-2" { - uriString := "https://portal.sso.eu-west-2.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "eu-west-3" { - uriString := "https://portal.sso.eu-west-3.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "me-south-1" { - uriString := "https://portal.sso.me-south-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "sa-east-1" { - uriString := "https://portal.sso.sa-east-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "us-east-1" { - uriString := "https://portal.sso.us-east-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "us-east-2" { - uriString := "https://portal.sso.us-east-2.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "us-west-2" { - uriString := "https://portal.sso.us-west-2.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "us-gov-east-1" { - uriString := "https://portal.sso.us-gov-east-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "us-gov-west-1" { - uriString := "https://portal.sso.us-gov-west-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - uriString := func() string { - var out strings.Builder - out.WriteString("https://portal.sso.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - return endpoint, fmt.Errorf("Endpoint resolution failed. Invalid operation or environment input.") - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: Missing Region") -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/generated.json b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/generated.json deleted file mode 100644 index ab6af36e8..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/generated.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "dependencies": { - "github.com/aws/aws-sdk-go-v2": "v1.4.0", - "github.com/aws/aws-sdk-go-v2/internal/configsources": "v0.0.0-00010101000000-000000000000", - "github.com/aws/aws-sdk-go-v2/internal/endpoints/v2": "v2.0.0-00010101000000-000000000000", - "github.com/aws/smithy-go": "v1.4.0", - "github.com/google/go-cmp": "v0.5.4" - }, - "files": [ - "api_client.go", - "api_client_test.go", - "api_op_GetRoleCredentials.go", - "api_op_ListAccountRoles.go", - "api_op_ListAccounts.go", - "api_op_Logout.go", - "deserializers.go", - "doc.go", - "endpoints.go", - "endpoints_test.go", - "generated.json", - "internal/endpoints/endpoints.go", - "internal/endpoints/endpoints_test.go", - "protocol_test.go", - "serializers.go", - "types/errors.go", - "types/types.go", - "validators.go" - ], - "go": "1.15", - "module": "github.com/aws/aws-sdk-go-v2/service/sso", - "unstable": false -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/go_module_metadata.go deleted file mode 100644 index 98050334e..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/go_module_metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. - -package sso - -// goModuleVersion is the tagged release for this module -const goModuleVersion = "1.13.5" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/internal/endpoints/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/internal/endpoints/endpoints.go deleted file mode 100644 index 1da26791c..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/internal/endpoints/endpoints.go +++ /dev/null @@ -1,492 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package endpoints - -import ( - "github.com/aws/aws-sdk-go-v2/aws" - endpoints "github.com/aws/aws-sdk-go-v2/internal/endpoints/v2" - "github.com/aws/smithy-go/logging" - "regexp" -) - -// Options is the endpoint resolver configuration options -type Options struct { - // Logger is a logging implementation that log events should be sent to. - Logger logging.Logger - - // LogDeprecated indicates that deprecated endpoints should be logged to the - // provided logger. - LogDeprecated bool - - // ResolvedRegion is used to override the region to be resolved, rather then the - // using the value passed to the ResolveEndpoint method. This value is used by the - // SDK to translate regions like fips-us-east-1 or us-east-1-fips to an alternative - // name. You must not set this value directly in your application. - ResolvedRegion string - - // DisableHTTPS informs the resolver to return an endpoint that does not use the - // HTTPS scheme. - DisableHTTPS bool - - // UseDualStackEndpoint specifies the resolver must resolve a dual-stack endpoint. - UseDualStackEndpoint aws.DualStackEndpointState - - // UseFIPSEndpoint specifies the resolver must resolve a FIPS endpoint. - UseFIPSEndpoint aws.FIPSEndpointState -} - -func (o Options) GetResolvedRegion() string { - return o.ResolvedRegion -} - -func (o Options) GetDisableHTTPS() bool { - return o.DisableHTTPS -} - -func (o Options) GetUseDualStackEndpoint() aws.DualStackEndpointState { - return o.UseDualStackEndpoint -} - -func (o Options) GetUseFIPSEndpoint() aws.FIPSEndpointState { - return o.UseFIPSEndpoint -} - -func transformToSharedOptions(options Options) endpoints.Options { - return endpoints.Options{ - Logger: options.Logger, - LogDeprecated: options.LogDeprecated, - ResolvedRegion: options.ResolvedRegion, - DisableHTTPS: options.DisableHTTPS, - UseDualStackEndpoint: options.UseDualStackEndpoint, - UseFIPSEndpoint: options.UseFIPSEndpoint, - } -} - -// Resolver SSO endpoint resolver -type Resolver struct { - partitions endpoints.Partitions -} - -// ResolveEndpoint resolves the service endpoint for the given region and options -func (r *Resolver) ResolveEndpoint(region string, options Options) (endpoint aws.Endpoint, err error) { - if len(region) == 0 { - return endpoint, &aws.MissingRegionError{} - } - - opt := transformToSharedOptions(options) - return r.partitions.ResolveEndpoint(region, opt) -} - -// New returns a new Resolver -func New() *Resolver { - return &Resolver{ - partitions: defaultPartitions, - } -} - -var partitionRegexp = struct { - Aws *regexp.Regexp - AwsCn *regexp.Regexp - AwsIso *regexp.Regexp - AwsIsoB *regexp.Regexp - AwsIsoE *regexp.Regexp - AwsIsoF *regexp.Regexp - AwsUsGov *regexp.Regexp -}{ - - Aws: regexp.MustCompile("^(us|eu|ap|sa|ca|me|af|il)\\-\\w+\\-\\d+$"), - AwsCn: regexp.MustCompile("^cn\\-\\w+\\-\\d+$"), - AwsIso: regexp.MustCompile("^us\\-iso\\-\\w+\\-\\d+$"), - AwsIsoB: regexp.MustCompile("^us\\-isob\\-\\w+\\-\\d+$"), - AwsIsoE: regexp.MustCompile("^eu\\-isoe\\-\\w+\\-\\d+$"), - AwsIsoF: regexp.MustCompile("^us\\-isof\\-\\w+\\-\\d+$"), - AwsUsGov: regexp.MustCompile("^us\\-gov\\-\\w+\\-\\d+$"), -} - -var defaultPartitions = endpoints.Partitions{ - { - ID: "aws", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.DualStackVariant, - }: { - Hostname: "portal.sso.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "portal.sso-fips.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: { - Hostname: "portal.sso-fips.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "portal.sso.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.Aws, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "af-south-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.af-south-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "af-south-1", - }, - }, - endpoints.EndpointKey{ - Region: "ap-east-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.ap-east-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-east-1", - }, - }, - endpoints.EndpointKey{ - Region: "ap-northeast-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.ap-northeast-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-northeast-1", - }, - }, - endpoints.EndpointKey{ - Region: "ap-northeast-2", - }: endpoints.Endpoint{ - Hostname: "portal.sso.ap-northeast-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-northeast-2", - }, - }, - endpoints.EndpointKey{ - Region: "ap-northeast-3", - }: endpoints.Endpoint{ - Hostname: "portal.sso.ap-northeast-3.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-northeast-3", - }, - }, - endpoints.EndpointKey{ - Region: "ap-south-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.ap-south-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-south-1", - }, - }, - endpoints.EndpointKey{ - Region: "ap-southeast-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.ap-southeast-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-southeast-1", - }, - }, - endpoints.EndpointKey{ - Region: "ap-southeast-2", - }: endpoints.Endpoint{ - Hostname: "portal.sso.ap-southeast-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-southeast-2", - }, - }, - endpoints.EndpointKey{ - Region: "ap-southeast-3", - }: endpoints.Endpoint{ - Hostname: "portal.sso.ap-southeast-3.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-southeast-3", - }, - }, - endpoints.EndpointKey{ - Region: "ca-central-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.ca-central-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ca-central-1", - }, - }, - endpoints.EndpointKey{ - Region: "eu-central-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.eu-central-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "eu-central-1", - }, - }, - endpoints.EndpointKey{ - Region: "eu-north-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.eu-north-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "eu-north-1", - }, - }, - endpoints.EndpointKey{ - Region: "eu-south-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.eu-south-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "eu-south-1", - }, - }, - endpoints.EndpointKey{ - Region: "eu-west-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.eu-west-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "eu-west-1", - }, - }, - endpoints.EndpointKey{ - Region: "eu-west-2", - }: endpoints.Endpoint{ - Hostname: "portal.sso.eu-west-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "eu-west-2", - }, - }, - endpoints.EndpointKey{ - Region: "eu-west-3", - }: endpoints.Endpoint{ - Hostname: "portal.sso.eu-west-3.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "eu-west-3", - }, - }, - endpoints.EndpointKey{ - Region: "me-south-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.me-south-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "me-south-1", - }, - }, - endpoints.EndpointKey{ - Region: "sa-east-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.sa-east-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "sa-east-1", - }, - }, - endpoints.EndpointKey{ - Region: "us-east-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.us-east-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-east-1", - }, - }, - endpoints.EndpointKey{ - Region: "us-east-2", - }: endpoints.Endpoint{ - Hostname: "portal.sso.us-east-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-east-2", - }, - }, - endpoints.EndpointKey{ - Region: "us-west-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.us-west-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-west-1", - }, - }, - endpoints.EndpointKey{ - Region: "us-west-2", - }: endpoints.Endpoint{ - Hostname: "portal.sso.us-west-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - { - ID: "aws-cn", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.DualStackVariant, - }: { - Hostname: "portal.sso.{region}.api.amazonwebservices.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "portal.sso-fips.{region}.amazonaws.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: { - Hostname: "portal.sso-fips.{region}.api.amazonwebservices.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "portal.sso.{region}.amazonaws.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsCn, - IsRegionalized: true, - }, - { - ID: "aws-iso", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "portal.sso-fips.{region}.c2s.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "portal.sso.{region}.c2s.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIso, - IsRegionalized: true, - }, - { - ID: "aws-iso-b", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "portal.sso-fips.{region}.sc2s.sgov.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "portal.sso.{region}.sc2s.sgov.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIsoB, - IsRegionalized: true, - }, - { - ID: "aws-iso-e", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "portal.sso-fips.{region}.cloud.adc-e.uk", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "portal.sso.{region}.cloud.adc-e.uk", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIsoE, - IsRegionalized: true, - }, - { - ID: "aws-iso-f", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "portal.sso-fips.{region}.csp.hci.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "portal.sso.{region}.csp.hci.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIsoF, - IsRegionalized: true, - }, - { - ID: "aws-us-gov", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.DualStackVariant, - }: { - Hostname: "portal.sso.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "portal.sso-fips.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: { - Hostname: "portal.sso-fips.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "portal.sso.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsUsGov, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "us-gov-east-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.us-gov-east-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-gov-east-1", - }, - }, - endpoints.EndpointKey{ - Region: "us-gov-west-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.us-gov-west-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/serializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/serializers.go deleted file mode 100644 index 02e314115..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/serializers.go +++ /dev/null @@ -1,284 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sso - -import ( - "context" - "fmt" - smithy "github.com/aws/smithy-go" - "github.com/aws/smithy-go/encoding/httpbinding" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -type awsRestjson1_serializeOpGetRoleCredentials struct { -} - -func (*awsRestjson1_serializeOpGetRoleCredentials) ID() string { - return "OperationSerializer" -} - -func (m *awsRestjson1_serializeOpGetRoleCredentials) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - request, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} - } - - input, ok := in.Parameters.(*GetRoleCredentialsInput) - _ = input - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} - } - - opPath, opQuery := httpbinding.SplitURI("/federation/credentials") - request.URL.Path = smithyhttp.JoinPath(request.URL.Path, opPath) - request.URL.RawQuery = smithyhttp.JoinRawQuery(request.URL.RawQuery, opQuery) - request.Method = "GET" - var restEncoder *httpbinding.Encoder - if request.URL.RawPath == "" { - restEncoder, err = httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) - } else { - request.URL.RawPath = smithyhttp.JoinPath(request.URL.RawPath, opPath) - restEncoder, err = httpbinding.NewEncoderWithRawPath(request.URL.Path, request.URL.RawPath, request.URL.RawQuery, request.Header) - } - - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if err := awsRestjson1_serializeOpHttpBindingsGetRoleCredentialsInput(input, restEncoder); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request.Request, err = restEncoder.Encode(request.Request); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - in.Request = request - - return next.HandleSerialize(ctx, in) -} -func awsRestjson1_serializeOpHttpBindingsGetRoleCredentialsInput(v *GetRoleCredentialsInput, encoder *httpbinding.Encoder) error { - if v == nil { - return fmt.Errorf("unsupported serialization of nil %T", v) - } - - if v.AccessToken != nil && len(*v.AccessToken) > 0 { - locationName := "X-Amz-Sso_bearer_token" - encoder.SetHeader(locationName).String(*v.AccessToken) - } - - if v.AccountId != nil { - encoder.SetQuery("account_id").String(*v.AccountId) - } - - if v.RoleName != nil { - encoder.SetQuery("role_name").String(*v.RoleName) - } - - return nil -} - -type awsRestjson1_serializeOpListAccountRoles struct { -} - -func (*awsRestjson1_serializeOpListAccountRoles) ID() string { - return "OperationSerializer" -} - -func (m *awsRestjson1_serializeOpListAccountRoles) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - request, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} - } - - input, ok := in.Parameters.(*ListAccountRolesInput) - _ = input - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} - } - - opPath, opQuery := httpbinding.SplitURI("/assignment/roles") - request.URL.Path = smithyhttp.JoinPath(request.URL.Path, opPath) - request.URL.RawQuery = smithyhttp.JoinRawQuery(request.URL.RawQuery, opQuery) - request.Method = "GET" - var restEncoder *httpbinding.Encoder - if request.URL.RawPath == "" { - restEncoder, err = httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) - } else { - request.URL.RawPath = smithyhttp.JoinPath(request.URL.RawPath, opPath) - restEncoder, err = httpbinding.NewEncoderWithRawPath(request.URL.Path, request.URL.RawPath, request.URL.RawQuery, request.Header) - } - - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if err := awsRestjson1_serializeOpHttpBindingsListAccountRolesInput(input, restEncoder); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request.Request, err = restEncoder.Encode(request.Request); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - in.Request = request - - return next.HandleSerialize(ctx, in) -} -func awsRestjson1_serializeOpHttpBindingsListAccountRolesInput(v *ListAccountRolesInput, encoder *httpbinding.Encoder) error { - if v == nil { - return fmt.Errorf("unsupported serialization of nil %T", v) - } - - if v.AccessToken != nil && len(*v.AccessToken) > 0 { - locationName := "X-Amz-Sso_bearer_token" - encoder.SetHeader(locationName).String(*v.AccessToken) - } - - if v.AccountId != nil { - encoder.SetQuery("account_id").String(*v.AccountId) - } - - if v.MaxResults != nil { - encoder.SetQuery("max_result").Integer(*v.MaxResults) - } - - if v.NextToken != nil { - encoder.SetQuery("next_token").String(*v.NextToken) - } - - return nil -} - -type awsRestjson1_serializeOpListAccounts struct { -} - -func (*awsRestjson1_serializeOpListAccounts) ID() string { - return "OperationSerializer" -} - -func (m *awsRestjson1_serializeOpListAccounts) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - request, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} - } - - input, ok := in.Parameters.(*ListAccountsInput) - _ = input - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} - } - - opPath, opQuery := httpbinding.SplitURI("/assignment/accounts") - request.URL.Path = smithyhttp.JoinPath(request.URL.Path, opPath) - request.URL.RawQuery = smithyhttp.JoinRawQuery(request.URL.RawQuery, opQuery) - request.Method = "GET" - var restEncoder *httpbinding.Encoder - if request.URL.RawPath == "" { - restEncoder, err = httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) - } else { - request.URL.RawPath = smithyhttp.JoinPath(request.URL.RawPath, opPath) - restEncoder, err = httpbinding.NewEncoderWithRawPath(request.URL.Path, request.URL.RawPath, request.URL.RawQuery, request.Header) - } - - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if err := awsRestjson1_serializeOpHttpBindingsListAccountsInput(input, restEncoder); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request.Request, err = restEncoder.Encode(request.Request); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - in.Request = request - - return next.HandleSerialize(ctx, in) -} -func awsRestjson1_serializeOpHttpBindingsListAccountsInput(v *ListAccountsInput, encoder *httpbinding.Encoder) error { - if v == nil { - return fmt.Errorf("unsupported serialization of nil %T", v) - } - - if v.AccessToken != nil && len(*v.AccessToken) > 0 { - locationName := "X-Amz-Sso_bearer_token" - encoder.SetHeader(locationName).String(*v.AccessToken) - } - - if v.MaxResults != nil { - encoder.SetQuery("max_result").Integer(*v.MaxResults) - } - - if v.NextToken != nil { - encoder.SetQuery("next_token").String(*v.NextToken) - } - - return nil -} - -type awsRestjson1_serializeOpLogout struct { -} - -func (*awsRestjson1_serializeOpLogout) ID() string { - return "OperationSerializer" -} - -func (m *awsRestjson1_serializeOpLogout) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - request, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} - } - - input, ok := in.Parameters.(*LogoutInput) - _ = input - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} - } - - opPath, opQuery := httpbinding.SplitURI("/logout") - request.URL.Path = smithyhttp.JoinPath(request.URL.Path, opPath) - request.URL.RawQuery = smithyhttp.JoinRawQuery(request.URL.RawQuery, opQuery) - request.Method = "POST" - var restEncoder *httpbinding.Encoder - if request.URL.RawPath == "" { - restEncoder, err = httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) - } else { - request.URL.RawPath = smithyhttp.JoinPath(request.URL.RawPath, opPath) - restEncoder, err = httpbinding.NewEncoderWithRawPath(request.URL.Path, request.URL.RawPath, request.URL.RawQuery, request.Header) - } - - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if err := awsRestjson1_serializeOpHttpBindingsLogoutInput(input, restEncoder); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request.Request, err = restEncoder.Encode(request.Request); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - in.Request = request - - return next.HandleSerialize(ctx, in) -} -func awsRestjson1_serializeOpHttpBindingsLogoutInput(v *LogoutInput, encoder *httpbinding.Encoder) error { - if v == nil { - return fmt.Errorf("unsupported serialization of nil %T", v) - } - - if v.AccessToken != nil && len(*v.AccessToken) > 0 { - locationName := "X-Amz-Sso_bearer_token" - encoder.SetHeader(locationName).String(*v.AccessToken) - } - - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/types/errors.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/types/errors.go deleted file mode 100644 index e97a126e8..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/types/errors.go +++ /dev/null @@ -1,115 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package types - -import ( - "fmt" - smithy "github.com/aws/smithy-go" -) - -// Indicates that a problem occurred with the input to the request. For example, a -// required parameter might be missing or out of range. -type InvalidRequestException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidRequestException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidRequestException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidRequestException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidRequestException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidRequestException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The specified resource doesn't exist. -type ResourceNotFoundException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *ResourceNotFoundException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ResourceNotFoundException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ResourceNotFoundException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ResourceNotFoundException" - } - return *e.ErrorCodeOverride -} -func (e *ResourceNotFoundException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Indicates that the request is being made too frequently and is more than what -// the server can handle. -type TooManyRequestsException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *TooManyRequestsException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *TooManyRequestsException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *TooManyRequestsException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "TooManyRequestsException" - } - return *e.ErrorCodeOverride -} -func (e *TooManyRequestsException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Indicates that the request is not authorized. This can happen due to an invalid -// access token in the request. -type UnauthorizedException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *UnauthorizedException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *UnauthorizedException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *UnauthorizedException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "UnauthorizedException" - } - return *e.ErrorCodeOverride -} -func (e *UnauthorizedException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/types/types.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/types/types.go deleted file mode 100644 index 8dc02296b..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/types/types.go +++ /dev/null @@ -1,61 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package types - -import ( - smithydocument "github.com/aws/smithy-go/document" -) - -// Provides information about your AWS account. -type AccountInfo struct { - - // The identifier of the AWS account that is assigned to the user. - AccountId *string - - // The display name of the AWS account that is assigned to the user. - AccountName *string - - // The email address of the AWS account that is assigned to the user. - EmailAddress *string - - noSmithyDocumentSerde -} - -// Provides information about the role credentials that are assigned to the user. -type RoleCredentials struct { - - // The identifier used for the temporary security credentials. For more - // information, see Using Temporary Security Credentials to Request Access to AWS - // Resources (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html) - // in the AWS IAM User Guide. - AccessKeyId *string - - // The date on which temporary security credentials expire. - Expiration int64 - - // The key that is used to sign the request. For more information, see Using - // Temporary Security Credentials to Request Access to AWS Resources (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html) - // in the AWS IAM User Guide. - SecretAccessKey *string - - // The token used for temporary credentials. For more information, see Using - // Temporary Security Credentials to Request Access to AWS Resources (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html) - // in the AWS IAM User Guide. - SessionToken *string - - noSmithyDocumentSerde -} - -// Provides information about the role that is assigned to the user. -type RoleInfo struct { - - // The identifier of the AWS account assigned to the user. - AccountId *string - - // The friendly name of the role that is assigned to the user. - RoleName *string - - noSmithyDocumentSerde -} - -type noSmithyDocumentSerde = smithydocument.NoSerde diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/validators.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/validators.go deleted file mode 100644 index f6bf461f7..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/validators.go +++ /dev/null @@ -1,175 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sso - -import ( - "context" - "fmt" - smithy "github.com/aws/smithy-go" - "github.com/aws/smithy-go/middleware" -) - -type validateOpGetRoleCredentials struct { -} - -func (*validateOpGetRoleCredentials) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetRoleCredentials) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetRoleCredentialsInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetRoleCredentialsInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpListAccountRoles struct { -} - -func (*validateOpListAccountRoles) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpListAccountRoles) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*ListAccountRolesInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpListAccountRolesInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpListAccounts struct { -} - -func (*validateOpListAccounts) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpListAccounts) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*ListAccountsInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpListAccountsInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpLogout struct { -} - -func (*validateOpLogout) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpLogout) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*LogoutInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpLogoutInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -func addOpGetRoleCredentialsValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetRoleCredentials{}, middleware.After) -} - -func addOpListAccountRolesValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpListAccountRoles{}, middleware.After) -} - -func addOpListAccountsValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpListAccounts{}, middleware.After) -} - -func addOpLogoutValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpLogout{}, middleware.After) -} - -func validateOpGetRoleCredentialsInput(v *GetRoleCredentialsInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetRoleCredentialsInput"} - if v.RoleName == nil { - invalidParams.Add(smithy.NewErrParamRequired("RoleName")) - } - if v.AccountId == nil { - invalidParams.Add(smithy.NewErrParamRequired("AccountId")) - } - if v.AccessToken == nil { - invalidParams.Add(smithy.NewErrParamRequired("AccessToken")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpListAccountRolesInput(v *ListAccountRolesInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ListAccountRolesInput"} - if v.AccessToken == nil { - invalidParams.Add(smithy.NewErrParamRequired("AccessToken")) - } - if v.AccountId == nil { - invalidParams.Add(smithy.NewErrParamRequired("AccountId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpListAccountsInput(v *ListAccountsInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ListAccountsInput"} - if v.AccessToken == nil { - invalidParams.Add(smithy.NewErrParamRequired("AccessToken")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpLogoutInput(v *LogoutInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "LogoutInput"} - if v.AccessToken == nil { - invalidParams.Add(smithy.NewErrParamRequired("AccessToken")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/CHANGELOG.md deleted file mode 100644 index 608ac60ce..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/CHANGELOG.md +++ /dev/null @@ -1,278 +0,0 @@ -# v1.15.5 (2023-08-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.4 (2023-08-18) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.3 (2023-08-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.2 (2023-08-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.1 (2023-08-01) - -* No change notes available for this release. - -# v1.15.0 (2023-07-31) - -* **Feature**: Adds support for smithy-modeled endpoint resolution. A new rules-based endpoint resolution will be added to the SDK which will supercede and deprecate existing endpoint resolution. Specifically, EndpointResolver will be deprecated while BaseEndpoint and EndpointResolverV2 will take its place. For more information, please see the Endpoints section in our Developer Guide. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.14 (2023-07-28) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.13 (2023-07-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.12 (2023-06-15) - -* No change notes available for this release. - -# v1.14.11 (2023-06-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.10 (2023-05-04) - -* No change notes available for this release. - -# v1.14.9 (2023-04-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.8 (2023-04-10) - -* No change notes available for this release. - -# v1.14.7 (2023-04-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.6 (2023-03-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.5 (2023-03-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.4 (2023-02-22) - -* **Bug Fix**: Prevent nil pointer dereference when retrieving error codes. - -# v1.14.3 (2023-02-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.2 (2023-02-15) - -* **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. -* **Bug Fix**: Correct error type parsing for restJson services. - -# v1.14.1 (2023-02-03) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.0 (2023-01-05) - -* **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). - -# v1.13.11 (2022-12-19) - -* No change notes available for this release. - -# v1.13.10 (2022-12-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.9 (2022-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.8 (2022-10-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.7 (2022-10-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.6 (2022-09-30) - -* **Documentation**: Documentation updates for the IAM Identity Center OIDC CLI Reference. - -# v1.13.5 (2022-09-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.4 (2022-09-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.3 (2022-09-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.2 (2022-08-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.1 (2022-08-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.0 (2022-08-25) - -* **Feature**: Updated required request parameters on IAM Identity Center's OIDC CreateToken action. - -# v1.12.14 (2022-08-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.13 (2022-08-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.12 (2022-08-08) - -* **Documentation**: Documentation updates to reflect service rename - AWS IAM Identity Center (successor to AWS Single Sign-On) -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.11 (2022-08-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.10 (2022-07-11) - -* No change notes available for this release. - -# v1.12.9 (2022-07-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.8 (2022-06-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.7 (2022-06-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.6 (2022-05-27) - -* No change notes available for this release. - -# v1.12.5 (2022-05-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.4 (2022-04-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.3 (2022-03-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.2 (2022-03-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.1 (2022-03-23) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.0 (2022-03-08) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.0 (2022-02-24) - -* **Feature**: API client updated -* **Feature**: Adds RetryMaxAttempts and RetryMod to API client Options. This allows the API clients' default Retryer to be configured from the shared configuration files or environment variables. Adding a new Retry mode of `Adaptive`. `Adaptive` retry mode is an experimental mode, adding client rate limiting when throttles reponses are received from an API. See [retry.AdaptiveMode](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/aws/retry#AdaptiveMode) for more details, and configuration options. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.0 (2022-01-14) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.0 (2022-01-07) - -* **Feature**: API client updated -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.2 (2021-12-02) - -* **Bug Fix**: Fixes a bug that prevented aws.EndpointResolverWithOptions from being used by the service client. ([#1514](https://github.com/aws/aws-sdk-go-v2/pull/1514)) -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.1 (2021-11-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.0 (2021-11-06) - -* **Feature**: The SDK now supports configuration of FIPS and DualStack endpoints using environment variables, shared configuration, or programmatically. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.7.0 (2021-10-21) - -* **Feature**: Updated to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.0 (2021-10-11) - -* **Feature**: API client updated -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.5.0 (2021-09-17) - -* **Feature**: Updated API client and endpoints to latest revision. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.0 (2021-08-27) - -* **Feature**: Updated API model to latest revision. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.3 (2021-08-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.2 (2021-08-04) - -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.1 (2021-07-15) - -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.0 (2021-06-25) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.1 (2021-05-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.0 (2021-05-14) - -* **Feature**: Constant has been added to modules to enable runtime version inspection for reporting. -* **Dependency Update**: Updated to the latest SDK module versions - diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/LICENSE.txt deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/LICENSE.txt +++ /dev/null @@ -1,202 +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/aws/aws-sdk-go-v2/service/ssooidc/api_client.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_client.go deleted file mode 100644 index 24a692276..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_client.go +++ /dev/null @@ -1,525 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssooidc - -import ( - "context" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/aws/defaults" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/retry" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" - internalConfig "github.com/aws/aws-sdk-go-v2/internal/configsources" - smithy "github.com/aws/smithy-go" - smithydocument "github.com/aws/smithy-go/document" - "github.com/aws/smithy-go/logging" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" - "net" - "net/http" - "time" -) - -const ServiceID = "SSO OIDC" -const ServiceAPIVersion = "2019-06-10" - -// Client provides the API client to make operations call for AWS SSO OIDC. -type Client struct { - options Options -} - -// New returns an initialized Client based on the functional options. Provide -// additional functional options to further configure the behavior of the client, -// such as changing the client's endpoint or adding custom middleware behavior. -func New(options Options, optFns ...func(*Options)) *Client { - options = options.Copy() - - resolveDefaultLogger(&options) - - setResolvedDefaultsMode(&options) - - resolveRetryer(&options) - - resolveHTTPClient(&options) - - resolveHTTPSignerV4(&options) - - for _, fn := range optFns { - fn(&options) - } - - client := &Client{ - options: options, - } - - return client -} - -type Options struct { - // Set of options to modify how an operation is invoked. These apply to all - // operations invoked for this client. Use functional options on operation call to - // modify this list for per operation behavior. - APIOptions []func(*middleware.Stack) error - - // The optional application specific identifier appended to the User-Agent header. - AppID string - - // This endpoint will be given as input to an EndpointResolverV2. It is used for - // providing a custom base endpoint that is subject to modifications by the - // processing EndpointResolverV2. - BaseEndpoint *string - - // Configures the events that will be sent to the configured logger. - ClientLogMode aws.ClientLogMode - - // The credentials object to use when signing requests. - Credentials aws.CredentialsProvider - - // The configuration DefaultsMode that the SDK should use when constructing the - // clients initial default settings. - DefaultsMode aws.DefaultsMode - - // The endpoint options to be used when attempting to resolve an endpoint. - EndpointOptions EndpointResolverOptions - - // The service endpoint resolver. - // - // Deprecated: Deprecated: EndpointResolver and WithEndpointResolver. Providing a - // value for this field will likely prevent you from using any endpoint-related - // service features released after the introduction of EndpointResolverV2 and - // BaseEndpoint. To migrate an EndpointResolver implementation that uses a custom - // endpoint, set the client option BaseEndpoint instead. - EndpointResolver EndpointResolver - - // Resolves the endpoint used for a particular service. This should be used over - // the deprecated EndpointResolver - EndpointResolverV2 EndpointResolverV2 - - // Signature Version 4 (SigV4) Signer - HTTPSignerV4 HTTPSignerV4 - - // The logger writer interface to write logging messages to. - Logger logging.Logger - - // The region to send requests to. (Required) - Region string - - // RetryMaxAttempts specifies the maximum number attempts an API client will call - // an operation that fails with a retryable error. A value of 0 is ignored, and - // will not be used to configure the API client created default retryer, or modify - // per operation call's retry max attempts. When creating a new API Clients this - // member will only be used if the Retryer Options member is nil. This value will - // be ignored if Retryer is not nil. If specified in an operation call's functional - // options with a value that is different than the constructed client's Options, - // the Client's Retryer will be wrapped to use the operation's specific - // RetryMaxAttempts value. - RetryMaxAttempts int - - // RetryMode specifies the retry mode the API client will be created with, if - // Retryer option is not also specified. When creating a new API Clients this - // member will only be used if the Retryer Options member is nil. This value will - // be ignored if Retryer is not nil. Currently does not support per operation call - // overrides, may in the future. - RetryMode aws.RetryMode - - // Retryer guides how HTTP requests should be retried in case of recoverable - // failures. When nil the API client will use a default retryer. The kind of - // default retry created by the API client can be changed with the RetryMode - // option. - Retryer aws.Retryer - - // The RuntimeEnvironment configuration, only populated if the DefaultsMode is set - // to DefaultsModeAuto and is initialized using config.LoadDefaultConfig . You - // should not populate this structure programmatically, or rely on the values here - // within your applications. - RuntimeEnvironment aws.RuntimeEnvironment - - // The initial DefaultsMode used when the client options were constructed. If the - // DefaultsMode was set to aws.DefaultsModeAuto this will store what the resolved - // value was at that point in time. Currently does not support per operation call - // overrides, may in the future. - resolvedDefaultsMode aws.DefaultsMode - - // The HTTP client to invoke API calls with. Defaults to client's default HTTP - // implementation if nil. - HTTPClient HTTPClient -} - -// WithAPIOptions returns a functional option for setting the Client's APIOptions -// option. -func WithAPIOptions(optFns ...func(*middleware.Stack) error) func(*Options) { - return func(o *Options) { - o.APIOptions = append(o.APIOptions, optFns...) - } -} - -// Deprecated: EndpointResolver and WithEndpointResolver. Providing a value for -// this field will likely prevent you from using any endpoint-related service -// features released after the introduction of EndpointResolverV2 and BaseEndpoint. -// To migrate an EndpointResolver implementation that uses a custom endpoint, set -// the client option BaseEndpoint instead. -func WithEndpointResolver(v EndpointResolver) func(*Options) { - return func(o *Options) { - o.EndpointResolver = v - } -} - -// WithEndpointResolverV2 returns a functional option for setting the Client's -// EndpointResolverV2 option. -func WithEndpointResolverV2(v EndpointResolverV2) func(*Options) { - return func(o *Options) { - o.EndpointResolverV2 = v - } -} - -type HTTPClient interface { - Do(*http.Request) (*http.Response, error) -} - -// Copy creates a clone where the APIOptions list is deep copied. -func (o Options) Copy() Options { - to := o - to.APIOptions = make([]func(*middleware.Stack) error, len(o.APIOptions)) - copy(to.APIOptions, o.APIOptions) - - return to -} -func (c *Client) invokeOperation(ctx context.Context, opID string, params interface{}, optFns []func(*Options), stackFns ...func(*middleware.Stack, Options) error) (result interface{}, metadata middleware.Metadata, err error) { - ctx = middleware.ClearStackValues(ctx) - stack := middleware.NewStack(opID, smithyhttp.NewStackRequest) - options := c.options.Copy() - resolveEndpointResolverV2(&options) - - for _, fn := range optFns { - fn(&options) - } - - finalizeRetryMaxAttemptOptions(&options, *c) - - finalizeClientEndpointResolverOptions(&options) - - for _, fn := range stackFns { - if err := fn(stack, options); err != nil { - return nil, metadata, err - } - } - - for _, fn := range options.APIOptions { - if err := fn(stack); err != nil { - return nil, metadata, err - } - } - - handler := middleware.DecorateHandler(smithyhttp.NewClientHandler(options.HTTPClient), stack) - result, metadata, err = handler.Handle(ctx, params) - if err != nil { - err = &smithy.OperationError{ - ServiceID: ServiceID, - OperationName: opID, - Err: err, - } - } - return result, metadata, err -} - -type noSmithyDocumentSerde = smithydocument.NoSerde - -type legacyEndpointContextSetter struct { - LegacyResolver EndpointResolver -} - -func (*legacyEndpointContextSetter) ID() string { - return "legacyEndpointContextSetter" -} - -func (m *legacyEndpointContextSetter) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - if m.LegacyResolver != nil { - ctx = awsmiddleware.SetRequiresLegacyEndpoints(ctx, true) - } - - return next.HandleInitialize(ctx, in) - -} -func addlegacyEndpointContextSetter(stack *middleware.Stack, o Options) error { - return stack.Initialize.Add(&legacyEndpointContextSetter{ - LegacyResolver: o.EndpointResolver, - }, middleware.Before) -} - -func resolveDefaultLogger(o *Options) { - if o.Logger != nil { - return - } - o.Logger = logging.Nop{} -} - -func addSetLoggerMiddleware(stack *middleware.Stack, o Options) error { - return middleware.AddSetLoggerMiddleware(stack, o.Logger) -} - -func setResolvedDefaultsMode(o *Options) { - if len(o.resolvedDefaultsMode) > 0 { - return - } - - var mode aws.DefaultsMode - mode.SetFromString(string(o.DefaultsMode)) - - if mode == aws.DefaultsModeAuto { - mode = defaults.ResolveDefaultsModeAuto(o.Region, o.RuntimeEnvironment) - } - - o.resolvedDefaultsMode = mode -} - -// NewFromConfig returns a new client from the provided config. -func NewFromConfig(cfg aws.Config, optFns ...func(*Options)) *Client { - opts := Options{ - Region: cfg.Region, - DefaultsMode: cfg.DefaultsMode, - RuntimeEnvironment: cfg.RuntimeEnvironment, - HTTPClient: cfg.HTTPClient, - Credentials: cfg.Credentials, - APIOptions: cfg.APIOptions, - Logger: cfg.Logger, - ClientLogMode: cfg.ClientLogMode, - AppID: cfg.AppID, - } - resolveAWSRetryerProvider(cfg, &opts) - resolveAWSRetryMaxAttempts(cfg, &opts) - resolveAWSRetryMode(cfg, &opts) - resolveAWSEndpointResolver(cfg, &opts) - resolveUseDualStackEndpoint(cfg, &opts) - resolveUseFIPSEndpoint(cfg, &opts) - return New(opts, optFns...) -} - -func resolveHTTPClient(o *Options) { - var buildable *awshttp.BuildableClient - - if o.HTTPClient != nil { - var ok bool - buildable, ok = o.HTTPClient.(*awshttp.BuildableClient) - if !ok { - return - } - } else { - buildable = awshttp.NewBuildableClient() - } - - modeConfig, err := defaults.GetModeConfiguration(o.resolvedDefaultsMode) - if err == nil { - buildable = buildable.WithDialerOptions(func(dialer *net.Dialer) { - if dialerTimeout, ok := modeConfig.GetConnectTimeout(); ok { - dialer.Timeout = dialerTimeout - } - }) - - buildable = buildable.WithTransportOptions(func(transport *http.Transport) { - if tlsHandshakeTimeout, ok := modeConfig.GetTLSNegotiationTimeout(); ok { - transport.TLSHandshakeTimeout = tlsHandshakeTimeout - } - }) - } - - o.HTTPClient = buildable -} - -func resolveRetryer(o *Options) { - if o.Retryer != nil { - return - } - - if len(o.RetryMode) == 0 { - modeConfig, err := defaults.GetModeConfiguration(o.resolvedDefaultsMode) - if err == nil { - o.RetryMode = modeConfig.RetryMode - } - } - if len(o.RetryMode) == 0 { - o.RetryMode = aws.RetryModeStandard - } - - var standardOptions []func(*retry.StandardOptions) - if v := o.RetryMaxAttempts; v != 0 { - standardOptions = append(standardOptions, func(so *retry.StandardOptions) { - so.MaxAttempts = v - }) - } - - switch o.RetryMode { - case aws.RetryModeAdaptive: - var adaptiveOptions []func(*retry.AdaptiveModeOptions) - if len(standardOptions) != 0 { - adaptiveOptions = append(adaptiveOptions, func(ao *retry.AdaptiveModeOptions) { - ao.StandardOptions = append(ao.StandardOptions, standardOptions...) - }) - } - o.Retryer = retry.NewAdaptiveMode(adaptiveOptions...) - - default: - o.Retryer = retry.NewStandard(standardOptions...) - } -} - -func resolveAWSRetryerProvider(cfg aws.Config, o *Options) { - if cfg.Retryer == nil { - return - } - o.Retryer = cfg.Retryer() -} - -func resolveAWSRetryMode(cfg aws.Config, o *Options) { - if len(cfg.RetryMode) == 0 { - return - } - o.RetryMode = cfg.RetryMode -} -func resolveAWSRetryMaxAttempts(cfg aws.Config, o *Options) { - if cfg.RetryMaxAttempts == 0 { - return - } - o.RetryMaxAttempts = cfg.RetryMaxAttempts -} - -func finalizeRetryMaxAttemptOptions(o *Options, client Client) { - if v := o.RetryMaxAttempts; v == 0 || v == client.options.RetryMaxAttempts { - return - } - - o.Retryer = retry.AddWithMaxAttempts(o.Retryer, o.RetryMaxAttempts) -} - -func resolveAWSEndpointResolver(cfg aws.Config, o *Options) { - if cfg.EndpointResolver == nil && cfg.EndpointResolverWithOptions == nil { - return - } - o.EndpointResolver = withEndpointResolver(cfg.EndpointResolver, cfg.EndpointResolverWithOptions) -} - -func addClientUserAgent(stack *middleware.Stack, options Options) error { - if err := awsmiddleware.AddSDKAgentKeyValue(awsmiddleware.APIMetadata, "ssooidc", goModuleVersion)(stack); err != nil { - return err - } - - if len(options.AppID) > 0 { - return awsmiddleware.AddSDKAgentKey(awsmiddleware.ApplicationIdentifier, options.AppID)(stack) - } - - return nil -} - -func addHTTPSignerV4Middleware(stack *middleware.Stack, o Options) error { - mw := v4.NewSignHTTPRequestMiddleware(v4.SignHTTPRequestMiddlewareOptions{ - CredentialsProvider: o.Credentials, - Signer: o.HTTPSignerV4, - LogSigning: o.ClientLogMode.IsSigning(), - }) - return stack.Finalize.Add(mw, middleware.After) -} - -type HTTPSignerV4 interface { - SignHTTP(ctx context.Context, credentials aws.Credentials, r *http.Request, payloadHash string, service string, region string, signingTime time.Time, optFns ...func(*v4.SignerOptions)) error -} - -func resolveHTTPSignerV4(o *Options) { - if o.HTTPSignerV4 != nil { - return - } - o.HTTPSignerV4 = newDefaultV4Signer(*o) -} - -func newDefaultV4Signer(o Options) *v4.Signer { - return v4.NewSigner(func(so *v4.SignerOptions) { - so.Logger = o.Logger - so.LogSigning = o.ClientLogMode.IsSigning() - }) -} - -func addRetryMiddlewares(stack *middleware.Stack, o Options) error { - mo := retry.AddRetryMiddlewaresOptions{ - Retryer: o.Retryer, - LogRetryAttempts: o.ClientLogMode.IsRetries(), - } - return retry.AddRetryMiddlewares(stack, mo) -} - -// resolves dual-stack endpoint configuration -func resolveUseDualStackEndpoint(cfg aws.Config, o *Options) error { - if len(cfg.ConfigSources) == 0 { - return nil - } - value, found, err := internalConfig.ResolveUseDualStackEndpoint(context.Background(), cfg.ConfigSources) - if err != nil { - return err - } - if found { - o.EndpointOptions.UseDualStackEndpoint = value - } - return nil -} - -// resolves FIPS endpoint configuration -func resolveUseFIPSEndpoint(cfg aws.Config, o *Options) error { - if len(cfg.ConfigSources) == 0 { - return nil - } - value, found, err := internalConfig.ResolveUseFIPSEndpoint(context.Background(), cfg.ConfigSources) - if err != nil { - return err - } - if found { - o.EndpointOptions.UseFIPSEndpoint = value - } - return nil -} - -func addRequestIDRetrieverMiddleware(stack *middleware.Stack) error { - return awsmiddleware.AddRequestIDRetrieverMiddleware(stack) -} - -func addResponseErrorMiddleware(stack *middleware.Stack) error { - return awshttp.AddResponseErrorMiddleware(stack) -} - -func addRequestResponseLogging(stack *middleware.Stack, o Options) error { - return stack.Deserialize.Add(&smithyhttp.RequestResponseLogger{ - LogRequest: o.ClientLogMode.IsRequest(), - LogRequestWithBody: o.ClientLogMode.IsRequestWithBody(), - LogResponse: o.ClientLogMode.IsResponse(), - LogResponseWithBody: o.ClientLogMode.IsResponseWithBody(), - }, middleware.After) -} - -type endpointDisableHTTPSMiddleware struct { - EndpointDisableHTTPS bool -} - -func (*endpointDisableHTTPSMiddleware) ID() string { - return "endpointDisableHTTPSMiddleware" -} - -func (m *endpointDisableHTTPSMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointDisableHTTPS && !smithyhttp.GetHostnameImmutable(ctx) { - req.URL.Scheme = "http" - } - - return next.HandleSerialize(ctx, in) - -} -func addendpointDisableHTTPSMiddleware(stack *middleware.Stack, o Options) error { - return stack.Serialize.Insert(&endpointDisableHTTPSMiddleware{ - EndpointDisableHTTPS: o.EndpointOptions.DisableHTTPS, - }, "OperationSerializer", middleware.Before) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_CreateToken.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_CreateToken.go deleted file mode 100644 index 43df6256c..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_CreateToken.go +++ /dev/null @@ -1,316 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssooidc - -import ( - "context" - "errors" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Creates and returns an access token for the authorized client. The access token -// issued will be used to fetch short-term credentials for the assigned roles in -// the AWS account. -func (c *Client) CreateToken(ctx context.Context, params *CreateTokenInput, optFns ...func(*Options)) (*CreateTokenOutput, error) { - if params == nil { - params = &CreateTokenInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "CreateToken", params, optFns, c.addOperationCreateTokenMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*CreateTokenOutput) - out.ResultMetadata = metadata - return out, nil -} - -type CreateTokenInput struct { - - // The unique identifier string for each client. This value should come from the - // persisted result of the RegisterClient API. - // - // This member is required. - ClientId *string - - // A secret string generated for the client. This value should come from the - // persisted result of the RegisterClient API. - // - // This member is required. - ClientSecret *string - - // Supports grant types for the authorization code, refresh token, and device code - // request. For device code requests, specify the following value: - // urn:ietf:params:oauth:grant-type:device_code For information about how to - // obtain the device code, see the StartDeviceAuthorization topic. - // - // This member is required. - GrantType *string - - // The authorization code received from the authorization service. This parameter - // is required to perform an authorization grant request to get access to a token. - Code *string - - // Used only when calling this API for the device code grant type. This short-term - // code is used to identify this authentication attempt. This should come from an - // in-memory reference to the result of the StartDeviceAuthorization API. - DeviceCode *string - - // The location of the application that will receive the authorization code. Users - // authorize the service to send the request to this location. - RedirectUri *string - - // Currently, refreshToken is not yet implemented and is not supported. For more - // information about the features and limitations of the current IAM Identity - // Center OIDC implementation, see Considerations for Using this Guide in the IAM - // Identity Center OIDC API Reference (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/Welcome.html) - // . The token used to obtain an access token in the event that the access token is - // invalid or expired. - RefreshToken *string - - // The list of scopes that is defined by the client. Upon authorization, this list - // is used to restrict permissions when granting an access token. - Scope []string - - noSmithyDocumentSerde -} - -type CreateTokenOutput struct { - - // An opaque token to access IAM Identity Center resources assigned to a user. - AccessToken *string - - // Indicates the time in seconds when an access token will expire. - ExpiresIn int32 - - // Currently, idToken is not yet implemented and is not supported. For more - // information about the features and limitations of the current IAM Identity - // Center OIDC implementation, see Considerations for Using this Guide in the IAM - // Identity Center OIDC API Reference (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/Welcome.html) - // . The identifier of the user that associated with the access token, if present. - IdToken *string - - // Currently, refreshToken is not yet implemented and is not supported. For more - // information about the features and limitations of the current IAM Identity - // Center OIDC implementation, see Considerations for Using this Guide in the IAM - // Identity Center OIDC API Reference (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/Welcome.html) - // . A token that, if present, can be used to refresh a previously issued access - // token that might have expired. - RefreshToken *string - - // Used to notify the client that the returned token is an access token. The - // supported type is BearerToken . - TokenType *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationCreateTokenMiddlewares(stack *middleware.Stack, options Options) (err error) { - err = stack.Serialize.Add(&awsRestjson1_serializeOpCreateToken{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsRestjson1_deserializeOpCreateToken{}, middleware.After) - if err != nil { - return err - } - if err = addlegacyEndpointContextSetter(stack, options); err != nil { - return err - } - if err = addSetLoggerMiddleware(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { - return err - } - if err = addClientUserAgent(stack, options); err != nil { - return err - } - if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = addCreateTokenResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addOpCreateTokenValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateToken(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { - return err - } - if err = addRequestIDRetrieverMiddleware(stack); err != nil { - return err - } - if err = addResponseErrorMiddleware(stack); err != nil { - return err - } - if err = addRequestResponseLogging(stack, options); err != nil { - return err - } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { - return err - } - return nil -} - -func newServiceMetadataMiddleware_opCreateToken(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "CreateToken", - } -} - -type opCreateTokenResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opCreateTokenResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opCreateTokenResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "awsssooidc" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "awsssooidc" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("awsssooidc") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addCreateTokenResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opCreateTokenResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_RegisterClient.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_RegisterClient.go deleted file mode 100644 index b88ebb706..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_RegisterClient.go +++ /dev/null @@ -1,281 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssooidc - -import ( - "context" - "errors" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Registers a client with IAM Identity Center. This allows clients to initiate -// device authorization. The output should be persisted for reuse through many -// authentication requests. -func (c *Client) RegisterClient(ctx context.Context, params *RegisterClientInput, optFns ...func(*Options)) (*RegisterClientOutput, error) { - if params == nil { - params = &RegisterClientInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "RegisterClient", params, optFns, c.addOperationRegisterClientMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*RegisterClientOutput) - out.ResultMetadata = metadata - return out, nil -} - -type RegisterClientInput struct { - - // The friendly name of the client. - // - // This member is required. - ClientName *string - - // The type of client. The service supports only public as a client type. Anything - // other than public will be rejected by the service. - // - // This member is required. - ClientType *string - - // The list of scopes that are defined by the client. Upon authorization, this - // list is used to restrict permissions when granting an access token. - Scopes []string - - noSmithyDocumentSerde -} - -type RegisterClientOutput struct { - - // The endpoint where the client can request authorization. - AuthorizationEndpoint *string - - // The unique identifier string for each client. This client uses this identifier - // to get authenticated by the service in subsequent calls. - ClientId *string - - // Indicates the time at which the clientId and clientSecret were issued. - ClientIdIssuedAt int64 - - // A secret string generated for the client. The client will use this string to - // get authenticated by the service in subsequent calls. - ClientSecret *string - - // Indicates the time at which the clientId and clientSecret will become invalid. - ClientSecretExpiresAt int64 - - // The endpoint where the client can get an access token. - TokenEndpoint *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationRegisterClientMiddlewares(stack *middleware.Stack, options Options) (err error) { - err = stack.Serialize.Add(&awsRestjson1_serializeOpRegisterClient{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsRestjson1_deserializeOpRegisterClient{}, middleware.After) - if err != nil { - return err - } - if err = addlegacyEndpointContextSetter(stack, options); err != nil { - return err - } - if err = addSetLoggerMiddleware(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { - return err - } - if err = addClientUserAgent(stack, options); err != nil { - return err - } - if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = addRegisterClientResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addOpRegisterClientValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opRegisterClient(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { - return err - } - if err = addRequestIDRetrieverMiddleware(stack); err != nil { - return err - } - if err = addResponseErrorMiddleware(stack); err != nil { - return err - } - if err = addRequestResponseLogging(stack, options); err != nil { - return err - } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { - return err - } - return nil -} - -func newServiceMetadataMiddleware_opRegisterClient(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "RegisterClient", - } -} - -type opRegisterClientResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opRegisterClientResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opRegisterClientResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "awsssooidc" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "awsssooidc" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("awsssooidc") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addRegisterClientResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opRegisterClientResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_StartDeviceAuthorization.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_StartDeviceAuthorization.go deleted file mode 100644 index 327da5f73..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_StartDeviceAuthorization.go +++ /dev/null @@ -1,289 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssooidc - -import ( - "context" - "errors" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Initiates device authorization by requesting a pair of verification codes from -// the authorization service. -func (c *Client) StartDeviceAuthorization(ctx context.Context, params *StartDeviceAuthorizationInput, optFns ...func(*Options)) (*StartDeviceAuthorizationOutput, error) { - if params == nil { - params = &StartDeviceAuthorizationInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "StartDeviceAuthorization", params, optFns, c.addOperationStartDeviceAuthorizationMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*StartDeviceAuthorizationOutput) - out.ResultMetadata = metadata - return out, nil -} - -type StartDeviceAuthorizationInput struct { - - // The unique identifier string for the client that is registered with IAM - // Identity Center. This value should come from the persisted result of the - // RegisterClient API operation. - // - // This member is required. - ClientId *string - - // A secret string that is generated for the client. This value should come from - // the persisted result of the RegisterClient API operation. - // - // This member is required. - ClientSecret *string - - // The URL for the AWS access portal. For more information, see Using the AWS - // access portal (https://docs.aws.amazon.com/singlesignon/latest/userguide/using-the-portal.html) - // in the IAM Identity Center User Guide. - // - // This member is required. - StartUrl *string - - noSmithyDocumentSerde -} - -type StartDeviceAuthorizationOutput struct { - - // The short-lived code that is used by the device when polling for a session - // token. - DeviceCode *string - - // Indicates the number of seconds in which the verification code will become - // invalid. - ExpiresIn int32 - - // Indicates the number of seconds the client must wait between attempts when - // polling for a session. - Interval int32 - - // A one-time user verification code. This is needed to authorize an in-use device. - UserCode *string - - // The URI of the verification page that takes the userCode to authorize the - // device. - VerificationUri *string - - // An alternate URL that the client can use to automatically launch a browser. - // This process skips the manual step in which the user visits the verification - // page and enters their code. - VerificationUriComplete *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationStartDeviceAuthorizationMiddlewares(stack *middleware.Stack, options Options) (err error) { - err = stack.Serialize.Add(&awsRestjson1_serializeOpStartDeviceAuthorization{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsRestjson1_deserializeOpStartDeviceAuthorization{}, middleware.After) - if err != nil { - return err - } - if err = addlegacyEndpointContextSetter(stack, options); err != nil { - return err - } - if err = addSetLoggerMiddleware(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { - return err - } - if err = addClientUserAgent(stack, options); err != nil { - return err - } - if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = addStartDeviceAuthorizationResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addOpStartDeviceAuthorizationValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opStartDeviceAuthorization(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { - return err - } - if err = addRequestIDRetrieverMiddleware(stack); err != nil { - return err - } - if err = addResponseErrorMiddleware(stack); err != nil { - return err - } - if err = addRequestResponseLogging(stack, options); err != nil { - return err - } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { - return err - } - return nil -} - -func newServiceMetadataMiddleware_opStartDeviceAuthorization(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "StartDeviceAuthorization", - } -} - -type opStartDeviceAuthorizationResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opStartDeviceAuthorizationResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opStartDeviceAuthorizationResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "awsssooidc" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "awsssooidc" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("awsssooidc") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addStartDeviceAuthorizationResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opStartDeviceAuthorizationResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/deserializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/deserializers.go deleted file mode 100644 index ca30d22f9..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/deserializers.go +++ /dev/null @@ -1,1689 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssooidc - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws/protocol/restjson" - "github.com/aws/aws-sdk-go-v2/service/ssooidc/types" - smithy "github.com/aws/smithy-go" - smithyio "github.com/aws/smithy-go/io" - "github.com/aws/smithy-go/middleware" - "github.com/aws/smithy-go/ptr" - smithyhttp "github.com/aws/smithy-go/transport/http" - "io" - "strings" -) - -type awsRestjson1_deserializeOpCreateToken struct { -} - -func (*awsRestjson1_deserializeOpCreateToken) ID() string { - return "OperationDeserializer" -} - -func (m *awsRestjson1_deserializeOpCreateToken) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( - out middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err = next.HandleDeserialize(ctx, in) - if err != nil { - return out, metadata, err - } - - response, ok := out.RawResponse.(*smithyhttp.Response) - if !ok { - return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} - } - - if response.StatusCode < 200 || response.StatusCode >= 300 { - return out, metadata, awsRestjson1_deserializeOpErrorCreateToken(response, &metadata) - } - output := &CreateTokenOutput{} - out.Result = output - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(response.Body, ringBuffer) - - decoder := json.NewDecoder(body) - decoder.UseNumber() - var shape interface{} - if err := decoder.Decode(&shape); err != nil && err != io.EOF { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return out, metadata, err - } - - err = awsRestjson1_deserializeOpDocumentCreateTokenOutput(&output, shape) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return out, metadata, err -} - -func awsRestjson1_deserializeOpErrorCreateToken(response *smithyhttp.Response, metadata *middleware.Metadata) error { - var errorBuffer bytes.Buffer - if _, err := io.Copy(&errorBuffer, response.Body); err != nil { - return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} - } - errorBody := bytes.NewReader(errorBuffer.Bytes()) - - errorCode := "UnknownError" - errorMessage := errorCode - - headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("AccessDeniedException", errorCode): - return awsRestjson1_deserializeErrorAccessDeniedException(response, errorBody) - - case strings.EqualFold("AuthorizationPendingException", errorCode): - return awsRestjson1_deserializeErrorAuthorizationPendingException(response, errorBody) - - case strings.EqualFold("ExpiredTokenException", errorCode): - return awsRestjson1_deserializeErrorExpiredTokenException(response, errorBody) - - case strings.EqualFold("InternalServerException", errorCode): - return awsRestjson1_deserializeErrorInternalServerException(response, errorBody) - - case strings.EqualFold("InvalidClientException", errorCode): - return awsRestjson1_deserializeErrorInvalidClientException(response, errorBody) - - case strings.EqualFold("InvalidGrantException", errorCode): - return awsRestjson1_deserializeErrorInvalidGrantException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsRestjson1_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("InvalidScopeException", errorCode): - return awsRestjson1_deserializeErrorInvalidScopeException(response, errorBody) - - case strings.EqualFold("SlowDownException", errorCode): - return awsRestjson1_deserializeErrorSlowDownException(response, errorBody) - - case strings.EqualFold("UnauthorizedClientException", errorCode): - return awsRestjson1_deserializeErrorUnauthorizedClientException(response, errorBody) - - case strings.EqualFold("UnsupportedGrantTypeException", errorCode): - return awsRestjson1_deserializeErrorUnsupportedGrantTypeException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -func awsRestjson1_deserializeOpDocumentCreateTokenOutput(v **CreateTokenOutput, value interface{}) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - if value == nil { - return nil - } - - shape, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var sv *CreateTokenOutput - if *v == nil { - sv = &CreateTokenOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "accessToken": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AccessToken to be of type string, got %T instead", value) - } - sv.AccessToken = ptr.String(jtv) - } - - case "expiresIn": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected ExpirationInSeconds to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.ExpiresIn = int32(i64) - } - - case "idToken": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected IdToken to be of type string, got %T instead", value) - } - sv.IdToken = ptr.String(jtv) - } - - case "refreshToken": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected RefreshToken to be of type string, got %T instead", value) - } - sv.RefreshToken = ptr.String(jtv) - } - - case "tokenType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected TokenType to be of type string, got %T instead", value) - } - sv.TokenType = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -type awsRestjson1_deserializeOpRegisterClient struct { -} - -func (*awsRestjson1_deserializeOpRegisterClient) ID() string { - return "OperationDeserializer" -} - -func (m *awsRestjson1_deserializeOpRegisterClient) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( - out middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err = next.HandleDeserialize(ctx, in) - if err != nil { - return out, metadata, err - } - - response, ok := out.RawResponse.(*smithyhttp.Response) - if !ok { - return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} - } - - if response.StatusCode < 200 || response.StatusCode >= 300 { - return out, metadata, awsRestjson1_deserializeOpErrorRegisterClient(response, &metadata) - } - output := &RegisterClientOutput{} - out.Result = output - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(response.Body, ringBuffer) - - decoder := json.NewDecoder(body) - decoder.UseNumber() - var shape interface{} - if err := decoder.Decode(&shape); err != nil && err != io.EOF { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return out, metadata, err - } - - err = awsRestjson1_deserializeOpDocumentRegisterClientOutput(&output, shape) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return out, metadata, err -} - -func awsRestjson1_deserializeOpErrorRegisterClient(response *smithyhttp.Response, metadata *middleware.Metadata) error { - var errorBuffer bytes.Buffer - if _, err := io.Copy(&errorBuffer, response.Body); err != nil { - return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} - } - errorBody := bytes.NewReader(errorBuffer.Bytes()) - - errorCode := "UnknownError" - errorMessage := errorCode - - headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerException", errorCode): - return awsRestjson1_deserializeErrorInternalServerException(response, errorBody) - - case strings.EqualFold("InvalidClientMetadataException", errorCode): - return awsRestjson1_deserializeErrorInvalidClientMetadataException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsRestjson1_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("InvalidScopeException", errorCode): - return awsRestjson1_deserializeErrorInvalidScopeException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -func awsRestjson1_deserializeOpDocumentRegisterClientOutput(v **RegisterClientOutput, value interface{}) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - if value == nil { - return nil - } - - shape, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var sv *RegisterClientOutput - if *v == nil { - sv = &RegisterClientOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "authorizationEndpoint": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected URI to be of type string, got %T instead", value) - } - sv.AuthorizationEndpoint = ptr.String(jtv) - } - - case "clientId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ClientId to be of type string, got %T instead", value) - } - sv.ClientId = ptr.String(jtv) - } - - case "clientIdIssuedAt": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected LongTimeStampType to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.ClientIdIssuedAt = i64 - } - - case "clientSecret": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ClientSecret to be of type string, got %T instead", value) - } - sv.ClientSecret = ptr.String(jtv) - } - - case "clientSecretExpiresAt": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected LongTimeStampType to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.ClientSecretExpiresAt = i64 - } - - case "tokenEndpoint": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected URI to be of type string, got %T instead", value) - } - sv.TokenEndpoint = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -type awsRestjson1_deserializeOpStartDeviceAuthorization struct { -} - -func (*awsRestjson1_deserializeOpStartDeviceAuthorization) ID() string { - return "OperationDeserializer" -} - -func (m *awsRestjson1_deserializeOpStartDeviceAuthorization) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( - out middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err = next.HandleDeserialize(ctx, in) - if err != nil { - return out, metadata, err - } - - response, ok := out.RawResponse.(*smithyhttp.Response) - if !ok { - return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} - } - - if response.StatusCode < 200 || response.StatusCode >= 300 { - return out, metadata, awsRestjson1_deserializeOpErrorStartDeviceAuthorization(response, &metadata) - } - output := &StartDeviceAuthorizationOutput{} - out.Result = output - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(response.Body, ringBuffer) - - decoder := json.NewDecoder(body) - decoder.UseNumber() - var shape interface{} - if err := decoder.Decode(&shape); err != nil && err != io.EOF { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return out, metadata, err - } - - err = awsRestjson1_deserializeOpDocumentStartDeviceAuthorizationOutput(&output, shape) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return out, metadata, err -} - -func awsRestjson1_deserializeOpErrorStartDeviceAuthorization(response *smithyhttp.Response, metadata *middleware.Metadata) error { - var errorBuffer bytes.Buffer - if _, err := io.Copy(&errorBuffer, response.Body); err != nil { - return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} - } - errorBody := bytes.NewReader(errorBuffer.Bytes()) - - errorCode := "UnknownError" - errorMessage := errorCode - - headerCode := response.Header.Get("X-Amzn-ErrorType") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - errorBody.Seek(0, io.SeekStart) - if len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerException", errorCode): - return awsRestjson1_deserializeErrorInternalServerException(response, errorBody) - - case strings.EqualFold("InvalidClientException", errorCode): - return awsRestjson1_deserializeErrorInvalidClientException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsRestjson1_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("SlowDownException", errorCode): - return awsRestjson1_deserializeErrorSlowDownException(response, errorBody) - - case strings.EqualFold("UnauthorizedClientException", errorCode): - return awsRestjson1_deserializeErrorUnauthorizedClientException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -func awsRestjson1_deserializeOpDocumentStartDeviceAuthorizationOutput(v **StartDeviceAuthorizationOutput, value interface{}) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - if value == nil { - return nil - } - - shape, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var sv *StartDeviceAuthorizationOutput - if *v == nil { - sv = &StartDeviceAuthorizationOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "deviceCode": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DeviceCode to be of type string, got %T instead", value) - } - sv.DeviceCode = ptr.String(jtv) - } - - case "expiresIn": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected ExpirationInSeconds to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.ExpiresIn = int32(i64) - } - - case "interval": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected IntervalInSeconds to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.Interval = int32(i64) - } - - case "userCode": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected UserCode to be of type string, got %T instead", value) - } - sv.UserCode = ptr.String(jtv) - } - - case "verificationUri": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected URI to be of type string, got %T instead", value) - } - sv.VerificationUri = ptr.String(jtv) - } - - case "verificationUriComplete": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected URI to be of type string, got %T instead", value) - } - sv.VerificationUriComplete = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeErrorAccessDeniedException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.AccessDeniedException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - var shape interface{} - if err := decoder.Decode(&shape); err != nil && err != io.EOF { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - err := awsRestjson1_deserializeDocumentAccessDeniedException(&output, shape) - - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - errorBody.Seek(0, io.SeekStart) - - return output -} - -func awsRestjson1_deserializeErrorAuthorizationPendingException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.AuthorizationPendingException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - var shape interface{} - if err := decoder.Decode(&shape); err != nil && err != io.EOF { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - err := awsRestjson1_deserializeDocumentAuthorizationPendingException(&output, shape) - - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - errorBody.Seek(0, io.SeekStart) - - return output -} - -func awsRestjson1_deserializeErrorExpiredTokenException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.ExpiredTokenException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - var shape interface{} - if err := decoder.Decode(&shape); err != nil && err != io.EOF { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - err := awsRestjson1_deserializeDocumentExpiredTokenException(&output, shape) - - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - errorBody.Seek(0, io.SeekStart) - - return output -} - -func awsRestjson1_deserializeErrorInternalServerException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.InternalServerException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - var shape interface{} - if err := decoder.Decode(&shape); err != nil && err != io.EOF { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - err := awsRestjson1_deserializeDocumentInternalServerException(&output, shape) - - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - errorBody.Seek(0, io.SeekStart) - - return output -} - -func awsRestjson1_deserializeErrorInvalidClientException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.InvalidClientException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - var shape interface{} - if err := decoder.Decode(&shape); err != nil && err != io.EOF { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - err := awsRestjson1_deserializeDocumentInvalidClientException(&output, shape) - - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - errorBody.Seek(0, io.SeekStart) - - return output -} - -func awsRestjson1_deserializeErrorInvalidClientMetadataException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.InvalidClientMetadataException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - var shape interface{} - if err := decoder.Decode(&shape); err != nil && err != io.EOF { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - err := awsRestjson1_deserializeDocumentInvalidClientMetadataException(&output, shape) - - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - errorBody.Seek(0, io.SeekStart) - - return output -} - -func awsRestjson1_deserializeErrorInvalidGrantException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.InvalidGrantException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - var shape interface{} - if err := decoder.Decode(&shape); err != nil && err != io.EOF { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - err := awsRestjson1_deserializeDocumentInvalidGrantException(&output, shape) - - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - errorBody.Seek(0, io.SeekStart) - - return output -} - -func awsRestjson1_deserializeErrorInvalidRequestException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.InvalidRequestException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - var shape interface{} - if err := decoder.Decode(&shape); err != nil && err != io.EOF { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - err := awsRestjson1_deserializeDocumentInvalidRequestException(&output, shape) - - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - errorBody.Seek(0, io.SeekStart) - - return output -} - -func awsRestjson1_deserializeErrorInvalidScopeException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.InvalidScopeException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - var shape interface{} - if err := decoder.Decode(&shape); err != nil && err != io.EOF { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - err := awsRestjson1_deserializeDocumentInvalidScopeException(&output, shape) - - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - errorBody.Seek(0, io.SeekStart) - - return output -} - -func awsRestjson1_deserializeErrorSlowDownException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.SlowDownException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - var shape interface{} - if err := decoder.Decode(&shape); err != nil && err != io.EOF { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - err := awsRestjson1_deserializeDocumentSlowDownException(&output, shape) - - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - errorBody.Seek(0, io.SeekStart) - - return output -} - -func awsRestjson1_deserializeErrorUnauthorizedClientException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.UnauthorizedClientException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - var shape interface{} - if err := decoder.Decode(&shape); err != nil && err != io.EOF { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - err := awsRestjson1_deserializeDocumentUnauthorizedClientException(&output, shape) - - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - errorBody.Seek(0, io.SeekStart) - - return output -} - -func awsRestjson1_deserializeErrorUnsupportedGrantTypeException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.UnsupportedGrantTypeException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - var shape interface{} - if err := decoder.Decode(&shape); err != nil && err != io.EOF { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - err := awsRestjson1_deserializeDocumentUnsupportedGrantTypeException(&output, shape) - - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return err - } - - errorBody.Seek(0, io.SeekStart) - - return output -} - -func awsRestjson1_deserializeDocumentAccessDeniedException(v **types.AccessDeniedException, value interface{}) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - if value == nil { - return nil - } - - shape, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var sv *types.AccessDeniedException - if *v == nil { - sv = &types.AccessDeniedException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "error": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Error to be of type string, got %T instead", value) - } - sv.Error_ = ptr.String(jtv) - } - - case "error_description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Error_description = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentAuthorizationPendingException(v **types.AuthorizationPendingException, value interface{}) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - if value == nil { - return nil - } - - shape, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var sv *types.AuthorizationPendingException - if *v == nil { - sv = &types.AuthorizationPendingException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "error": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Error to be of type string, got %T instead", value) - } - sv.Error_ = ptr.String(jtv) - } - - case "error_description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Error_description = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentExpiredTokenException(v **types.ExpiredTokenException, value interface{}) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - if value == nil { - return nil - } - - shape, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var sv *types.ExpiredTokenException - if *v == nil { - sv = &types.ExpiredTokenException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "error": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Error to be of type string, got %T instead", value) - } - sv.Error_ = ptr.String(jtv) - } - - case "error_description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Error_description = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentInternalServerException(v **types.InternalServerException, value interface{}) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - if value == nil { - return nil - } - - shape, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var sv *types.InternalServerException - if *v == nil { - sv = &types.InternalServerException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "error": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Error to be of type string, got %T instead", value) - } - sv.Error_ = ptr.String(jtv) - } - - case "error_description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Error_description = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentInvalidClientException(v **types.InvalidClientException, value interface{}) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - if value == nil { - return nil - } - - shape, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var sv *types.InvalidClientException - if *v == nil { - sv = &types.InvalidClientException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "error": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Error to be of type string, got %T instead", value) - } - sv.Error_ = ptr.String(jtv) - } - - case "error_description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Error_description = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentInvalidClientMetadataException(v **types.InvalidClientMetadataException, value interface{}) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - if value == nil { - return nil - } - - shape, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var sv *types.InvalidClientMetadataException - if *v == nil { - sv = &types.InvalidClientMetadataException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "error": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Error to be of type string, got %T instead", value) - } - sv.Error_ = ptr.String(jtv) - } - - case "error_description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Error_description = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentInvalidGrantException(v **types.InvalidGrantException, value interface{}) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - if value == nil { - return nil - } - - shape, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var sv *types.InvalidGrantException - if *v == nil { - sv = &types.InvalidGrantException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "error": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Error to be of type string, got %T instead", value) - } - sv.Error_ = ptr.String(jtv) - } - - case "error_description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Error_description = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentInvalidRequestException(v **types.InvalidRequestException, value interface{}) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - if value == nil { - return nil - } - - shape, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var sv *types.InvalidRequestException - if *v == nil { - sv = &types.InvalidRequestException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "error": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Error to be of type string, got %T instead", value) - } - sv.Error_ = ptr.String(jtv) - } - - case "error_description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Error_description = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentInvalidScopeException(v **types.InvalidScopeException, value interface{}) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - if value == nil { - return nil - } - - shape, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var sv *types.InvalidScopeException - if *v == nil { - sv = &types.InvalidScopeException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "error": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Error to be of type string, got %T instead", value) - } - sv.Error_ = ptr.String(jtv) - } - - case "error_description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Error_description = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentSlowDownException(v **types.SlowDownException, value interface{}) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - if value == nil { - return nil - } - - shape, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var sv *types.SlowDownException - if *v == nil { - sv = &types.SlowDownException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "error": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Error to be of type string, got %T instead", value) - } - sv.Error_ = ptr.String(jtv) - } - - case "error_description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Error_description = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentUnauthorizedClientException(v **types.UnauthorizedClientException, value interface{}) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - if value == nil { - return nil - } - - shape, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var sv *types.UnauthorizedClientException - if *v == nil { - sv = &types.UnauthorizedClientException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "error": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Error to be of type string, got %T instead", value) - } - sv.Error_ = ptr.String(jtv) - } - - case "error_description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Error_description = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentUnsupportedGrantTypeException(v **types.UnsupportedGrantTypeException, value interface{}) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - if value == nil { - return nil - } - - shape, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var sv *types.UnsupportedGrantTypeException - if *v == nil { - sv = &types.UnsupportedGrantTypeException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "error": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Error to be of type string, got %T instead", value) - } - sv.Error_ = ptr.String(jtv) - } - - case "error_description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Error_description = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/doc.go deleted file mode 100644 index 2239427d8..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/doc.go +++ /dev/null @@ -1,36 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -// Package ssooidc provides the API client, operations, and parameter types for -// AWS SSO OIDC. -// -// AWS IAM Identity Center (successor to AWS Single Sign-On) OpenID Connect (OIDC) -// is a web service that enables a client (such as AWS CLI or a native application) -// to register with IAM Identity Center. The service also enables the client to -// fetch the user’s access token upon successful authentication and authorization -// with IAM Identity Center. Although AWS Single Sign-On was renamed, the sso and -// identitystore API namespaces will continue to retain their original name for -// backward compatibility purposes. For more information, see IAM Identity Center -// rename (https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html#renamed) -// . Considerations for Using This Guide Before you begin using this guide, we -// recommend that you first review the following important information about how -// the IAM Identity Center OIDC service works. -// - The IAM Identity Center OIDC service currently implements only the portions -// of the OAuth 2.0 Device Authorization Grant standard ( -// https://tools.ietf.org/html/rfc8628 (https://tools.ietf.org/html/rfc8628) ) -// that are necessary to enable single sign-on authentication with the AWS CLI. -// Support for other OIDC flows frequently needed for native applications, such as -// Authorization Code Flow (+ PKCE), will be addressed in future releases. -// - The service emits only OIDC access tokens, such that obtaining a new token -// (For example, token refresh) requires explicit user re-authentication. -// - The access tokens provided by this service grant access to all AWS account -// entitlements assigned to an IAM Identity Center user, not just a particular -// application. -// - The documentation in this guide does not describe the mechanism to convert -// the access token into AWS Auth (“sigv4”) credentials for use with IAM-protected -// AWS service endpoints. For more information, see GetRoleCredentials (https://docs.aws.amazon.com/singlesignon/latest/PortalAPIReference/API_GetRoleCredentials.html) -// in the IAM Identity Center Portal API Reference Guide. -// -// For general information about IAM Identity Center, see What is IAM Identity -// Center? (https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) -// in the IAM Identity Center User Guide. -package ssooidc diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/endpoints.go deleted file mode 100644 index 282d078b5..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/endpoints.go +++ /dev/null @@ -1,753 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssooidc - -import ( - "context" - "errors" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn" - internalendpoints "github.com/aws/aws-sdk-go-v2/service/ssooidc/internal/endpoints" - smithyendpoints "github.com/aws/smithy-go/endpoints" - "github.com/aws/smithy-go/middleware" - "github.com/aws/smithy-go/ptr" - smithyhttp "github.com/aws/smithy-go/transport/http" - "net/http" - "net/url" - "strings" -) - -// EndpointResolverOptions is the service endpoint resolver options -type EndpointResolverOptions = internalendpoints.Options - -// EndpointResolver interface for resolving service endpoints. -type EndpointResolver interface { - ResolveEndpoint(region string, options EndpointResolverOptions) (aws.Endpoint, error) -} - -var _ EndpointResolver = &internalendpoints.Resolver{} - -// NewDefaultEndpointResolver constructs a new service endpoint resolver -func NewDefaultEndpointResolver() *internalendpoints.Resolver { - return internalendpoints.New() -} - -// EndpointResolverFunc is a helper utility that wraps a function so it satisfies -// the EndpointResolver interface. This is useful when you want to add additional -// endpoint resolving logic, or stub out specific endpoints with custom values. -type EndpointResolverFunc func(region string, options EndpointResolverOptions) (aws.Endpoint, error) - -func (fn EndpointResolverFunc) ResolveEndpoint(region string, options EndpointResolverOptions) (endpoint aws.Endpoint, err error) { - return fn(region, options) -} - -// EndpointResolverFromURL returns an EndpointResolver configured using the -// provided endpoint url. By default, the resolved endpoint resolver uses the -// client region as signing region, and the endpoint source is set to -// EndpointSourceCustom.You can provide functional options to configure endpoint -// values for the resolved endpoint. -func EndpointResolverFromURL(url string, optFns ...func(*aws.Endpoint)) EndpointResolver { - e := aws.Endpoint{URL: url, Source: aws.EndpointSourceCustom} - for _, fn := range optFns { - fn(&e) - } - - return EndpointResolverFunc( - func(region string, options EndpointResolverOptions) (aws.Endpoint, error) { - if len(e.SigningRegion) == 0 { - e.SigningRegion = region - } - return e, nil - }, - ) -} - -type ResolveEndpoint struct { - Resolver EndpointResolver - Options EndpointResolverOptions -} - -func (*ResolveEndpoint) ID() string { - return "ResolveEndpoint" -} - -func (m *ResolveEndpoint) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if !awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.Resolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - eo := m.Options - eo.Logger = middleware.GetLogger(ctx) - - var endpoint aws.Endpoint - endpoint, err = m.Resolver.ResolveEndpoint(awsmiddleware.GetRegion(ctx), eo) - if err != nil { - nf := (&aws.EndpointNotFoundError{}) - if errors.As(err, &nf) { - ctx = awsmiddleware.SetRequiresLegacyEndpoints(ctx, false) - return next.HandleSerialize(ctx, in) - } - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL, err = url.Parse(endpoint.URL) - if err != nil { - return out, metadata, fmt.Errorf("failed to parse endpoint URL: %w", err) - } - - if len(awsmiddleware.GetSigningName(ctx)) == 0 { - signingName := endpoint.SigningName - if len(signingName) == 0 { - signingName = "awsssooidc" - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - } - ctx = awsmiddleware.SetEndpointSource(ctx, endpoint.Source) - ctx = smithyhttp.SetHostnameImmutable(ctx, endpoint.HostnameImmutable) - ctx = awsmiddleware.SetSigningRegion(ctx, endpoint.SigningRegion) - ctx = awsmiddleware.SetPartitionID(ctx, endpoint.PartitionID) - return next.HandleSerialize(ctx, in) -} -func addResolveEndpointMiddleware(stack *middleware.Stack, o Options) error { - return stack.Serialize.Insert(&ResolveEndpoint{ - Resolver: o.EndpointResolver, - Options: o.EndpointOptions, - }, "OperationSerializer", middleware.Before) -} - -func removeResolveEndpointMiddleware(stack *middleware.Stack) error { - _, err := stack.Serialize.Remove((&ResolveEndpoint{}).ID()) - return err -} - -type wrappedEndpointResolver struct { - awsResolver aws.EndpointResolverWithOptions -} - -func (w *wrappedEndpointResolver) ResolveEndpoint(region string, options EndpointResolverOptions) (endpoint aws.Endpoint, err error) { - return w.awsResolver.ResolveEndpoint(ServiceID, region, options) -} - -type awsEndpointResolverAdaptor func(service, region string) (aws.Endpoint, error) - -func (a awsEndpointResolverAdaptor) ResolveEndpoint(service, region string, options ...interface{}) (aws.Endpoint, error) { - return a(service, region) -} - -var _ aws.EndpointResolverWithOptions = awsEndpointResolverAdaptor(nil) - -// withEndpointResolver returns an aws.EndpointResolverWithOptions that first delegates endpoint resolution to the awsResolver. -// If awsResolver returns aws.EndpointNotFoundError error, the v1 resolver middleware will swallow the error, -// and set an appropriate context flag such that fallback will occur when EndpointResolverV2 is invoked -// via its middleware. -// -// If another error (besides aws.EndpointNotFoundError) is returned, then that error will be propagated. -func withEndpointResolver(awsResolver aws.EndpointResolver, awsResolverWithOptions aws.EndpointResolverWithOptions) EndpointResolver { - var resolver aws.EndpointResolverWithOptions - - if awsResolverWithOptions != nil { - resolver = awsResolverWithOptions - } else if awsResolver != nil { - resolver = awsEndpointResolverAdaptor(awsResolver.ResolveEndpoint) - } - - return &wrappedEndpointResolver{ - awsResolver: resolver, - } -} - -func finalizeClientEndpointResolverOptions(options *Options) { - options.EndpointOptions.LogDeprecated = options.ClientLogMode.IsDeprecatedUsage() - - if len(options.EndpointOptions.ResolvedRegion) == 0 { - const fipsInfix = "-fips-" - const fipsPrefix = "fips-" - const fipsSuffix = "-fips" - - if strings.Contains(options.Region, fipsInfix) || - strings.Contains(options.Region, fipsPrefix) || - strings.Contains(options.Region, fipsSuffix) { - options.EndpointOptions.ResolvedRegion = strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll( - options.Region, fipsInfix, "-"), fipsPrefix, ""), fipsSuffix, "") - options.EndpointOptions.UseFIPSEndpoint = aws.FIPSEndpointStateEnabled - } - } - -} - -func resolveEndpointResolverV2(options *Options) { - if options.EndpointResolverV2 == nil { - options.EndpointResolverV2 = NewDefaultEndpointResolverV2() - } -} - -// Utility function to aid with translating pseudo-regions to classical regions -// with the appropriate setting indicated by the pseudo-region -func mapPseudoRegion(pr string) (region string, fips aws.FIPSEndpointState) { - const fipsInfix = "-fips-" - const fipsPrefix = "fips-" - const fipsSuffix = "-fips" - - if strings.Contains(pr, fipsInfix) || - strings.Contains(pr, fipsPrefix) || - strings.Contains(pr, fipsSuffix) { - region = strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll( - pr, fipsInfix, "-"), fipsPrefix, ""), fipsSuffix, "") - fips = aws.FIPSEndpointStateEnabled - } else { - region = pr - } - - return region, fips -} - -// builtInParameterResolver is the interface responsible for resolving BuiltIn -// values during the sourcing of EndpointParameters -type builtInParameterResolver interface { - ResolveBuiltIns(*EndpointParameters) error -} - -// builtInResolver resolves modeled BuiltIn values using only the members defined -// below. -type builtInResolver struct { - // The AWS region used to dispatch the request. - Region string - - // Sourced BuiltIn value in a historical enabled or disabled state. - UseDualStack aws.DualStackEndpointState - - // Sourced BuiltIn value in a historical enabled or disabled state. - UseFIPS aws.FIPSEndpointState - - // Base endpoint that can potentially be modified during Endpoint resolution. - Endpoint *string -} - -// Invoked at runtime to resolve BuiltIn Values. Only resolution code specific to -// each BuiltIn value is generated. -func (b *builtInResolver) ResolveBuiltIns(params *EndpointParameters) error { - - region, _ := mapPseudoRegion(b.Region) - if len(region) == 0 { - return fmt.Errorf("Could not resolve AWS::Region") - } else { - params.Region = aws.String(region) - } - if b.UseDualStack == aws.DualStackEndpointStateEnabled { - params.UseDualStack = aws.Bool(true) - } else { - params.UseDualStack = aws.Bool(false) - } - if b.UseFIPS == aws.FIPSEndpointStateEnabled { - params.UseFIPS = aws.Bool(true) - } else { - params.UseFIPS = aws.Bool(false) - } - params.Endpoint = b.Endpoint - return nil -} - -// EndpointParameters provides the parameters that influence how endpoints are -// resolved. -type EndpointParameters struct { - // The AWS region used to dispatch the request. - // - // Parameter is - // required. - // - // AWS::Region - Region *string - - // When true, use the dual-stack endpoint. If the configured endpoint does not - // support dual-stack, dispatching the request MAY return an error. - // - // Defaults to - // false if no value is provided. - // - // AWS::UseDualStack - UseDualStack *bool - - // When true, send this request to the FIPS-compliant regional endpoint. If the - // configured endpoint does not have a FIPS compliant endpoint, dispatching the - // request will return an error. - // - // Defaults to false if no value is - // provided. - // - // AWS::UseFIPS - UseFIPS *bool - - // Override the endpoint used to send this request - // - // Parameter is - // required. - // - // SDK::Endpoint - Endpoint *string -} - -// ValidateRequired validates required parameters are set. -func (p EndpointParameters) ValidateRequired() error { - if p.UseDualStack == nil { - return fmt.Errorf("parameter UseDualStack is required") - } - - if p.UseFIPS == nil { - return fmt.Errorf("parameter UseFIPS is required") - } - - return nil -} - -// WithDefaults returns a shallow copy of EndpointParameterswith default values -// applied to members where applicable. -func (p EndpointParameters) WithDefaults() EndpointParameters { - if p.UseDualStack == nil { - p.UseDualStack = ptr.Bool(false) - } - - if p.UseFIPS == nil { - p.UseFIPS = ptr.Bool(false) - } - return p -} - -// EndpointResolverV2 provides the interface for resolving service endpoints. -type EndpointResolverV2 interface { - // ResolveEndpoint attempts to resolve the endpoint with the provided options, - // returning the endpoint if found. Otherwise an error is returned. - ResolveEndpoint(ctx context.Context, params EndpointParameters) ( - smithyendpoints.Endpoint, error, - ) -} - -// resolver provides the implementation for resolving endpoints. -type resolver struct{} - -func NewDefaultEndpointResolverV2() EndpointResolverV2 { - return &resolver{} -} - -// ResolveEndpoint attempts to resolve the endpoint with the provided options, -// returning the endpoint if found. Otherwise an error is returned. -func (r *resolver) ResolveEndpoint( - ctx context.Context, params EndpointParameters, -) ( - endpoint smithyendpoints.Endpoint, err error, -) { - params = params.WithDefaults() - if err = params.ValidateRequired(); err != nil { - return endpoint, fmt.Errorf("endpoint parameters are not valid, %w", err) - } - _UseDualStack := *params.UseDualStack - _UseFIPS := *params.UseFIPS - - if exprVal := params.Endpoint; exprVal != nil { - _Endpoint := *exprVal - _ = _Endpoint - if _UseFIPS == true { - return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: FIPS and custom endpoint are not supported") - } - if _UseDualStack == true { - return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: Dualstack and custom endpoint are not supported") - } - uriString := _Endpoint - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if exprVal := params.Region; exprVal != nil { - _Region := *exprVal - _ = _Region - if exprVal := awsrulesfn.GetPartition(_Region); exprVal != nil { - _PartitionResult := *exprVal - _ = _PartitionResult - if _UseFIPS == true { - if _UseDualStack == true { - if true == _PartitionResult.SupportsFIPS { - if true == _PartitionResult.SupportsDualStack { - uriString := func() string { - var out strings.Builder - out.WriteString("https://oidc-fips.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DualStackDnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "FIPS and DualStack are enabled, but this partition does not support one or both") - } - } - if _UseFIPS == true { - if true == _PartitionResult.SupportsFIPS { - uriString := func() string { - var out strings.Builder - out.WriteString("https://oidc-fips.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "FIPS is enabled but this partition does not support FIPS") - } - if _UseDualStack == true { - if true == _PartitionResult.SupportsDualStack { - uriString := func() string { - var out strings.Builder - out.WriteString("https://oidc.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DualStackDnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "DualStack is enabled but this partition does not support DualStack") - } - if _Region == "ap-east-1" { - uriString := "https://oidc.ap-east-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "ap-northeast-1" { - uriString := "https://oidc.ap-northeast-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "ap-northeast-2" { - uriString := "https://oidc.ap-northeast-2.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "ap-northeast-3" { - uriString := "https://oidc.ap-northeast-3.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "ap-south-1" { - uriString := "https://oidc.ap-south-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "ap-southeast-1" { - uriString := "https://oidc.ap-southeast-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "ap-southeast-2" { - uriString := "https://oidc.ap-southeast-2.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "ca-central-1" { - uriString := "https://oidc.ca-central-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "eu-central-1" { - uriString := "https://oidc.eu-central-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "eu-north-1" { - uriString := "https://oidc.eu-north-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "eu-south-1" { - uriString := "https://oidc.eu-south-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "eu-west-1" { - uriString := "https://oidc.eu-west-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "eu-west-2" { - uriString := "https://oidc.eu-west-2.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "eu-west-3" { - uriString := "https://oidc.eu-west-3.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "me-south-1" { - uriString := "https://oidc.me-south-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "sa-east-1" { - uriString := "https://oidc.sa-east-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "us-east-1" { - uriString := "https://oidc.us-east-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "us-east-2" { - uriString := "https://oidc.us-east-2.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "us-west-2" { - uriString := "https://oidc.us-west-2.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "us-gov-east-1" { - uriString := "https://oidc.us-gov-east-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if _Region == "us-gov-west-1" { - uriString := "https://oidc.us-gov-west-1.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - uriString := func() string { - var out strings.Builder - out.WriteString("https://oidc.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - return endpoint, fmt.Errorf("Endpoint resolution failed. Invalid operation or environment input.") - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: Missing Region") -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/generated.json b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/generated.json deleted file mode 100644 index fe2d075ad..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/generated.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "dependencies": { - "github.com/aws/aws-sdk-go-v2": "v1.4.0", - "github.com/aws/aws-sdk-go-v2/internal/configsources": "v0.0.0-00010101000000-000000000000", - "github.com/aws/aws-sdk-go-v2/internal/endpoints/v2": "v2.0.0-00010101000000-000000000000", - "github.com/aws/smithy-go": "v1.4.0", - "github.com/google/go-cmp": "v0.5.4" - }, - "files": [ - "api_client.go", - "api_client_test.go", - "api_op_CreateToken.go", - "api_op_RegisterClient.go", - "api_op_StartDeviceAuthorization.go", - "deserializers.go", - "doc.go", - "endpoints.go", - "endpoints_test.go", - "generated.json", - "internal/endpoints/endpoints.go", - "internal/endpoints/endpoints_test.go", - "protocol_test.go", - "serializers.go", - "types/errors.go", - "types/types.go", - "validators.go" - ], - "go": "1.15", - "module": "github.com/aws/aws-sdk-go-v2/service/ssooidc", - "unstable": false -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/go_module_metadata.go deleted file mode 100644 index 435045414..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/go_module_metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. - -package ssooidc - -// goModuleVersion is the tagged release for this module -const goModuleVersion = "1.15.5" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/internal/endpoints/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/internal/endpoints/endpoints.go deleted file mode 100644 index 8df344e93..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/internal/endpoints/endpoints.go +++ /dev/null @@ -1,492 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package endpoints - -import ( - "github.com/aws/aws-sdk-go-v2/aws" - endpoints "github.com/aws/aws-sdk-go-v2/internal/endpoints/v2" - "github.com/aws/smithy-go/logging" - "regexp" -) - -// Options is the endpoint resolver configuration options -type Options struct { - // Logger is a logging implementation that log events should be sent to. - Logger logging.Logger - - // LogDeprecated indicates that deprecated endpoints should be logged to the - // provided logger. - LogDeprecated bool - - // ResolvedRegion is used to override the region to be resolved, rather then the - // using the value passed to the ResolveEndpoint method. This value is used by the - // SDK to translate regions like fips-us-east-1 or us-east-1-fips to an alternative - // name. You must not set this value directly in your application. - ResolvedRegion string - - // DisableHTTPS informs the resolver to return an endpoint that does not use the - // HTTPS scheme. - DisableHTTPS bool - - // UseDualStackEndpoint specifies the resolver must resolve a dual-stack endpoint. - UseDualStackEndpoint aws.DualStackEndpointState - - // UseFIPSEndpoint specifies the resolver must resolve a FIPS endpoint. - UseFIPSEndpoint aws.FIPSEndpointState -} - -func (o Options) GetResolvedRegion() string { - return o.ResolvedRegion -} - -func (o Options) GetDisableHTTPS() bool { - return o.DisableHTTPS -} - -func (o Options) GetUseDualStackEndpoint() aws.DualStackEndpointState { - return o.UseDualStackEndpoint -} - -func (o Options) GetUseFIPSEndpoint() aws.FIPSEndpointState { - return o.UseFIPSEndpoint -} - -func transformToSharedOptions(options Options) endpoints.Options { - return endpoints.Options{ - Logger: options.Logger, - LogDeprecated: options.LogDeprecated, - ResolvedRegion: options.ResolvedRegion, - DisableHTTPS: options.DisableHTTPS, - UseDualStackEndpoint: options.UseDualStackEndpoint, - UseFIPSEndpoint: options.UseFIPSEndpoint, - } -} - -// Resolver SSO OIDC endpoint resolver -type Resolver struct { - partitions endpoints.Partitions -} - -// ResolveEndpoint resolves the service endpoint for the given region and options -func (r *Resolver) ResolveEndpoint(region string, options Options) (endpoint aws.Endpoint, err error) { - if len(region) == 0 { - return endpoint, &aws.MissingRegionError{} - } - - opt := transformToSharedOptions(options) - return r.partitions.ResolveEndpoint(region, opt) -} - -// New returns a new Resolver -func New() *Resolver { - return &Resolver{ - partitions: defaultPartitions, - } -} - -var partitionRegexp = struct { - Aws *regexp.Regexp - AwsCn *regexp.Regexp - AwsIso *regexp.Regexp - AwsIsoB *regexp.Regexp - AwsIsoE *regexp.Regexp - AwsIsoF *regexp.Regexp - AwsUsGov *regexp.Regexp -}{ - - Aws: regexp.MustCompile("^(us|eu|ap|sa|ca|me|af|il)\\-\\w+\\-\\d+$"), - AwsCn: regexp.MustCompile("^cn\\-\\w+\\-\\d+$"), - AwsIso: regexp.MustCompile("^us\\-iso\\-\\w+\\-\\d+$"), - AwsIsoB: regexp.MustCompile("^us\\-isob\\-\\w+\\-\\d+$"), - AwsIsoE: regexp.MustCompile("^eu\\-isoe\\-\\w+\\-\\d+$"), - AwsIsoF: regexp.MustCompile("^us\\-isof\\-\\w+\\-\\d+$"), - AwsUsGov: regexp.MustCompile("^us\\-gov\\-\\w+\\-\\d+$"), -} - -var defaultPartitions = endpoints.Partitions{ - { - ID: "aws", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.DualStackVariant, - }: { - Hostname: "oidc.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "oidc-fips.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: { - Hostname: "oidc-fips.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "oidc.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.Aws, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "af-south-1", - }: endpoints.Endpoint{ - Hostname: "oidc.af-south-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "af-south-1", - }, - }, - endpoints.EndpointKey{ - Region: "ap-east-1", - }: endpoints.Endpoint{ - Hostname: "oidc.ap-east-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-east-1", - }, - }, - endpoints.EndpointKey{ - Region: "ap-northeast-1", - }: endpoints.Endpoint{ - Hostname: "oidc.ap-northeast-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-northeast-1", - }, - }, - endpoints.EndpointKey{ - Region: "ap-northeast-2", - }: endpoints.Endpoint{ - Hostname: "oidc.ap-northeast-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-northeast-2", - }, - }, - endpoints.EndpointKey{ - Region: "ap-northeast-3", - }: endpoints.Endpoint{ - Hostname: "oidc.ap-northeast-3.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-northeast-3", - }, - }, - endpoints.EndpointKey{ - Region: "ap-south-1", - }: endpoints.Endpoint{ - Hostname: "oidc.ap-south-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-south-1", - }, - }, - endpoints.EndpointKey{ - Region: "ap-southeast-1", - }: endpoints.Endpoint{ - Hostname: "oidc.ap-southeast-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-southeast-1", - }, - }, - endpoints.EndpointKey{ - Region: "ap-southeast-2", - }: endpoints.Endpoint{ - Hostname: "oidc.ap-southeast-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-southeast-2", - }, - }, - endpoints.EndpointKey{ - Region: "ap-southeast-3", - }: endpoints.Endpoint{ - Hostname: "oidc.ap-southeast-3.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-southeast-3", - }, - }, - endpoints.EndpointKey{ - Region: "ca-central-1", - }: endpoints.Endpoint{ - Hostname: "oidc.ca-central-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ca-central-1", - }, - }, - endpoints.EndpointKey{ - Region: "eu-central-1", - }: endpoints.Endpoint{ - Hostname: "oidc.eu-central-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "eu-central-1", - }, - }, - endpoints.EndpointKey{ - Region: "eu-north-1", - }: endpoints.Endpoint{ - Hostname: "oidc.eu-north-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "eu-north-1", - }, - }, - endpoints.EndpointKey{ - Region: "eu-south-1", - }: endpoints.Endpoint{ - Hostname: "oidc.eu-south-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "eu-south-1", - }, - }, - endpoints.EndpointKey{ - Region: "eu-west-1", - }: endpoints.Endpoint{ - Hostname: "oidc.eu-west-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "eu-west-1", - }, - }, - endpoints.EndpointKey{ - Region: "eu-west-2", - }: endpoints.Endpoint{ - Hostname: "oidc.eu-west-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "eu-west-2", - }, - }, - endpoints.EndpointKey{ - Region: "eu-west-3", - }: endpoints.Endpoint{ - Hostname: "oidc.eu-west-3.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "eu-west-3", - }, - }, - endpoints.EndpointKey{ - Region: "me-south-1", - }: endpoints.Endpoint{ - Hostname: "oidc.me-south-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "me-south-1", - }, - }, - endpoints.EndpointKey{ - Region: "sa-east-1", - }: endpoints.Endpoint{ - Hostname: "oidc.sa-east-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "sa-east-1", - }, - }, - endpoints.EndpointKey{ - Region: "us-east-1", - }: endpoints.Endpoint{ - Hostname: "oidc.us-east-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-east-1", - }, - }, - endpoints.EndpointKey{ - Region: "us-east-2", - }: endpoints.Endpoint{ - Hostname: "oidc.us-east-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-east-2", - }, - }, - endpoints.EndpointKey{ - Region: "us-west-1", - }: endpoints.Endpoint{ - Hostname: "oidc.us-west-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-west-1", - }, - }, - endpoints.EndpointKey{ - Region: "us-west-2", - }: endpoints.Endpoint{ - Hostname: "oidc.us-west-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - { - ID: "aws-cn", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.DualStackVariant, - }: { - Hostname: "oidc.{region}.api.amazonwebservices.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "oidc-fips.{region}.amazonaws.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: { - Hostname: "oidc-fips.{region}.api.amazonwebservices.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "oidc.{region}.amazonaws.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsCn, - IsRegionalized: true, - }, - { - ID: "aws-iso", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "oidc-fips.{region}.c2s.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "oidc.{region}.c2s.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIso, - IsRegionalized: true, - }, - { - ID: "aws-iso-b", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "oidc-fips.{region}.sc2s.sgov.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "oidc.{region}.sc2s.sgov.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIsoB, - IsRegionalized: true, - }, - { - ID: "aws-iso-e", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "oidc-fips.{region}.cloud.adc-e.uk", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "oidc.{region}.cloud.adc-e.uk", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIsoE, - IsRegionalized: true, - }, - { - ID: "aws-iso-f", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "oidc-fips.{region}.csp.hci.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "oidc.{region}.csp.hci.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIsoF, - IsRegionalized: true, - }, - { - ID: "aws-us-gov", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.DualStackVariant, - }: { - Hostname: "oidc.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "oidc-fips.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: { - Hostname: "oidc-fips.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "oidc.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsUsGov, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "us-gov-east-1", - }: endpoints.Endpoint{ - Hostname: "oidc.us-gov-east-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-gov-east-1", - }, - }, - endpoints.EndpointKey{ - Region: "us-gov-west-1", - }: endpoints.Endpoint{ - Hostname: "oidc.us-gov-west-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/serializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/serializers.go deleted file mode 100644 index efca8b250..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/serializers.go +++ /dev/null @@ -1,309 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssooidc - -import ( - "bytes" - "context" - "fmt" - smithy "github.com/aws/smithy-go" - "github.com/aws/smithy-go/encoding/httpbinding" - smithyjson "github.com/aws/smithy-go/encoding/json" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -type awsRestjson1_serializeOpCreateToken struct { -} - -func (*awsRestjson1_serializeOpCreateToken) ID() string { - return "OperationSerializer" -} - -func (m *awsRestjson1_serializeOpCreateToken) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - request, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} - } - - input, ok := in.Parameters.(*CreateTokenInput) - _ = input - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} - } - - opPath, opQuery := httpbinding.SplitURI("/token") - request.URL.Path = smithyhttp.JoinPath(request.URL.Path, opPath) - request.URL.RawQuery = smithyhttp.JoinRawQuery(request.URL.RawQuery, opQuery) - request.Method = "POST" - var restEncoder *httpbinding.Encoder - if request.URL.RawPath == "" { - restEncoder, err = httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) - } else { - request.URL.RawPath = smithyhttp.JoinPath(request.URL.RawPath, opPath) - restEncoder, err = httpbinding.NewEncoderWithRawPath(request.URL.Path, request.URL.RawPath, request.URL.RawQuery, request.Header) - } - - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - restEncoder.SetHeader("Content-Type").String("application/json") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsRestjson1_serializeOpDocumentCreateTokenInput(input, jsonEncoder.Value); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request.Request, err = restEncoder.Encode(request.Request); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - in.Request = request - - return next.HandleSerialize(ctx, in) -} -func awsRestjson1_serializeOpHttpBindingsCreateTokenInput(v *CreateTokenInput, encoder *httpbinding.Encoder) error { - if v == nil { - return fmt.Errorf("unsupported serialization of nil %T", v) - } - - return nil -} - -func awsRestjson1_serializeOpDocumentCreateTokenInput(v *CreateTokenInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.ClientId != nil { - ok := object.Key("clientId") - ok.String(*v.ClientId) - } - - if v.ClientSecret != nil { - ok := object.Key("clientSecret") - ok.String(*v.ClientSecret) - } - - if v.Code != nil { - ok := object.Key("code") - ok.String(*v.Code) - } - - if v.DeviceCode != nil { - ok := object.Key("deviceCode") - ok.String(*v.DeviceCode) - } - - if v.GrantType != nil { - ok := object.Key("grantType") - ok.String(*v.GrantType) - } - - if v.RedirectUri != nil { - ok := object.Key("redirectUri") - ok.String(*v.RedirectUri) - } - - if v.RefreshToken != nil { - ok := object.Key("refreshToken") - ok.String(*v.RefreshToken) - } - - if v.Scope != nil { - ok := object.Key("scope") - if err := awsRestjson1_serializeDocumentScopes(v.Scope, ok); err != nil { - return err - } - } - - return nil -} - -type awsRestjson1_serializeOpRegisterClient struct { -} - -func (*awsRestjson1_serializeOpRegisterClient) ID() string { - return "OperationSerializer" -} - -func (m *awsRestjson1_serializeOpRegisterClient) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - request, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} - } - - input, ok := in.Parameters.(*RegisterClientInput) - _ = input - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} - } - - opPath, opQuery := httpbinding.SplitURI("/client/register") - request.URL.Path = smithyhttp.JoinPath(request.URL.Path, opPath) - request.URL.RawQuery = smithyhttp.JoinRawQuery(request.URL.RawQuery, opQuery) - request.Method = "POST" - var restEncoder *httpbinding.Encoder - if request.URL.RawPath == "" { - restEncoder, err = httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) - } else { - request.URL.RawPath = smithyhttp.JoinPath(request.URL.RawPath, opPath) - restEncoder, err = httpbinding.NewEncoderWithRawPath(request.URL.Path, request.URL.RawPath, request.URL.RawQuery, request.Header) - } - - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - restEncoder.SetHeader("Content-Type").String("application/json") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsRestjson1_serializeOpDocumentRegisterClientInput(input, jsonEncoder.Value); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request.Request, err = restEncoder.Encode(request.Request); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - in.Request = request - - return next.HandleSerialize(ctx, in) -} -func awsRestjson1_serializeOpHttpBindingsRegisterClientInput(v *RegisterClientInput, encoder *httpbinding.Encoder) error { - if v == nil { - return fmt.Errorf("unsupported serialization of nil %T", v) - } - - return nil -} - -func awsRestjson1_serializeOpDocumentRegisterClientInput(v *RegisterClientInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.ClientName != nil { - ok := object.Key("clientName") - ok.String(*v.ClientName) - } - - if v.ClientType != nil { - ok := object.Key("clientType") - ok.String(*v.ClientType) - } - - if v.Scopes != nil { - ok := object.Key("scopes") - if err := awsRestjson1_serializeDocumentScopes(v.Scopes, ok); err != nil { - return err - } - } - - return nil -} - -type awsRestjson1_serializeOpStartDeviceAuthorization struct { -} - -func (*awsRestjson1_serializeOpStartDeviceAuthorization) ID() string { - return "OperationSerializer" -} - -func (m *awsRestjson1_serializeOpStartDeviceAuthorization) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - request, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} - } - - input, ok := in.Parameters.(*StartDeviceAuthorizationInput) - _ = input - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} - } - - opPath, opQuery := httpbinding.SplitURI("/device_authorization") - request.URL.Path = smithyhttp.JoinPath(request.URL.Path, opPath) - request.URL.RawQuery = smithyhttp.JoinRawQuery(request.URL.RawQuery, opQuery) - request.Method = "POST" - var restEncoder *httpbinding.Encoder - if request.URL.RawPath == "" { - restEncoder, err = httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) - } else { - request.URL.RawPath = smithyhttp.JoinPath(request.URL.RawPath, opPath) - restEncoder, err = httpbinding.NewEncoderWithRawPath(request.URL.Path, request.URL.RawPath, request.URL.RawQuery, request.Header) - } - - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - restEncoder.SetHeader("Content-Type").String("application/json") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsRestjson1_serializeOpDocumentStartDeviceAuthorizationInput(input, jsonEncoder.Value); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request, err = request.SetStream(bytes.NewReader(jsonEncoder.Bytes())); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request.Request, err = restEncoder.Encode(request.Request); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - in.Request = request - - return next.HandleSerialize(ctx, in) -} -func awsRestjson1_serializeOpHttpBindingsStartDeviceAuthorizationInput(v *StartDeviceAuthorizationInput, encoder *httpbinding.Encoder) error { - if v == nil { - return fmt.Errorf("unsupported serialization of nil %T", v) - } - - return nil -} - -func awsRestjson1_serializeOpDocumentStartDeviceAuthorizationInput(v *StartDeviceAuthorizationInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.ClientId != nil { - ok := object.Key("clientId") - ok.String(*v.ClientId) - } - - if v.ClientSecret != nil { - ok := object.Key("clientSecret") - ok.String(*v.ClientSecret) - } - - if v.StartUrl != nil { - ok := object.Key("startUrl") - ok.String(*v.StartUrl) - } - - return nil -} - -func awsRestjson1_serializeDocumentScopes(v []string, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - av.String(v[i]) - } - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/types/errors.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/types/errors.go deleted file mode 100644 index 115a51a9e..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/types/errors.go +++ /dev/null @@ -1,366 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package types - -import ( - "fmt" - smithy "github.com/aws/smithy-go" -) - -// You do not have sufficient access to perform this action. -type AccessDeniedException struct { - Message *string - - ErrorCodeOverride *string - - Error_ *string - Error_description *string - - noSmithyDocumentSerde -} - -func (e *AccessDeniedException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *AccessDeniedException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *AccessDeniedException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "AccessDeniedException" - } - return *e.ErrorCodeOverride -} -func (e *AccessDeniedException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Indicates that a request to authorize a client with an access user session -// token is pending. -type AuthorizationPendingException struct { - Message *string - - ErrorCodeOverride *string - - Error_ *string - Error_description *string - - noSmithyDocumentSerde -} - -func (e *AuthorizationPendingException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *AuthorizationPendingException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *AuthorizationPendingException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "AuthorizationPendingException" - } - return *e.ErrorCodeOverride -} -func (e *AuthorizationPendingException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Indicates that the token issued by the service is expired and is no longer -// valid. -type ExpiredTokenException struct { - Message *string - - ErrorCodeOverride *string - - Error_ *string - Error_description *string - - noSmithyDocumentSerde -} - -func (e *ExpiredTokenException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ExpiredTokenException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ExpiredTokenException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ExpiredTokenException" - } - return *e.ErrorCodeOverride -} -func (e *ExpiredTokenException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Indicates that an error from the service occurred while trying to process a -// request. -type InternalServerException struct { - Message *string - - ErrorCodeOverride *string - - Error_ *string - Error_description *string - - noSmithyDocumentSerde -} - -func (e *InternalServerException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InternalServerException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InternalServerException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InternalServerException" - } - return *e.ErrorCodeOverride -} -func (e *InternalServerException) ErrorFault() smithy.ErrorFault { return smithy.FaultServer } - -// Indicates that the clientId or clientSecret in the request is invalid. For -// example, this can occur when a client sends an incorrect clientId or an expired -// clientSecret . -type InvalidClientException struct { - Message *string - - ErrorCodeOverride *string - - Error_ *string - Error_description *string - - noSmithyDocumentSerde -} - -func (e *InvalidClientException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidClientException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidClientException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidClientException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidClientException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Indicates that the client information sent in the request during registration -// is invalid. -type InvalidClientMetadataException struct { - Message *string - - ErrorCodeOverride *string - - Error_ *string - Error_description *string - - noSmithyDocumentSerde -} - -func (e *InvalidClientMetadataException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidClientMetadataException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidClientMetadataException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidClientMetadataException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidClientMetadataException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Indicates that a request contains an invalid grant. This can occur if a client -// makes a CreateToken request with an invalid grant type. -type InvalidGrantException struct { - Message *string - - ErrorCodeOverride *string - - Error_ *string - Error_description *string - - noSmithyDocumentSerde -} - -func (e *InvalidGrantException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidGrantException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidGrantException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidGrantException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidGrantException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Indicates that something is wrong with the input to the request. For example, a -// required parameter might be missing or out of range. -type InvalidRequestException struct { - Message *string - - ErrorCodeOverride *string - - Error_ *string - Error_description *string - - noSmithyDocumentSerde -} - -func (e *InvalidRequestException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidRequestException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidRequestException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidRequestException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidRequestException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Indicates that the scope provided in the request is invalid. -type InvalidScopeException struct { - Message *string - - ErrorCodeOverride *string - - Error_ *string - Error_description *string - - noSmithyDocumentSerde -} - -func (e *InvalidScopeException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidScopeException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidScopeException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidScopeException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidScopeException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Indicates that the client is making the request too frequently and is more than -// the service can handle. -type SlowDownException struct { - Message *string - - ErrorCodeOverride *string - - Error_ *string - Error_description *string - - noSmithyDocumentSerde -} - -func (e *SlowDownException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *SlowDownException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *SlowDownException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "SlowDownException" - } - return *e.ErrorCodeOverride -} -func (e *SlowDownException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Indicates that the client is not currently authorized to make the request. This -// can happen when a clientId is not issued for a public client. -type UnauthorizedClientException struct { - Message *string - - ErrorCodeOverride *string - - Error_ *string - Error_description *string - - noSmithyDocumentSerde -} - -func (e *UnauthorizedClientException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *UnauthorizedClientException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *UnauthorizedClientException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "UnauthorizedClientException" - } - return *e.ErrorCodeOverride -} -func (e *UnauthorizedClientException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Indicates that the grant type in the request is not supported by the service. -type UnsupportedGrantTypeException struct { - Message *string - - ErrorCodeOverride *string - - Error_ *string - Error_description *string - - noSmithyDocumentSerde -} - -func (e *UnsupportedGrantTypeException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *UnsupportedGrantTypeException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *UnsupportedGrantTypeException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "UnsupportedGrantTypeException" - } - return *e.ErrorCodeOverride -} -func (e *UnsupportedGrantTypeException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/types/types.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/types/types.go deleted file mode 100644 index 0ec0789f8..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/types/types.go +++ /dev/null @@ -1,9 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package types - -import ( - smithydocument "github.com/aws/smithy-go/document" -) - -type noSmithyDocumentSerde = smithydocument.NoSerde diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/validators.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/validators.go deleted file mode 100644 index 5a309484e..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/validators.go +++ /dev/null @@ -1,142 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssooidc - -import ( - "context" - "fmt" - smithy "github.com/aws/smithy-go" - "github.com/aws/smithy-go/middleware" -) - -type validateOpCreateToken struct { -} - -func (*validateOpCreateToken) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpCreateToken) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*CreateTokenInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpCreateTokenInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpRegisterClient struct { -} - -func (*validateOpRegisterClient) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpRegisterClient) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*RegisterClientInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpRegisterClientInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpStartDeviceAuthorization struct { -} - -func (*validateOpStartDeviceAuthorization) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpStartDeviceAuthorization) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*StartDeviceAuthorizationInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpStartDeviceAuthorizationInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -func addOpCreateTokenValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpCreateToken{}, middleware.After) -} - -func addOpRegisterClientValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpRegisterClient{}, middleware.After) -} - -func addOpStartDeviceAuthorizationValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpStartDeviceAuthorization{}, middleware.After) -} - -func validateOpCreateTokenInput(v *CreateTokenInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "CreateTokenInput"} - if v.ClientId == nil { - invalidParams.Add(smithy.NewErrParamRequired("ClientId")) - } - if v.ClientSecret == nil { - invalidParams.Add(smithy.NewErrParamRequired("ClientSecret")) - } - if v.GrantType == nil { - invalidParams.Add(smithy.NewErrParamRequired("GrantType")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpRegisterClientInput(v *RegisterClientInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "RegisterClientInput"} - if v.ClientName == nil { - invalidParams.Add(smithy.NewErrParamRequired("ClientName")) - } - if v.ClientType == nil { - invalidParams.Add(smithy.NewErrParamRequired("ClientType")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpStartDeviceAuthorizationInput(v *StartDeviceAuthorizationInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "StartDeviceAuthorizationInput"} - if v.ClientId == nil { - invalidParams.Add(smithy.NewErrParamRequired("ClientId")) - } - if v.ClientSecret == nil { - invalidParams.Add(smithy.NewErrParamRequired("ClientSecret")) - } - if v.StartUrl == nil { - invalidParams.Add(smithy.NewErrParamRequired("StartUrl")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/CHANGELOG.md deleted file mode 100644 index a3f535af8..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/CHANGELOG.md +++ /dev/null @@ -1,307 +0,0 @@ -# v1.21.5 (2023-08-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.21.4 (2023-08-18) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.21.3 (2023-08-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.21.2 (2023-08-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.21.1 (2023-08-01) - -* No change notes available for this release. - -# v1.21.0 (2023-07-31) - -* **Feature**: Adds support for smithy-modeled endpoint resolution. A new rules-based endpoint resolution will be added to the SDK which will supercede and deprecate existing endpoint resolution. Specifically, EndpointResolver will be deprecated while BaseEndpoint and EndpointResolverV2 will take its place. For more information, please see the Endpoints section in our Developer Guide. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.20.1 (2023-07-28) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.20.0 (2023-07-25) - -* **Feature**: API updates for the AWS Security Token Service - -# v1.19.3 (2023-07-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.19.2 (2023-06-15) - -* No change notes available for this release. - -# v1.19.1 (2023-06-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.19.0 (2023-05-08) - -* **Feature**: Documentation updates for AWS Security Token Service. - -# v1.18.11 (2023-05-04) - -* No change notes available for this release. - -# v1.18.10 (2023-04-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.9 (2023-04-10) - -* No change notes available for this release. - -# v1.18.8 (2023-04-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.7 (2023-03-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.6 (2023-03-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.5 (2023-02-22) - -* **Bug Fix**: Prevent nil pointer dereference when retrieving error codes. - -# v1.18.4 (2023-02-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.3 (2023-02-03) - -* **Dependency Update**: Updated to the latest SDK module versions -* **Dependency Update**: Upgrade smithy to 1.27.2 and correct empty query list serialization. - -# v1.18.2 (2023-01-25) - -* **Documentation**: Doc only change to update wording in a key topic - -# v1.18.1 (2023-01-23) - -* No change notes available for this release. - -# v1.18.0 (2023-01-05) - -* **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). - -# v1.17.7 (2022-12-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.6 (2022-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.5 (2022-11-22) - -* No change notes available for this release. - -# v1.17.4 (2022-11-17) - -* **Documentation**: Documentation updates for AWS Security Token Service. - -# v1.17.3 (2022-11-16) - -* No change notes available for this release. - -# v1.17.2 (2022-11-10) - -* No change notes available for this release. - -# v1.17.1 (2022-10-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.0 (2022-10-21) - -* **Feature**: Add presign functionality for sts:AssumeRole operation -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.19 (2022-09-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.18 (2022-09-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.17 (2022-09-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.16 (2022-08-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.15 (2022-08-30) - -* No change notes available for this release. - -# v1.16.14 (2022-08-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.13 (2022-08-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.12 (2022-08-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.11 (2022-08-08) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.10 (2022-08-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.9 (2022-07-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.8 (2022-06-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.7 (2022-06-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.6 (2022-05-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.5 (2022-05-16) - -* **Documentation**: Documentation updates for AWS Security Token Service. - -# v1.16.4 (2022-04-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.3 (2022-03-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.2 (2022-03-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.1 (2022-03-23) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.0 (2022-03-08) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Documentation**: Updated service client model to latest release. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.0 (2022-02-24) - -* **Feature**: API client updated -* **Feature**: Adds RetryMaxAttempts and RetryMod to API client Options. This allows the API clients' default Retryer to be configured from the shared configuration files or environment variables. Adding a new Retry mode of `Adaptive`. `Adaptive` retry mode is an experimental mode, adding client rate limiting when throttles reponses are received from an API. See [retry.AdaptiveMode](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/aws/retry#AdaptiveMode) for more details, and configuration options. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.0 (2022-01-14) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.0 (2022-01-07) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.0 (2021-12-21) - -* **Feature**: Updated to latest service endpoints - -# v1.11.1 (2021-12-02) - -* **Bug Fix**: Fixes a bug that prevented aws.EndpointResolverWithOptions from being used by the service client. ([#1514](https://github.com/aws/aws-sdk-go-v2/pull/1514)) -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.0 (2021-11-30) - -* **Feature**: API client updated - -# v1.10.1 (2021-11-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.0 (2021-11-12) - -* **Feature**: Service clients now support custom endpoints that have an initial URI path defined. - -# v1.9.0 (2021-11-06) - -* **Feature**: The SDK now supports configuration of FIPS and DualStack endpoints using environment variables, shared configuration, or programmatically. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.0 (2021-10-21) - -* **Feature**: API client updated -* **Feature**: Updated to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.7.2 (2021-10-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.7.1 (2021-09-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.7.0 (2021-08-27) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.2 (2021-08-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.1 (2021-08-04) - -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.0 (2021-07-15) - -* **Feature**: The ErrorCode method on generated service error types has been corrected to match the API model. -* **Documentation**: Updated service model to latest revision. -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.5.0 (2021-06-25) - -* **Feature**: API client updated -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.1 (2021-05-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.0 (2021-05-14) - -* **Feature**: Constant has been added to modules to enable runtime version inspection for reporting. -* **Dependency Update**: Updated to the latest SDK module versions - diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/LICENSE.txt deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/LICENSE.txt +++ /dev/null @@ -1,202 +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/aws/aws-sdk-go-v2/service/sts/api_client.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_client.go deleted file mode 100644 index 22ac69043..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_client.go +++ /dev/null @@ -1,629 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -import ( - "context" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/aws/defaults" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/protocol/query" - "github.com/aws/aws-sdk-go-v2/aws/retry" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" - internalConfig "github.com/aws/aws-sdk-go-v2/internal/configsources" - presignedurlcust "github.com/aws/aws-sdk-go-v2/service/internal/presigned-url" - smithy "github.com/aws/smithy-go" - smithydocument "github.com/aws/smithy-go/document" - "github.com/aws/smithy-go/logging" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" - "net" - "net/http" - "time" -) - -const ServiceID = "STS" -const ServiceAPIVersion = "2011-06-15" - -// Client provides the API client to make operations call for AWS Security Token -// Service. -type Client struct { - options Options -} - -// New returns an initialized Client based on the functional options. Provide -// additional functional options to further configure the behavior of the client, -// such as changing the client's endpoint or adding custom middleware behavior. -func New(options Options, optFns ...func(*Options)) *Client { - options = options.Copy() - - resolveDefaultLogger(&options) - - setResolvedDefaultsMode(&options) - - resolveRetryer(&options) - - resolveHTTPClient(&options) - - resolveHTTPSignerV4(&options) - - for _, fn := range optFns { - fn(&options) - } - - client := &Client{ - options: options, - } - - return client -} - -type Options struct { - // Set of options to modify how an operation is invoked. These apply to all - // operations invoked for this client. Use functional options on operation call to - // modify this list for per operation behavior. - APIOptions []func(*middleware.Stack) error - - // The optional application specific identifier appended to the User-Agent header. - AppID string - - // This endpoint will be given as input to an EndpointResolverV2. It is used for - // providing a custom base endpoint that is subject to modifications by the - // processing EndpointResolverV2. - BaseEndpoint *string - - // Configures the events that will be sent to the configured logger. - ClientLogMode aws.ClientLogMode - - // The credentials object to use when signing requests. - Credentials aws.CredentialsProvider - - // The configuration DefaultsMode that the SDK should use when constructing the - // clients initial default settings. - DefaultsMode aws.DefaultsMode - - // The endpoint options to be used when attempting to resolve an endpoint. - EndpointOptions EndpointResolverOptions - - // The service endpoint resolver. - // - // Deprecated: Deprecated: EndpointResolver and WithEndpointResolver. Providing a - // value for this field will likely prevent you from using any endpoint-related - // service features released after the introduction of EndpointResolverV2 and - // BaseEndpoint. To migrate an EndpointResolver implementation that uses a custom - // endpoint, set the client option BaseEndpoint instead. - EndpointResolver EndpointResolver - - // Resolves the endpoint used for a particular service. This should be used over - // the deprecated EndpointResolver - EndpointResolverV2 EndpointResolverV2 - - // Signature Version 4 (SigV4) Signer - HTTPSignerV4 HTTPSignerV4 - - // The logger writer interface to write logging messages to. - Logger logging.Logger - - // The region to send requests to. (Required) - Region string - - // RetryMaxAttempts specifies the maximum number attempts an API client will call - // an operation that fails with a retryable error. A value of 0 is ignored, and - // will not be used to configure the API client created default retryer, or modify - // per operation call's retry max attempts. When creating a new API Clients this - // member will only be used if the Retryer Options member is nil. This value will - // be ignored if Retryer is not nil. If specified in an operation call's functional - // options with a value that is different than the constructed client's Options, - // the Client's Retryer will be wrapped to use the operation's specific - // RetryMaxAttempts value. - RetryMaxAttempts int - - // RetryMode specifies the retry mode the API client will be created with, if - // Retryer option is not also specified. When creating a new API Clients this - // member will only be used if the Retryer Options member is nil. This value will - // be ignored if Retryer is not nil. Currently does not support per operation call - // overrides, may in the future. - RetryMode aws.RetryMode - - // Retryer guides how HTTP requests should be retried in case of recoverable - // failures. When nil the API client will use a default retryer. The kind of - // default retry created by the API client can be changed with the RetryMode - // option. - Retryer aws.Retryer - - // The RuntimeEnvironment configuration, only populated if the DefaultsMode is set - // to DefaultsModeAuto and is initialized using config.LoadDefaultConfig . You - // should not populate this structure programmatically, or rely on the values here - // within your applications. - RuntimeEnvironment aws.RuntimeEnvironment - - // The initial DefaultsMode used when the client options were constructed. If the - // DefaultsMode was set to aws.DefaultsModeAuto this will store what the resolved - // value was at that point in time. Currently does not support per operation call - // overrides, may in the future. - resolvedDefaultsMode aws.DefaultsMode - - // The HTTP client to invoke API calls with. Defaults to client's default HTTP - // implementation if nil. - HTTPClient HTTPClient -} - -// WithAPIOptions returns a functional option for setting the Client's APIOptions -// option. -func WithAPIOptions(optFns ...func(*middleware.Stack) error) func(*Options) { - return func(o *Options) { - o.APIOptions = append(o.APIOptions, optFns...) - } -} - -// Deprecated: EndpointResolver and WithEndpointResolver. Providing a value for -// this field will likely prevent you from using any endpoint-related service -// features released after the introduction of EndpointResolverV2 and BaseEndpoint. -// To migrate an EndpointResolver implementation that uses a custom endpoint, set -// the client option BaseEndpoint instead. -func WithEndpointResolver(v EndpointResolver) func(*Options) { - return func(o *Options) { - o.EndpointResolver = v - } -} - -// WithEndpointResolverV2 returns a functional option for setting the Client's -// EndpointResolverV2 option. -func WithEndpointResolverV2(v EndpointResolverV2) func(*Options) { - return func(o *Options) { - o.EndpointResolverV2 = v - } -} - -type HTTPClient interface { - Do(*http.Request) (*http.Response, error) -} - -// Copy creates a clone where the APIOptions list is deep copied. -func (o Options) Copy() Options { - to := o - to.APIOptions = make([]func(*middleware.Stack) error, len(o.APIOptions)) - copy(to.APIOptions, o.APIOptions) - - return to -} -func (c *Client) invokeOperation(ctx context.Context, opID string, params interface{}, optFns []func(*Options), stackFns ...func(*middleware.Stack, Options) error) (result interface{}, metadata middleware.Metadata, err error) { - ctx = middleware.ClearStackValues(ctx) - stack := middleware.NewStack(opID, smithyhttp.NewStackRequest) - options := c.options.Copy() - resolveEndpointResolverV2(&options) - - for _, fn := range optFns { - fn(&options) - } - - finalizeRetryMaxAttemptOptions(&options, *c) - - finalizeClientEndpointResolverOptions(&options) - - for _, fn := range stackFns { - if err := fn(stack, options); err != nil { - return nil, metadata, err - } - } - - for _, fn := range options.APIOptions { - if err := fn(stack); err != nil { - return nil, metadata, err - } - } - - handler := middleware.DecorateHandler(smithyhttp.NewClientHandler(options.HTTPClient), stack) - result, metadata, err = handler.Handle(ctx, params) - if err != nil { - err = &smithy.OperationError{ - ServiceID: ServiceID, - OperationName: opID, - Err: err, - } - } - return result, metadata, err -} - -type noSmithyDocumentSerde = smithydocument.NoSerde - -type legacyEndpointContextSetter struct { - LegacyResolver EndpointResolver -} - -func (*legacyEndpointContextSetter) ID() string { - return "legacyEndpointContextSetter" -} - -func (m *legacyEndpointContextSetter) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - if m.LegacyResolver != nil { - ctx = awsmiddleware.SetRequiresLegacyEndpoints(ctx, true) - } - - return next.HandleInitialize(ctx, in) - -} -func addlegacyEndpointContextSetter(stack *middleware.Stack, o Options) error { - return stack.Initialize.Add(&legacyEndpointContextSetter{ - LegacyResolver: o.EndpointResolver, - }, middleware.Before) -} - -func resolveDefaultLogger(o *Options) { - if o.Logger != nil { - return - } - o.Logger = logging.Nop{} -} - -func addSetLoggerMiddleware(stack *middleware.Stack, o Options) error { - return middleware.AddSetLoggerMiddleware(stack, o.Logger) -} - -func setResolvedDefaultsMode(o *Options) { - if len(o.resolvedDefaultsMode) > 0 { - return - } - - var mode aws.DefaultsMode - mode.SetFromString(string(o.DefaultsMode)) - - if mode == aws.DefaultsModeAuto { - mode = defaults.ResolveDefaultsModeAuto(o.Region, o.RuntimeEnvironment) - } - - o.resolvedDefaultsMode = mode -} - -// NewFromConfig returns a new client from the provided config. -func NewFromConfig(cfg aws.Config, optFns ...func(*Options)) *Client { - opts := Options{ - Region: cfg.Region, - DefaultsMode: cfg.DefaultsMode, - RuntimeEnvironment: cfg.RuntimeEnvironment, - HTTPClient: cfg.HTTPClient, - Credentials: cfg.Credentials, - APIOptions: cfg.APIOptions, - Logger: cfg.Logger, - ClientLogMode: cfg.ClientLogMode, - AppID: cfg.AppID, - } - resolveAWSRetryerProvider(cfg, &opts) - resolveAWSRetryMaxAttempts(cfg, &opts) - resolveAWSRetryMode(cfg, &opts) - resolveAWSEndpointResolver(cfg, &opts) - resolveUseDualStackEndpoint(cfg, &opts) - resolveUseFIPSEndpoint(cfg, &opts) - return New(opts, optFns...) -} - -func resolveHTTPClient(o *Options) { - var buildable *awshttp.BuildableClient - - if o.HTTPClient != nil { - var ok bool - buildable, ok = o.HTTPClient.(*awshttp.BuildableClient) - if !ok { - return - } - } else { - buildable = awshttp.NewBuildableClient() - } - - modeConfig, err := defaults.GetModeConfiguration(o.resolvedDefaultsMode) - if err == nil { - buildable = buildable.WithDialerOptions(func(dialer *net.Dialer) { - if dialerTimeout, ok := modeConfig.GetConnectTimeout(); ok { - dialer.Timeout = dialerTimeout - } - }) - - buildable = buildable.WithTransportOptions(func(transport *http.Transport) { - if tlsHandshakeTimeout, ok := modeConfig.GetTLSNegotiationTimeout(); ok { - transport.TLSHandshakeTimeout = tlsHandshakeTimeout - } - }) - } - - o.HTTPClient = buildable -} - -func resolveRetryer(o *Options) { - if o.Retryer != nil { - return - } - - if len(o.RetryMode) == 0 { - modeConfig, err := defaults.GetModeConfiguration(o.resolvedDefaultsMode) - if err == nil { - o.RetryMode = modeConfig.RetryMode - } - } - if len(o.RetryMode) == 0 { - o.RetryMode = aws.RetryModeStandard - } - - var standardOptions []func(*retry.StandardOptions) - if v := o.RetryMaxAttempts; v != 0 { - standardOptions = append(standardOptions, func(so *retry.StandardOptions) { - so.MaxAttempts = v - }) - } - - switch o.RetryMode { - case aws.RetryModeAdaptive: - var adaptiveOptions []func(*retry.AdaptiveModeOptions) - if len(standardOptions) != 0 { - adaptiveOptions = append(adaptiveOptions, func(ao *retry.AdaptiveModeOptions) { - ao.StandardOptions = append(ao.StandardOptions, standardOptions...) - }) - } - o.Retryer = retry.NewAdaptiveMode(adaptiveOptions...) - - default: - o.Retryer = retry.NewStandard(standardOptions...) - } -} - -func resolveAWSRetryerProvider(cfg aws.Config, o *Options) { - if cfg.Retryer == nil { - return - } - o.Retryer = cfg.Retryer() -} - -func resolveAWSRetryMode(cfg aws.Config, o *Options) { - if len(cfg.RetryMode) == 0 { - return - } - o.RetryMode = cfg.RetryMode -} -func resolveAWSRetryMaxAttempts(cfg aws.Config, o *Options) { - if cfg.RetryMaxAttempts == 0 { - return - } - o.RetryMaxAttempts = cfg.RetryMaxAttempts -} - -func finalizeRetryMaxAttemptOptions(o *Options, client Client) { - if v := o.RetryMaxAttempts; v == 0 || v == client.options.RetryMaxAttempts { - return - } - - o.Retryer = retry.AddWithMaxAttempts(o.Retryer, o.RetryMaxAttempts) -} - -func resolveAWSEndpointResolver(cfg aws.Config, o *Options) { - if cfg.EndpointResolver == nil && cfg.EndpointResolverWithOptions == nil { - return - } - o.EndpointResolver = withEndpointResolver(cfg.EndpointResolver, cfg.EndpointResolverWithOptions) -} - -func addClientUserAgent(stack *middleware.Stack, options Options) error { - if err := awsmiddleware.AddSDKAgentKeyValue(awsmiddleware.APIMetadata, "sts", goModuleVersion)(stack); err != nil { - return err - } - - if len(options.AppID) > 0 { - return awsmiddleware.AddSDKAgentKey(awsmiddleware.ApplicationIdentifier, options.AppID)(stack) - } - - return nil -} - -func addHTTPSignerV4Middleware(stack *middleware.Stack, o Options) error { - mw := v4.NewSignHTTPRequestMiddleware(v4.SignHTTPRequestMiddlewareOptions{ - CredentialsProvider: o.Credentials, - Signer: o.HTTPSignerV4, - LogSigning: o.ClientLogMode.IsSigning(), - }) - return stack.Finalize.Add(mw, middleware.After) -} - -type HTTPSignerV4 interface { - SignHTTP(ctx context.Context, credentials aws.Credentials, r *http.Request, payloadHash string, service string, region string, signingTime time.Time, optFns ...func(*v4.SignerOptions)) error -} - -func resolveHTTPSignerV4(o *Options) { - if o.HTTPSignerV4 != nil { - return - } - o.HTTPSignerV4 = newDefaultV4Signer(*o) -} - -func newDefaultV4Signer(o Options) *v4.Signer { - return v4.NewSigner(func(so *v4.SignerOptions) { - so.Logger = o.Logger - so.LogSigning = o.ClientLogMode.IsSigning() - }) -} - -func addRetryMiddlewares(stack *middleware.Stack, o Options) error { - mo := retry.AddRetryMiddlewaresOptions{ - Retryer: o.Retryer, - LogRetryAttempts: o.ClientLogMode.IsRetries(), - } - return retry.AddRetryMiddlewares(stack, mo) -} - -// resolves dual-stack endpoint configuration -func resolveUseDualStackEndpoint(cfg aws.Config, o *Options) error { - if len(cfg.ConfigSources) == 0 { - return nil - } - value, found, err := internalConfig.ResolveUseDualStackEndpoint(context.Background(), cfg.ConfigSources) - if err != nil { - return err - } - if found { - o.EndpointOptions.UseDualStackEndpoint = value - } - return nil -} - -// resolves FIPS endpoint configuration -func resolveUseFIPSEndpoint(cfg aws.Config, o *Options) error { - if len(cfg.ConfigSources) == 0 { - return nil - } - value, found, err := internalConfig.ResolveUseFIPSEndpoint(context.Background(), cfg.ConfigSources) - if err != nil { - return err - } - if found { - o.EndpointOptions.UseFIPSEndpoint = value - } - return nil -} - -func addRequestIDRetrieverMiddleware(stack *middleware.Stack) error { - return awsmiddleware.AddRequestIDRetrieverMiddleware(stack) -} - -func addResponseErrorMiddleware(stack *middleware.Stack) error { - return awshttp.AddResponseErrorMiddleware(stack) -} - -// HTTPPresignerV4 represents presigner interface used by presign url client -type HTTPPresignerV4 interface { - PresignHTTP( - ctx context.Context, credentials aws.Credentials, r *http.Request, - payloadHash string, service string, region string, signingTime time.Time, - optFns ...func(*v4.SignerOptions), - ) (url string, signedHeader http.Header, err error) -} - -// PresignOptions represents the presign client options -type PresignOptions struct { - - // ClientOptions are list of functional options to mutate client options used by - // the presign client. - ClientOptions []func(*Options) - - // Presigner is the presigner used by the presign url client - Presigner HTTPPresignerV4 -} - -func (o PresignOptions) copy() PresignOptions { - clientOptions := make([]func(*Options), len(o.ClientOptions)) - copy(clientOptions, o.ClientOptions) - o.ClientOptions = clientOptions - return o -} - -// WithPresignClientFromClientOptions is a helper utility to retrieve a function -// that takes PresignOption as input -func WithPresignClientFromClientOptions(optFns ...func(*Options)) func(*PresignOptions) { - return withPresignClientFromClientOptions(optFns).options -} - -type withPresignClientFromClientOptions []func(*Options) - -func (w withPresignClientFromClientOptions) options(o *PresignOptions) { - o.ClientOptions = append(o.ClientOptions, w...) -} - -// PresignClient represents the presign url client -type PresignClient struct { - client *Client - options PresignOptions -} - -// NewPresignClient generates a presign client using provided API Client and -// presign options -func NewPresignClient(c *Client, optFns ...func(*PresignOptions)) *PresignClient { - var options PresignOptions - for _, fn := range optFns { - fn(&options) - } - if len(options.ClientOptions) != 0 { - c = New(c.options, options.ClientOptions...) - } - - if options.Presigner == nil { - options.Presigner = newDefaultV4Signer(c.options) - } - - return &PresignClient{ - client: c, - options: options, - } -} - -func withNopHTTPClientAPIOption(o *Options) { - o.HTTPClient = smithyhttp.NopClient{} -} - -type presignConverter PresignOptions - -func (c presignConverter) convertToPresignMiddleware(stack *middleware.Stack, options Options) (err error) { - stack.Finalize.Clear() - stack.Deserialize.Clear() - stack.Build.Remove((*awsmiddleware.ClientRequestID)(nil).ID()) - stack.Build.Remove("UserAgent") - pmw := v4.NewPresignHTTPRequestMiddleware(v4.PresignHTTPRequestMiddlewareOptions{ - CredentialsProvider: options.Credentials, - Presigner: c.Presigner, - LogSigning: options.ClientLogMode.IsSigning(), - }) - err = stack.Finalize.Add(pmw, middleware.After) - if err != nil { - return err - } - if err = smithyhttp.AddNoPayloadDefaultContentTypeRemover(stack); err != nil { - return err - } - // convert request to a GET request - err = query.AddAsGetRequestMiddleware(stack) - if err != nil { - return err - } - err = presignedurlcust.AddAsIsPresigingMiddleware(stack) - if err != nil { - return err - } - return nil -} - -func addRequestResponseLogging(stack *middleware.Stack, o Options) error { - return stack.Deserialize.Add(&smithyhttp.RequestResponseLogger{ - LogRequest: o.ClientLogMode.IsRequest(), - LogRequestWithBody: o.ClientLogMode.IsRequestWithBody(), - LogResponse: o.ClientLogMode.IsResponse(), - LogResponseWithBody: o.ClientLogMode.IsResponseWithBody(), - }, middleware.After) -} - -type endpointDisableHTTPSMiddleware struct { - EndpointDisableHTTPS bool -} - -func (*endpointDisableHTTPSMiddleware) ID() string { - return "endpointDisableHTTPSMiddleware" -} - -func (m *endpointDisableHTTPSMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointDisableHTTPS && !smithyhttp.GetHostnameImmutable(ctx) { - req.URL.Scheme = "http" - } - - return next.HandleSerialize(ctx, in) - -} -func addendpointDisableHTTPSMiddleware(stack *middleware.Stack, o Options) error { - return stack.Serialize.Insert(&endpointDisableHTTPSMiddleware{ - EndpointDisableHTTPS: o.EndpointOptions.DisableHTTPS, - }, "OperationSerializer", middleware.Before) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRole.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRole.go deleted file mode 100644 index 0ef7affc5..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRole.go +++ /dev/null @@ -1,558 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -import ( - "context" - "errors" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - "github.com/aws/aws-sdk-go-v2/service/sts/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Returns a set of temporary security credentials that you can use to access -// Amazon Web Services resources. These temporary credentials consist of an access -// key ID, a secret access key, and a security token. Typically, you use AssumeRole -// within your account or for cross-account access. For a comparison of AssumeRole -// with other API operations that produce temporary credentials, see Requesting -// Temporary Security Credentials (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the Amazon Web Services STS API operations (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. Permissions The temporary security credentials created by -// AssumeRole can be used to make API calls to any Amazon Web Services service -// with the following exception: You cannot call the Amazon Web Services STS -// GetFederationToken or GetSessionToken API operations. (Optional) You can pass -// inline or managed session policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) -// to this operation. You can pass a single JSON policy document to use as an -// inline session policy. You can also specify up to 10 managed policy Amazon -// Resource Names (ARNs) to use as managed session policies. The plaintext that you -// use for both inline and managed session policies can't exceed 2,048 characters. -// Passing policies to this operation returns new temporary credentials. The -// resulting session's permissions are the intersection of the role's -// identity-based policy and the session policies. You can use the role's temporary -// credentials in subsequent Amazon Web Services API calls to access resources in -// the account that owns the role. You cannot use session policies to grant more -// permissions than those allowed by the identity-based policy of the role that is -// being assumed. For more information, see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) -// in the IAM User Guide. When you create a role, you create two policies: a role -// trust policy that specifies who can assume the role, and a permissions policy -// that specifies what can be done with the role. You specify the trusted principal -// that is allowed to assume the role in the role trust policy. To assume a role -// from a different account, your Amazon Web Services account must be trusted by -// the role. The trust relationship is defined in the role's trust policy when the -// role is created. That trust policy states which accounts are allowed to delegate -// that access to users in the account. A user who wants to access a role in a -// different account must also have permissions that are delegated from the account -// administrator. The administrator must attach a policy that allows the user to -// call AssumeRole for the ARN of the role in the other account. To allow a user -// to assume a role in the same account, you can do either of the following: -// - Attach a policy to the user that allows the user to call AssumeRole (as long -// as the role's trust policy trusts the account). -// - Add the user as a principal directly in the role's trust policy. -// -// You can do either because the role’s trust policy acts as an IAM resource-based -// policy. When a resource-based policy grants access to a principal in the same -// account, no additional identity-based policy is required. For more information -// about trust policies and resource-based policies, see IAM Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html) -// in the IAM User Guide. Tags (Optional) You can pass tag key-value pairs to your -// session. These tags are called session tags. For more information about session -// tags, see Passing Session Tags in STS (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) -// in the IAM User Guide. An administrator must grant you the permissions necessary -// to pass session tags. The administrator can also create granular permissions to -// allow you to pass only specific session tags. For more information, see -// Tutorial: Using Tags for Attribute-Based Access Control (https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_attribute-based-access-control.html) -// in the IAM User Guide. You can set the session tags as transitive. Transitive -// tags persist during role chaining. For more information, see Chaining Roles -// with Session Tags (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html#id_session-tags_role-chaining) -// in the IAM User Guide. Using MFA with AssumeRole (Optional) You can include -// multi-factor authentication (MFA) information when you call AssumeRole . This is -// useful for cross-account scenarios to ensure that the user that assumes the role -// has been authenticated with an Amazon Web Services MFA device. In that scenario, -// the trust policy of the role being assumed includes a condition that tests for -// MFA authentication. If the caller does not include valid MFA information, the -// request to assume the role is denied. The condition in a trust policy that tests -// for MFA authentication might look like the following example. "Condition": -// {"Bool": {"aws:MultiFactorAuthPresent": true}} For more information, see -// Configuring MFA-Protected API Access (https://docs.aws.amazon.com/IAM/latest/UserGuide/MFAProtectedAPI.html) -// in the IAM User Guide guide. To use MFA with AssumeRole , you pass values for -// the SerialNumber and TokenCode parameters. The SerialNumber value identifies -// the user's hardware or virtual MFA device. The TokenCode is the time-based -// one-time password (TOTP) that the MFA device produces. -func (c *Client) AssumeRole(ctx context.Context, params *AssumeRoleInput, optFns ...func(*Options)) (*AssumeRoleOutput, error) { - if params == nil { - params = &AssumeRoleInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "AssumeRole", params, optFns, c.addOperationAssumeRoleMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*AssumeRoleOutput) - out.ResultMetadata = metadata - return out, nil -} - -type AssumeRoleInput struct { - - // The Amazon Resource Name (ARN) of the role to assume. - // - // This member is required. - RoleArn *string - - // An identifier for the assumed role session. Use the role session name to - // uniquely identify a session when the same role is assumed by different - // principals or for different reasons. In cross-account scenarios, the role - // session name is visible to, and can be logged by the account that owns the role. - // The role session name is also used in the ARN of the assumed role principal. - // This means that subsequent cross-account API requests that use the temporary - // security credentials will expose the role session name to the external account - // in their CloudTrail logs. The regex used to validate this parameter is a string - // of characters consisting of upper- and lower-case alphanumeric characters with - // no spaces. You can also include underscores or any of the following characters: - // =,.@- - // - // This member is required. - RoleSessionName *string - - // The duration, in seconds, of the role session. The value specified can range - // from 900 seconds (15 minutes) up to the maximum session duration set for the - // role. The maximum session duration setting can have a value from 1 hour to 12 - // hours. If you specify a value higher than this setting or the administrator - // setting (whichever is lower), the operation fails. For example, if you specify a - // session duration of 12 hours, but your administrator set the maximum session - // duration to 6 hours, your operation fails. Role chaining limits your Amazon Web - // Services CLI or Amazon Web Services API role session to a maximum of one hour. - // When you use the AssumeRole API operation to assume a role, you can specify the - // duration of your role session with the DurationSeconds parameter. You can - // specify a parameter value of up to 43200 seconds (12 hours), depending on the - // maximum session duration setting for your role. However, if you assume a role - // using role chaining and provide a DurationSeconds parameter value greater than - // one hour, the operation fails. To learn how to view the maximum value for your - // role, see View the Maximum Session Duration Setting for a Role (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session) - // in the IAM User Guide. By default, the value is set to 3600 seconds. The - // DurationSeconds parameter is separate from the duration of a console session - // that you might request using the returned credentials. The request to the - // federation endpoint for a console sign-in token takes a SessionDuration - // parameter that specifies the maximum length of the console session. For more - // information, see Creating a URL that Enables Federated Users to Access the - // Amazon Web Services Management Console (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html) - // in the IAM User Guide. - DurationSeconds *int32 - - // A unique identifier that might be required when you assume a role in another - // account. If the administrator of the account to which the role belongs provided - // you with an external ID, then provide that value in the ExternalId parameter. - // This value can be any string, such as a passphrase or account number. A - // cross-account role is usually set up to trust everyone in an account. Therefore, - // the administrator of the trusting account might send an external ID to the - // administrator of the trusted account. That way, only someone with the ID can - // assume the role, rather than everyone in the account. For more information about - // the external ID, see How to Use an External ID When Granting Access to Your - // Amazon Web Services Resources to a Third Party (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html) - // in the IAM User Guide. The regex used to validate this parameter is a string of - // characters consisting of upper- and lower-case alphanumeric characters with no - // spaces. You can also include underscores or any of the following characters: - // =,.@:/- - ExternalId *string - - // An IAM policy in JSON format that you want to use as an inline session policy. - // This parameter is optional. Passing policies to this operation returns new - // temporary credentials. The resulting session's permissions are the intersection - // of the role's identity-based policy and the session policies. You can use the - // role's temporary credentials in subsequent Amazon Web Services API calls to - // access resources in the account that owns the role. You cannot use session - // policies to grant more permissions than those allowed by the identity-based - // policy of the role that is being assumed. For more information, see Session - // Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // in the IAM User Guide. The plaintext that you use for both inline and managed - // session policies can't exceed 2,048 characters. The JSON policy characters can - // be any ASCII character from the space character to the end of the valid - // character list (\u0020 through \u00FF). It can also include the tab (\u0009), - // linefeed (\u000A), and carriage return (\u000D) characters. An Amazon Web - // Services conversion compresses the passed inline session policy, managed policy - // ARNs, and session tags into a packed binary format that has a separate limit. - // Your request can fail for this limit even if your plaintext meets the other - // requirements. The PackedPolicySize response element indicates by percentage how - // close the policies and tags for your request are to the upper size limit. - Policy *string - - // The Amazon Resource Names (ARNs) of the IAM managed policies that you want to - // use as managed session policies. The policies must exist in the same account as - // the role. This parameter is optional. You can provide up to 10 managed policy - // ARNs. However, the plaintext that you use for both inline and managed session - // policies can't exceed 2,048 characters. For more information about ARNs, see - // Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces (https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) - // in the Amazon Web Services General Reference. An Amazon Web Services conversion - // compresses the passed inline session policy, managed policy ARNs, and session - // tags into a packed binary format that has a separate limit. Your request can - // fail for this limit even if your plaintext meets the other requirements. The - // PackedPolicySize response element indicates by percentage how close the policies - // and tags for your request are to the upper size limit. Passing policies to this - // operation returns new temporary credentials. The resulting session's permissions - // are the intersection of the role's identity-based policy and the session - // policies. You can use the role's temporary credentials in subsequent Amazon Web - // Services API calls to access resources in the account that owns the role. You - // cannot use session policies to grant more permissions than those allowed by the - // identity-based policy of the role that is being assumed. For more information, - // see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // in the IAM User Guide. - PolicyArns []types.PolicyDescriptorType - - // Reserved for future use. - ProvidedContexts []types.ProvidedContext - - // The identification number of the MFA device that is associated with the user - // who is making the AssumeRole call. Specify this value if the trust policy of - // the role being assumed includes a condition that requires MFA authentication. - // The value is either the serial number for a hardware device (such as - // GAHT12345678 ) or an Amazon Resource Name (ARN) for a virtual device (such as - // arn:aws:iam::123456789012:mfa/user ). The regex used to validate this parameter - // is a string of characters consisting of upper- and lower-case alphanumeric - // characters with no spaces. You can also include underscores or any of the - // following characters: =,.@- - SerialNumber *string - - // The source identity specified by the principal that is calling the AssumeRole - // operation. You can require users to specify a source identity when they assume a - // role. You do this by using the sts:SourceIdentity condition key in a role trust - // policy. You can use source identity information in CloudTrail logs to determine - // who took actions with a role. You can use the aws:SourceIdentity condition key - // to further control access to Amazon Web Services resources based on the value of - // source identity. For more information about using source identity, see Monitor - // and control actions taken with assumed roles (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_monitor.html) - // in the IAM User Guide. The regex used to validate this parameter is a string of - // characters consisting of upper- and lower-case alphanumeric characters with no - // spaces. You can also include underscores or any of the following characters: - // =,.@-. You cannot use a value that begins with the text aws: . This prefix is - // reserved for Amazon Web Services internal use. - SourceIdentity *string - - // A list of session tags that you want to pass. Each session tag consists of a - // key name and an associated value. For more information about session tags, see - // Tagging Amazon Web Services STS Sessions (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) - // in the IAM User Guide. This parameter is optional. You can pass up to 50 session - // tags. The plaintext session tag keys can’t exceed 128 characters, and the values - // can’t exceed 256 characters. For these and additional limits, see IAM and STS - // Character Limits (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html#reference_iam-limits-entity-length) - // in the IAM User Guide. An Amazon Web Services conversion compresses the passed - // inline session policy, managed policy ARNs, and session tags into a packed - // binary format that has a separate limit. Your request can fail for this limit - // even if your plaintext meets the other requirements. The PackedPolicySize - // response element indicates by percentage how close the policies and tags for - // your request are to the upper size limit. You can pass a session tag with the - // same key as a tag that is already attached to the role. When you do, session - // tags override a role tag with the same key. Tag key–value pairs are not case - // sensitive, but case is preserved. This means that you cannot have separate - // Department and department tag keys. Assume that the role has the Department = - // Marketing tag and you pass the department = engineering session tag. Department - // and department are not saved as separate tags, and the session tag passed in - // the request takes precedence over the role tag. Additionally, if you used - // temporary credentials to perform this operation, the new session inherits any - // transitive session tags from the calling session. If you pass a session tag with - // the same key as an inherited tag, the operation fails. To view the inherited - // tags for a session, see the CloudTrail logs. For more information, see Viewing - // Session Tags in CloudTrail (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html#id_session-tags_ctlogs) - // in the IAM User Guide. - Tags []types.Tag - - // The value provided by the MFA device, if the trust policy of the role being - // assumed requires MFA. (In other words, if the policy includes a condition that - // tests for MFA). If the role being assumed requires MFA and if the TokenCode - // value is missing or expired, the AssumeRole call returns an "access denied" - // error. The format for this parameter, as described by its regex pattern, is a - // sequence of six numeric digits. - TokenCode *string - - // A list of keys for session tags that you want to set as transitive. If you set - // a tag key as transitive, the corresponding key and value passes to subsequent - // sessions in a role chain. For more information, see Chaining Roles with Session - // Tags (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html#id_session-tags_role-chaining) - // in the IAM User Guide. This parameter is optional. When you set session tags as - // transitive, the session policy and session tags packed binary limit is not - // affected. If you choose not to specify a transitive tag key, then no tags are - // passed from this session to any subsequent sessions. - TransitiveTagKeys []string - - noSmithyDocumentSerde -} - -// Contains the response to a successful AssumeRole request, including temporary -// Amazon Web Services credentials that can be used to make Amazon Web Services -// requests. -type AssumeRoleOutput struct { - - // The Amazon Resource Name (ARN) and the assumed role ID, which are identifiers - // that you can use to refer to the resulting temporary security credentials. For - // example, you can reference these credentials as a principal in a resource-based - // policy by using the ARN or assumed role ID. The ARN and ID include the - // RoleSessionName that you specified when you called AssumeRole . - AssumedRoleUser *types.AssumedRoleUser - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security (or session) token. The size of the security token - // that STS API operations return is not fixed. We strongly recommend that you make - // no assumptions about the maximum size. - Credentials *types.Credentials - - // A percentage value that indicates the packed size of the session policies and - // session tags combined passed in the request. The request fails if the packed - // size is greater than 100 percent, which means the policies and tags exceeded the - // allowed space. - PackedPolicySize *int32 - - // The source identity specified by the principal that is calling the AssumeRole - // operation. You can require users to specify a source identity when they assume a - // role. You do this by using the sts:SourceIdentity condition key in a role trust - // policy. You can use source identity information in CloudTrail logs to determine - // who took actions with a role. You can use the aws:SourceIdentity condition key - // to further control access to Amazon Web Services resources based on the value of - // source identity. For more information about using source identity, see Monitor - // and control actions taken with assumed roles (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_monitor.html) - // in the IAM User Guide. The regex used to validate this parameter is a string of - // characters consisting of upper- and lower-case alphanumeric characters with no - // spaces. You can also include underscores or any of the following characters: - // =,.@- - SourceIdentity *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationAssumeRoleMiddlewares(stack *middleware.Stack, options Options) (err error) { - err = stack.Serialize.Add(&awsAwsquery_serializeOpAssumeRole{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsquery_deserializeOpAssumeRole{}, middleware.After) - if err != nil { - return err - } - if err = addlegacyEndpointContextSetter(stack, options); err != nil { - return err - } - if err = addSetLoggerMiddleware(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { - return err - } - if err = addClientUserAgent(stack, options); err != nil { - return err - } - if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = addAssumeRoleResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addOpAssumeRoleValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAssumeRole(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { - return err - } - if err = addRequestIDRetrieverMiddleware(stack); err != nil { - return err - } - if err = addResponseErrorMiddleware(stack); err != nil { - return err - } - if err = addRequestResponseLogging(stack, options); err != nil { - return err - } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { - return err - } - return nil -} - -func newServiceMetadataMiddleware_opAssumeRole(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - SigningName: "sts", - OperationName: "AssumeRole", - } -} - -// PresignAssumeRole is used to generate a presigned HTTP Request which contains -// presigned URL, signed headers and HTTP method used. -func (c *PresignClient) PresignAssumeRole(ctx context.Context, params *AssumeRoleInput, optFns ...func(*PresignOptions)) (*v4.PresignedHTTPRequest, error) { - if params == nil { - params = &AssumeRoleInput{} - } - options := c.options.copy() - for _, fn := range optFns { - fn(&options) - } - clientOptFns := append(options.ClientOptions, withNopHTTPClientAPIOption) - - result, _, err := c.client.invokeOperation(ctx, "AssumeRole", params, clientOptFns, - c.client.addOperationAssumeRoleMiddlewares, - presignConverter(options).convertToPresignMiddleware, - ) - if err != nil { - return nil, err - } - - out := result.(*v4.PresignedHTTPRequest) - return out, nil -} - -type opAssumeRoleResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opAssumeRoleResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opAssumeRoleResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "sts" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "sts" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("sts") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addAssumeRoleResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opAssumeRoleResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoleWithSAML.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoleWithSAML.go deleted file mode 100644 index 9c33720d4..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoleWithSAML.go +++ /dev/null @@ -1,482 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -import ( - "context" - "errors" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - "github.com/aws/aws-sdk-go-v2/service/sts/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Returns a set of temporary security credentials for users who have been -// authenticated via a SAML authentication response. This operation provides a -// mechanism for tying an enterprise identity store or directory to role-based -// Amazon Web Services access without user-specific credentials or configuration. -// For a comparison of AssumeRoleWithSAML with the other API operations that -// produce temporary credentials, see Requesting Temporary Security Credentials (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the Amazon Web Services STS API operations (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. The temporary security credentials returned by this -// operation consist of an access key ID, a secret access key, and a security -// token. Applications can use these temporary security credentials to sign calls -// to Amazon Web Services services. Session Duration By default, the temporary -// security credentials created by AssumeRoleWithSAML last for one hour. However, -// you can use the optional DurationSeconds parameter to specify the duration of -// your session. Your role session lasts for the duration that you specify, or -// until the time specified in the SAML authentication response's -// SessionNotOnOrAfter value, whichever is shorter. You can provide a -// DurationSeconds value from 900 seconds (15 minutes) up to the maximum session -// duration setting for the role. This setting can have a value from 1 hour to 12 -// hours. To learn how to view the maximum value for your role, see View the -// Maximum Session Duration Setting for a Role (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session) -// in the IAM User Guide. The maximum session duration limit applies when you use -// the AssumeRole* API operations or the assume-role* CLI commands. However the -// limit does not apply when you use those operations to create a console URL. For -// more information, see Using IAM Roles (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html) -// in the IAM User Guide. Role chaining (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#iam-term-role-chaining) -// limits your CLI or Amazon Web Services API role session to a maximum of one -// hour. When you use the AssumeRole API operation to assume a role, you can -// specify the duration of your role session with the DurationSeconds parameter. -// You can specify a parameter value of up to 43200 seconds (12 hours), depending -// on the maximum session duration setting for your role. However, if you assume a -// role using role chaining and provide a DurationSeconds parameter value greater -// than one hour, the operation fails. Permissions The temporary security -// credentials created by AssumeRoleWithSAML can be used to make API calls to any -// Amazon Web Services service with the following exception: you cannot call the -// STS GetFederationToken or GetSessionToken API operations. (Optional) You can -// pass inline or managed session policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) -// to this operation. You can pass a single JSON policy document to use as an -// inline session policy. You can also specify up to 10 managed policy Amazon -// Resource Names (ARNs) to use as managed session policies. The plaintext that you -// use for both inline and managed session policies can't exceed 2,048 characters. -// Passing policies to this operation returns new temporary credentials. The -// resulting session's permissions are the intersection of the role's -// identity-based policy and the session policies. You can use the role's temporary -// credentials in subsequent Amazon Web Services API calls to access resources in -// the account that owns the role. You cannot use session policies to grant more -// permissions than those allowed by the identity-based policy of the role that is -// being assumed. For more information, see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) -// in the IAM User Guide. Calling AssumeRoleWithSAML does not require the use of -// Amazon Web Services security credentials. The identity of the caller is -// validated by using keys in the metadata document that is uploaded for the SAML -// provider entity for your identity provider. Calling AssumeRoleWithSAML can -// result in an entry in your CloudTrail logs. The entry includes the value in the -// NameID element of the SAML assertion. We recommend that you use a NameIDType -// that is not associated with any personally identifiable information (PII). For -// example, you could instead use the persistent identifier ( -// urn:oasis:names:tc:SAML:2.0:nameid-format:persistent ). Tags (Optional) You can -// configure your IdP to pass attributes into your SAML assertion as session tags. -// Each session tag consists of a key name and an associated value. For more -// information about session tags, see Passing Session Tags in STS (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) -// in the IAM User Guide. You can pass up to 50 session tags. The plaintext session -// tag keys can’t exceed 128 characters and the values can’t exceed 256 characters. -// For these and additional limits, see IAM and STS Character Limits (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html#reference_iam-limits-entity-length) -// in the IAM User Guide. An Amazon Web Services conversion compresses the passed -// inline session policy, managed policy ARNs, and session tags into a packed -// binary format that has a separate limit. Your request can fail for this limit -// even if your plaintext meets the other requirements. The PackedPolicySize -// response element indicates by percentage how close the policies and tags for -// your request are to the upper size limit. You can pass a session tag with the -// same key as a tag that is attached to the role. When you do, session tags -// override the role's tags with the same key. An administrator must grant you the -// permissions necessary to pass session tags. The administrator can also create -// granular permissions to allow you to pass only specific session tags. For more -// information, see Tutorial: Using Tags for Attribute-Based Access Control (https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_attribute-based-access-control.html) -// in the IAM User Guide. You can set the session tags as transitive. Transitive -// tags persist during role chaining. For more information, see Chaining Roles -// with Session Tags (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html#id_session-tags_role-chaining) -// in the IAM User Guide. SAML Configuration Before your application can call -// AssumeRoleWithSAML , you must configure your SAML identity provider (IdP) to -// issue the claims required by Amazon Web Services. Additionally, you must use -// Identity and Access Management (IAM) to create a SAML provider entity in your -// Amazon Web Services account that represents your identity provider. You must -// also create an IAM role that specifies this SAML provider in its trust policy. -// For more information, see the following resources: -// - About SAML 2.0-based Federation (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_saml.html) -// in the IAM User Guide. -// - Creating SAML Identity Providers (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html) -// in the IAM User Guide. -// - Configuring a Relying Party and Claims (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml_relying-party.html) -// in the IAM User Guide. -// - Creating a Role for SAML 2.0 Federation (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-idp_saml.html) -// in the IAM User Guide. -func (c *Client) AssumeRoleWithSAML(ctx context.Context, params *AssumeRoleWithSAMLInput, optFns ...func(*Options)) (*AssumeRoleWithSAMLOutput, error) { - if params == nil { - params = &AssumeRoleWithSAMLInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "AssumeRoleWithSAML", params, optFns, c.addOperationAssumeRoleWithSAMLMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*AssumeRoleWithSAMLOutput) - out.ResultMetadata = metadata - return out, nil -} - -type AssumeRoleWithSAMLInput struct { - - // The Amazon Resource Name (ARN) of the SAML provider in IAM that describes the - // IdP. - // - // This member is required. - PrincipalArn *string - - // The Amazon Resource Name (ARN) of the role that the caller is assuming. - // - // This member is required. - RoleArn *string - - // The base64 encoded SAML authentication response provided by the IdP. For more - // information, see Configuring a Relying Party and Adding Claims (https://docs.aws.amazon.com/IAM/latest/UserGuide/create-role-saml-IdP-tasks.html) - // in the IAM User Guide. - // - // This member is required. - SAMLAssertion *string - - // The duration, in seconds, of the role session. Your role session lasts for the - // duration that you specify for the DurationSeconds parameter, or until the time - // specified in the SAML authentication response's SessionNotOnOrAfter value, - // whichever is shorter. You can provide a DurationSeconds value from 900 seconds - // (15 minutes) up to the maximum session duration setting for the role. This - // setting can have a value from 1 hour to 12 hours. If you specify a value higher - // than this setting, the operation fails. For example, if you specify a session - // duration of 12 hours, but your administrator set the maximum session duration to - // 6 hours, your operation fails. To learn how to view the maximum value for your - // role, see View the Maximum Session Duration Setting for a Role (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session) - // in the IAM User Guide. By default, the value is set to 3600 seconds. The - // DurationSeconds parameter is separate from the duration of a console session - // that you might request using the returned credentials. The request to the - // federation endpoint for a console sign-in token takes a SessionDuration - // parameter that specifies the maximum length of the console session. For more - // information, see Creating a URL that Enables Federated Users to Access the - // Amazon Web Services Management Console (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html) - // in the IAM User Guide. - DurationSeconds *int32 - - // An IAM policy in JSON format that you want to use as an inline session policy. - // This parameter is optional. Passing policies to this operation returns new - // temporary credentials. The resulting session's permissions are the intersection - // of the role's identity-based policy and the session policies. You can use the - // role's temporary credentials in subsequent Amazon Web Services API calls to - // access resources in the account that owns the role. You cannot use session - // policies to grant more permissions than those allowed by the identity-based - // policy of the role that is being assumed. For more information, see Session - // Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // in the IAM User Guide. The plaintext that you use for both inline and managed - // session policies can't exceed 2,048 characters. The JSON policy characters can - // be any ASCII character from the space character to the end of the valid - // character list (\u0020 through \u00FF). It can also include the tab (\u0009), - // linefeed (\u000A), and carriage return (\u000D) characters. An Amazon Web - // Services conversion compresses the passed inline session policy, managed policy - // ARNs, and session tags into a packed binary format that has a separate limit. - // Your request can fail for this limit even if your plaintext meets the other - // requirements. The PackedPolicySize response element indicates by percentage how - // close the policies and tags for your request are to the upper size limit. - Policy *string - - // The Amazon Resource Names (ARNs) of the IAM managed policies that you want to - // use as managed session policies. The policies must exist in the same account as - // the role. This parameter is optional. You can provide up to 10 managed policy - // ARNs. However, the plaintext that you use for both inline and managed session - // policies can't exceed 2,048 characters. For more information about ARNs, see - // Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces (https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) - // in the Amazon Web Services General Reference. An Amazon Web Services conversion - // compresses the passed inline session policy, managed policy ARNs, and session - // tags into a packed binary format that has a separate limit. Your request can - // fail for this limit even if your plaintext meets the other requirements. The - // PackedPolicySize response element indicates by percentage how close the policies - // and tags for your request are to the upper size limit. Passing policies to this - // operation returns new temporary credentials. The resulting session's permissions - // are the intersection of the role's identity-based policy and the session - // policies. You can use the role's temporary credentials in subsequent Amazon Web - // Services API calls to access resources in the account that owns the role. You - // cannot use session policies to grant more permissions than those allowed by the - // identity-based policy of the role that is being assumed. For more information, - // see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // in the IAM User Guide. - PolicyArns []types.PolicyDescriptorType - - noSmithyDocumentSerde -} - -// Contains the response to a successful AssumeRoleWithSAML request, including -// temporary Amazon Web Services credentials that can be used to make Amazon Web -// Services requests. -type AssumeRoleWithSAMLOutput struct { - - // The identifiers for the temporary security credentials that the operation - // returns. - AssumedRoleUser *types.AssumedRoleUser - - // The value of the Recipient attribute of the SubjectConfirmationData element of - // the SAML assertion. - Audience *string - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security (or session) token. The size of the security token - // that STS API operations return is not fixed. We strongly recommend that you make - // no assumptions about the maximum size. - Credentials *types.Credentials - - // The value of the Issuer element of the SAML assertion. - Issuer *string - - // A hash value based on the concatenation of the following: - // - The Issuer response value. - // - The Amazon Web Services account ID. - // - The friendly name (the last part of the ARN) of the SAML provider in IAM. - // The combination of NameQualifier and Subject can be used to uniquely identify a - // user. The following pseudocode shows how the hash value is calculated: BASE64 ( - // SHA1 ( "https://example.com/saml" + "123456789012" + "/MySAMLIdP" ) ) - NameQualifier *string - - // A percentage value that indicates the packed size of the session policies and - // session tags combined passed in the request. The request fails if the packed - // size is greater than 100 percent, which means the policies and tags exceeded the - // allowed space. - PackedPolicySize *int32 - - // The value in the SourceIdentity attribute in the SAML assertion. You can - // require users to set a source identity value when they assume a role. You do - // this by using the sts:SourceIdentity condition key in a role trust policy. That - // way, actions that are taken with the role are associated with that user. After - // the source identity is set, the value cannot be changed. It is present in the - // request for all actions that are taken by the role and persists across chained - // role (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts#iam-term-role-chaining) - // sessions. You can configure your SAML identity provider to use an attribute - // associated with your users, like user name or email, as the source identity when - // calling AssumeRoleWithSAML . You do this by adding an attribute to the SAML - // assertion. For more information about using source identity, see Monitor and - // control actions taken with assumed roles (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_monitor.html) - // in the IAM User Guide. The regex used to validate this parameter is a string of - // characters consisting of upper- and lower-case alphanumeric characters with no - // spaces. You can also include underscores or any of the following characters: - // =,.@- - SourceIdentity *string - - // The value of the NameID element in the Subject element of the SAML assertion. - Subject *string - - // The format of the name ID, as defined by the Format attribute in the NameID - // element of the SAML assertion. Typical examples of the format are transient or - // persistent . If the format includes the prefix - // urn:oasis:names:tc:SAML:2.0:nameid-format , that prefix is removed. For example, - // urn:oasis:names:tc:SAML:2.0:nameid-format:transient is returned as transient . - // If the format includes any other prefix, the format is returned with no - // modifications. - SubjectType *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationAssumeRoleWithSAMLMiddlewares(stack *middleware.Stack, options Options) (err error) { - err = stack.Serialize.Add(&awsAwsquery_serializeOpAssumeRoleWithSAML{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsquery_deserializeOpAssumeRoleWithSAML{}, middleware.After) - if err != nil { - return err - } - if err = addlegacyEndpointContextSetter(stack, options); err != nil { - return err - } - if err = addSetLoggerMiddleware(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { - return err - } - if err = addClientUserAgent(stack, options); err != nil { - return err - } - if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = addAssumeRoleWithSAMLResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addOpAssumeRoleWithSAMLValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAssumeRoleWithSAML(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { - return err - } - if err = addRequestIDRetrieverMiddleware(stack); err != nil { - return err - } - if err = addResponseErrorMiddleware(stack); err != nil { - return err - } - if err = addRequestResponseLogging(stack, options); err != nil { - return err - } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { - return err - } - return nil -} - -func newServiceMetadataMiddleware_opAssumeRoleWithSAML(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - SigningName: "sts", - OperationName: "AssumeRoleWithSAML", - } -} - -type opAssumeRoleWithSAMLResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opAssumeRoleWithSAMLResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opAssumeRoleWithSAMLResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "sts" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "sts" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("sts") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addAssumeRoleWithSAMLResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opAssumeRoleWithSAMLResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoleWithWebIdentity.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoleWithWebIdentity.go deleted file mode 100644 index fa4a60845..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoleWithWebIdentity.go +++ /dev/null @@ -1,501 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -import ( - "context" - "errors" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - "github.com/aws/aws-sdk-go-v2/service/sts/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Returns a set of temporary security credentials for users who have been -// authenticated in a mobile or web application with a web identity provider. -// Example providers include the OAuth 2.0 providers Login with Amazon and -// Facebook, or any OpenID Connect-compatible identity provider such as Google or -// Amazon Cognito federated identities (https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html) -// . For mobile applications, we recommend that you use Amazon Cognito. You can use -// Amazon Cognito with the Amazon Web Services SDK for iOS Developer Guide (http://aws.amazon.com/sdkforios/) -// and the Amazon Web Services SDK for Android Developer Guide (http://aws.amazon.com/sdkforandroid/) -// to uniquely identify a user. You can also supply the user with a consistent -// identity throughout the lifetime of an application. To learn more about Amazon -// Cognito, see Amazon Cognito identity pools (https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html) -// in Amazon Cognito Developer Guide. Calling AssumeRoleWithWebIdentity does not -// require the use of Amazon Web Services security credentials. Therefore, you can -// distribute an application (for example, on mobile devices) that requests -// temporary security credentials without including long-term Amazon Web Services -// credentials in the application. You also don't need to deploy server-based proxy -// services that use long-term Amazon Web Services credentials. Instead, the -// identity of the caller is validated by using a token from the web identity -// provider. For a comparison of AssumeRoleWithWebIdentity with the other API -// operations that produce temporary credentials, see Requesting Temporary -// Security Credentials (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the Amazon Web Services STS API operations (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. The temporary security credentials returned by this API -// consist of an access key ID, a secret access key, and a security token. -// Applications can use these temporary security credentials to sign calls to -// Amazon Web Services service API operations. Session Duration By default, the -// temporary security credentials created by AssumeRoleWithWebIdentity last for -// one hour. However, you can use the optional DurationSeconds parameter to -// specify the duration of your session. You can provide a value from 900 seconds -// (15 minutes) up to the maximum session duration setting for the role. This -// setting can have a value from 1 hour to 12 hours. To learn how to view the -// maximum value for your role, see View the Maximum Session Duration Setting for -// a Role (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session) -// in the IAM User Guide. The maximum session duration limit applies when you use -// the AssumeRole* API operations or the assume-role* CLI commands. However the -// limit does not apply when you use those operations to create a console URL. For -// more information, see Using IAM Roles (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html) -// in the IAM User Guide. Permissions The temporary security credentials created by -// AssumeRoleWithWebIdentity can be used to make API calls to any Amazon Web -// Services service with the following exception: you cannot call the STS -// GetFederationToken or GetSessionToken API operations. (Optional) You can pass -// inline or managed session policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) -// to this operation. You can pass a single JSON policy document to use as an -// inline session policy. You can also specify up to 10 managed policy Amazon -// Resource Names (ARNs) to use as managed session policies. The plaintext that you -// use for both inline and managed session policies can't exceed 2,048 characters. -// Passing policies to this operation returns new temporary credentials. The -// resulting session's permissions are the intersection of the role's -// identity-based policy and the session policies. You can use the role's temporary -// credentials in subsequent Amazon Web Services API calls to access resources in -// the account that owns the role. You cannot use session policies to grant more -// permissions than those allowed by the identity-based policy of the role that is -// being assumed. For more information, see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) -// in the IAM User Guide. Tags (Optional) You can configure your IdP to pass -// attributes into your web identity token as session tags. Each session tag -// consists of a key name and an associated value. For more information about -// session tags, see Passing Session Tags in STS (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) -// in the IAM User Guide. You can pass up to 50 session tags. The plaintext session -// tag keys can’t exceed 128 characters and the values can’t exceed 256 characters. -// For these and additional limits, see IAM and STS Character Limits (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html#reference_iam-limits-entity-length) -// in the IAM User Guide. An Amazon Web Services conversion compresses the passed -// inline session policy, managed policy ARNs, and session tags into a packed -// binary format that has a separate limit. Your request can fail for this limit -// even if your plaintext meets the other requirements. The PackedPolicySize -// response element indicates by percentage how close the policies and tags for -// your request are to the upper size limit. You can pass a session tag with the -// same key as a tag that is attached to the role. When you do, the session tag -// overrides the role tag with the same key. An administrator must grant you the -// permissions necessary to pass session tags. The administrator can also create -// granular permissions to allow you to pass only specific session tags. For more -// information, see Tutorial: Using Tags for Attribute-Based Access Control (https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_attribute-based-access-control.html) -// in the IAM User Guide. You can set the session tags as transitive. Transitive -// tags persist during role chaining. For more information, see Chaining Roles -// with Session Tags (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html#id_session-tags_role-chaining) -// in the IAM User Guide. Identities Before your application can call -// AssumeRoleWithWebIdentity , you must have an identity token from a supported -// identity provider and create a role that the application can assume. The role -// that your application assumes must trust the identity provider that is -// associated with the identity token. In other words, the identity provider must -// be specified in the role's trust policy. Calling AssumeRoleWithWebIdentity can -// result in an entry in your CloudTrail logs. The entry includes the Subject (http://openid.net/specs/openid-connect-core-1_0.html#Claims) -// of the provided web identity token. We recommend that you avoid using any -// personally identifiable information (PII) in this field. For example, you could -// instead use a GUID or a pairwise identifier, as suggested in the OIDC -// specification (http://openid.net/specs/openid-connect-core-1_0.html#SubjectIDTypes) -// . For more information about how to use web identity federation and the -// AssumeRoleWithWebIdentity API, see the following resources: -// - Using Web Identity Federation API Operations for Mobile Apps (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_oidc_manual.html) -// and Federation Through a Web-based Identity Provider (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_assumerolewithwebidentity) -// . -// - Web Identity Federation Playground (https://aws.amazon.com/blogs/aws/the-aws-web-identity-federation-playground/) -// . Walk through the process of authenticating through Login with Amazon, -// Facebook, or Google, getting temporary security credentials, and then using -// those credentials to make a request to Amazon Web Services. -// - Amazon Web Services SDK for iOS Developer Guide (http://aws.amazon.com/sdkforios/) -// and Amazon Web Services SDK for Android Developer Guide (http://aws.amazon.com/sdkforandroid/) -// . These toolkits contain sample apps that show how to invoke the identity -// providers. The toolkits then show how to use the information from these -// providers to get and use temporary security credentials. -// - Web Identity Federation with Mobile Applications (http://aws.amazon.com/articles/web-identity-federation-with-mobile-applications) -// . This article discusses web identity federation and shows an example of how to -// use web identity federation to get access to content in Amazon S3. -func (c *Client) AssumeRoleWithWebIdentity(ctx context.Context, params *AssumeRoleWithWebIdentityInput, optFns ...func(*Options)) (*AssumeRoleWithWebIdentityOutput, error) { - if params == nil { - params = &AssumeRoleWithWebIdentityInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "AssumeRoleWithWebIdentity", params, optFns, c.addOperationAssumeRoleWithWebIdentityMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*AssumeRoleWithWebIdentityOutput) - out.ResultMetadata = metadata - return out, nil -} - -type AssumeRoleWithWebIdentityInput struct { - - // The Amazon Resource Name (ARN) of the role that the caller is assuming. - // - // This member is required. - RoleArn *string - - // An identifier for the assumed role session. Typically, you pass the name or - // identifier that is associated with the user who is using your application. That - // way, the temporary security credentials that your application will use are - // associated with that user. This session name is included as part of the ARN and - // assumed role ID in the AssumedRoleUser response element. The regex used to - // validate this parameter is a string of characters consisting of upper- and - // lower-case alphanumeric characters with no spaces. You can also include - // underscores or any of the following characters: =,.@- - // - // This member is required. - RoleSessionName *string - - // The OAuth 2.0 access token or OpenID Connect ID token that is provided by the - // identity provider. Your application must get this token by authenticating the - // user who is using your application with a web identity provider before the - // application makes an AssumeRoleWithWebIdentity call. Only tokens with RSA - // algorithms (RS256) are supported. - // - // This member is required. - WebIdentityToken *string - - // The duration, in seconds, of the role session. The value can range from 900 - // seconds (15 minutes) up to the maximum session duration setting for the role. - // This setting can have a value from 1 hour to 12 hours. If you specify a value - // higher than this setting, the operation fails. For example, if you specify a - // session duration of 12 hours, but your administrator set the maximum session - // duration to 6 hours, your operation fails. To learn how to view the maximum - // value for your role, see View the Maximum Session Duration Setting for a Role (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session) - // in the IAM User Guide. By default, the value is set to 3600 seconds. The - // DurationSeconds parameter is separate from the duration of a console session - // that you might request using the returned credentials. The request to the - // federation endpoint for a console sign-in token takes a SessionDuration - // parameter that specifies the maximum length of the console session. For more - // information, see Creating a URL that Enables Federated Users to Access the - // Amazon Web Services Management Console (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html) - // in the IAM User Guide. - DurationSeconds *int32 - - // An IAM policy in JSON format that you want to use as an inline session policy. - // This parameter is optional. Passing policies to this operation returns new - // temporary credentials. The resulting session's permissions are the intersection - // of the role's identity-based policy and the session policies. You can use the - // role's temporary credentials in subsequent Amazon Web Services API calls to - // access resources in the account that owns the role. You cannot use session - // policies to grant more permissions than those allowed by the identity-based - // policy of the role that is being assumed. For more information, see Session - // Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // in the IAM User Guide. The plaintext that you use for both inline and managed - // session policies can't exceed 2,048 characters. The JSON policy characters can - // be any ASCII character from the space character to the end of the valid - // character list (\u0020 through \u00FF). It can also include the tab (\u0009), - // linefeed (\u000A), and carriage return (\u000D) characters. An Amazon Web - // Services conversion compresses the passed inline session policy, managed policy - // ARNs, and session tags into a packed binary format that has a separate limit. - // Your request can fail for this limit even if your plaintext meets the other - // requirements. The PackedPolicySize response element indicates by percentage how - // close the policies and tags for your request are to the upper size limit. - Policy *string - - // The Amazon Resource Names (ARNs) of the IAM managed policies that you want to - // use as managed session policies. The policies must exist in the same account as - // the role. This parameter is optional. You can provide up to 10 managed policy - // ARNs. However, the plaintext that you use for both inline and managed session - // policies can't exceed 2,048 characters. For more information about ARNs, see - // Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces (https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) - // in the Amazon Web Services General Reference. An Amazon Web Services conversion - // compresses the passed inline session policy, managed policy ARNs, and session - // tags into a packed binary format that has a separate limit. Your request can - // fail for this limit even if your plaintext meets the other requirements. The - // PackedPolicySize response element indicates by percentage how close the policies - // and tags for your request are to the upper size limit. Passing policies to this - // operation returns new temporary credentials. The resulting session's permissions - // are the intersection of the role's identity-based policy and the session - // policies. You can use the role's temporary credentials in subsequent Amazon Web - // Services API calls to access resources in the account that owns the role. You - // cannot use session policies to grant more permissions than those allowed by the - // identity-based policy of the role that is being assumed. For more information, - // see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // in the IAM User Guide. - PolicyArns []types.PolicyDescriptorType - - // The fully qualified host component of the domain name of the OAuth 2.0 identity - // provider. Do not specify this value for an OpenID Connect identity provider. - // Currently www.amazon.com and graph.facebook.com are the only supported identity - // providers for OAuth 2.0 access tokens. Do not include URL schemes and port - // numbers. Do not specify this value for OpenID Connect ID tokens. - ProviderId *string - - noSmithyDocumentSerde -} - -// Contains the response to a successful AssumeRoleWithWebIdentity request, -// including temporary Amazon Web Services credentials that can be used to make -// Amazon Web Services requests. -type AssumeRoleWithWebIdentityOutput struct { - - // The Amazon Resource Name (ARN) and the assumed role ID, which are identifiers - // that you can use to refer to the resulting temporary security credentials. For - // example, you can reference these credentials as a principal in a resource-based - // policy by using the ARN or assumed role ID. The ARN and ID include the - // RoleSessionName that you specified when you called AssumeRole . - AssumedRoleUser *types.AssumedRoleUser - - // The intended audience (also known as client ID) of the web identity token. This - // is traditionally the client identifier issued to the application that requested - // the web identity token. - Audience *string - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security token. The size of the security token that STS API - // operations return is not fixed. We strongly recommend that you make no - // assumptions about the maximum size. - Credentials *types.Credentials - - // A percentage value that indicates the packed size of the session policies and - // session tags combined passed in the request. The request fails if the packed - // size is greater than 100 percent, which means the policies and tags exceeded the - // allowed space. - PackedPolicySize *int32 - - // The issuing authority of the web identity token presented. For OpenID Connect - // ID tokens, this contains the value of the iss field. For OAuth 2.0 access - // tokens, this contains the value of the ProviderId parameter that was passed in - // the AssumeRoleWithWebIdentity request. - Provider *string - - // The value of the source identity that is returned in the JSON web token (JWT) - // from the identity provider. You can require users to set a source identity value - // when they assume a role. You do this by using the sts:SourceIdentity condition - // key in a role trust policy. That way, actions that are taken with the role are - // associated with that user. After the source identity is set, the value cannot be - // changed. It is present in the request for all actions that are taken by the role - // and persists across chained role (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts#iam-term-role-chaining) - // sessions. You can configure your identity provider to use an attribute - // associated with your users, like user name or email, as the source identity when - // calling AssumeRoleWithWebIdentity . You do this by adding a claim to the JSON - // web token. To learn more about OIDC tokens and claims, see Using Tokens with - // User Pools (https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html) - // in the Amazon Cognito Developer Guide. For more information about using source - // identity, see Monitor and control actions taken with assumed roles (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_monitor.html) - // in the IAM User Guide. The regex used to validate this parameter is a string of - // characters consisting of upper- and lower-case alphanumeric characters with no - // spaces. You can also include underscores or any of the following characters: - // =,.@- - SourceIdentity *string - - // The unique user identifier that is returned by the identity provider. This - // identifier is associated with the WebIdentityToken that was submitted with the - // AssumeRoleWithWebIdentity call. The identifier is typically unique to the user - // and the application that acquired the WebIdentityToken (pairwise identifier). - // For OpenID Connect ID tokens, this field contains the value returned by the - // identity provider as the token's sub (Subject) claim. - SubjectFromWebIdentityToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationAssumeRoleWithWebIdentityMiddlewares(stack *middleware.Stack, options Options) (err error) { - err = stack.Serialize.Add(&awsAwsquery_serializeOpAssumeRoleWithWebIdentity{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsquery_deserializeOpAssumeRoleWithWebIdentity{}, middleware.After) - if err != nil { - return err - } - if err = addlegacyEndpointContextSetter(stack, options); err != nil { - return err - } - if err = addSetLoggerMiddleware(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { - return err - } - if err = addClientUserAgent(stack, options); err != nil { - return err - } - if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = addAssumeRoleWithWebIdentityResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addOpAssumeRoleWithWebIdentityValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAssumeRoleWithWebIdentity(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { - return err - } - if err = addRequestIDRetrieverMiddleware(stack); err != nil { - return err - } - if err = addResponseErrorMiddleware(stack); err != nil { - return err - } - if err = addRequestResponseLogging(stack, options); err != nil { - return err - } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { - return err - } - return nil -} - -func newServiceMetadataMiddleware_opAssumeRoleWithWebIdentity(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - SigningName: "sts", - OperationName: "AssumeRoleWithWebIdentity", - } -} - -type opAssumeRoleWithWebIdentityResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opAssumeRoleWithWebIdentityResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opAssumeRoleWithWebIdentityResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "sts" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "sts" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("sts") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addAssumeRoleWithWebIdentityResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opAssumeRoleWithWebIdentityResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_DecodeAuthorizationMessage.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_DecodeAuthorizationMessage.go deleted file mode 100644 index baf2f9686..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_DecodeAuthorizationMessage.go +++ /dev/null @@ -1,285 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -import ( - "context" - "errors" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Decodes additional information about the authorization status of a request from -// an encoded message returned in response to an Amazon Web Services request. For -// example, if a user is not authorized to perform an operation that he or she has -// requested, the request returns a Client.UnauthorizedOperation response (an HTTP -// 403 response). Some Amazon Web Services operations additionally return an -// encoded message that can provide details about this authorization failure. Only -// certain Amazon Web Services operations return an encoded authorization message. -// The documentation for an individual operation indicates whether that operation -// returns an encoded message in addition to returning an HTTP code. The message is -// encoded because the details of the authorization status can contain privileged -// information that the user who requested the operation should not see. To decode -// an authorization status message, a user must be granted permissions through an -// IAM policy (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html) -// to request the DecodeAuthorizationMessage ( sts:DecodeAuthorizationMessage ) -// action. The decoded message includes the following type of information: -// - Whether the request was denied due to an explicit deny or due to the -// absence of an explicit allow. For more information, see Determining Whether a -// Request is Allowed or Denied (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html#policy-eval-denyallow) -// in the IAM User Guide. -// - The principal who made the request. -// - The requested action. -// - The requested resource. -// - The values of condition keys in the context of the user's request. -func (c *Client) DecodeAuthorizationMessage(ctx context.Context, params *DecodeAuthorizationMessageInput, optFns ...func(*Options)) (*DecodeAuthorizationMessageOutput, error) { - if params == nil { - params = &DecodeAuthorizationMessageInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DecodeAuthorizationMessage", params, optFns, c.addOperationDecodeAuthorizationMessageMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DecodeAuthorizationMessageOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DecodeAuthorizationMessageInput struct { - - // The encoded message that was returned with the response. - // - // This member is required. - EncodedMessage *string - - noSmithyDocumentSerde -} - -// A document that contains additional information about the authorization status -// of a request from an encoded message that is returned in response to an Amazon -// Web Services request. -type DecodeAuthorizationMessageOutput struct { - - // The API returns a response with the decoded message. - DecodedMessage *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDecodeAuthorizationMessageMiddlewares(stack *middleware.Stack, options Options) (err error) { - err = stack.Serialize.Add(&awsAwsquery_serializeOpDecodeAuthorizationMessage{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsquery_deserializeOpDecodeAuthorizationMessage{}, middleware.After) - if err != nil { - return err - } - if err = addlegacyEndpointContextSetter(stack, options); err != nil { - return err - } - if err = addSetLoggerMiddleware(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { - return err - } - if err = addClientUserAgent(stack, options); err != nil { - return err - } - if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = addDecodeAuthorizationMessageResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addOpDecodeAuthorizationMessageValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDecodeAuthorizationMessage(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { - return err - } - if err = addRequestIDRetrieverMiddleware(stack); err != nil { - return err - } - if err = addResponseErrorMiddleware(stack); err != nil { - return err - } - if err = addRequestResponseLogging(stack, options); err != nil { - return err - } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { - return err - } - return nil -} - -func newServiceMetadataMiddleware_opDecodeAuthorizationMessage(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - SigningName: "sts", - OperationName: "DecodeAuthorizationMessage", - } -} - -type opDecodeAuthorizationMessageResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opDecodeAuthorizationMessageResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opDecodeAuthorizationMessageResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "sts" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "sts" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("sts") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addDecodeAuthorizationMessageResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opDecodeAuthorizationMessageResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetAccessKeyInfo.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetAccessKeyInfo.go deleted file mode 100644 index f1dd167da..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetAccessKeyInfo.go +++ /dev/null @@ -1,278 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -import ( - "context" - "errors" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Returns the account identifier for the specified access key ID. Access keys -// consist of two parts: an access key ID (for example, AKIAIOSFODNN7EXAMPLE ) and -// a secret access key (for example, wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY ). -// For more information about access keys, see Managing Access Keys for IAM Users (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html) -// in the IAM User Guide. When you pass an access key ID to this operation, it -// returns the ID of the Amazon Web Services account to which the keys belong. -// Access key IDs beginning with AKIA are long-term credentials for an IAM user or -// the Amazon Web Services account root user. Access key IDs beginning with ASIA -// are temporary credentials that are created using STS operations. If the account -// in the response belongs to you, you can sign in as the root user and review your -// root user access keys. Then, you can pull a credentials report (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_getting-report.html) -// to learn which IAM user owns the keys. To learn who requested the temporary -// credentials for an ASIA access key, view the STS events in your CloudTrail logs (https://docs.aws.amazon.com/IAM/latest/UserGuide/cloudtrail-integration.html) -// in the IAM User Guide. This operation does not indicate the state of the access -// key. The key might be active, inactive, or deleted. Active keys might not have -// permissions to perform an operation. Providing a deleted access key might return -// an error that the key doesn't exist. -func (c *Client) GetAccessKeyInfo(ctx context.Context, params *GetAccessKeyInfoInput, optFns ...func(*Options)) (*GetAccessKeyInfoOutput, error) { - if params == nil { - params = &GetAccessKeyInfoInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetAccessKeyInfo", params, optFns, c.addOperationGetAccessKeyInfoMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetAccessKeyInfoOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetAccessKeyInfoInput struct { - - // The identifier of an access key. This parameter allows (through its regex - // pattern) a string of characters that can consist of any upper- or lowercase - // letter or digit. - // - // This member is required. - AccessKeyId *string - - noSmithyDocumentSerde -} - -type GetAccessKeyInfoOutput struct { - - // The number used to identify the Amazon Web Services account. - Account *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetAccessKeyInfoMiddlewares(stack *middleware.Stack, options Options) (err error) { - err = stack.Serialize.Add(&awsAwsquery_serializeOpGetAccessKeyInfo{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsquery_deserializeOpGetAccessKeyInfo{}, middleware.After) - if err != nil { - return err - } - if err = addlegacyEndpointContextSetter(stack, options); err != nil { - return err - } - if err = addSetLoggerMiddleware(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { - return err - } - if err = addClientUserAgent(stack, options); err != nil { - return err - } - if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = addGetAccessKeyInfoResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addOpGetAccessKeyInfoValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetAccessKeyInfo(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { - return err - } - if err = addRequestIDRetrieverMiddleware(stack); err != nil { - return err - } - if err = addResponseErrorMiddleware(stack); err != nil { - return err - } - if err = addRequestResponseLogging(stack, options); err != nil { - return err - } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { - return err - } - return nil -} - -func newServiceMetadataMiddleware_opGetAccessKeyInfo(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - SigningName: "sts", - OperationName: "GetAccessKeyInfo", - } -} - -type opGetAccessKeyInfoResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opGetAccessKeyInfoResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opGetAccessKeyInfoResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "sts" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "sts" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("sts") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addGetAccessKeyInfoResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opGetAccessKeyInfoResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetCallerIdentity.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetCallerIdentity.go deleted file mode 100644 index 66e5d99d4..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetCallerIdentity.go +++ /dev/null @@ -1,294 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -import ( - "context" - "errors" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - smithyendpoints "github.com/aws/smithy-go/endpoints" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Returns details about the IAM user or role whose credentials are used to call -// the operation. No permissions are required to perform this operation. If an -// administrator attaches a policy to your identity that explicitly denies access -// to the sts:GetCallerIdentity action, you can still perform this operation. -// Permissions are not required because the same information is returned when -// access is denied. To view an example response, see I Am Not Authorized to -// Perform: iam:DeleteVirtualMFADevice (https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot_general.html#troubleshoot_general_access-denied-delete-mfa) -// in the IAM User Guide. -func (c *Client) GetCallerIdentity(ctx context.Context, params *GetCallerIdentityInput, optFns ...func(*Options)) (*GetCallerIdentityOutput, error) { - if params == nil { - params = &GetCallerIdentityInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetCallerIdentity", params, optFns, c.addOperationGetCallerIdentityMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetCallerIdentityOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetCallerIdentityInput struct { - noSmithyDocumentSerde -} - -// Contains the response to a successful GetCallerIdentity request, including -// information about the entity making the request. -type GetCallerIdentityOutput struct { - - // The Amazon Web Services account ID number of the account that owns or contains - // the calling entity. - Account *string - - // The Amazon Web Services ARN associated with the calling entity. - Arn *string - - // The unique identifier of the calling entity. The exact value depends on the - // type of entity that is making the call. The values returned are those listed in - // the aws:userid column in the Principal table (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_variables.html#principaltable) - // found on the Policy Variables reference page in the IAM User Guide. - UserId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetCallerIdentityMiddlewares(stack *middleware.Stack, options Options) (err error) { - err = stack.Serialize.Add(&awsAwsquery_serializeOpGetCallerIdentity{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsquery_deserializeOpGetCallerIdentity{}, middleware.After) - if err != nil { - return err - } - if err = addlegacyEndpointContextSetter(stack, options); err != nil { - return err - } - if err = addSetLoggerMiddleware(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { - return err - } - if err = addClientUserAgent(stack, options); err != nil { - return err - } - if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = addGetCallerIdentityResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetCallerIdentity(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { - return err - } - if err = addRequestIDRetrieverMiddleware(stack); err != nil { - return err - } - if err = addResponseErrorMiddleware(stack); err != nil { - return err - } - if err = addRequestResponseLogging(stack, options); err != nil { - return err - } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { - return err - } - return nil -} - -func newServiceMetadataMiddleware_opGetCallerIdentity(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - SigningName: "sts", - OperationName: "GetCallerIdentity", - } -} - -// PresignGetCallerIdentity is used to generate a presigned HTTP Request which -// contains presigned URL, signed headers and HTTP method used. -func (c *PresignClient) PresignGetCallerIdentity(ctx context.Context, params *GetCallerIdentityInput, optFns ...func(*PresignOptions)) (*v4.PresignedHTTPRequest, error) { - if params == nil { - params = &GetCallerIdentityInput{} - } - options := c.options.copy() - for _, fn := range optFns { - fn(&options) - } - clientOptFns := append(options.ClientOptions, withNopHTTPClientAPIOption) - - result, _, err := c.client.invokeOperation(ctx, "GetCallerIdentity", params, clientOptFns, - c.client.addOperationGetCallerIdentityMiddlewares, - presignConverter(options).convertToPresignMiddleware, - ) - if err != nil { - return nil, err - } - - out := result.(*v4.PresignedHTTPRequest) - return out, nil -} - -type opGetCallerIdentityResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opGetCallerIdentityResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opGetCallerIdentityResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "sts" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "sts" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("sts") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addGetCallerIdentityResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opGetCallerIdentityResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetFederationToken.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetFederationToken.go deleted file mode 100644 index d577ef686..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetFederationToken.go +++ /dev/null @@ -1,445 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -import ( - "context" - "errors" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - "github.com/aws/aws-sdk-go-v2/service/sts/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Returns a set of temporary security credentials (consisting of an access key -// ID, a secret access key, and a security token) for a user. A typical use is in a -// proxy application that gets temporary security credentials on behalf of -// distributed applications inside a corporate network. You must call the -// GetFederationToken operation using the long-term security credentials of an IAM -// user. As a result, this call is appropriate in contexts where those credentials -// can be safeguarded, usually in a server-based application. For a comparison of -// GetFederationToken with the other API operations that produce temporary -// credentials, see Requesting Temporary Security Credentials (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the Amazon Web Services STS API operations (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. Although it is possible to call GetFederationToken using -// the security credentials of an Amazon Web Services account root user rather than -// an IAM user that you create for the purpose of a proxy application, we do not -// recommend it. For more information, see Safeguard your root user credentials -// and don't use them for everyday tasks (https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#lock-away-credentials) -// in the IAM User Guide. You can create a mobile-based or browser-based app that -// can authenticate users using a web identity provider like Login with Amazon, -// Facebook, Google, or an OpenID Connect-compatible identity provider. In this -// case, we recommend that you use Amazon Cognito (http://aws.amazon.com/cognito/) -// or AssumeRoleWithWebIdentity . For more information, see Federation Through a -// Web-based Identity Provider (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_assumerolewithwebidentity) -// in the IAM User Guide. Session duration The temporary credentials are valid for -// the specified duration, from 900 seconds (15 minutes) up to a maximum of 129,600 -// seconds (36 hours). The default session duration is 43,200 seconds (12 hours). -// Temporary credentials obtained by using the root user credentials have a maximum -// duration of 3,600 seconds (1 hour). Permissions You can use the temporary -// credentials created by GetFederationToken in any Amazon Web Services service -// with the following exceptions: -// - You cannot call any IAM operations using the CLI or the Amazon Web Services -// API. This limitation does not apply to console sessions. -// - You cannot call any STS operations except GetCallerIdentity . -// -// You can use temporary credentials for single sign-on (SSO) to the console. You -// must pass an inline or managed session policy (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) -// to this operation. You can pass a single JSON policy document to use as an -// inline session policy. You can also specify up to 10 managed policy Amazon -// Resource Names (ARNs) to use as managed session policies. The plaintext that you -// use for both inline and managed session policies can't exceed 2,048 characters. -// Though the session policy parameters are optional, if you do not pass a policy, -// then the resulting federated user session has no permissions. When you pass -// session policies, the session permissions are the intersection of the IAM user -// policies and the session policies that you pass. This gives you a way to further -// restrict the permissions for a federated user. You cannot use session policies -// to grant more permissions than those that are defined in the permissions policy -// of the IAM user. For more information, see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) -// in the IAM User Guide. For information about using GetFederationToken to create -// temporary security credentials, see GetFederationToken—Federation Through a -// Custom Identity Broker (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_getfederationtoken) -// . You can use the credentials to access a resource that has a resource-based -// policy. If that policy specifically references the federated user session in the -// Principal element of the policy, the session has the permissions allowed by the -// policy. These permissions are granted in addition to the permissions granted by -// the session policies. Tags (Optional) You can pass tag key-value pairs to your -// session. These are called session tags. For more information about session tags, -// see Passing Session Tags in STS (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) -// in the IAM User Guide. You can create a mobile-based or browser-based app that -// can authenticate users using a web identity provider like Login with Amazon, -// Facebook, Google, or an OpenID Connect-compatible identity provider. In this -// case, we recommend that you use Amazon Cognito (http://aws.amazon.com/cognito/) -// or AssumeRoleWithWebIdentity . For more information, see Federation Through a -// Web-based Identity Provider (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_assumerolewithwebidentity) -// in the IAM User Guide. An administrator must grant you the permissions necessary -// to pass session tags. The administrator can also create granular permissions to -// allow you to pass only specific session tags. For more information, see -// Tutorial: Using Tags for Attribute-Based Access Control (https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_attribute-based-access-control.html) -// in the IAM User Guide. Tag key–value pairs are not case sensitive, but case is -// preserved. This means that you cannot have separate Department and department -// tag keys. Assume that the user that you are federating has the Department = -// Marketing tag and you pass the department = engineering session tag. Department -// and department are not saved as separate tags, and the session tag passed in -// the request takes precedence over the user tag. -func (c *Client) GetFederationToken(ctx context.Context, params *GetFederationTokenInput, optFns ...func(*Options)) (*GetFederationTokenOutput, error) { - if params == nil { - params = &GetFederationTokenInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetFederationToken", params, optFns, c.addOperationGetFederationTokenMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetFederationTokenOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetFederationTokenInput struct { - - // The name of the federated user. The name is used as an identifier for the - // temporary security credentials (such as Bob ). For example, you can reference - // the federated user name in a resource-based policy, such as in an Amazon S3 - // bucket policy. The regex used to validate this parameter is a string of - // characters consisting of upper- and lower-case alphanumeric characters with no - // spaces. You can also include underscores or any of the following characters: - // =,.@- - // - // This member is required. - Name *string - - // The duration, in seconds, that the session should last. Acceptable durations - // for federation sessions range from 900 seconds (15 minutes) to 129,600 seconds - // (36 hours), with 43,200 seconds (12 hours) as the default. Sessions obtained - // using root user credentials are restricted to a maximum of 3,600 seconds (one - // hour). If the specified duration is longer than one hour, the session obtained - // by using root user credentials defaults to one hour. - DurationSeconds *int32 - - // An IAM policy in JSON format that you want to use as an inline session policy. - // You must pass an inline or managed session policy (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // to this operation. You can pass a single JSON policy document to use as an - // inline session policy. You can also specify up to 10 managed policy Amazon - // Resource Names (ARNs) to use as managed session policies. This parameter is - // optional. However, if you do not pass any session policies, then the resulting - // federated user session has no permissions. When you pass session policies, the - // session permissions are the intersection of the IAM user policies and the - // session policies that you pass. This gives you a way to further restrict the - // permissions for a federated user. You cannot use session policies to grant more - // permissions than those that are defined in the permissions policy of the IAM - // user. For more information, see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // in the IAM User Guide. The resulting credentials can be used to access a - // resource that has a resource-based policy. If that policy specifically - // references the federated user session in the Principal element of the policy, - // the session has the permissions allowed by the policy. These permissions are - // granted in addition to the permissions that are granted by the session policies. - // The plaintext that you use for both inline and managed session policies can't - // exceed 2,048 characters. The JSON policy characters can be any ASCII character - // from the space character to the end of the valid character list (\u0020 through - // \u00FF). It can also include the tab (\u0009), linefeed (\u000A), and carriage - // return (\u000D) characters. An Amazon Web Services conversion compresses the - // passed inline session policy, managed policy ARNs, and session tags into a - // packed binary format that has a separate limit. Your request can fail for this - // limit even if your plaintext meets the other requirements. The PackedPolicySize - // response element indicates by percentage how close the policies and tags for - // your request are to the upper size limit. - Policy *string - - // The Amazon Resource Names (ARNs) of the IAM managed policies that you want to - // use as a managed session policy. The policies must exist in the same account as - // the IAM user that is requesting federated access. You must pass an inline or - // managed session policy (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // to this operation. You can pass a single JSON policy document to use as an - // inline session policy. You can also specify up to 10 managed policy Amazon - // Resource Names (ARNs) to use as managed session policies. The plaintext that you - // use for both inline and managed session policies can't exceed 2,048 characters. - // You can provide up to 10 managed policy ARNs. For more information about ARNs, - // see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces (https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) - // in the Amazon Web Services General Reference. This parameter is optional. - // However, if you do not pass any session policies, then the resulting federated - // user session has no permissions. When you pass session policies, the session - // permissions are the intersection of the IAM user policies and the session - // policies that you pass. This gives you a way to further restrict the permissions - // for a federated user. You cannot use session policies to grant more permissions - // than those that are defined in the permissions policy of the IAM user. For more - // information, see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // in the IAM User Guide. The resulting credentials can be used to access a - // resource that has a resource-based policy. If that policy specifically - // references the federated user session in the Principal element of the policy, - // the session has the permissions allowed by the policy. These permissions are - // granted in addition to the permissions that are granted by the session policies. - // An Amazon Web Services conversion compresses the passed inline session policy, - // managed policy ARNs, and session tags into a packed binary format that has a - // separate limit. Your request can fail for this limit even if your plaintext - // meets the other requirements. The PackedPolicySize response element indicates - // by percentage how close the policies and tags for your request are to the upper - // size limit. - PolicyArns []types.PolicyDescriptorType - - // A list of session tags. Each session tag consists of a key name and an - // associated value. For more information about session tags, see Passing Session - // Tags in STS (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) - // in the IAM User Guide. This parameter is optional. You can pass up to 50 session - // tags. The plaintext session tag keys can’t exceed 128 characters and the values - // can’t exceed 256 characters. For these and additional limits, see IAM and STS - // Character Limits (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html#reference_iam-limits-entity-length) - // in the IAM User Guide. An Amazon Web Services conversion compresses the passed - // inline session policy, managed policy ARNs, and session tags into a packed - // binary format that has a separate limit. Your request can fail for this limit - // even if your plaintext meets the other requirements. The PackedPolicySize - // response element indicates by percentage how close the policies and tags for - // your request are to the upper size limit. You can pass a session tag with the - // same key as a tag that is already attached to the user you are federating. When - // you do, session tags override a user tag with the same key. Tag key–value pairs - // are not case sensitive, but case is preserved. This means that you cannot have - // separate Department and department tag keys. Assume that the role has the - // Department = Marketing tag and you pass the department = engineering session - // tag. Department and department are not saved as separate tags, and the session - // tag passed in the request takes precedence over the role tag. - Tags []types.Tag - - noSmithyDocumentSerde -} - -// Contains the response to a successful GetFederationToken request, including -// temporary Amazon Web Services credentials that can be used to make Amazon Web -// Services requests. -type GetFederationTokenOutput struct { - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security (or session) token. The size of the security token - // that STS API operations return is not fixed. We strongly recommend that you make - // no assumptions about the maximum size. - Credentials *types.Credentials - - // Identifiers for the federated user associated with the credentials (such as - // arn:aws:sts::123456789012:federated-user/Bob or 123456789012:Bob ). You can use - // the federated user's ARN in your resource-based policies, such as an Amazon S3 - // bucket policy. - FederatedUser *types.FederatedUser - - // A percentage value that indicates the packed size of the session policies and - // session tags combined passed in the request. The request fails if the packed - // size is greater than 100 percent, which means the policies and tags exceeded the - // allowed space. - PackedPolicySize *int32 - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetFederationTokenMiddlewares(stack *middleware.Stack, options Options) (err error) { - err = stack.Serialize.Add(&awsAwsquery_serializeOpGetFederationToken{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsquery_deserializeOpGetFederationToken{}, middleware.After) - if err != nil { - return err - } - if err = addlegacyEndpointContextSetter(stack, options); err != nil { - return err - } - if err = addSetLoggerMiddleware(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { - return err - } - if err = addClientUserAgent(stack, options); err != nil { - return err - } - if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = addGetFederationTokenResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addOpGetFederationTokenValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetFederationToken(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { - return err - } - if err = addRequestIDRetrieverMiddleware(stack); err != nil { - return err - } - if err = addResponseErrorMiddleware(stack); err != nil { - return err - } - if err = addRequestResponseLogging(stack, options); err != nil { - return err - } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { - return err - } - return nil -} - -func newServiceMetadataMiddleware_opGetFederationToken(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - SigningName: "sts", - OperationName: "GetFederationToken", - } -} - -type opGetFederationTokenResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opGetFederationTokenResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opGetFederationTokenResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "sts" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "sts" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("sts") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addGetFederationTokenResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opGetFederationTokenResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetSessionToken.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetSessionToken.go deleted file mode 100644 index 7a2345e80..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetSessionToken.go +++ /dev/null @@ -1,328 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -import ( - "context" - "errors" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - "github.com/aws/aws-sdk-go-v2/service/sts/types" - smithyendpoints "github.com/aws/smithy-go/endpoints" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Returns a set of temporary credentials for an Amazon Web Services account or -// IAM user. The credentials consist of an access key ID, a secret access key, and -// a security token. Typically, you use GetSessionToken if you want to use MFA to -// protect programmatic calls to specific Amazon Web Services API operations like -// Amazon EC2 StopInstances . MFA-enabled IAM users must call GetSessionToken and -// submit an MFA code that is associated with their MFA device. Using the temporary -// security credentials that the call returns, IAM users can then make programmatic -// calls to API operations that require MFA authentication. An incorrect MFA code -// causes the API to return an access denied error. For a comparison of -// GetSessionToken with the other API operations that produce temporary -// credentials, see Requesting Temporary Security Credentials (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the Amazon Web Services STS API operations (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. No permissions are required for users to perform this -// operation. The purpose of the sts:GetSessionToken operation is to authenticate -// the user using MFA. You cannot use policies to control authentication -// operations. For more information, see Permissions for GetSessionToken (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_getsessiontoken.html) -// in the IAM User Guide. Session Duration The GetSessionToken operation must be -// called by using the long-term Amazon Web Services security credentials of an IAM -// user. Credentials that are created by IAM users are valid for the duration that -// you specify. This duration can range from 900 seconds (15 minutes) up to a -// maximum of 129,600 seconds (36 hours), with a default of 43,200 seconds (12 -// hours). Credentials based on account credentials can range from 900 seconds (15 -// minutes) up to 3,600 seconds (1 hour), with a default of 1 hour. Permissions The -// temporary security credentials created by GetSessionToken can be used to make -// API calls to any Amazon Web Services service with the following exceptions: -// - You cannot call any IAM API operations unless MFA authentication -// information is included in the request. -// - You cannot call any STS API except AssumeRole or GetCallerIdentity . -// -// The credentials that GetSessionToken returns are based on permissions -// associated with the IAM user whose credentials were used to call the operation. -// The temporary credentials have the same permissions as the IAM user. Although it -// is possible to call GetSessionToken using the security credentials of an Amazon -// Web Services account root user rather than an IAM user, we do not recommend it. -// If GetSessionToken is called using root user credentials, the temporary -// credentials have root user permissions. For more information, see Safeguard -// your root user credentials and don't use them for everyday tasks (https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#lock-away-credentials) -// in the IAM User Guide For more information about using GetSessionToken to -// create temporary credentials, see Temporary Credentials for Users in Untrusted -// Environments (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_getsessiontoken) -// in the IAM User Guide. -func (c *Client) GetSessionToken(ctx context.Context, params *GetSessionTokenInput, optFns ...func(*Options)) (*GetSessionTokenOutput, error) { - if params == nil { - params = &GetSessionTokenInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetSessionToken", params, optFns, c.addOperationGetSessionTokenMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetSessionTokenOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetSessionTokenInput struct { - - // The duration, in seconds, that the credentials should remain valid. Acceptable - // durations for IAM user sessions range from 900 seconds (15 minutes) to 129,600 - // seconds (36 hours), with 43,200 seconds (12 hours) as the default. Sessions for - // Amazon Web Services account owners are restricted to a maximum of 3,600 seconds - // (one hour). If the duration is longer than one hour, the session for Amazon Web - // Services account owners defaults to one hour. - DurationSeconds *int32 - - // The identification number of the MFA device that is associated with the IAM - // user who is making the GetSessionToken call. Specify this value if the IAM user - // has a policy that requires MFA authentication. The value is either the serial - // number for a hardware device (such as GAHT12345678 ) or an Amazon Resource Name - // (ARN) for a virtual device (such as arn:aws:iam::123456789012:mfa/user ). You - // can find the device for an IAM user by going to the Amazon Web Services - // Management Console and viewing the user's security credentials. The regex used - // to validate this parameter is a string of characters consisting of upper- and - // lower-case alphanumeric characters with no spaces. You can also include - // underscores or any of the following characters: =,.@:/- - SerialNumber *string - - // The value provided by the MFA device, if MFA is required. If any policy - // requires the IAM user to submit an MFA code, specify this value. If MFA - // authentication is required, the user must provide a code when requesting a set - // of temporary security credentials. A user who fails to provide the code receives - // an "access denied" response when requesting resources that require MFA - // authentication. The format for this parameter, as described by its regex - // pattern, is a sequence of six numeric digits. - TokenCode *string - - noSmithyDocumentSerde -} - -// Contains the response to a successful GetSessionToken request, including -// temporary Amazon Web Services credentials that can be used to make Amazon Web -// Services requests. -type GetSessionTokenOutput struct { - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security (or session) token. The size of the security token - // that STS API operations return is not fixed. We strongly recommend that you make - // no assumptions about the maximum size. - Credentials *types.Credentials - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetSessionTokenMiddlewares(stack *middleware.Stack, options Options) (err error) { - err = stack.Serialize.Add(&awsAwsquery_serializeOpGetSessionToken{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsquery_deserializeOpGetSessionToken{}, middleware.After) - if err != nil { - return err - } - if err = addlegacyEndpointContextSetter(stack, options); err != nil { - return err - } - if err = addSetLoggerMiddleware(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = addHTTPSignerV4Middleware(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { - return err - } - if err = addClientUserAgent(stack, options); err != nil { - return err - } - if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { - return err - } - if err = addGetSessionTokenResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetSessionToken(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.AddRecursionDetection(stack); err != nil { - return err - } - if err = addRequestIDRetrieverMiddleware(stack); err != nil { - return err - } - if err = addResponseErrorMiddleware(stack); err != nil { - return err - } - if err = addRequestResponseLogging(stack, options); err != nil { - return err - } - if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { - return err - } - return nil -} - -func newServiceMetadataMiddleware_opGetSessionToken(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - SigningName: "sts", - OperationName: "GetSessionToken", - } -} - -type opGetSessionTokenResolveEndpointMiddleware struct { - EndpointResolver EndpointResolverV2 - BuiltInResolver builtInParameterResolver -} - -func (*opGetSessionTokenResolveEndpointMiddleware) ID() string { - return "ResolveEndpointV2" -} - -func (m *opGetSessionTokenResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.EndpointResolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - params := EndpointParameters{} - - m.BuiltInResolver.ResolveBuiltIns(¶ms) - - var resolvedEndpoint smithyendpoints.Endpoint - resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL = &resolvedEndpoint.URI - - for k := range resolvedEndpoint.Headers { - req.Header.Set( - k, - resolvedEndpoint.Headers.Get(k), - ) - } - - authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) - if err != nil { - var nfe *internalauth.NoAuthenticationSchemesFoundError - if errors.As(err, &nfe) { - // if no auth scheme is found, default to sigv4 - signingName := "sts" - signingRegion := m.BuiltInResolver.(*builtInResolver).Region - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - - } - var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError - if errors.As(err, &ue) { - return out, metadata, fmt.Errorf( - "This operation requests signer version(s) %v but the client only supports %v", - ue.UnsupportedSchemes, - internalauth.SupportedSchemes, - ) - } - } - - for _, authScheme := range authSchemes { - switch authScheme.(type) { - case *internalauth.AuthenticationSchemeV4: - v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4) - var signingName, signingRegion string - if v4Scheme.SigningName == nil { - signingName = "sts" - } else { - signingName = *v4Scheme.SigningName - } - if v4Scheme.SigningRegion == nil { - signingRegion = m.BuiltInResolver.(*builtInResolver).Region - } else { - signingRegion = *v4Scheme.SigningRegion - } - if v4Scheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) - break - case *internalauth.AuthenticationSchemeV4A: - v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) - if v4aScheme.SigningName == nil { - v4aScheme.SigningName = aws.String("sts") - } - if v4aScheme.DisableDoubleEncoding != nil { - // The signer sets an equivalent value at client initialization time. - // Setting this context value will cause the signer to extract it - // and override the value set at client initialization time. - ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding) - } - ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName) - ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0]) - break - case *internalauth.AuthenticationSchemeNone: - break - } - } - - return next.HandleSerialize(ctx, in) -} - -func addGetSessionTokenResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { - return stack.Serialize.Insert(&opGetSessionTokenResolveEndpointMiddleware{ - EndpointResolver: options.EndpointResolverV2, - BuiltInResolver: &builtInResolver{ - Region: options.Region, - UseDualStack: options.EndpointOptions.UseDualStackEndpoint, - UseFIPS: options.EndpointOptions.UseFIPSEndpoint, - Endpoint: options.BaseEndpoint, - }, - }, "ResolveEndpoint", middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/deserializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/deserializers.go deleted file mode 100644 index 5d634ce35..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/deserializers.go +++ /dev/null @@ -1,2507 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -import ( - "bytes" - "context" - "encoding/xml" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - awsxml "github.com/aws/aws-sdk-go-v2/aws/protocol/xml" - "github.com/aws/aws-sdk-go-v2/service/sts/types" - smithy "github.com/aws/smithy-go" - smithyxml "github.com/aws/smithy-go/encoding/xml" - smithyio "github.com/aws/smithy-go/io" - "github.com/aws/smithy-go/middleware" - "github.com/aws/smithy-go/ptr" - smithytime "github.com/aws/smithy-go/time" - smithyhttp "github.com/aws/smithy-go/transport/http" - "io" - "strconv" - "strings" -) - -type awsAwsquery_deserializeOpAssumeRole struct { -} - -func (*awsAwsquery_deserializeOpAssumeRole) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsquery_deserializeOpAssumeRole) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( - out middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err = next.HandleDeserialize(ctx, in) - if err != nil { - return out, metadata, err - } - - response, ok := out.RawResponse.(*smithyhttp.Response) - if !ok { - return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} - } - - if response.StatusCode < 200 || response.StatusCode >= 300 { - return out, metadata, awsAwsquery_deserializeOpErrorAssumeRole(response, &metadata) - } - output := &AssumeRoleOutput{} - out.Result = output - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(response.Body, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return out, metadata, nil - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("AssumeRoleResult") - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return out, metadata, err - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeOpDocumentAssumeRoleOutput(&output, decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return out, metadata, err - } - - return out, metadata, err -} - -func awsAwsquery_deserializeOpErrorAssumeRole(response *smithyhttp.Response, metadata *middleware.Metadata) error { - var errorBuffer bytes.Buffer - if _, err := io.Copy(&errorBuffer, response.Body); err != nil { - return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} - } - errorBody := bytes.NewReader(errorBuffer.Bytes()) - - errorCode := "UnknownError" - errorMessage := errorCode - - errorComponents, err := awsxml.GetErrorResponseComponents(errorBody, false) - if err != nil { - return err - } - if reqID := errorComponents.RequestID; len(reqID) != 0 { - awsmiddleware.SetRequestIDMetadata(metadata, reqID) - } - if len(errorComponents.Code) != 0 { - errorCode = errorComponents.Code - } - if len(errorComponents.Message) != 0 { - errorMessage = errorComponents.Message - } - errorBody.Seek(0, io.SeekStart) - switch { - case strings.EqualFold("ExpiredTokenException", errorCode): - return awsAwsquery_deserializeErrorExpiredTokenException(response, errorBody) - - case strings.EqualFold("MalformedPolicyDocument", errorCode): - return awsAwsquery_deserializeErrorMalformedPolicyDocumentException(response, errorBody) - - case strings.EqualFold("PackedPolicyTooLarge", errorCode): - return awsAwsquery_deserializeErrorPackedPolicyTooLargeException(response, errorBody) - - case strings.EqualFold("RegionDisabledException", errorCode): - return awsAwsquery_deserializeErrorRegionDisabledException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsquery_deserializeOpAssumeRoleWithSAML struct { -} - -func (*awsAwsquery_deserializeOpAssumeRoleWithSAML) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsquery_deserializeOpAssumeRoleWithSAML) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( - out middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err = next.HandleDeserialize(ctx, in) - if err != nil { - return out, metadata, err - } - - response, ok := out.RawResponse.(*smithyhttp.Response) - if !ok { - return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} - } - - if response.StatusCode < 200 || response.StatusCode >= 300 { - return out, metadata, awsAwsquery_deserializeOpErrorAssumeRoleWithSAML(response, &metadata) - } - output := &AssumeRoleWithSAMLOutput{} - out.Result = output - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(response.Body, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return out, metadata, nil - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("AssumeRoleWithSAMLResult") - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return out, metadata, err - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeOpDocumentAssumeRoleWithSAMLOutput(&output, decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return out, metadata, err - } - - return out, metadata, err -} - -func awsAwsquery_deserializeOpErrorAssumeRoleWithSAML(response *smithyhttp.Response, metadata *middleware.Metadata) error { - var errorBuffer bytes.Buffer - if _, err := io.Copy(&errorBuffer, response.Body); err != nil { - return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} - } - errorBody := bytes.NewReader(errorBuffer.Bytes()) - - errorCode := "UnknownError" - errorMessage := errorCode - - errorComponents, err := awsxml.GetErrorResponseComponents(errorBody, false) - if err != nil { - return err - } - if reqID := errorComponents.RequestID; len(reqID) != 0 { - awsmiddleware.SetRequestIDMetadata(metadata, reqID) - } - if len(errorComponents.Code) != 0 { - errorCode = errorComponents.Code - } - if len(errorComponents.Message) != 0 { - errorMessage = errorComponents.Message - } - errorBody.Seek(0, io.SeekStart) - switch { - case strings.EqualFold("ExpiredTokenException", errorCode): - return awsAwsquery_deserializeErrorExpiredTokenException(response, errorBody) - - case strings.EqualFold("IDPRejectedClaim", errorCode): - return awsAwsquery_deserializeErrorIDPRejectedClaimException(response, errorBody) - - case strings.EqualFold("InvalidIdentityToken", errorCode): - return awsAwsquery_deserializeErrorInvalidIdentityTokenException(response, errorBody) - - case strings.EqualFold("MalformedPolicyDocument", errorCode): - return awsAwsquery_deserializeErrorMalformedPolicyDocumentException(response, errorBody) - - case strings.EqualFold("PackedPolicyTooLarge", errorCode): - return awsAwsquery_deserializeErrorPackedPolicyTooLargeException(response, errorBody) - - case strings.EqualFold("RegionDisabledException", errorCode): - return awsAwsquery_deserializeErrorRegionDisabledException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsquery_deserializeOpAssumeRoleWithWebIdentity struct { -} - -func (*awsAwsquery_deserializeOpAssumeRoleWithWebIdentity) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsquery_deserializeOpAssumeRoleWithWebIdentity) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( - out middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err = next.HandleDeserialize(ctx, in) - if err != nil { - return out, metadata, err - } - - response, ok := out.RawResponse.(*smithyhttp.Response) - if !ok { - return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} - } - - if response.StatusCode < 200 || response.StatusCode >= 300 { - return out, metadata, awsAwsquery_deserializeOpErrorAssumeRoleWithWebIdentity(response, &metadata) - } - output := &AssumeRoleWithWebIdentityOutput{} - out.Result = output - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(response.Body, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return out, metadata, nil - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("AssumeRoleWithWebIdentityResult") - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return out, metadata, err - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeOpDocumentAssumeRoleWithWebIdentityOutput(&output, decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return out, metadata, err - } - - return out, metadata, err -} - -func awsAwsquery_deserializeOpErrorAssumeRoleWithWebIdentity(response *smithyhttp.Response, metadata *middleware.Metadata) error { - var errorBuffer bytes.Buffer - if _, err := io.Copy(&errorBuffer, response.Body); err != nil { - return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} - } - errorBody := bytes.NewReader(errorBuffer.Bytes()) - - errorCode := "UnknownError" - errorMessage := errorCode - - errorComponents, err := awsxml.GetErrorResponseComponents(errorBody, false) - if err != nil { - return err - } - if reqID := errorComponents.RequestID; len(reqID) != 0 { - awsmiddleware.SetRequestIDMetadata(metadata, reqID) - } - if len(errorComponents.Code) != 0 { - errorCode = errorComponents.Code - } - if len(errorComponents.Message) != 0 { - errorMessage = errorComponents.Message - } - errorBody.Seek(0, io.SeekStart) - switch { - case strings.EqualFold("ExpiredTokenException", errorCode): - return awsAwsquery_deserializeErrorExpiredTokenException(response, errorBody) - - case strings.EqualFold("IDPCommunicationError", errorCode): - return awsAwsquery_deserializeErrorIDPCommunicationErrorException(response, errorBody) - - case strings.EqualFold("IDPRejectedClaim", errorCode): - return awsAwsquery_deserializeErrorIDPRejectedClaimException(response, errorBody) - - case strings.EqualFold("InvalidIdentityToken", errorCode): - return awsAwsquery_deserializeErrorInvalidIdentityTokenException(response, errorBody) - - case strings.EqualFold("MalformedPolicyDocument", errorCode): - return awsAwsquery_deserializeErrorMalformedPolicyDocumentException(response, errorBody) - - case strings.EqualFold("PackedPolicyTooLarge", errorCode): - return awsAwsquery_deserializeErrorPackedPolicyTooLargeException(response, errorBody) - - case strings.EqualFold("RegionDisabledException", errorCode): - return awsAwsquery_deserializeErrorRegionDisabledException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsquery_deserializeOpDecodeAuthorizationMessage struct { -} - -func (*awsAwsquery_deserializeOpDecodeAuthorizationMessage) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsquery_deserializeOpDecodeAuthorizationMessage) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( - out middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err = next.HandleDeserialize(ctx, in) - if err != nil { - return out, metadata, err - } - - response, ok := out.RawResponse.(*smithyhttp.Response) - if !ok { - return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} - } - - if response.StatusCode < 200 || response.StatusCode >= 300 { - return out, metadata, awsAwsquery_deserializeOpErrorDecodeAuthorizationMessage(response, &metadata) - } - output := &DecodeAuthorizationMessageOutput{} - out.Result = output - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(response.Body, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return out, metadata, nil - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("DecodeAuthorizationMessageResult") - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return out, metadata, err - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeOpDocumentDecodeAuthorizationMessageOutput(&output, decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return out, metadata, err - } - - return out, metadata, err -} - -func awsAwsquery_deserializeOpErrorDecodeAuthorizationMessage(response *smithyhttp.Response, metadata *middleware.Metadata) error { - var errorBuffer bytes.Buffer - if _, err := io.Copy(&errorBuffer, response.Body); err != nil { - return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} - } - errorBody := bytes.NewReader(errorBuffer.Bytes()) - - errorCode := "UnknownError" - errorMessage := errorCode - - errorComponents, err := awsxml.GetErrorResponseComponents(errorBody, false) - if err != nil { - return err - } - if reqID := errorComponents.RequestID; len(reqID) != 0 { - awsmiddleware.SetRequestIDMetadata(metadata, reqID) - } - if len(errorComponents.Code) != 0 { - errorCode = errorComponents.Code - } - if len(errorComponents.Message) != 0 { - errorMessage = errorComponents.Message - } - errorBody.Seek(0, io.SeekStart) - switch { - case strings.EqualFold("InvalidAuthorizationMessageException", errorCode): - return awsAwsquery_deserializeErrorInvalidAuthorizationMessageException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsquery_deserializeOpGetAccessKeyInfo struct { -} - -func (*awsAwsquery_deserializeOpGetAccessKeyInfo) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsquery_deserializeOpGetAccessKeyInfo) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( - out middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err = next.HandleDeserialize(ctx, in) - if err != nil { - return out, metadata, err - } - - response, ok := out.RawResponse.(*smithyhttp.Response) - if !ok { - return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} - } - - if response.StatusCode < 200 || response.StatusCode >= 300 { - return out, metadata, awsAwsquery_deserializeOpErrorGetAccessKeyInfo(response, &metadata) - } - output := &GetAccessKeyInfoOutput{} - out.Result = output - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(response.Body, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return out, metadata, nil - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("GetAccessKeyInfoResult") - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return out, metadata, err - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeOpDocumentGetAccessKeyInfoOutput(&output, decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return out, metadata, err - } - - return out, metadata, err -} - -func awsAwsquery_deserializeOpErrorGetAccessKeyInfo(response *smithyhttp.Response, metadata *middleware.Metadata) error { - var errorBuffer bytes.Buffer - if _, err := io.Copy(&errorBuffer, response.Body); err != nil { - return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} - } - errorBody := bytes.NewReader(errorBuffer.Bytes()) - - errorCode := "UnknownError" - errorMessage := errorCode - - errorComponents, err := awsxml.GetErrorResponseComponents(errorBody, false) - if err != nil { - return err - } - if reqID := errorComponents.RequestID; len(reqID) != 0 { - awsmiddleware.SetRequestIDMetadata(metadata, reqID) - } - if len(errorComponents.Code) != 0 { - errorCode = errorComponents.Code - } - if len(errorComponents.Message) != 0 { - errorMessage = errorComponents.Message - } - errorBody.Seek(0, io.SeekStart) - switch { - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsquery_deserializeOpGetCallerIdentity struct { -} - -func (*awsAwsquery_deserializeOpGetCallerIdentity) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsquery_deserializeOpGetCallerIdentity) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( - out middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err = next.HandleDeserialize(ctx, in) - if err != nil { - return out, metadata, err - } - - response, ok := out.RawResponse.(*smithyhttp.Response) - if !ok { - return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} - } - - if response.StatusCode < 200 || response.StatusCode >= 300 { - return out, metadata, awsAwsquery_deserializeOpErrorGetCallerIdentity(response, &metadata) - } - output := &GetCallerIdentityOutput{} - out.Result = output - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(response.Body, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return out, metadata, nil - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("GetCallerIdentityResult") - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return out, metadata, err - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeOpDocumentGetCallerIdentityOutput(&output, decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return out, metadata, err - } - - return out, metadata, err -} - -func awsAwsquery_deserializeOpErrorGetCallerIdentity(response *smithyhttp.Response, metadata *middleware.Metadata) error { - var errorBuffer bytes.Buffer - if _, err := io.Copy(&errorBuffer, response.Body); err != nil { - return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} - } - errorBody := bytes.NewReader(errorBuffer.Bytes()) - - errorCode := "UnknownError" - errorMessage := errorCode - - errorComponents, err := awsxml.GetErrorResponseComponents(errorBody, false) - if err != nil { - return err - } - if reqID := errorComponents.RequestID; len(reqID) != 0 { - awsmiddleware.SetRequestIDMetadata(metadata, reqID) - } - if len(errorComponents.Code) != 0 { - errorCode = errorComponents.Code - } - if len(errorComponents.Message) != 0 { - errorMessage = errorComponents.Message - } - errorBody.Seek(0, io.SeekStart) - switch { - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsquery_deserializeOpGetFederationToken struct { -} - -func (*awsAwsquery_deserializeOpGetFederationToken) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsquery_deserializeOpGetFederationToken) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( - out middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err = next.HandleDeserialize(ctx, in) - if err != nil { - return out, metadata, err - } - - response, ok := out.RawResponse.(*smithyhttp.Response) - if !ok { - return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} - } - - if response.StatusCode < 200 || response.StatusCode >= 300 { - return out, metadata, awsAwsquery_deserializeOpErrorGetFederationToken(response, &metadata) - } - output := &GetFederationTokenOutput{} - out.Result = output - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(response.Body, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return out, metadata, nil - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("GetFederationTokenResult") - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return out, metadata, err - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeOpDocumentGetFederationTokenOutput(&output, decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return out, metadata, err - } - - return out, metadata, err -} - -func awsAwsquery_deserializeOpErrorGetFederationToken(response *smithyhttp.Response, metadata *middleware.Metadata) error { - var errorBuffer bytes.Buffer - if _, err := io.Copy(&errorBuffer, response.Body); err != nil { - return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} - } - errorBody := bytes.NewReader(errorBuffer.Bytes()) - - errorCode := "UnknownError" - errorMessage := errorCode - - errorComponents, err := awsxml.GetErrorResponseComponents(errorBody, false) - if err != nil { - return err - } - if reqID := errorComponents.RequestID; len(reqID) != 0 { - awsmiddleware.SetRequestIDMetadata(metadata, reqID) - } - if len(errorComponents.Code) != 0 { - errorCode = errorComponents.Code - } - if len(errorComponents.Message) != 0 { - errorMessage = errorComponents.Message - } - errorBody.Seek(0, io.SeekStart) - switch { - case strings.EqualFold("MalformedPolicyDocument", errorCode): - return awsAwsquery_deserializeErrorMalformedPolicyDocumentException(response, errorBody) - - case strings.EqualFold("PackedPolicyTooLarge", errorCode): - return awsAwsquery_deserializeErrorPackedPolicyTooLargeException(response, errorBody) - - case strings.EqualFold("RegionDisabledException", errorCode): - return awsAwsquery_deserializeErrorRegionDisabledException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsquery_deserializeOpGetSessionToken struct { -} - -func (*awsAwsquery_deserializeOpGetSessionToken) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsquery_deserializeOpGetSessionToken) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( - out middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err = next.HandleDeserialize(ctx, in) - if err != nil { - return out, metadata, err - } - - response, ok := out.RawResponse.(*smithyhttp.Response) - if !ok { - return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} - } - - if response.StatusCode < 200 || response.StatusCode >= 300 { - return out, metadata, awsAwsquery_deserializeOpErrorGetSessionToken(response, &metadata) - } - output := &GetSessionTokenOutput{} - out.Result = output - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(response.Body, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return out, metadata, nil - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("GetSessionTokenResult") - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return out, metadata, err - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeOpDocumentGetSessionTokenOutput(&output, decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - err = &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - return out, metadata, err - } - - return out, metadata, err -} - -func awsAwsquery_deserializeOpErrorGetSessionToken(response *smithyhttp.Response, metadata *middleware.Metadata) error { - var errorBuffer bytes.Buffer - if _, err := io.Copy(&errorBuffer, response.Body); err != nil { - return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} - } - errorBody := bytes.NewReader(errorBuffer.Bytes()) - - errorCode := "UnknownError" - errorMessage := errorCode - - errorComponents, err := awsxml.GetErrorResponseComponents(errorBody, false) - if err != nil { - return err - } - if reqID := errorComponents.RequestID; len(reqID) != 0 { - awsmiddleware.SetRequestIDMetadata(metadata, reqID) - } - if len(errorComponents.Code) != 0 { - errorCode = errorComponents.Code - } - if len(errorComponents.Message) != 0 { - errorMessage = errorComponents.Message - } - errorBody.Seek(0, io.SeekStart) - switch { - case strings.EqualFold("RegionDisabledException", errorCode): - return awsAwsquery_deserializeErrorRegionDisabledException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -func awsAwsquery_deserializeErrorExpiredTokenException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.ExpiredTokenException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(errorBody, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return output - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("Error") - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeDocumentExpiredTokenException(&output, decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return output -} - -func awsAwsquery_deserializeErrorIDPCommunicationErrorException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.IDPCommunicationErrorException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(errorBody, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return output - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("Error") - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeDocumentIDPCommunicationErrorException(&output, decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return output -} - -func awsAwsquery_deserializeErrorIDPRejectedClaimException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.IDPRejectedClaimException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(errorBody, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return output - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("Error") - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeDocumentIDPRejectedClaimException(&output, decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return output -} - -func awsAwsquery_deserializeErrorInvalidAuthorizationMessageException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.InvalidAuthorizationMessageException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(errorBody, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return output - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("Error") - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeDocumentInvalidAuthorizationMessageException(&output, decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return output -} - -func awsAwsquery_deserializeErrorInvalidIdentityTokenException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.InvalidIdentityTokenException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(errorBody, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return output - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("Error") - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeDocumentInvalidIdentityTokenException(&output, decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return output -} - -func awsAwsquery_deserializeErrorMalformedPolicyDocumentException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.MalformedPolicyDocumentException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(errorBody, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return output - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("Error") - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeDocumentMalformedPolicyDocumentException(&output, decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return output -} - -func awsAwsquery_deserializeErrorPackedPolicyTooLargeException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.PackedPolicyTooLargeException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(errorBody, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return output - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("Error") - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeDocumentPackedPolicyTooLargeException(&output, decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return output -} - -func awsAwsquery_deserializeErrorRegionDisabledException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.RegionDisabledException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(errorBody, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return output - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("Error") - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeDocumentRegionDisabledException(&output, decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return output -} - -func awsAwsquery_deserializeDocumentAssumedRoleUser(v **types.AssumedRoleUser, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *types.AssumedRoleUser - if *v == nil { - sv = &types.AssumedRoleUser{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("Arn", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Arn = ptr.String(xtv) - } - - case strings.EqualFold("AssumedRoleId", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.AssumedRoleId = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeDocumentCredentials(v **types.Credentials, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *types.Credentials - if *v == nil { - sv = &types.Credentials{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("AccessKeyId", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.AccessKeyId = ptr.String(xtv) - } - - case strings.EqualFold("Expiration", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - t, err := smithytime.ParseDateTime(xtv) - if err != nil { - return err - } - sv.Expiration = ptr.Time(t) - } - - case strings.EqualFold("SecretAccessKey", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.SecretAccessKey = ptr.String(xtv) - } - - case strings.EqualFold("SessionToken", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.SessionToken = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeDocumentExpiredTokenException(v **types.ExpiredTokenException, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *types.ExpiredTokenException - if *v == nil { - sv = &types.ExpiredTokenException{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("message", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Message = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeDocumentFederatedUser(v **types.FederatedUser, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *types.FederatedUser - if *v == nil { - sv = &types.FederatedUser{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("Arn", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Arn = ptr.String(xtv) - } - - case strings.EqualFold("FederatedUserId", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.FederatedUserId = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeDocumentIDPCommunicationErrorException(v **types.IDPCommunicationErrorException, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *types.IDPCommunicationErrorException - if *v == nil { - sv = &types.IDPCommunicationErrorException{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("message", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Message = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeDocumentIDPRejectedClaimException(v **types.IDPRejectedClaimException, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *types.IDPRejectedClaimException - if *v == nil { - sv = &types.IDPRejectedClaimException{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("message", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Message = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeDocumentInvalidAuthorizationMessageException(v **types.InvalidAuthorizationMessageException, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *types.InvalidAuthorizationMessageException - if *v == nil { - sv = &types.InvalidAuthorizationMessageException{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("message", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Message = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeDocumentInvalidIdentityTokenException(v **types.InvalidIdentityTokenException, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *types.InvalidIdentityTokenException - if *v == nil { - sv = &types.InvalidIdentityTokenException{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("message", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Message = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeDocumentMalformedPolicyDocumentException(v **types.MalformedPolicyDocumentException, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *types.MalformedPolicyDocumentException - if *v == nil { - sv = &types.MalformedPolicyDocumentException{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("message", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Message = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeDocumentPackedPolicyTooLargeException(v **types.PackedPolicyTooLargeException, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *types.PackedPolicyTooLargeException - if *v == nil { - sv = &types.PackedPolicyTooLargeException{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("message", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Message = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeDocumentRegionDisabledException(v **types.RegionDisabledException, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *types.RegionDisabledException - if *v == nil { - sv = &types.RegionDisabledException{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("message", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Message = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeOpDocumentAssumeRoleOutput(v **AssumeRoleOutput, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *AssumeRoleOutput - if *v == nil { - sv = &AssumeRoleOutput{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("AssumedRoleUser", t.Name.Local): - nodeDecoder := smithyxml.WrapNodeDecoder(decoder.Decoder, t) - if err := awsAwsquery_deserializeDocumentAssumedRoleUser(&sv.AssumedRoleUser, nodeDecoder); err != nil { - return err - } - - case strings.EqualFold("Credentials", t.Name.Local): - nodeDecoder := smithyxml.WrapNodeDecoder(decoder.Decoder, t) - if err := awsAwsquery_deserializeDocumentCredentials(&sv.Credentials, nodeDecoder); err != nil { - return err - } - - case strings.EqualFold("PackedPolicySize", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - i64, err := strconv.ParseInt(xtv, 10, 64) - if err != nil { - return err - } - sv.PackedPolicySize = ptr.Int32(int32(i64)) - } - - case strings.EqualFold("SourceIdentity", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.SourceIdentity = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeOpDocumentAssumeRoleWithSAMLOutput(v **AssumeRoleWithSAMLOutput, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *AssumeRoleWithSAMLOutput - if *v == nil { - sv = &AssumeRoleWithSAMLOutput{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("AssumedRoleUser", t.Name.Local): - nodeDecoder := smithyxml.WrapNodeDecoder(decoder.Decoder, t) - if err := awsAwsquery_deserializeDocumentAssumedRoleUser(&sv.AssumedRoleUser, nodeDecoder); err != nil { - return err - } - - case strings.EqualFold("Audience", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Audience = ptr.String(xtv) - } - - case strings.EqualFold("Credentials", t.Name.Local): - nodeDecoder := smithyxml.WrapNodeDecoder(decoder.Decoder, t) - if err := awsAwsquery_deserializeDocumentCredentials(&sv.Credentials, nodeDecoder); err != nil { - return err - } - - case strings.EqualFold("Issuer", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Issuer = ptr.String(xtv) - } - - case strings.EqualFold("NameQualifier", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.NameQualifier = ptr.String(xtv) - } - - case strings.EqualFold("PackedPolicySize", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - i64, err := strconv.ParseInt(xtv, 10, 64) - if err != nil { - return err - } - sv.PackedPolicySize = ptr.Int32(int32(i64)) - } - - case strings.EqualFold("SourceIdentity", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.SourceIdentity = ptr.String(xtv) - } - - case strings.EqualFold("Subject", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Subject = ptr.String(xtv) - } - - case strings.EqualFold("SubjectType", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.SubjectType = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeOpDocumentAssumeRoleWithWebIdentityOutput(v **AssumeRoleWithWebIdentityOutput, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *AssumeRoleWithWebIdentityOutput - if *v == nil { - sv = &AssumeRoleWithWebIdentityOutput{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("AssumedRoleUser", t.Name.Local): - nodeDecoder := smithyxml.WrapNodeDecoder(decoder.Decoder, t) - if err := awsAwsquery_deserializeDocumentAssumedRoleUser(&sv.AssumedRoleUser, nodeDecoder); err != nil { - return err - } - - case strings.EqualFold("Audience", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Audience = ptr.String(xtv) - } - - case strings.EqualFold("Credentials", t.Name.Local): - nodeDecoder := smithyxml.WrapNodeDecoder(decoder.Decoder, t) - if err := awsAwsquery_deserializeDocumentCredentials(&sv.Credentials, nodeDecoder); err != nil { - return err - } - - case strings.EqualFold("PackedPolicySize", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - i64, err := strconv.ParseInt(xtv, 10, 64) - if err != nil { - return err - } - sv.PackedPolicySize = ptr.Int32(int32(i64)) - } - - case strings.EqualFold("Provider", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Provider = ptr.String(xtv) - } - - case strings.EqualFold("SourceIdentity", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.SourceIdentity = ptr.String(xtv) - } - - case strings.EqualFold("SubjectFromWebIdentityToken", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.SubjectFromWebIdentityToken = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeOpDocumentDecodeAuthorizationMessageOutput(v **DecodeAuthorizationMessageOutput, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *DecodeAuthorizationMessageOutput - if *v == nil { - sv = &DecodeAuthorizationMessageOutput{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("DecodedMessage", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.DecodedMessage = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeOpDocumentGetAccessKeyInfoOutput(v **GetAccessKeyInfoOutput, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *GetAccessKeyInfoOutput - if *v == nil { - sv = &GetAccessKeyInfoOutput{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("Account", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Account = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeOpDocumentGetCallerIdentityOutput(v **GetCallerIdentityOutput, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *GetCallerIdentityOutput - if *v == nil { - sv = &GetCallerIdentityOutput{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("Account", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Account = ptr.String(xtv) - } - - case strings.EqualFold("Arn", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Arn = ptr.String(xtv) - } - - case strings.EqualFold("UserId", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.UserId = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeOpDocumentGetFederationTokenOutput(v **GetFederationTokenOutput, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *GetFederationTokenOutput - if *v == nil { - sv = &GetFederationTokenOutput{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("Credentials", t.Name.Local): - nodeDecoder := smithyxml.WrapNodeDecoder(decoder.Decoder, t) - if err := awsAwsquery_deserializeDocumentCredentials(&sv.Credentials, nodeDecoder); err != nil { - return err - } - - case strings.EqualFold("FederatedUser", t.Name.Local): - nodeDecoder := smithyxml.WrapNodeDecoder(decoder.Decoder, t) - if err := awsAwsquery_deserializeDocumentFederatedUser(&sv.FederatedUser, nodeDecoder); err != nil { - return err - } - - case strings.EqualFold("PackedPolicySize", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - i64, err := strconv.ParseInt(xtv, 10, 64) - if err != nil { - return err - } - sv.PackedPolicySize = ptr.Int32(int32(i64)) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeOpDocumentGetSessionTokenOutput(v **GetSessionTokenOutput, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *GetSessionTokenOutput - if *v == nil { - sv = &GetSessionTokenOutput{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("Credentials", t.Name.Local): - nodeDecoder := smithyxml.WrapNodeDecoder(decoder.Decoder, t) - if err := awsAwsquery_deserializeDocumentCredentials(&sv.Credentials, nodeDecoder); err != nil { - return err - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/doc.go deleted file mode 100644 index d963fd8d1..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/doc.go +++ /dev/null @@ -1,11 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -// Package sts provides the API client, operations, and parameter types for AWS -// Security Token Service. -// -// Security Token Service Security Token Service (STS) enables you to request -// temporary, limited-privilege credentials for users. This guide provides -// descriptions of the STS API. For more information about using this service, see -// Temporary Security Credentials (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html) -// . -package sts diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/endpoints.go deleted file mode 100644 index ef1caae8d..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/endpoints.go +++ /dev/null @@ -1,976 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -import ( - "context" - "errors" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn" - internalendpoints "github.com/aws/aws-sdk-go-v2/service/sts/internal/endpoints" - smithy "github.com/aws/smithy-go" - smithyendpoints "github.com/aws/smithy-go/endpoints" - "github.com/aws/smithy-go/middleware" - "github.com/aws/smithy-go/ptr" - smithyhttp "github.com/aws/smithy-go/transport/http" - "net/http" - "net/url" - "strings" -) - -// EndpointResolverOptions is the service endpoint resolver options -type EndpointResolverOptions = internalendpoints.Options - -// EndpointResolver interface for resolving service endpoints. -type EndpointResolver interface { - ResolveEndpoint(region string, options EndpointResolverOptions) (aws.Endpoint, error) -} - -var _ EndpointResolver = &internalendpoints.Resolver{} - -// NewDefaultEndpointResolver constructs a new service endpoint resolver -func NewDefaultEndpointResolver() *internalendpoints.Resolver { - return internalendpoints.New() -} - -// EndpointResolverFunc is a helper utility that wraps a function so it satisfies -// the EndpointResolver interface. This is useful when you want to add additional -// endpoint resolving logic, or stub out specific endpoints with custom values. -type EndpointResolverFunc func(region string, options EndpointResolverOptions) (aws.Endpoint, error) - -func (fn EndpointResolverFunc) ResolveEndpoint(region string, options EndpointResolverOptions) (endpoint aws.Endpoint, err error) { - return fn(region, options) -} - -// EndpointResolverFromURL returns an EndpointResolver configured using the -// provided endpoint url. By default, the resolved endpoint resolver uses the -// client region as signing region, and the endpoint source is set to -// EndpointSourceCustom.You can provide functional options to configure endpoint -// values for the resolved endpoint. -func EndpointResolverFromURL(url string, optFns ...func(*aws.Endpoint)) EndpointResolver { - e := aws.Endpoint{URL: url, Source: aws.EndpointSourceCustom} - for _, fn := range optFns { - fn(&e) - } - - return EndpointResolverFunc( - func(region string, options EndpointResolverOptions) (aws.Endpoint, error) { - if len(e.SigningRegion) == 0 { - e.SigningRegion = region - } - return e, nil - }, - ) -} - -type ResolveEndpoint struct { - Resolver EndpointResolver - Options EndpointResolverOptions -} - -func (*ResolveEndpoint) ID() string { - return "ResolveEndpoint" -} - -func (m *ResolveEndpoint) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if !awsmiddleware.GetRequiresLegacyEndpoints(ctx) { - return next.HandleSerialize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - if m.Resolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - eo := m.Options - eo.Logger = middleware.GetLogger(ctx) - - var endpoint aws.Endpoint - endpoint, err = m.Resolver.ResolveEndpoint(awsmiddleware.GetRegion(ctx), eo) - if err != nil { - nf := (&aws.EndpointNotFoundError{}) - if errors.As(err, &nf) { - ctx = awsmiddleware.SetRequiresLegacyEndpoints(ctx, false) - return next.HandleSerialize(ctx, in) - } - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL, err = url.Parse(endpoint.URL) - if err != nil { - return out, metadata, fmt.Errorf("failed to parse endpoint URL: %w", err) - } - - if len(awsmiddleware.GetSigningName(ctx)) == 0 { - signingName := endpoint.SigningName - if len(signingName) == 0 { - signingName = "sts" - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - } - ctx = awsmiddleware.SetEndpointSource(ctx, endpoint.Source) - ctx = smithyhttp.SetHostnameImmutable(ctx, endpoint.HostnameImmutable) - ctx = awsmiddleware.SetSigningRegion(ctx, endpoint.SigningRegion) - ctx = awsmiddleware.SetPartitionID(ctx, endpoint.PartitionID) - return next.HandleSerialize(ctx, in) -} -func addResolveEndpointMiddleware(stack *middleware.Stack, o Options) error { - return stack.Serialize.Insert(&ResolveEndpoint{ - Resolver: o.EndpointResolver, - Options: o.EndpointOptions, - }, "OperationSerializer", middleware.Before) -} - -func removeResolveEndpointMiddleware(stack *middleware.Stack) error { - _, err := stack.Serialize.Remove((&ResolveEndpoint{}).ID()) - return err -} - -type wrappedEndpointResolver struct { - awsResolver aws.EndpointResolverWithOptions -} - -func (w *wrappedEndpointResolver) ResolveEndpoint(region string, options EndpointResolverOptions) (endpoint aws.Endpoint, err error) { - return w.awsResolver.ResolveEndpoint(ServiceID, region, options) -} - -type awsEndpointResolverAdaptor func(service, region string) (aws.Endpoint, error) - -func (a awsEndpointResolverAdaptor) ResolveEndpoint(service, region string, options ...interface{}) (aws.Endpoint, error) { - return a(service, region) -} - -var _ aws.EndpointResolverWithOptions = awsEndpointResolverAdaptor(nil) - -// withEndpointResolver returns an aws.EndpointResolverWithOptions that first delegates endpoint resolution to the awsResolver. -// If awsResolver returns aws.EndpointNotFoundError error, the v1 resolver middleware will swallow the error, -// and set an appropriate context flag such that fallback will occur when EndpointResolverV2 is invoked -// via its middleware. -// -// If another error (besides aws.EndpointNotFoundError) is returned, then that error will be propagated. -func withEndpointResolver(awsResolver aws.EndpointResolver, awsResolverWithOptions aws.EndpointResolverWithOptions) EndpointResolver { - var resolver aws.EndpointResolverWithOptions - - if awsResolverWithOptions != nil { - resolver = awsResolverWithOptions - } else if awsResolver != nil { - resolver = awsEndpointResolverAdaptor(awsResolver.ResolveEndpoint) - } - - return &wrappedEndpointResolver{ - awsResolver: resolver, - } -} - -func finalizeClientEndpointResolverOptions(options *Options) { - options.EndpointOptions.LogDeprecated = options.ClientLogMode.IsDeprecatedUsage() - - if len(options.EndpointOptions.ResolvedRegion) == 0 { - const fipsInfix = "-fips-" - const fipsPrefix = "fips-" - const fipsSuffix = "-fips" - - if strings.Contains(options.Region, fipsInfix) || - strings.Contains(options.Region, fipsPrefix) || - strings.Contains(options.Region, fipsSuffix) { - options.EndpointOptions.ResolvedRegion = strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll( - options.Region, fipsInfix, "-"), fipsPrefix, ""), fipsSuffix, "") - options.EndpointOptions.UseFIPSEndpoint = aws.FIPSEndpointStateEnabled - } - } - -} - -func resolveEndpointResolverV2(options *Options) { - if options.EndpointResolverV2 == nil { - options.EndpointResolverV2 = NewDefaultEndpointResolverV2() - } -} - -// Utility function to aid with translating pseudo-regions to classical regions -// with the appropriate setting indicated by the pseudo-region -func mapPseudoRegion(pr string) (region string, fips aws.FIPSEndpointState) { - const fipsInfix = "-fips-" - const fipsPrefix = "fips-" - const fipsSuffix = "-fips" - - if strings.Contains(pr, fipsInfix) || - strings.Contains(pr, fipsPrefix) || - strings.Contains(pr, fipsSuffix) { - region = strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll( - pr, fipsInfix, "-"), fipsPrefix, ""), fipsSuffix, "") - fips = aws.FIPSEndpointStateEnabled - } else { - region = pr - } - - return region, fips -} - -// builtInParameterResolver is the interface responsible for resolving BuiltIn -// values during the sourcing of EndpointParameters -type builtInParameterResolver interface { - ResolveBuiltIns(*EndpointParameters) error -} - -// builtInResolver resolves modeled BuiltIn values using only the members defined -// below. -type builtInResolver struct { - // The AWS region used to dispatch the request. - Region string - - // Sourced BuiltIn value in a historical enabled or disabled state. - UseDualStack aws.DualStackEndpointState - - // Sourced BuiltIn value in a historical enabled or disabled state. - UseFIPS aws.FIPSEndpointState - - // Base endpoint that can potentially be modified during Endpoint resolution. - Endpoint *string - - // Whether the global endpoint should be used, rather then the regional endpoint - // for us-east-1. - UseGlobalEndpoint bool -} - -// Invoked at runtime to resolve BuiltIn Values. Only resolution code specific to -// each BuiltIn value is generated. -func (b *builtInResolver) ResolveBuiltIns(params *EndpointParameters) error { - - region, _ := mapPseudoRegion(b.Region) - if len(region) == 0 { - return fmt.Errorf("Could not resolve AWS::Region") - } else { - params.Region = aws.String(region) - } - if b.UseDualStack == aws.DualStackEndpointStateEnabled { - params.UseDualStack = aws.Bool(true) - } else { - params.UseDualStack = aws.Bool(false) - } - if b.UseFIPS == aws.FIPSEndpointStateEnabled { - params.UseFIPS = aws.Bool(true) - } else { - params.UseFIPS = aws.Bool(false) - } - params.Endpoint = b.Endpoint - params.UseGlobalEndpoint = aws.Bool(b.UseGlobalEndpoint) - return nil -} - -// EndpointParameters provides the parameters that influence how endpoints are -// resolved. -type EndpointParameters struct { - // The AWS region used to dispatch the request. - // - // Parameter is - // required. - // - // AWS::Region - Region *string - - // When true, use the dual-stack endpoint. If the configured endpoint does not - // support dual-stack, dispatching the request MAY return an error. - // - // Defaults to - // false if no value is provided. - // - // AWS::UseDualStack - UseDualStack *bool - - // When true, send this request to the FIPS-compliant regional endpoint. If the - // configured endpoint does not have a FIPS compliant endpoint, dispatching the - // request will return an error. - // - // Defaults to false if no value is - // provided. - // - // AWS::UseFIPS - UseFIPS *bool - - // Override the endpoint used to send this request - // - // Parameter is - // required. - // - // SDK::Endpoint - Endpoint *string - - // Whether the global endpoint should be used, rather then the regional endpoint - // for us-east-1. - // - // Defaults to false if no value is - // provided. - // - // AWS::STS::UseGlobalEndpoint - UseGlobalEndpoint *bool -} - -// ValidateRequired validates required parameters are set. -func (p EndpointParameters) ValidateRequired() error { - if p.UseDualStack == nil { - return fmt.Errorf("parameter UseDualStack is required") - } - - if p.UseFIPS == nil { - return fmt.Errorf("parameter UseFIPS is required") - } - - if p.UseGlobalEndpoint == nil { - return fmt.Errorf("parameter UseGlobalEndpoint is required") - } - - return nil -} - -// WithDefaults returns a shallow copy of EndpointParameterswith default values -// applied to members where applicable. -func (p EndpointParameters) WithDefaults() EndpointParameters { - if p.UseDualStack == nil { - p.UseDualStack = ptr.Bool(false) - } - - if p.UseFIPS == nil { - p.UseFIPS = ptr.Bool(false) - } - - if p.UseGlobalEndpoint == nil { - p.UseGlobalEndpoint = ptr.Bool(false) - } - return p -} - -// EndpointResolverV2 provides the interface for resolving service endpoints. -type EndpointResolverV2 interface { - // ResolveEndpoint attempts to resolve the endpoint with the provided options, - // returning the endpoint if found. Otherwise an error is returned. - ResolveEndpoint(ctx context.Context, params EndpointParameters) ( - smithyendpoints.Endpoint, error, - ) -} - -// resolver provides the implementation for resolving endpoints. -type resolver struct{} - -func NewDefaultEndpointResolverV2() EndpointResolverV2 { - return &resolver{} -} - -// ResolveEndpoint attempts to resolve the endpoint with the provided options, -// returning the endpoint if found. Otherwise an error is returned. -func (r *resolver) ResolveEndpoint( - ctx context.Context, params EndpointParameters, -) ( - endpoint smithyendpoints.Endpoint, err error, -) { - params = params.WithDefaults() - if err = params.ValidateRequired(); err != nil { - return endpoint, fmt.Errorf("endpoint parameters are not valid, %w", err) - } - _UseDualStack := *params.UseDualStack - _UseFIPS := *params.UseFIPS - _UseGlobalEndpoint := *params.UseGlobalEndpoint - - if _UseGlobalEndpoint == true { - if !(params.Endpoint != nil) { - if exprVal := params.Region; exprVal != nil { - _Region := *exprVal - _ = _Region - if exprVal := awsrulesfn.GetPartition(_Region); exprVal != nil { - _PartitionResult := *exprVal - _ = _PartitionResult - if _UseFIPS == false { - if _UseDualStack == false { - if _Region == "ap-northeast-1" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - out.Set("authSchemes", []interface{}{ - map[string]interface{}{ - "name": "sigv4", - "signingName": "sts", - "signingRegion": "us-east-1", - }, - }) - return out - }(), - }, nil - } - if _Region == "ap-south-1" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - out.Set("authSchemes", []interface{}{ - map[string]interface{}{ - "name": "sigv4", - "signingName": "sts", - "signingRegion": "us-east-1", - }, - }) - return out - }(), - }, nil - } - if _Region == "ap-southeast-1" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - out.Set("authSchemes", []interface{}{ - map[string]interface{}{ - "name": "sigv4", - "signingName": "sts", - "signingRegion": "us-east-1", - }, - }) - return out - }(), - }, nil - } - if _Region == "ap-southeast-2" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - out.Set("authSchemes", []interface{}{ - map[string]interface{}{ - "name": "sigv4", - "signingName": "sts", - "signingRegion": "us-east-1", - }, - }) - return out - }(), - }, nil - } - if _Region == "aws-global" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - out.Set("authSchemes", []interface{}{ - map[string]interface{}{ - "name": "sigv4", - "signingName": "sts", - "signingRegion": "us-east-1", - }, - }) - return out - }(), - }, nil - } - if _Region == "ca-central-1" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - out.Set("authSchemes", []interface{}{ - map[string]interface{}{ - "name": "sigv4", - "signingName": "sts", - "signingRegion": "us-east-1", - }, - }) - return out - }(), - }, nil - } - if _Region == "eu-central-1" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - out.Set("authSchemes", []interface{}{ - map[string]interface{}{ - "name": "sigv4", - "signingName": "sts", - "signingRegion": "us-east-1", - }, - }) - return out - }(), - }, nil - } - if _Region == "eu-north-1" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - out.Set("authSchemes", []interface{}{ - map[string]interface{}{ - "name": "sigv4", - "signingName": "sts", - "signingRegion": "us-east-1", - }, - }) - return out - }(), - }, nil - } - if _Region == "eu-west-1" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - out.Set("authSchemes", []interface{}{ - map[string]interface{}{ - "name": "sigv4", - "signingName": "sts", - "signingRegion": "us-east-1", - }, - }) - return out - }(), - }, nil - } - if _Region == "eu-west-2" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - out.Set("authSchemes", []interface{}{ - map[string]interface{}{ - "name": "sigv4", - "signingName": "sts", - "signingRegion": "us-east-1", - }, - }) - return out - }(), - }, nil - } - if _Region == "eu-west-3" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - out.Set("authSchemes", []interface{}{ - map[string]interface{}{ - "name": "sigv4", - "signingName": "sts", - "signingRegion": "us-east-1", - }, - }) - return out - }(), - }, nil - } - if _Region == "sa-east-1" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - out.Set("authSchemes", []interface{}{ - map[string]interface{}{ - "name": "sigv4", - "signingName": "sts", - "signingRegion": "us-east-1", - }, - }) - return out - }(), - }, nil - } - if _Region == "us-east-1" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - out.Set("authSchemes", []interface{}{ - map[string]interface{}{ - "name": "sigv4", - "signingName": "sts", - "signingRegion": "us-east-1", - }, - }) - return out - }(), - }, nil - } - if _Region == "us-east-2" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - out.Set("authSchemes", []interface{}{ - map[string]interface{}{ - "name": "sigv4", - "signingName": "sts", - "signingRegion": "us-east-1", - }, - }) - return out - }(), - }, nil - } - if _Region == "us-west-1" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - out.Set("authSchemes", []interface{}{ - map[string]interface{}{ - "name": "sigv4", - "signingName": "sts", - "signingRegion": "us-east-1", - }, - }) - return out - }(), - }, nil - } - if _Region == "us-west-2" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - out.Set("authSchemes", []interface{}{ - map[string]interface{}{ - "name": "sigv4", - "signingName": "sts", - "signingRegion": "us-east-1", - }, - }) - return out - }(), - }, nil - } - uriString := func() string { - var out strings.Builder - out.WriteString("https://sts.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - out.Set("authSchemes", []interface{}{ - map[string]interface{}{ - "name": "sigv4", - "signingName": "sts", - "signingRegion": _Region, - }, - }) - return out - }(), - }, nil - } - } - } - } - } - } - if exprVal := params.Endpoint; exprVal != nil { - _Endpoint := *exprVal - _ = _Endpoint - if _UseFIPS == true { - return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: FIPS and custom endpoint are not supported") - } - if _UseDualStack == true { - return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: Dualstack and custom endpoint are not supported") - } - uriString := _Endpoint - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if exprVal := params.Region; exprVal != nil { - _Region := *exprVal - _ = _Region - if exprVal := awsrulesfn.GetPartition(_Region); exprVal != nil { - _PartitionResult := *exprVal - _ = _PartitionResult - if _UseFIPS == true { - if _UseDualStack == true { - if true == _PartitionResult.SupportsFIPS { - if true == _PartitionResult.SupportsDualStack { - uriString := func() string { - var out strings.Builder - out.WriteString("https://sts-fips.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DualStackDnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "FIPS and DualStack are enabled, but this partition does not support one or both") - } - } - if _UseFIPS == true { - if true == _PartitionResult.SupportsFIPS { - if "aws-us-gov" == _PartitionResult.Name { - uriString := func() string { - var out strings.Builder - out.WriteString("https://sts.") - out.WriteString(_Region) - out.WriteString(".amazonaws.com") - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - uriString := func() string { - var out strings.Builder - out.WriteString("https://sts-fips.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "FIPS is enabled but this partition does not support FIPS") - } - if _UseDualStack == true { - if true == _PartitionResult.SupportsDualStack { - uriString := func() string { - var out strings.Builder - out.WriteString("https://sts.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DualStackDnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "DualStack is enabled but this partition does not support DualStack") - } - if _Region == "aws-global" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - out.Set("authSchemes", []interface{}{ - map[string]interface{}{ - "name": "sigv4", - "signingName": "sts", - "signingRegion": "us-east-1", - }, - }) - return out - }(), - }, nil - } - uriString := func() string { - var out strings.Builder - out.WriteString("https://sts.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - return endpoint, fmt.Errorf("Endpoint resolution failed. Invalid operation or environment input.") - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: Missing Region") -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/generated.json b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/generated.json deleted file mode 100644 index 2ae7a9b23..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/generated.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "dependencies": { - "github.com/aws/aws-sdk-go-v2": "v1.4.0", - "github.com/aws/aws-sdk-go-v2/internal/configsources": "v0.0.0-00010101000000-000000000000", - "github.com/aws/aws-sdk-go-v2/internal/endpoints/v2": "v2.0.0-00010101000000-000000000000", - "github.com/aws/aws-sdk-go-v2/service/internal/presigned-url": "v1.0.7", - "github.com/aws/smithy-go": "v1.4.0", - "github.com/google/go-cmp": "v0.5.4" - }, - "files": [ - "api_client.go", - "api_client_test.go", - "api_op_AssumeRole.go", - "api_op_AssumeRoleWithSAML.go", - "api_op_AssumeRoleWithWebIdentity.go", - "api_op_DecodeAuthorizationMessage.go", - "api_op_GetAccessKeyInfo.go", - "api_op_GetCallerIdentity.go", - "api_op_GetFederationToken.go", - "api_op_GetSessionToken.go", - "deserializers.go", - "doc.go", - "endpoints.go", - "endpoints_test.go", - "generated.json", - "internal/endpoints/endpoints.go", - "internal/endpoints/endpoints_test.go", - "protocol_test.go", - "serializers.go", - "types/errors.go", - "types/types.go", - "validators.go" - ], - "go": "1.15", - "module": "github.com/aws/aws-sdk-go-v2/service/sts", - "unstable": false -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/go_module_metadata.go deleted file mode 100644 index f0a57a675..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/go_module_metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. - -package sts - -// goModuleVersion is the tagged release for this module -const goModuleVersion = "1.21.5" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/internal/endpoints/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/internal/endpoints/endpoints.go deleted file mode 100644 index ca4c88190..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/internal/endpoints/endpoints.go +++ /dev/null @@ -1,509 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package endpoints - -import ( - "github.com/aws/aws-sdk-go-v2/aws" - endpoints "github.com/aws/aws-sdk-go-v2/internal/endpoints/v2" - "github.com/aws/smithy-go/logging" - "regexp" -) - -// Options is the endpoint resolver configuration options -type Options struct { - // Logger is a logging implementation that log events should be sent to. - Logger logging.Logger - - // LogDeprecated indicates that deprecated endpoints should be logged to the - // provided logger. - LogDeprecated bool - - // ResolvedRegion is used to override the region to be resolved, rather then the - // using the value passed to the ResolveEndpoint method. This value is used by the - // SDK to translate regions like fips-us-east-1 or us-east-1-fips to an alternative - // name. You must not set this value directly in your application. - ResolvedRegion string - - // DisableHTTPS informs the resolver to return an endpoint that does not use the - // HTTPS scheme. - DisableHTTPS bool - - // UseDualStackEndpoint specifies the resolver must resolve a dual-stack endpoint. - UseDualStackEndpoint aws.DualStackEndpointState - - // UseFIPSEndpoint specifies the resolver must resolve a FIPS endpoint. - UseFIPSEndpoint aws.FIPSEndpointState -} - -func (o Options) GetResolvedRegion() string { - return o.ResolvedRegion -} - -func (o Options) GetDisableHTTPS() bool { - return o.DisableHTTPS -} - -func (o Options) GetUseDualStackEndpoint() aws.DualStackEndpointState { - return o.UseDualStackEndpoint -} - -func (o Options) GetUseFIPSEndpoint() aws.FIPSEndpointState { - return o.UseFIPSEndpoint -} - -func transformToSharedOptions(options Options) endpoints.Options { - return endpoints.Options{ - Logger: options.Logger, - LogDeprecated: options.LogDeprecated, - ResolvedRegion: options.ResolvedRegion, - DisableHTTPS: options.DisableHTTPS, - UseDualStackEndpoint: options.UseDualStackEndpoint, - UseFIPSEndpoint: options.UseFIPSEndpoint, - } -} - -// Resolver STS endpoint resolver -type Resolver struct { - partitions endpoints.Partitions -} - -// ResolveEndpoint resolves the service endpoint for the given region and options -func (r *Resolver) ResolveEndpoint(region string, options Options) (endpoint aws.Endpoint, err error) { - if len(region) == 0 { - return endpoint, &aws.MissingRegionError{} - } - - opt := transformToSharedOptions(options) - return r.partitions.ResolveEndpoint(region, opt) -} - -// New returns a new Resolver -func New() *Resolver { - return &Resolver{ - partitions: defaultPartitions, - } -} - -var partitionRegexp = struct { - Aws *regexp.Regexp - AwsCn *regexp.Regexp - AwsIso *regexp.Regexp - AwsIsoB *regexp.Regexp - AwsIsoE *regexp.Regexp - AwsIsoF *regexp.Regexp - AwsUsGov *regexp.Regexp -}{ - - Aws: regexp.MustCompile("^(us|eu|ap|sa|ca|me|af|il)\\-\\w+\\-\\d+$"), - AwsCn: regexp.MustCompile("^cn\\-\\w+\\-\\d+$"), - AwsIso: regexp.MustCompile("^us\\-iso\\-\\w+\\-\\d+$"), - AwsIsoB: regexp.MustCompile("^us\\-isob\\-\\w+\\-\\d+$"), - AwsIsoE: regexp.MustCompile("^eu\\-isoe\\-\\w+\\-\\d+$"), - AwsIsoF: regexp.MustCompile("^us\\-isof\\-\\w+\\-\\d+$"), - AwsUsGov: regexp.MustCompile("^us\\-gov\\-\\w+\\-\\d+$"), -} - -var defaultPartitions = endpoints.Partitions{ - { - ID: "aws", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.DualStackVariant, - }: { - Hostname: "sts.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "sts-fips.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: { - Hostname: "sts-fips.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "sts.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.Aws, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "af-south-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-east-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-northeast-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-northeast-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-northeast-3", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-south-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-south-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-southeast-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-southeast-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-southeast-3", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-southeast-4", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "aws-global", - }: endpoints.Endpoint{ - Hostname: "sts.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-east-1", - }, - }, - endpoints.EndpointKey{ - Region: "ca-central-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-central-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-central-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-north-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-south-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-south-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-west-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-west-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-west-3", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "il-central-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "me-central-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "me-south-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "sa-east-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-east-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-east-1", - Variant: endpoints.FIPSVariant, - }: { - Hostname: "sts-fips.us-east-1.amazonaws.com", - }, - endpoints.EndpointKey{ - Region: "us-east-1-fips", - }: endpoints.Endpoint{ - Hostname: "sts-fips.us-east-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-east-1", - }, - Deprecated: aws.TrueTernary, - }, - endpoints.EndpointKey{ - Region: "us-east-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-east-2", - Variant: endpoints.FIPSVariant, - }: { - Hostname: "sts-fips.us-east-2.amazonaws.com", - }, - endpoints.EndpointKey{ - Region: "us-east-2-fips", - }: endpoints.Endpoint{ - Hostname: "sts-fips.us-east-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-east-2", - }, - Deprecated: aws.TrueTernary, - }, - endpoints.EndpointKey{ - Region: "us-west-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-west-1", - Variant: endpoints.FIPSVariant, - }: { - Hostname: "sts-fips.us-west-1.amazonaws.com", - }, - endpoints.EndpointKey{ - Region: "us-west-1-fips", - }: endpoints.Endpoint{ - Hostname: "sts-fips.us-west-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-west-1", - }, - Deprecated: aws.TrueTernary, - }, - endpoints.EndpointKey{ - Region: "us-west-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-west-2", - Variant: endpoints.FIPSVariant, - }: { - Hostname: "sts-fips.us-west-2.amazonaws.com", - }, - endpoints.EndpointKey{ - Region: "us-west-2-fips", - }: endpoints.Endpoint{ - Hostname: "sts-fips.us-west-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-west-2", - }, - Deprecated: aws.TrueTernary, - }, - }, - }, - { - ID: "aws-cn", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.DualStackVariant, - }: { - Hostname: "sts.{region}.api.amazonwebservices.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "sts-fips.{region}.amazonaws.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: { - Hostname: "sts-fips.{region}.api.amazonwebservices.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "sts.{region}.amazonaws.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsCn, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "cn-north-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "cn-northwest-1", - }: endpoints.Endpoint{}, - }, - }, - { - ID: "aws-iso", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "sts-fips.{region}.c2s.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "sts.{region}.c2s.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIso, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "us-iso-east-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-iso-west-1", - }: endpoints.Endpoint{}, - }, - }, - { - ID: "aws-iso-b", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "sts-fips.{region}.sc2s.sgov.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "sts.{region}.sc2s.sgov.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIsoB, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "us-isob-east-1", - }: endpoints.Endpoint{}, - }, - }, - { - ID: "aws-iso-e", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "sts-fips.{region}.cloud.adc-e.uk", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "sts.{region}.cloud.adc-e.uk", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIsoE, - IsRegionalized: true, - }, - { - ID: "aws-iso-f", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "sts-fips.{region}.csp.hci.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "sts.{region}.csp.hci.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIsoF, - IsRegionalized: true, - }, - { - ID: "aws-us-gov", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.DualStackVariant, - }: { - Hostname: "sts.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "sts.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: { - Hostname: "sts-fips.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "sts.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsUsGov, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "us-gov-east-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-gov-east-1", - Variant: endpoints.FIPSVariant, - }: { - Hostname: "sts.us-gov-east-1.amazonaws.com", - }, - endpoints.EndpointKey{ - Region: "us-gov-east-1-fips", - }: endpoints.Endpoint{ - Hostname: "sts.us-gov-east-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: aws.TrueTernary, - }, - endpoints.EndpointKey{ - Region: "us-gov-west-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-gov-west-1", - Variant: endpoints.FIPSVariant, - }: { - Hostname: "sts.us-gov-west-1.amazonaws.com", - }, - endpoints.EndpointKey{ - Region: "us-gov-west-1-fips", - }: endpoints.Endpoint{ - Hostname: "sts.us-gov-west-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: aws.TrueTernary, - }, - }, - }, -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/serializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/serializers.go deleted file mode 100644 index 4c08061c0..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/serializers.go +++ /dev/null @@ -1,862 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -import ( - "bytes" - "context" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws/protocol/query" - "github.com/aws/aws-sdk-go-v2/service/sts/types" - smithy "github.com/aws/smithy-go" - "github.com/aws/smithy-go/encoding/httpbinding" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" - "path" -) - -type awsAwsquery_serializeOpAssumeRole struct { -} - -func (*awsAwsquery_serializeOpAssumeRole) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsquery_serializeOpAssumeRole) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - request, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} - } - - input, ok := in.Parameters.(*AssumeRoleInput) - _ = input - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} - } - - operationPath := "/" - if len(request.Request.URL.Path) == 0 { - request.Request.URL.Path = operationPath - } else { - request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) - if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { - request.Request.URL.Path += "/" - } - } - request.Request.Method = "POST" - httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - httpBindingEncoder.SetHeader("Content-Type").String("application/x-www-form-urlencoded") - - bodyWriter := bytes.NewBuffer(nil) - bodyEncoder := query.NewEncoder(bodyWriter) - body := bodyEncoder.Object() - body.Key("Action").String("AssumeRole") - body.Key("Version").String("2011-06-15") - - if err := awsAwsquery_serializeOpDocumentAssumeRoleInput(input, bodyEncoder.Value); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - err = bodyEncoder.Encode() - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request, err = request.SetStream(bytes.NewReader(bodyWriter.Bytes())); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - in.Request = request - - return next.HandleSerialize(ctx, in) -} - -type awsAwsquery_serializeOpAssumeRoleWithSAML struct { -} - -func (*awsAwsquery_serializeOpAssumeRoleWithSAML) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsquery_serializeOpAssumeRoleWithSAML) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - request, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} - } - - input, ok := in.Parameters.(*AssumeRoleWithSAMLInput) - _ = input - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} - } - - operationPath := "/" - if len(request.Request.URL.Path) == 0 { - request.Request.URL.Path = operationPath - } else { - request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) - if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { - request.Request.URL.Path += "/" - } - } - request.Request.Method = "POST" - httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - httpBindingEncoder.SetHeader("Content-Type").String("application/x-www-form-urlencoded") - - bodyWriter := bytes.NewBuffer(nil) - bodyEncoder := query.NewEncoder(bodyWriter) - body := bodyEncoder.Object() - body.Key("Action").String("AssumeRoleWithSAML") - body.Key("Version").String("2011-06-15") - - if err := awsAwsquery_serializeOpDocumentAssumeRoleWithSAMLInput(input, bodyEncoder.Value); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - err = bodyEncoder.Encode() - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request, err = request.SetStream(bytes.NewReader(bodyWriter.Bytes())); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - in.Request = request - - return next.HandleSerialize(ctx, in) -} - -type awsAwsquery_serializeOpAssumeRoleWithWebIdentity struct { -} - -func (*awsAwsquery_serializeOpAssumeRoleWithWebIdentity) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsquery_serializeOpAssumeRoleWithWebIdentity) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - request, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} - } - - input, ok := in.Parameters.(*AssumeRoleWithWebIdentityInput) - _ = input - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} - } - - operationPath := "/" - if len(request.Request.URL.Path) == 0 { - request.Request.URL.Path = operationPath - } else { - request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) - if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { - request.Request.URL.Path += "/" - } - } - request.Request.Method = "POST" - httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - httpBindingEncoder.SetHeader("Content-Type").String("application/x-www-form-urlencoded") - - bodyWriter := bytes.NewBuffer(nil) - bodyEncoder := query.NewEncoder(bodyWriter) - body := bodyEncoder.Object() - body.Key("Action").String("AssumeRoleWithWebIdentity") - body.Key("Version").String("2011-06-15") - - if err := awsAwsquery_serializeOpDocumentAssumeRoleWithWebIdentityInput(input, bodyEncoder.Value); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - err = bodyEncoder.Encode() - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request, err = request.SetStream(bytes.NewReader(bodyWriter.Bytes())); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - in.Request = request - - return next.HandleSerialize(ctx, in) -} - -type awsAwsquery_serializeOpDecodeAuthorizationMessage struct { -} - -func (*awsAwsquery_serializeOpDecodeAuthorizationMessage) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsquery_serializeOpDecodeAuthorizationMessage) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - request, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} - } - - input, ok := in.Parameters.(*DecodeAuthorizationMessageInput) - _ = input - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} - } - - operationPath := "/" - if len(request.Request.URL.Path) == 0 { - request.Request.URL.Path = operationPath - } else { - request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) - if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { - request.Request.URL.Path += "/" - } - } - request.Request.Method = "POST" - httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - httpBindingEncoder.SetHeader("Content-Type").String("application/x-www-form-urlencoded") - - bodyWriter := bytes.NewBuffer(nil) - bodyEncoder := query.NewEncoder(bodyWriter) - body := bodyEncoder.Object() - body.Key("Action").String("DecodeAuthorizationMessage") - body.Key("Version").String("2011-06-15") - - if err := awsAwsquery_serializeOpDocumentDecodeAuthorizationMessageInput(input, bodyEncoder.Value); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - err = bodyEncoder.Encode() - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request, err = request.SetStream(bytes.NewReader(bodyWriter.Bytes())); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - in.Request = request - - return next.HandleSerialize(ctx, in) -} - -type awsAwsquery_serializeOpGetAccessKeyInfo struct { -} - -func (*awsAwsquery_serializeOpGetAccessKeyInfo) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsquery_serializeOpGetAccessKeyInfo) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - request, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} - } - - input, ok := in.Parameters.(*GetAccessKeyInfoInput) - _ = input - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} - } - - operationPath := "/" - if len(request.Request.URL.Path) == 0 { - request.Request.URL.Path = operationPath - } else { - request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) - if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { - request.Request.URL.Path += "/" - } - } - request.Request.Method = "POST" - httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - httpBindingEncoder.SetHeader("Content-Type").String("application/x-www-form-urlencoded") - - bodyWriter := bytes.NewBuffer(nil) - bodyEncoder := query.NewEncoder(bodyWriter) - body := bodyEncoder.Object() - body.Key("Action").String("GetAccessKeyInfo") - body.Key("Version").String("2011-06-15") - - if err := awsAwsquery_serializeOpDocumentGetAccessKeyInfoInput(input, bodyEncoder.Value); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - err = bodyEncoder.Encode() - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request, err = request.SetStream(bytes.NewReader(bodyWriter.Bytes())); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - in.Request = request - - return next.HandleSerialize(ctx, in) -} - -type awsAwsquery_serializeOpGetCallerIdentity struct { -} - -func (*awsAwsquery_serializeOpGetCallerIdentity) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsquery_serializeOpGetCallerIdentity) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - request, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} - } - - input, ok := in.Parameters.(*GetCallerIdentityInput) - _ = input - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} - } - - operationPath := "/" - if len(request.Request.URL.Path) == 0 { - request.Request.URL.Path = operationPath - } else { - request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) - if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { - request.Request.URL.Path += "/" - } - } - request.Request.Method = "POST" - httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - httpBindingEncoder.SetHeader("Content-Type").String("application/x-www-form-urlencoded") - - bodyWriter := bytes.NewBuffer(nil) - bodyEncoder := query.NewEncoder(bodyWriter) - body := bodyEncoder.Object() - body.Key("Action").String("GetCallerIdentity") - body.Key("Version").String("2011-06-15") - - err = bodyEncoder.Encode() - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request, err = request.SetStream(bytes.NewReader(bodyWriter.Bytes())); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - in.Request = request - - return next.HandleSerialize(ctx, in) -} - -type awsAwsquery_serializeOpGetFederationToken struct { -} - -func (*awsAwsquery_serializeOpGetFederationToken) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsquery_serializeOpGetFederationToken) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - request, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} - } - - input, ok := in.Parameters.(*GetFederationTokenInput) - _ = input - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} - } - - operationPath := "/" - if len(request.Request.URL.Path) == 0 { - request.Request.URL.Path = operationPath - } else { - request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) - if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { - request.Request.URL.Path += "/" - } - } - request.Request.Method = "POST" - httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - httpBindingEncoder.SetHeader("Content-Type").String("application/x-www-form-urlencoded") - - bodyWriter := bytes.NewBuffer(nil) - bodyEncoder := query.NewEncoder(bodyWriter) - body := bodyEncoder.Object() - body.Key("Action").String("GetFederationToken") - body.Key("Version").String("2011-06-15") - - if err := awsAwsquery_serializeOpDocumentGetFederationTokenInput(input, bodyEncoder.Value); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - err = bodyEncoder.Encode() - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request, err = request.SetStream(bytes.NewReader(bodyWriter.Bytes())); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - in.Request = request - - return next.HandleSerialize(ctx, in) -} - -type awsAwsquery_serializeOpGetSessionToken struct { -} - -func (*awsAwsquery_serializeOpGetSessionToken) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsquery_serializeOpGetSessionToken) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - request, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} - } - - input, ok := in.Parameters.(*GetSessionTokenInput) - _ = input - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} - } - - operationPath := "/" - if len(request.Request.URL.Path) == 0 { - request.Request.URL.Path = operationPath - } else { - request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) - if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { - request.Request.URL.Path += "/" - } - } - request.Request.Method = "POST" - httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - httpBindingEncoder.SetHeader("Content-Type").String("application/x-www-form-urlencoded") - - bodyWriter := bytes.NewBuffer(nil) - bodyEncoder := query.NewEncoder(bodyWriter) - body := bodyEncoder.Object() - body.Key("Action").String("GetSessionToken") - body.Key("Version").String("2011-06-15") - - if err := awsAwsquery_serializeOpDocumentGetSessionTokenInput(input, bodyEncoder.Value); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - err = bodyEncoder.Encode() - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request, err = request.SetStream(bytes.NewReader(bodyWriter.Bytes())); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - in.Request = request - - return next.HandleSerialize(ctx, in) -} -func awsAwsquery_serializeDocumentPolicyDescriptorListType(v []types.PolicyDescriptorType, value query.Value) error { - array := value.Array("member") - - for i := range v { - av := array.Value() - if err := awsAwsquery_serializeDocumentPolicyDescriptorType(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsquery_serializeDocumentPolicyDescriptorType(v *types.PolicyDescriptorType, value query.Value) error { - object := value.Object() - _ = object - - if v.Arn != nil { - objectKey := object.Key("arn") - objectKey.String(*v.Arn) - } - - return nil -} - -func awsAwsquery_serializeDocumentProvidedContext(v *types.ProvidedContext, value query.Value) error { - object := value.Object() - _ = object - - if v.ContextAssertion != nil { - objectKey := object.Key("ContextAssertion") - objectKey.String(*v.ContextAssertion) - } - - if v.ProviderArn != nil { - objectKey := object.Key("ProviderArn") - objectKey.String(*v.ProviderArn) - } - - return nil -} - -func awsAwsquery_serializeDocumentProvidedContextsListType(v []types.ProvidedContext, value query.Value) error { - array := value.Array("member") - - for i := range v { - av := array.Value() - if err := awsAwsquery_serializeDocumentProvidedContext(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsquery_serializeDocumentTag(v *types.Tag, value query.Value) error { - object := value.Object() - _ = object - - if v.Key != nil { - objectKey := object.Key("Key") - objectKey.String(*v.Key) - } - - if v.Value != nil { - objectKey := object.Key("Value") - objectKey.String(*v.Value) - } - - return nil -} - -func awsAwsquery_serializeDocumentTagKeyListType(v []string, value query.Value) error { - array := value.Array("member") - - for i := range v { - av := array.Value() - av.String(v[i]) - } - return nil -} - -func awsAwsquery_serializeDocumentTagListType(v []types.Tag, value query.Value) error { - array := value.Array("member") - - for i := range v { - av := array.Value() - if err := awsAwsquery_serializeDocumentTag(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsquery_serializeOpDocumentAssumeRoleInput(v *AssumeRoleInput, value query.Value) error { - object := value.Object() - _ = object - - if v.DurationSeconds != nil { - objectKey := object.Key("DurationSeconds") - objectKey.Integer(*v.DurationSeconds) - } - - if v.ExternalId != nil { - objectKey := object.Key("ExternalId") - objectKey.String(*v.ExternalId) - } - - if v.Policy != nil { - objectKey := object.Key("Policy") - objectKey.String(*v.Policy) - } - - if v.PolicyArns != nil { - objectKey := object.Key("PolicyArns") - if err := awsAwsquery_serializeDocumentPolicyDescriptorListType(v.PolicyArns, objectKey); err != nil { - return err - } - } - - if v.ProvidedContexts != nil { - objectKey := object.Key("ProvidedContexts") - if err := awsAwsquery_serializeDocumentProvidedContextsListType(v.ProvidedContexts, objectKey); err != nil { - return err - } - } - - if v.RoleArn != nil { - objectKey := object.Key("RoleArn") - objectKey.String(*v.RoleArn) - } - - if v.RoleSessionName != nil { - objectKey := object.Key("RoleSessionName") - objectKey.String(*v.RoleSessionName) - } - - if v.SerialNumber != nil { - objectKey := object.Key("SerialNumber") - objectKey.String(*v.SerialNumber) - } - - if v.SourceIdentity != nil { - objectKey := object.Key("SourceIdentity") - objectKey.String(*v.SourceIdentity) - } - - if v.Tags != nil { - objectKey := object.Key("Tags") - if err := awsAwsquery_serializeDocumentTagListType(v.Tags, objectKey); err != nil { - return err - } - } - - if v.TokenCode != nil { - objectKey := object.Key("TokenCode") - objectKey.String(*v.TokenCode) - } - - if v.TransitiveTagKeys != nil { - objectKey := object.Key("TransitiveTagKeys") - if err := awsAwsquery_serializeDocumentTagKeyListType(v.TransitiveTagKeys, objectKey); err != nil { - return err - } - } - - return nil -} - -func awsAwsquery_serializeOpDocumentAssumeRoleWithSAMLInput(v *AssumeRoleWithSAMLInput, value query.Value) error { - object := value.Object() - _ = object - - if v.DurationSeconds != nil { - objectKey := object.Key("DurationSeconds") - objectKey.Integer(*v.DurationSeconds) - } - - if v.Policy != nil { - objectKey := object.Key("Policy") - objectKey.String(*v.Policy) - } - - if v.PolicyArns != nil { - objectKey := object.Key("PolicyArns") - if err := awsAwsquery_serializeDocumentPolicyDescriptorListType(v.PolicyArns, objectKey); err != nil { - return err - } - } - - if v.PrincipalArn != nil { - objectKey := object.Key("PrincipalArn") - objectKey.String(*v.PrincipalArn) - } - - if v.RoleArn != nil { - objectKey := object.Key("RoleArn") - objectKey.String(*v.RoleArn) - } - - if v.SAMLAssertion != nil { - objectKey := object.Key("SAMLAssertion") - objectKey.String(*v.SAMLAssertion) - } - - return nil -} - -func awsAwsquery_serializeOpDocumentAssumeRoleWithWebIdentityInput(v *AssumeRoleWithWebIdentityInput, value query.Value) error { - object := value.Object() - _ = object - - if v.DurationSeconds != nil { - objectKey := object.Key("DurationSeconds") - objectKey.Integer(*v.DurationSeconds) - } - - if v.Policy != nil { - objectKey := object.Key("Policy") - objectKey.String(*v.Policy) - } - - if v.PolicyArns != nil { - objectKey := object.Key("PolicyArns") - if err := awsAwsquery_serializeDocumentPolicyDescriptorListType(v.PolicyArns, objectKey); err != nil { - return err - } - } - - if v.ProviderId != nil { - objectKey := object.Key("ProviderId") - objectKey.String(*v.ProviderId) - } - - if v.RoleArn != nil { - objectKey := object.Key("RoleArn") - objectKey.String(*v.RoleArn) - } - - if v.RoleSessionName != nil { - objectKey := object.Key("RoleSessionName") - objectKey.String(*v.RoleSessionName) - } - - if v.WebIdentityToken != nil { - objectKey := object.Key("WebIdentityToken") - objectKey.String(*v.WebIdentityToken) - } - - return nil -} - -func awsAwsquery_serializeOpDocumentDecodeAuthorizationMessageInput(v *DecodeAuthorizationMessageInput, value query.Value) error { - object := value.Object() - _ = object - - if v.EncodedMessage != nil { - objectKey := object.Key("EncodedMessage") - objectKey.String(*v.EncodedMessage) - } - - return nil -} - -func awsAwsquery_serializeOpDocumentGetAccessKeyInfoInput(v *GetAccessKeyInfoInput, value query.Value) error { - object := value.Object() - _ = object - - if v.AccessKeyId != nil { - objectKey := object.Key("AccessKeyId") - objectKey.String(*v.AccessKeyId) - } - - return nil -} - -func awsAwsquery_serializeOpDocumentGetCallerIdentityInput(v *GetCallerIdentityInput, value query.Value) error { - object := value.Object() - _ = object - - return nil -} - -func awsAwsquery_serializeOpDocumentGetFederationTokenInput(v *GetFederationTokenInput, value query.Value) error { - object := value.Object() - _ = object - - if v.DurationSeconds != nil { - objectKey := object.Key("DurationSeconds") - objectKey.Integer(*v.DurationSeconds) - } - - if v.Name != nil { - objectKey := object.Key("Name") - objectKey.String(*v.Name) - } - - if v.Policy != nil { - objectKey := object.Key("Policy") - objectKey.String(*v.Policy) - } - - if v.PolicyArns != nil { - objectKey := object.Key("PolicyArns") - if err := awsAwsquery_serializeDocumentPolicyDescriptorListType(v.PolicyArns, objectKey); err != nil { - return err - } - } - - if v.Tags != nil { - objectKey := object.Key("Tags") - if err := awsAwsquery_serializeDocumentTagListType(v.Tags, objectKey); err != nil { - return err - } - } - - return nil -} - -func awsAwsquery_serializeOpDocumentGetSessionTokenInput(v *GetSessionTokenInput, value query.Value) error { - object := value.Object() - _ = object - - if v.DurationSeconds != nil { - objectKey := object.Key("DurationSeconds") - objectKey.Integer(*v.DurationSeconds) - } - - if v.SerialNumber != nil { - objectKey := object.Key("SerialNumber") - objectKey.String(*v.SerialNumber) - } - - if v.TokenCode != nil { - objectKey := object.Key("TokenCode") - objectKey.String(*v.TokenCode) - } - - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/types/errors.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/types/errors.go deleted file mode 100644 index 097875b27..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/types/errors.go +++ /dev/null @@ -1,244 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package types - -import ( - "fmt" - smithy "github.com/aws/smithy-go" -) - -// The web identity token that was passed is expired or is not valid. Get a new -// identity token from the identity provider and then retry the request. -type ExpiredTokenException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *ExpiredTokenException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ExpiredTokenException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ExpiredTokenException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ExpiredTokenException" - } - return *e.ErrorCodeOverride -} -func (e *ExpiredTokenException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The request could not be fulfilled because the identity provider (IDP) that was -// asked to verify the incoming identity token could not be reached. This is often -// a transient error caused by network conditions. Retry the request a limited -// number of times so that you don't exceed the request rate. If the error -// persists, the identity provider might be down or not responding. -type IDPCommunicationErrorException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *IDPCommunicationErrorException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *IDPCommunicationErrorException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *IDPCommunicationErrorException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "IDPCommunicationError" - } - return *e.ErrorCodeOverride -} -func (e *IDPCommunicationErrorException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The identity provider (IdP) reported that authentication failed. This might be -// because the claim is invalid. If this error is returned for the -// AssumeRoleWithWebIdentity operation, it can also mean that the claim has expired -// or has been explicitly revoked. -type IDPRejectedClaimException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *IDPRejectedClaimException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *IDPRejectedClaimException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *IDPRejectedClaimException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "IDPRejectedClaim" - } - return *e.ErrorCodeOverride -} -func (e *IDPRejectedClaimException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The error returned if the message passed to DecodeAuthorizationMessage was -// invalid. This can happen if the token contains invalid characters, such as -// linebreaks. -type InvalidAuthorizationMessageException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidAuthorizationMessageException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidAuthorizationMessageException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidAuthorizationMessageException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidAuthorizationMessageException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidAuthorizationMessageException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// The web identity token that was passed could not be validated by Amazon Web -// Services. Get a new identity token from the identity provider and then retry the -// request. -type InvalidIdentityTokenException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidIdentityTokenException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidIdentityTokenException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidIdentityTokenException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidIdentityToken" - } - return *e.ErrorCodeOverride -} -func (e *InvalidIdentityTokenException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The request was rejected because the policy document was malformed. The error -// message describes the specific error. -type MalformedPolicyDocumentException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *MalformedPolicyDocumentException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *MalformedPolicyDocumentException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *MalformedPolicyDocumentException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "MalformedPolicyDocument" - } - return *e.ErrorCodeOverride -} -func (e *MalformedPolicyDocumentException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The request was rejected because the total packed size of the session policies -// and session tags combined was too large. An Amazon Web Services conversion -// compresses the session policy document, session policy ARNs, and session tags -// into a packed binary format that has a separate limit. The error message -// indicates by percentage how close the policies and tags are to the upper size -// limit. For more information, see Passing Session Tags in STS (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) -// in the IAM User Guide. You could receive this error even though you meet other -// defined session policy and session tag limits. For more information, see IAM -// and STS Entity Character Limits (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html#reference_iam-limits-entity-length) -// in the IAM User Guide. -type PackedPolicyTooLargeException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *PackedPolicyTooLargeException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *PackedPolicyTooLargeException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *PackedPolicyTooLargeException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "PackedPolicyTooLarge" - } - return *e.ErrorCodeOverride -} -func (e *PackedPolicyTooLargeException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// STS is not activated in the requested region for the account that is being -// asked to generate credentials. The account administrator must use the IAM -// console to activate STS in that region. For more information, see Activating -// and Deactivating Amazon Web Services STS in an Amazon Web Services Region (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) -// in the IAM User Guide. -type RegionDisabledException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *RegionDisabledException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *RegionDisabledException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *RegionDisabledException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "RegionDisabledException" - } - return *e.ErrorCodeOverride -} -func (e *RegionDisabledException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/types/types.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/types/types.go deleted file mode 100644 index 572a70512..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/types/types.go +++ /dev/null @@ -1,130 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package types - -import ( - smithydocument "github.com/aws/smithy-go/document" - "time" -) - -// The identifiers for the temporary security credentials that the operation -// returns. -type AssumedRoleUser struct { - - // The ARN of the temporary security credentials that are returned from the - // AssumeRole action. For more information about ARNs and how to use them in - // policies, see IAM Identifiers (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html) - // in the IAM User Guide. - // - // This member is required. - Arn *string - - // A unique identifier that contains the role ID and the role session name of the - // role that is being assumed. The role ID is generated by Amazon Web Services when - // the role is created. - // - // This member is required. - AssumedRoleId *string - - noSmithyDocumentSerde -} - -// Amazon Web Services credentials for API authentication. -type Credentials struct { - - // The access key ID that identifies the temporary security credentials. - // - // This member is required. - AccessKeyId *string - - // The date on which the current credentials expire. - // - // This member is required. - Expiration *time.Time - - // The secret access key that can be used to sign requests. - // - // This member is required. - SecretAccessKey *string - - // The token that users must pass to the service API to use the temporary - // credentials. - // - // This member is required. - SessionToken *string - - noSmithyDocumentSerde -} - -// Identifiers for the federated user that is associated with the credentials. -type FederatedUser struct { - - // The ARN that specifies the federated user that is associated with the - // credentials. For more information about ARNs and how to use them in policies, - // see IAM Identifiers (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html) - // in the IAM User Guide. - // - // This member is required. - Arn *string - - // The string that identifies the federated user associated with the credentials, - // similar to the unique ID of an IAM user. - // - // This member is required. - FederatedUserId *string - - noSmithyDocumentSerde -} - -// A reference to the IAM managed policy that is passed as a session policy for a -// role session or a federated user session. -type PolicyDescriptorType struct { - - // The Amazon Resource Name (ARN) of the IAM managed policy to use as a session - // policy for the role. For more information about ARNs, see Amazon Resource Names - // (ARNs) and Amazon Web Services Service Namespaces (https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) - // in the Amazon Web Services General Reference. - Arn *string - - noSmithyDocumentSerde -} - -// Reserved for future use. -type ProvidedContext struct { - - // Reserved for future use. - ContextAssertion *string - - // Reserved for future use. - ProviderArn *string - - noSmithyDocumentSerde -} - -// You can pass custom key-value pair attributes when you assume a role or -// federate a user. These are called session tags. You can then use the session -// tags to control access to resources. For more information, see Tagging Amazon -// Web Services STS Sessions (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) -// in the IAM User Guide. -type Tag struct { - - // The key for a session tag. You can pass up to 50 session tags. The plain text - // session tag keys can’t exceed 128 characters. For these and additional limits, - // see IAM and STS Character Limits (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html#reference_iam-limits-entity-length) - // in the IAM User Guide. - // - // This member is required. - Key *string - - // The value for a session tag. You can pass up to 50 session tags. The plain text - // session tag values can’t exceed 256 characters. For these and additional limits, - // see IAM and STS Character Limits (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html#reference_iam-limits-entity-length) - // in the IAM User Guide. - // - // This member is required. - Value *string - - noSmithyDocumentSerde -} - -type noSmithyDocumentSerde = smithydocument.NoSerde diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/validators.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/validators.go deleted file mode 100644 index 3e4bad2a9..000000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/validators.go +++ /dev/null @@ -1,305 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -import ( - "context" - "fmt" - "github.com/aws/aws-sdk-go-v2/service/sts/types" - smithy "github.com/aws/smithy-go" - "github.com/aws/smithy-go/middleware" -) - -type validateOpAssumeRole struct { -} - -func (*validateOpAssumeRole) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpAssumeRole) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*AssumeRoleInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpAssumeRoleInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpAssumeRoleWithSAML struct { -} - -func (*validateOpAssumeRoleWithSAML) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpAssumeRoleWithSAML) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*AssumeRoleWithSAMLInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpAssumeRoleWithSAMLInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpAssumeRoleWithWebIdentity struct { -} - -func (*validateOpAssumeRoleWithWebIdentity) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpAssumeRoleWithWebIdentity) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*AssumeRoleWithWebIdentityInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpAssumeRoleWithWebIdentityInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDecodeAuthorizationMessage struct { -} - -func (*validateOpDecodeAuthorizationMessage) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDecodeAuthorizationMessage) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DecodeAuthorizationMessageInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDecodeAuthorizationMessageInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetAccessKeyInfo struct { -} - -func (*validateOpGetAccessKeyInfo) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetAccessKeyInfo) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetAccessKeyInfoInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetAccessKeyInfoInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetFederationToken struct { -} - -func (*validateOpGetFederationToken) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetFederationToken) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetFederationTokenInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetFederationTokenInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -func addOpAssumeRoleValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpAssumeRole{}, middleware.After) -} - -func addOpAssumeRoleWithSAMLValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpAssumeRoleWithSAML{}, middleware.After) -} - -func addOpAssumeRoleWithWebIdentityValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpAssumeRoleWithWebIdentity{}, middleware.After) -} - -func addOpDecodeAuthorizationMessageValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDecodeAuthorizationMessage{}, middleware.After) -} - -func addOpGetAccessKeyInfoValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetAccessKeyInfo{}, middleware.After) -} - -func addOpGetFederationTokenValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetFederationToken{}, middleware.After) -} - -func validateTag(v *types.Tag) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "Tag"} - if v.Key == nil { - invalidParams.Add(smithy.NewErrParamRequired("Key")) - } - if v.Value == nil { - invalidParams.Add(smithy.NewErrParamRequired("Value")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateTagListType(v []types.Tag) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "TagListType"} - for i := range v { - if err := validateTag(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpAssumeRoleInput(v *AssumeRoleInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "AssumeRoleInput"} - if v.RoleArn == nil { - invalidParams.Add(smithy.NewErrParamRequired("RoleArn")) - } - if v.RoleSessionName == nil { - invalidParams.Add(smithy.NewErrParamRequired("RoleSessionName")) - } - if v.Tags != nil { - if err := validateTagListType(v.Tags); err != nil { - invalidParams.AddNested("Tags", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpAssumeRoleWithSAMLInput(v *AssumeRoleWithSAMLInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "AssumeRoleWithSAMLInput"} - if v.RoleArn == nil { - invalidParams.Add(smithy.NewErrParamRequired("RoleArn")) - } - if v.PrincipalArn == nil { - invalidParams.Add(smithy.NewErrParamRequired("PrincipalArn")) - } - if v.SAMLAssertion == nil { - invalidParams.Add(smithy.NewErrParamRequired("SAMLAssertion")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpAssumeRoleWithWebIdentityInput(v *AssumeRoleWithWebIdentityInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "AssumeRoleWithWebIdentityInput"} - if v.RoleArn == nil { - invalidParams.Add(smithy.NewErrParamRequired("RoleArn")) - } - if v.RoleSessionName == nil { - invalidParams.Add(smithy.NewErrParamRequired("RoleSessionName")) - } - if v.WebIdentityToken == nil { - invalidParams.Add(smithy.NewErrParamRequired("WebIdentityToken")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDecodeAuthorizationMessageInput(v *DecodeAuthorizationMessageInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DecodeAuthorizationMessageInput"} - if v.EncodedMessage == nil { - invalidParams.Add(smithy.NewErrParamRequired("EncodedMessage")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetAccessKeyInfoInput(v *GetAccessKeyInfoInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetAccessKeyInfoInput"} - if v.AccessKeyId == nil { - invalidParams.Add(smithy.NewErrParamRequired("AccessKeyId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetFederationTokenInput(v *GetFederationTokenInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetFederationTokenInput"} - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if v.Tags != nil { - if err := validateTagListType(v.Tags); err != nil { - invalidParams.AddNested("Tags", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} diff --git a/vendor/github.com/aws/smithy-go/.gitignore b/vendor/github.com/aws/smithy-go/.gitignore deleted file mode 100644 index c92d6105e..000000000 --- a/vendor/github.com/aws/smithy-go/.gitignore +++ /dev/null @@ -1,26 +0,0 @@ -# Eclipse -.classpath -.project -.settings/ - -# Intellij -.idea/ -*.iml -*.iws - -# Mac -.DS_Store - -# Maven -target/ -**/dependency-reduced-pom.xml - -# Gradle -/.gradle -build/ -*/out/ -*/*/out/ - -# VS Code -bin/ -.vscode/ diff --git a/vendor/github.com/aws/smithy-go/.travis.yml b/vendor/github.com/aws/smithy-go/.travis.yml deleted file mode 100644 index f8d1035cc..000000000 --- a/vendor/github.com/aws/smithy-go/.travis.yml +++ /dev/null @@ -1,28 +0,0 @@ -language: go -sudo: true -dist: bionic - -branches: - only: - - main - -os: - - linux - - osx - # Travis doesn't work with windows and Go tip - #- windows - -go: - - tip - -matrix: - allow_failures: - - go: tip - -before_install: - - if [ "$TRAVIS_OS_NAME" = "windows" ]; then choco install make; fi - - (cd /tmp/; go get golang.org/x/lint/golint) - -script: - - make go test -v ./...; - diff --git a/vendor/github.com/aws/smithy-go/CHANGELOG.md b/vendor/github.com/aws/smithy-go/CHANGELOG.md deleted file mode 100644 index b9171b88b..000000000 --- a/vendor/github.com/aws/smithy-go/CHANGELOG.md +++ /dev/null @@ -1,182 +0,0 @@ -# Release (2023-08-18) - -* No change notes available for this release. - -# Release (2023-08-07) - -## Module Highlights -* `github.com/aws/smithy-go`: v1.14.1 - * **Bug Fix**: Prevent duplicated error returns in EndpointResolverV2 default implementation. - -# Release (2023-07-31) - -## General Highlights -* **Feature**: Adds support for smithy-modeled endpoint resolution. - -# Release (2022-12-02) - -* No change notes available for this release. - -# Release (2022-10-24) - -## Module Highlights -* `github.com/aws/smithy-go`: v1.13.4 - * **Bug Fix**: fixed document type checking for encoding nested types - -# Release (2022-09-14) - -* No change notes available for this release. - -# Release (v1.13.2) - -* No change notes available for this release. - -# Release (v1.13.1) - -* No change notes available for this release. - -# Release (v1.13.0) - -## Module Highlights -* `github.com/aws/smithy-go`: v1.13.0 - * **Feature**: Adds support for the Smithy httpBearerAuth authentication trait to smithy-go. This allows the SDK to support the bearer authentication flow for API operations decorated with httpBearerAuth. An API client will need to be provided with its own bearer.TokenProvider implementation or use the bearer.StaticTokenProvider implementation. - -# Release (v1.12.1) - -## Module Highlights -* `github.com/aws/smithy-go`: v1.12.1 - * **Bug Fix**: Fixes a bug where JSON object keys were not escaped. - -# Release (v1.12.0) - -## Module Highlights -* `github.com/aws/smithy-go`: v1.12.0 - * **Feature**: `transport/http`: Add utility for setting context metadata when operation serializer automatically assigns content-type default value. - -# Release (v1.11.3) - -## Module Highlights -* `github.com/aws/smithy-go`: v1.11.3 - * **Dependency Update**: Updates smithy-go unit test dependency go-cmp to 0.5.8. - -# Release (v1.11.2) - -* No change notes available for this release. - -# Release (v1.11.1) - -## Module Highlights -* `github.com/aws/smithy-go`: v1.11.1 - * **Bug Fix**: Updates the smithy-go HTTP Request to correctly handle building the request to an http.Request. Related to [aws/aws-sdk-go-v2#1583](https://github.com/aws/aws-sdk-go-v2/issues/1583) - -# Release (v1.11.0) - -## Module Highlights -* `github.com/aws/smithy-go`: v1.11.0 - * **Feature**: Updates deserialization of header list to supported quoted strings - -# Release (v1.10.0) - -## Module Highlights -* `github.com/aws/smithy-go`: v1.10.0 - * **Feature**: Add `ptr.Duration`, `ptr.ToDuration`, `ptr.DurationSlice`, `ptr.ToDurationSlice`, `ptr.DurationMap`, and `ptr.ToDurationMap` functions for the `time.Duration` type. - -# Release (v1.9.1) - -## Module Highlights -* `github.com/aws/smithy-go`: v1.9.1 - * **Documentation**: Fixes various typos in Go package documentation. - -# Release (v1.9.0) - -## Module Highlights -* `github.com/aws/smithy-go`: v1.9.0 - * **Feature**: sync: OnceErr, can be used to concurrently record a signal when an error has occurred. - * **Bug Fix**: `transport/http`: CloseResponseBody and ErrorCloseResponseBody middleware have been updated to ensure that the body is fully drained before closing. - -# Release v1.8.1 - -### Smithy Go Module -* **Bug Fix**: Fixed an issue that would cause the HTTP Content-Length to be set to 0 if the stream body was not set. - * Fixes [aws/aws-sdk-go-v2#1418](https://github.com/aws/aws-sdk-go-v2/issues/1418) - -# Release v1.8.0 - -### Smithy Go Module - -* `time`: Add support for parsing additional DateTime timestamp format ([#324](https://github.com/aws/smithy-go/pull/324)) - * Adds support for parsing DateTime timestamp formatted time similar to RFC 3339, but without the `Z` character, nor UTC offset. - * Fixes [#1387](https://github.com/aws/aws-sdk-go-v2/issues/1387) - -# Release v1.7.0 - -### Smithy Go Module -* `ptr`: Handle error for deferred file close call ([#314](https://github.com/aws/smithy-go/pull/314)) - * Handle error for defer close call -* `middleware`: Add Clone to Metadata ([#318](https://github.com/aws/smithy-go/pull/318)) - * Adds a new Clone method to the middleware Metadata type. This provides a shallow clone of the entries in the Metadata. -* `document`: Add new package for document shape serialization support ([#310](https://github.com/aws/smithy-go/pull/310)) - -### Codegen -* Add Smithy Document Shape Support ([#310](https://github.com/aws/smithy-go/pull/310)) - * Adds support for Smithy Document shapes and supporting types for protocols to implement support - -# Release v1.6.0 (2021-07-15) - -### Smithy Go Module -* `encoding/httpbinding`: Support has been added for encoding `float32` and `float64` values that are `NaN`, `Infinity`, or `-Infinity`. ([#316](https://github.com/aws/smithy-go/pull/316)) - -### Codegen -* Adds support for handling `float32` and `float64` `NaN` values in HTTP Protocol Unit Tests. ([#316](https://github.com/aws/smithy-go/pull/316)) -* Adds support protocol generator implementations to override the error code string returned by `ErrorCode` methods on generated error types. ([#315](https://github.com/aws/smithy-go/pull/315)) - -# Release v1.5.0 (2021-06-25) - -### Smithy Go module -* `time`: Update time parsing to not be as strict for HTTPDate and DateTime ([#307](https://github.com/aws/smithy-go/pull/307)) - * Fixes [#302](https://github.com/aws/smithy-go/issues/302) by changing time to UTC before formatting so no local offset time is lost. - -### Codegen -* Adds support for integrating client members via plugins ([#301](https://github.com/aws/smithy-go/pull/301)) -* Fix serialization of enum types marked with payload trait ([#296](https://github.com/aws/smithy-go/pull/296)) -* Update generation of API client modules to include a manifest of files generated ([#283](https://github.com/aws/smithy-go/pull/283)) -* Update Group Java group ID for smithy-go generator ([#298](https://github.com/aws/smithy-go/pull/298)) -* Support the delegation of determining the errors that can occur for an operation ([#304](https://github.com/aws/smithy-go/pull/304)) -* Support for marking and documenting deprecated client config fields. ([#303](https://github.com/aws/smithy-go/pull/303)) - -# Release v1.4.0 (2021-05-06) - -### Smithy Go module -* `encoding/xml`: Fix escaping of Next Line and Line Start in XML Encoder ([#267](https://github.com/aws/smithy-go/pull/267)) - -### Codegen -* Add support for Smithy 1.7 ([#289](https://github.com/aws/smithy-go/pull/289)) -* Add support for httpQueryParams location -* Add support for model renaming conflict resolution with service closure - -# Release v1.3.1 (2021-04-08) - -### Smithy Go module -* `transport/http`: Loosen endpoint hostname validation to allow specifying port numbers. ([#279](https://github.com/aws/smithy-go/pull/279)) -* `io`: Fix RingBuffer panics due to out of bounds index. ([#282](https://github.com/aws/smithy-go/pull/282)) - -# Release v1.3.0 (2021-04-01) - -### Smithy Go module -* `transport/http`: Add utility to safely join string to url path, and url raw query. - -### Codegen -* Update HttpBindingProtocolGenerator to use http/transport JoinPath and JoinQuery utility. - -# Release v1.2.0 (2021-03-12) - -### Smithy Go module -* Fix support for parsing shortened year format in HTTP Date header. -* Fix GitHub APIDiff action workflow to get gorelease tool correctly. -* Fix codegen artifact unit test for Go 1.16 - -### Codegen -* Fix generating paginator nil parameter handling before usage. -* Fix Serialize unboxed members decorated as required. -* Add ability to define resolvers at both client construction and operation invocation. -* Support for extending paginators with custom runtime trait diff --git a/vendor/github.com/aws/smithy-go/CODE_OF_CONDUCT.md b/vendor/github.com/aws/smithy-go/CODE_OF_CONDUCT.md deleted file mode 100644 index 5b627cfa6..000000000 --- a/vendor/github.com/aws/smithy-go/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,4 +0,0 @@ -## Code of Conduct -This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). -For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact -opensource-codeofconduct@amazon.com with any additional questions or comments. diff --git a/vendor/github.com/aws/smithy-go/CONTRIBUTING.md b/vendor/github.com/aws/smithy-go/CONTRIBUTING.md deleted file mode 100644 index c4b6a1c50..000000000 --- a/vendor/github.com/aws/smithy-go/CONTRIBUTING.md +++ /dev/null @@ -1,59 +0,0 @@ -# Contributing Guidelines - -Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional -documentation, we greatly value feedback and contributions from our community. - -Please read through this document before submitting any issues or pull requests to ensure we have all the necessary -information to effectively respond to your bug report or contribution. - - -## Reporting Bugs/Feature Requests - -We welcome you to use the GitHub issue tracker to report bugs or suggest features. - -When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already -reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: - -* A reproducible test case or series of steps -* The version of our code being used -* Any modifications you've made relevant to the bug -* Anything unusual about your environment or deployment - - -## Contributing via Pull Requests -Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: - -1. You are working against the latest source on the *main* branch. -2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. -3. You open an issue to discuss any significant work - we would hate for your time to be wasted. - -To send us a pull request, please: - -1. Fork the repository. -2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. -3. Ensure local tests pass. -4. Commit to your fork using clear commit messages. -5. Send us a pull request, answering any default questions in the pull request interface. -6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. - -GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and -[creating a pull request](https://help.github.com/articles/creating-a-pull-request/). - - -## Finding contributions to work on -Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start. - - -## Code of Conduct -This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). -For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact -opensource-codeofconduct@amazon.com with any additional questions or comments. - - -## Security issue notifications -If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. - - -## Licensing - -See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. diff --git a/vendor/github.com/aws/smithy-go/LICENSE b/vendor/github.com/aws/smithy-go/LICENSE deleted file mode 100644 index 67db85882..000000000 --- a/vendor/github.com/aws/smithy-go/LICENSE +++ /dev/null @@ -1,175 +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. diff --git a/vendor/github.com/aws/smithy-go/Makefile b/vendor/github.com/aws/smithy-go/Makefile deleted file mode 100644 index 4b3c20937..000000000 --- a/vendor/github.com/aws/smithy-go/Makefile +++ /dev/null @@ -1,97 +0,0 @@ -PRE_RELEASE_VERSION ?= - -RELEASE_MANIFEST_FILE ?= -RELEASE_CHGLOG_DESC_FILE ?= - -REPOTOOLS_VERSION ?= latest -REPOTOOLS_MODULE = github.com/awslabs/aws-go-multi-module-repository-tools -REPOTOOLS_CMD_CALCULATE_RELEASE = ${REPOTOOLS_MODULE}/cmd/calculaterelease@${REPOTOOLS_VERSION} -REPOTOOLS_CMD_CALCULATE_RELEASE_ADDITIONAL_ARGS ?= -REPOTOOLS_CMD_UPDATE_REQUIRES = ${REPOTOOLS_MODULE}/cmd/updaterequires@${REPOTOOLS_VERSION} -REPOTOOLS_CMD_UPDATE_MODULE_METADATA = ${REPOTOOLS_MODULE}/cmd/updatemodulemeta@${REPOTOOLS_VERSION} -REPOTOOLS_CMD_GENERATE_CHANGELOG = ${REPOTOOLS_MODULE}/cmd/generatechangelog@${REPOTOOLS_VERSION} -REPOTOOLS_CMD_CHANGELOG = ${REPOTOOLS_MODULE}/cmd/changelog@${REPOTOOLS_VERSION} -REPOTOOLS_CMD_TAG_RELEASE = ${REPOTOOLS_MODULE}/cmd/tagrelease@${REPOTOOLS_VERSION} -REPOTOOLS_CMD_MODULE_VERSION = ${REPOTOOLS_MODULE}/cmd/moduleversion@${REPOTOOLS_VERSION} - -UNIT_TEST_TAGS= -BUILD_TAGS= - -ifneq ($(PRE_RELEASE_VERSION),) - REPOTOOLS_CMD_CALCULATE_RELEASE_ADDITIONAL_ARGS += -preview=${PRE_RELEASE_VERSION} -endif - -smithy-publish-local: - cd codegen && ./gradlew publishToMavenLocal - -smithy-build: - cd codegen && ./gradlew build - -smithy-clean: - cd codegen && ./gradlew clean - -################## -# Linting/Verify # -################## -.PHONY: verify vet - -verify: vet - -vet: - go vet ${BUILD_TAGS} --all ./... - -################ -# Unit Testing # -################ -.PHONY: unit unit-race unit-test unit-race-test - -unit: verify - go vet ${BUILD_TAGS} --all ./... && \ - go test ${BUILD_TAGS} ${RUN_NONE} ./... && \ - go test -timeout=1m ${UNIT_TEST_TAGS} ./... - -unit-race: verify - go vet ${BUILD_TAGS} --all ./... && \ - go test ${BUILD_TAGS} ${RUN_NONE} ./... && \ - go test -timeout=1m ${UNIT_TEST_TAGS} -race -cpu=4 ./... - -unit-test: verify - go test -timeout=1m ${UNIT_TEST_TAGS} ./... - -unit-race-test: verify - go test -timeout=1m ${UNIT_TEST_TAGS} -race -cpu=4 ./... - -##################### -# Release Process # -##################### -.PHONY: preview-release pre-release-validation release - -preview-release: - go run ${REPOTOOLS_CMD_CALCULATE_RELEASE} ${REPOTOOLS_CMD_CALCULATE_RELEASE_ADDITIONAL_ARGS} - -pre-release-validation: - @if [[ -z "${RELEASE_MANIFEST_FILE}" ]]; then \ - echo "RELEASE_MANIFEST_FILE is required to specify the file to write the release manifest" && false; \ - fi - @if [[ -z "${RELEASE_CHGLOG_DESC_FILE}" ]]; then \ - echo "RELEASE_CHGLOG_DESC_FILE is required to specify the file to write the release notes" && false; \ - fi - -release: pre-release-validation - go run ${REPOTOOLS_CMD_CALCULATE_RELEASE} -o ${RELEASE_MANIFEST_FILE} ${REPOTOOLS_CMD_CALCULATE_RELEASE_ADDITIONAL_ARGS} - go run ${REPOTOOLS_CMD_UPDATE_REQUIRES} -release ${RELEASE_MANIFEST_FILE} - go run ${REPOTOOLS_CMD_UPDATE_MODULE_METADATA} -release ${RELEASE_MANIFEST_FILE} - go run ${REPOTOOLS_CMD_GENERATE_CHANGELOG} -release ${RELEASE_MANIFEST_FILE} -o ${RELEASE_CHGLOG_DESC_FILE} - go run ${REPOTOOLS_CMD_CHANGELOG} rm -all - go run ${REPOTOOLS_CMD_TAG_RELEASE} -release ${RELEASE_MANIFEST_FILE} - -module-version: - @go run ${REPOTOOLS_CMD_MODULE_VERSION} . - -############## -# Repo Tools # -############## -.PHONY: install-changelog - -install-changelog: - go install ${REPOTOOLS_MODULE}/cmd/changelog@${REPOTOOLS_VERSION} diff --git a/vendor/github.com/aws/smithy-go/NOTICE b/vendor/github.com/aws/smithy-go/NOTICE deleted file mode 100644 index 616fc5889..000000000 --- a/vendor/github.com/aws/smithy-go/NOTICE +++ /dev/null @@ -1 +0,0 @@ -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. diff --git a/vendor/github.com/aws/smithy-go/README.md b/vendor/github.com/aws/smithy-go/README.md deleted file mode 100644 index a4bb43fbe..000000000 --- a/vendor/github.com/aws/smithy-go/README.md +++ /dev/null @@ -1,12 +0,0 @@ -## Smithy Go - -[![Go Build Status](https://github.com/aws/smithy-go/actions/workflows/go.yml/badge.svg?branch=main)](https://github.com/aws/smithy-go/actions/workflows/go.yml)[![Codegen Build Status](https://github.com/aws/smithy-go/actions/workflows/codegen.yml/badge.svg?branch=main)](https://github.com/aws/smithy-go/actions/workflows/codegen.yml) - -[Smithy](https://smithy.io/) code generators for Go. - -**WARNING: All interfaces are subject to change.** - -## License - -This project is licensed under the Apache-2.0 License. - diff --git a/vendor/github.com/aws/smithy-go/auth/bearer/docs.go b/vendor/github.com/aws/smithy-go/auth/bearer/docs.go deleted file mode 100644 index 1c9b9715c..000000000 --- a/vendor/github.com/aws/smithy-go/auth/bearer/docs.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package bearer provides middleware and utilities for authenticating API -// operation calls with a Bearer Token. -package bearer diff --git a/vendor/github.com/aws/smithy-go/auth/bearer/middleware.go b/vendor/github.com/aws/smithy-go/auth/bearer/middleware.go deleted file mode 100644 index 8c7d72099..000000000 --- a/vendor/github.com/aws/smithy-go/auth/bearer/middleware.go +++ /dev/null @@ -1,104 +0,0 @@ -package bearer - -import ( - "context" - "fmt" - - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Message is the middleware stack's request transport message value. -type Message interface{} - -// Signer provides an interface for implementations to decorate a request -// message with a bearer token. The signer is responsible for validating the -// message type is compatible with the signer. -type Signer interface { - SignWithBearerToken(context.Context, Token, Message) (Message, error) -} - -// AuthenticationMiddleware provides the Finalize middleware step for signing -// an request message with a bearer token. -type AuthenticationMiddleware struct { - signer Signer - tokenProvider TokenProvider -} - -// AddAuthenticationMiddleware helper adds the AuthenticationMiddleware to the -// middleware Stack in the Finalize step with the options provided. -func AddAuthenticationMiddleware(s *middleware.Stack, signer Signer, tokenProvider TokenProvider) error { - return s.Finalize.Add( - NewAuthenticationMiddleware(signer, tokenProvider), - middleware.After, - ) -} - -// NewAuthenticationMiddleware returns an initialized AuthenticationMiddleware. -func NewAuthenticationMiddleware(signer Signer, tokenProvider TokenProvider) *AuthenticationMiddleware { - return &AuthenticationMiddleware{ - signer: signer, - tokenProvider: tokenProvider, - } -} - -const authenticationMiddlewareID = "BearerTokenAuthentication" - -// ID returns the resolver identifier -func (m *AuthenticationMiddleware) ID() string { - return authenticationMiddlewareID -} - -// HandleFinalize implements the FinalizeMiddleware interface in order to -// update the request with bearer token authentication. -func (m *AuthenticationMiddleware) HandleFinalize( - ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler, -) ( - out middleware.FinalizeOutput, metadata middleware.Metadata, err error, -) { - token, err := m.tokenProvider.RetrieveBearerToken(ctx) - if err != nil { - return out, metadata, fmt.Errorf("failed AuthenticationMiddleware wrap message, %w", err) - } - - signedMessage, err := m.signer.SignWithBearerToken(ctx, token, in.Request) - if err != nil { - return out, metadata, fmt.Errorf("failed AuthenticationMiddleware sign message, %w", err) - } - - in.Request = signedMessage - return next.HandleFinalize(ctx, in) -} - -// SignHTTPSMessage provides a bearer token authentication implementation that -// will sign the message with the provided bearer token. -// -// Will fail if the message is not a smithy-go HTTP request or the request is -// not HTTPS. -type SignHTTPSMessage struct{} - -// NewSignHTTPSMessage returns an initialized signer for HTTP messages. -func NewSignHTTPSMessage() *SignHTTPSMessage { - return &SignHTTPSMessage{} -} - -// SignWithBearerToken returns a copy of the HTTP request with the bearer token -// added via the "Authorization" header, per RFC 6750, https://datatracker.ietf.org/doc/html/rfc6750. -// -// Returns an error if the request's URL scheme is not HTTPS, or the request -// message is not an smithy-go HTTP Request pointer type. -func (SignHTTPSMessage) SignWithBearerToken(ctx context.Context, token Token, message Message) (Message, error) { - req, ok := message.(*smithyhttp.Request) - if !ok { - return nil, fmt.Errorf("expect smithy-go HTTP Request, got %T", message) - } - - if !req.IsHTTPS() { - return nil, fmt.Errorf("bearer token with HTTP request requires HTTPS") - } - - reqClone := req.Clone() - reqClone.Header.Set("Authorization", "Bearer "+token.Value) - - return reqClone, nil -} diff --git a/vendor/github.com/aws/smithy-go/auth/bearer/token.go b/vendor/github.com/aws/smithy-go/auth/bearer/token.go deleted file mode 100644 index be260d4c7..000000000 --- a/vendor/github.com/aws/smithy-go/auth/bearer/token.go +++ /dev/null @@ -1,50 +0,0 @@ -package bearer - -import ( - "context" - "time" -) - -// Token provides a type wrapping a bearer token and expiration metadata. -type Token struct { - Value string - - CanExpire bool - Expires time.Time -} - -// Expired returns if the token's Expires time is before or equal to the time -// provided. If CanExpires is false, Expired will always return false. -func (t Token) Expired(now time.Time) bool { - if !t.CanExpire { - return false - } - now = now.Round(0) - return now.Equal(t.Expires) || now.After(t.Expires) -} - -// TokenProvider provides interface for retrieving bearer tokens. -type TokenProvider interface { - RetrieveBearerToken(context.Context) (Token, error) -} - -// TokenProviderFunc provides a helper utility to wrap a function as a type -// that implements the TokenProvider interface. -type TokenProviderFunc func(context.Context) (Token, error) - -// RetrieveBearerToken calls the wrapped function, returning the Token or -// error. -func (fn TokenProviderFunc) RetrieveBearerToken(ctx context.Context) (Token, error) { - return fn(ctx) -} - -// StaticTokenProvider provides a utility for wrapping a static bearer token -// value within an implementation of a token provider. -type StaticTokenProvider struct { - Token Token -} - -// RetrieveBearerToken returns the static token specified. -func (s StaticTokenProvider) RetrieveBearerToken(context.Context) (Token, error) { - return s.Token, nil -} diff --git a/vendor/github.com/aws/smithy-go/auth/bearer/token_cache.go b/vendor/github.com/aws/smithy-go/auth/bearer/token_cache.go deleted file mode 100644 index 223ddf52b..000000000 --- a/vendor/github.com/aws/smithy-go/auth/bearer/token_cache.go +++ /dev/null @@ -1,208 +0,0 @@ -package bearer - -import ( - "context" - "fmt" - "sync/atomic" - "time" - - smithycontext "github.com/aws/smithy-go/context" - "github.com/aws/smithy-go/internal/sync/singleflight" -) - -// package variable that can be override in unit tests. -var timeNow = time.Now - -// TokenCacheOptions provides a set of optional configuration options for the -// TokenCache TokenProvider. -type TokenCacheOptions struct { - // The duration before the token will expire when the credentials will be - // refreshed. If DisableAsyncRefresh is true, the RetrieveBearerToken calls - // will be blocking. - // - // Asynchronous refreshes are deduplicated, and only one will be in-flight - // at a time. If the token expires while an asynchronous refresh is in - // flight, the next call to RetrieveBearerToken will block on that refresh - // to return. - RefreshBeforeExpires time.Duration - - // The timeout the underlying TokenProvider's RetrieveBearerToken call must - // return within, or will be canceled. Defaults to 0, no timeout. - // - // If 0 timeout, its possible for the underlying tokenProvider's - // RetrieveBearerToken call to block forever. Preventing subsequent - // TokenCache attempts to refresh the token. - // - // If this timeout is reached all pending deduplicated calls to - // TokenCache RetrieveBearerToken will fail with an error. - RetrieveBearerTokenTimeout time.Duration - - // The minimum duration between asynchronous refresh attempts. If the next - // asynchronous recent refresh attempt was within the minimum delay - // duration, the call to retrieve will return the current cached token, if - // not expired. - // - // The asynchronous retrieve is deduplicated across multiple calls when - // RetrieveBearerToken is called. The asynchronous retrieve is not a - // periodic task. It is only performed when the token has not yet expired, - // and the current item is within the RefreshBeforeExpires window, and the - // TokenCache's RetrieveBearerToken method is called. - // - // If 0, (default) there will be no minimum delay between asynchronous - // refresh attempts. - // - // If DisableAsyncRefresh is true, this option is ignored. - AsyncRefreshMinimumDelay time.Duration - - // Sets if the TokenCache will attempt to refresh the token in the - // background asynchronously instead of blocking for credentials to be - // refreshed. If disabled token refresh will be blocking. - // - // The first call to RetrieveBearerToken will always be blocking, because - // there is no cached token. - DisableAsyncRefresh bool -} - -// TokenCache provides an utility to cache Bearer Authentication tokens from a -// wrapped TokenProvider. The TokenCache can be has options to configure the -// cache's early and asynchronous refresh of the token. -type TokenCache struct { - options TokenCacheOptions - provider TokenProvider - - cachedToken atomic.Value - lastRefreshAttemptTime atomic.Value - sfGroup singleflight.Group -} - -// NewTokenCache returns a initialized TokenCache that implements the -// TokenProvider interface. Wrapping the provider passed in. Also taking a set -// of optional functional option parameters to configure the token cache. -func NewTokenCache(provider TokenProvider, optFns ...func(*TokenCacheOptions)) *TokenCache { - var options TokenCacheOptions - for _, fn := range optFns { - fn(&options) - } - - return &TokenCache{ - options: options, - provider: provider, - } -} - -// RetrieveBearerToken returns the token if it could be obtained, or error if a -// valid token could not be retrieved. -// -// The passed in Context's cancel/deadline/timeout will impacting only this -// individual retrieve call and not any other already queued up calls. This -// means underlying provider's RetrieveBearerToken calls could block for ever, -// and not be canceled with the Context. Set RetrieveBearerTokenTimeout to -// provide a timeout, preventing the underlying TokenProvider blocking forever. -// -// By default, if the passed in Context is canceled, all of its values will be -// considered expired. The wrapped TokenProvider will not be able to lookup the -// values from the Context once it is expired. This is done to protect against -// expired values no longer being valid. To disable this behavior, use -// smithy-go's context.WithPreserveExpiredValues to add a value to the Context -// before calling RetrieveBearerToken to enable support for expired values. -// -// Without RetrieveBearerTokenTimeout there is the potential for a underlying -// Provider's RetrieveBearerToken call to sit forever. Blocking in subsequent -// attempts at refreshing the token. -func (p *TokenCache) RetrieveBearerToken(ctx context.Context) (Token, error) { - cachedToken, ok := p.getCachedToken() - if !ok || cachedToken.Expired(timeNow()) { - return p.refreshBearerToken(ctx) - } - - // Check if the token should be refreshed before it expires. - refreshToken := cachedToken.Expired(timeNow().Add(p.options.RefreshBeforeExpires)) - if !refreshToken { - return cachedToken, nil - } - - if p.options.DisableAsyncRefresh { - return p.refreshBearerToken(ctx) - } - - p.tryAsyncRefresh(ctx) - - return cachedToken, nil -} - -// tryAsyncRefresh attempts to asynchronously refresh the token returning the -// already cached token. If it AsyncRefreshMinimumDelay option is not zero, and -// the duration since the last refresh is less than that value, nothing will be -// done. -func (p *TokenCache) tryAsyncRefresh(ctx context.Context) { - if p.options.AsyncRefreshMinimumDelay != 0 { - var lastRefreshAttempt time.Time - if v := p.lastRefreshAttemptTime.Load(); v != nil { - lastRefreshAttempt = v.(time.Time) - } - - if timeNow().Before(lastRefreshAttempt.Add(p.options.AsyncRefreshMinimumDelay)) { - return - } - } - - // Ignore the returned channel so this won't be blocking, and limit the - // number of additional goroutines created. - p.sfGroup.DoChan("async-refresh", func() (interface{}, error) { - res, err := p.refreshBearerToken(ctx) - if p.options.AsyncRefreshMinimumDelay != 0 { - var refreshAttempt time.Time - if err != nil { - refreshAttempt = timeNow() - } - p.lastRefreshAttemptTime.Store(refreshAttempt) - } - - return res, err - }) -} - -func (p *TokenCache) refreshBearerToken(ctx context.Context) (Token, error) { - resCh := p.sfGroup.DoChan("refresh-token", func() (interface{}, error) { - ctx := smithycontext.WithSuppressCancel(ctx) - if v := p.options.RetrieveBearerTokenTimeout; v != 0 { - var cancel func() - ctx, cancel = context.WithTimeout(ctx, v) - defer cancel() - } - return p.singleRetrieve(ctx) - }) - - select { - case res := <-resCh: - return res.Val.(Token), res.Err - case <-ctx.Done(): - return Token{}, fmt.Errorf("retrieve bearer token canceled, %w", ctx.Err()) - } -} - -func (p *TokenCache) singleRetrieve(ctx context.Context) (interface{}, error) { - token, err := p.provider.RetrieveBearerToken(ctx) - if err != nil { - return Token{}, fmt.Errorf("failed to retrieve bearer token, %w", err) - } - - p.cachedToken.Store(&token) - return token, nil -} - -// getCachedToken returns the currently cached token and true if found. Returns -// false if no token is cached. -func (p *TokenCache) getCachedToken() (Token, bool) { - v := p.cachedToken.Load() - if v == nil { - return Token{}, false - } - - t := v.(*Token) - if t == nil || t.Value == "" { - return Token{}, false - } - - return *t, true -} diff --git a/vendor/github.com/aws/smithy-go/context/suppress_expired.go b/vendor/github.com/aws/smithy-go/context/suppress_expired.go deleted file mode 100644 index a39b84a27..000000000 --- a/vendor/github.com/aws/smithy-go/context/suppress_expired.go +++ /dev/null @@ -1,81 +0,0 @@ -package context - -import "context" - -// valueOnlyContext provides a utility to preserve only the values of a -// Context. Suppressing any cancellation or deadline on that context being -// propagated downstream of this value. -// -// If preserveExpiredValues is false (default), and the valueCtx is canceled, -// calls to lookup values with the Values method, will always return nil. Setting -// preserveExpiredValues to true, will allow the valueOnlyContext to lookup -// values in valueCtx even if valueCtx is canceled. -// -// Based on the Go standard libraries net/lookup.go onlyValuesCtx utility. -// https://github.com/golang/go/blob/da2773fe3e2f6106634673a38dc3a6eb875fe7d8/src/net/lookup.go -type valueOnlyContext struct { - context.Context - - preserveExpiredValues bool - valuesCtx context.Context -} - -var _ context.Context = (*valueOnlyContext)(nil) - -// Value looks up the key, returning its value. If configured to not preserve -// values of expired context, and the wrapping context is canceled, nil will be -// returned. -func (v *valueOnlyContext) Value(key interface{}) interface{} { - if !v.preserveExpiredValues { - select { - case <-v.valuesCtx.Done(): - return nil - default: - } - } - - return v.valuesCtx.Value(key) -} - -// WithSuppressCancel wraps the Context value, suppressing its deadline and -// cancellation events being propagated downstream to consumer of the returned -// context. -// -// By default the wrapped Context's Values are available downstream until the -// wrapped Context is canceled. Once the wrapped Context is canceled, Values -// method called on the context return will no longer lookup any key. As they -// are now considered expired. -// -// To override this behavior, use WithPreserveExpiredValues on the Context -// before it is wrapped by WithSuppressCancel. This will make the Context -// returned by WithSuppressCancel allow lookup of expired values. -func WithSuppressCancel(ctx context.Context) context.Context { - return &valueOnlyContext{ - Context: context.Background(), - valuesCtx: ctx, - - preserveExpiredValues: GetPreserveExpiredValues(ctx), - } -} - -type preserveExpiredValuesKey struct{} - -// WithPreserveExpiredValues adds a Value to the Context if expired values -// should be preserved, and looked up by a Context wrapped by -// WithSuppressCancel. -// -// WithPreserveExpiredValues must be added as a value to a Context, before that -// Context is wrapped by WithSuppressCancel -func WithPreserveExpiredValues(ctx context.Context, enable bool) context.Context { - return context.WithValue(ctx, preserveExpiredValuesKey{}, enable) -} - -// GetPreserveExpiredValues looks up, and returns the PreserveExpressValues -// value in the context. Returning true if enabled, false otherwise. -func GetPreserveExpiredValues(ctx context.Context) bool { - v := ctx.Value(preserveExpiredValuesKey{}) - if v != nil { - return v.(bool) - } - return false -} diff --git a/vendor/github.com/aws/smithy-go/doc.go b/vendor/github.com/aws/smithy-go/doc.go deleted file mode 100644 index 87b0c74b7..000000000 --- a/vendor/github.com/aws/smithy-go/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package smithy provides the core components for a Smithy SDK. -package smithy diff --git a/vendor/github.com/aws/smithy-go/document.go b/vendor/github.com/aws/smithy-go/document.go deleted file mode 100644 index dec498c57..000000000 --- a/vendor/github.com/aws/smithy-go/document.go +++ /dev/null @@ -1,10 +0,0 @@ -package smithy - -// Document provides access to loosely structured data in a document-like -// format. -// -// Deprecated: See the github.com/aws/smithy-go/document package. -type Document interface { - UnmarshalDocument(interface{}) error - GetValue() (interface{}, error) -} diff --git a/vendor/github.com/aws/smithy-go/document/doc.go b/vendor/github.com/aws/smithy-go/document/doc.go deleted file mode 100644 index 03055b7a1..000000000 --- a/vendor/github.com/aws/smithy-go/document/doc.go +++ /dev/null @@ -1,12 +0,0 @@ -// Package document provides interface definitions and error types for document types. -// -// A document is a protocol-agnostic type which supports a JSON-like data-model. You can use this type to send -// UTF-8 strings, arbitrary precision numbers, booleans, nulls, a list of these values, and a map of UTF-8 -// strings to these values. -// -// API Clients expose document constructors in their respective client document packages which must be used to -// Marshal and Unmarshal Go types to and from their respective protocol representations. -// -// See the Marshaler and Unmarshaler type documentation for more details on how to Go types can be converted to and from -// document types. -package document diff --git a/vendor/github.com/aws/smithy-go/document/document.go b/vendor/github.com/aws/smithy-go/document/document.go deleted file mode 100644 index 8f852d95c..000000000 --- a/vendor/github.com/aws/smithy-go/document/document.go +++ /dev/null @@ -1,153 +0,0 @@ -package document - -import ( - "fmt" - "math/big" - "strconv" -) - -// Marshaler is an interface for a type that marshals a document to its protocol-specific byte representation and -// returns the resulting bytes. A non-nil error will be returned if an error is encountered during marshaling. -// -// Marshal supports basic scalars (int,uint,float,bool,string), big.Int, and big.Float, maps, slices, and structs. -// Anonymous nested types are flattened based on Go anonymous type visibility. -// -// When defining struct types. the `document` struct tag can be used to control how the value will be -// marshaled into the resulting protocol document. -// -// // Field is ignored -// Field int `document:"-"` -// -// // Field object of key "myName" -// Field int `document:"myName"` -// -// // Field object key of key "myName", and -// // Field is omitted if the field is a zero value for the type. -// Field int `document:"myName,omitempty"` -// -// // Field object key of "Field", and -// // Field is omitted if the field is a zero value for the type. -// Field int `document:",omitempty"` -// -// All struct fields, including anonymous fields, are marshaled unless the -// any of the following conditions are meet. -// -// - the field is not exported -// - document field tag is "-" -// - document field tag specifies "omitempty", and is a zero value. -// -// Pointer and interface values are encoded as the value pointed to or -// contained in the interface. A nil value encodes as a null -// value unless `omitempty` struct tag is provided. -// -// Channel, complex, and function values are not encoded and will be skipped -// when walking the value to be marshaled. -// -// time.Time is not supported and will cause the Marshaler to return an error. These values should be represented -// by your application as a string or numerical representation. -// -// Errors that occur when marshaling will stop the marshaler, and return the error. -// -// Marshal cannot represent cyclic data structures and will not handle them. -// Passing cyclic structures to Marshal will result in an infinite recursion. -type Marshaler interface { - MarshalSmithyDocument() ([]byte, error) -} - -// Unmarshaler is an interface for a type that unmarshals a document from its protocol-specific representation, and -// stores the result into the value pointed by v. If v is nil or not a pointer then InvalidUnmarshalError will be -// returned. -// -// Unmarshaler supports the same encodings produced by a document Marshaler. This includes support for the `document` -// struct field tag for controlling how struct fields are unmarshaled. -// -// Both generic interface{} and concrete types are valid unmarshal destination types. When unmarshaling a document -// into an empty interface the Unmarshaler will store one of these values: -// bool, for boolean values -// document.Number, for arbitrary-precision numbers (int64, float64, big.Int, big.Float) -// string, for string values -// []interface{}, for array values -// map[string]interface{}, for objects -// nil, for null values -// -// When unmarshaling, any error that occurs will halt the unmarshal and return the error. -type Unmarshaler interface { - UnmarshalSmithyDocument(v interface{}) error -} - -type noSerde interface { - noSmithyDocumentSerde() -} - -// NoSerde is a sentinel value to indicate that a given type should not be marshaled or unmarshaled -// into a protocol document. -type NoSerde struct{} - -func (n NoSerde) noSmithyDocumentSerde() {} - -var _ noSerde = (*NoSerde)(nil) - -// IsNoSerde returns whether the given type implements the no smithy document serde interface. -func IsNoSerde(x interface{}) bool { - _, ok := x.(noSerde) - return ok -} - -// Number is an arbitrary precision numerical value -type Number string - -// Int64 returns the number as a string. -func (n Number) String() string { - return string(n) -} - -// Int64 returns the number as an int64. -func (n Number) Int64() (int64, error) { - return n.intOfBitSize(64) -} - -func (n Number) intOfBitSize(bitSize int) (int64, error) { - return strconv.ParseInt(string(n), 10, bitSize) -} - -// Uint64 returns the number as a uint64. -func (n Number) Uint64() (uint64, error) { - return n.uintOfBitSize(64) -} - -func (n Number) uintOfBitSize(bitSize int) (uint64, error) { - return strconv.ParseUint(string(n), 10, bitSize) -} - -// Float32 returns the number parsed as a 32-bit float, returns a float64. -func (n Number) Float32() (float64, error) { - return n.floatOfBitSize(32) -} - -// Float64 returns the number as a float64. -func (n Number) Float64() (float64, error) { - return n.floatOfBitSize(64) -} - -// Float64 returns the number as a float64. -func (n Number) floatOfBitSize(bitSize int) (float64, error) { - return strconv.ParseFloat(string(n), bitSize) -} - -// BigFloat attempts to convert the number to a big.Float, returns an error if the operation fails. -func (n Number) BigFloat() (*big.Float, error) { - f, ok := (&big.Float{}).SetString(string(n)) - if !ok { - return nil, fmt.Errorf("failed to convert to big.Float") - } - return f, nil -} - -// BigInt attempts to convert the number to a big.Int, returns an error if the operation fails. -func (n Number) BigInt() (*big.Int, error) { - f, ok := (&big.Int{}).SetString(string(n), 10) - if !ok { - return nil, fmt.Errorf("failed to convert to big.Float") - } - return f, nil -} diff --git a/vendor/github.com/aws/smithy-go/document/errors.go b/vendor/github.com/aws/smithy-go/document/errors.go deleted file mode 100644 index 046a7a765..000000000 --- a/vendor/github.com/aws/smithy-go/document/errors.go +++ /dev/null @@ -1,75 +0,0 @@ -package document - -import ( - "fmt" - "reflect" -) - -// UnmarshalTypeError is an error type representing an error -// unmarshaling a Smithy document to a Go value type. This is different -// from UnmarshalError in that it does not wrap an underlying error type. -type UnmarshalTypeError struct { - Value string - Type reflect.Type -} - -// Error returns the string representation of the error. -// Satisfying the error interface. -func (e *UnmarshalTypeError) Error() string { - return fmt.Sprintf("unmarshal failed, cannot unmarshal %s into Go value type %s", - e.Value, e.Type.String()) -} - -// An InvalidUnmarshalError is an error type representing an invalid type -// encountered while unmarshaling a Smithy document to a Go value type. -type InvalidUnmarshalError struct { - Type reflect.Type -} - -// Error returns the string representation of the error. -// Satisfying the error interface. -func (e *InvalidUnmarshalError) Error() string { - var msg string - if e.Type == nil { - msg = "cannot unmarshal to nil value" - } else if e.Type.Kind() != reflect.Ptr { - msg = fmt.Sprintf("cannot unmarshal to non-pointer value, got %s", e.Type.String()) - } else { - msg = fmt.Sprintf("cannot unmarshal to nil value, %s", e.Type.String()) - } - - return fmt.Sprintf("unmarshal failed, %s", msg) -} - -// An UnmarshalError wraps an error that occurred while unmarshaling a -// Smithy document into a Go type. This is different from -// UnmarshalTypeError in that it wraps the underlying error that occurred. -type UnmarshalError struct { - Err error - Value string - Type reflect.Type -} - -// Unwrap returns the underlying unmarshaling error -func (e *UnmarshalError) Unwrap() error { - return e.Err -} - -// Error returns the string representation of the error. -// Satisfying the error interface. -func (e *UnmarshalError) Error() string { - return fmt.Sprintf("unmarshal failed, cannot unmarshal %q into %s, %v", - e.Value, e.Type.String(), e.Err) -} - -// An InvalidMarshalError is an error type representing an error -// occurring when marshaling a Go value type. -type InvalidMarshalError struct { - Message string -} - -// Error returns the string representation of the error. -// Satisfying the error interface. -func (e *InvalidMarshalError) Error() string { - return fmt.Sprintf("marshal failed, %s", e.Message) -} diff --git a/vendor/github.com/aws/smithy-go/encoding/doc.go b/vendor/github.com/aws/smithy-go/encoding/doc.go deleted file mode 100644 index 792fdfa08..000000000 --- a/vendor/github.com/aws/smithy-go/encoding/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Package encoding provides utilities for encoding values for specific -// document encodings. - -package encoding diff --git a/vendor/github.com/aws/smithy-go/encoding/encoding.go b/vendor/github.com/aws/smithy-go/encoding/encoding.go deleted file mode 100644 index 2fdfb5225..000000000 --- a/vendor/github.com/aws/smithy-go/encoding/encoding.go +++ /dev/null @@ -1,40 +0,0 @@ -package encoding - -import ( - "fmt" - "math" - "strconv" -) - -// EncodeFloat encodes a float value as per the stdlib encoder for json and xml protocol -// This encodes a float value into dst while attempting to conform to ES6 ToString for Numbers -// -// Based on encoding/json floatEncoder from the Go Standard Library -// https://golang.org/src/encoding/json/encode.go -func EncodeFloat(dst []byte, v float64, bits int) []byte { - if math.IsInf(v, 0) || math.IsNaN(v) { - panic(fmt.Sprintf("invalid float value: %s", strconv.FormatFloat(v, 'g', -1, bits))) - } - - abs := math.Abs(v) - fmt := byte('f') - - if abs != 0 { - if bits == 64 && (abs < 1e-6 || abs >= 1e21) || bits == 32 && (float32(abs) < 1e-6 || float32(abs) >= 1e21) { - fmt = 'e' - } - } - - dst = strconv.AppendFloat(dst, v, fmt, -1, bits) - - if fmt == 'e' { - // clean up e-09 to e-9 - n := len(dst) - if n >= 4 && dst[n-4] == 'e' && dst[n-3] == '-' && dst[n-2] == '0' { - dst[n-2] = dst[n-1] - dst = dst[:n-1] - } - } - - return dst -} diff --git a/vendor/github.com/aws/smithy-go/encoding/httpbinding/encode.go b/vendor/github.com/aws/smithy-go/encoding/httpbinding/encode.go deleted file mode 100644 index 543e7cf03..000000000 --- a/vendor/github.com/aws/smithy-go/encoding/httpbinding/encode.go +++ /dev/null @@ -1,123 +0,0 @@ -package httpbinding - -import ( - "fmt" - "net/http" - "net/url" - "strconv" - "strings" -) - -const ( - contentLengthHeader = "Content-Length" - floatNaN = "NaN" - floatInfinity = "Infinity" - floatNegInfinity = "-Infinity" -) - -// An Encoder provides encoding of REST URI path, query, and header components -// of an HTTP request. Can also encode a stream as the payload. -// -// Does not support SetFields. -type Encoder struct { - path, rawPath, pathBuffer []byte - - query url.Values - header http.Header -} - -// NewEncoder creates a new encoder from the passed in request. It assumes that -// raw path contains no valuable information at this point, so it passes in path -// as path and raw path for subsequent trans -func NewEncoder(path, query string, headers http.Header) (*Encoder, error) { - return NewEncoderWithRawPath(path, path, query, headers) -} - -// NewHTTPBindingEncoder creates a new encoder from the passed in request. All query and -// header values will be added on top of the request's existing values. Overwriting -// duplicate values. -func NewEncoderWithRawPath(path, rawPath, query string, headers http.Header) (*Encoder, error) { - parseQuery, err := url.ParseQuery(query) - if err != nil { - return nil, fmt.Errorf("failed to parse query string: %w", err) - } - - e := &Encoder{ - path: []byte(path), - rawPath: []byte(rawPath), - query: parseQuery, - header: headers.Clone(), - } - - return e, nil -} - -// Encode returns a REST protocol encoder for encoding HTTP bindings. -// -// Due net/http requiring `Content-Length` to be specified on the http.Request#ContentLength directly. Encode -// will look for whether the header is present, and if so will remove it and set the respective value on http.Request. -// -// Returns any error occurring during encoding. -func (e *Encoder) Encode(req *http.Request) (*http.Request, error) { - req.URL.Path, req.URL.RawPath = string(e.path), string(e.rawPath) - req.URL.RawQuery = e.query.Encode() - - // net/http ignores Content-Length header and requires it to be set on http.Request - if v := e.header.Get(contentLengthHeader); len(v) > 0 { - iv, err := strconv.ParseInt(v, 10, 64) - if err != nil { - return nil, err - } - req.ContentLength = iv - e.header.Del(contentLengthHeader) - } - - req.Header = e.header - - return req, nil -} - -// AddHeader returns a HeaderValue for appending to the given header name -func (e *Encoder) AddHeader(key string) HeaderValue { - return newHeaderValue(e.header, key, true) -} - -// SetHeader returns a HeaderValue for setting the given header name -func (e *Encoder) SetHeader(key string) HeaderValue { - return newHeaderValue(e.header, key, false) -} - -// Headers returns a Header used for encoding headers with the given prefix -func (e *Encoder) Headers(prefix string) Headers { - return Headers{ - header: e.header, - prefix: strings.TrimSpace(prefix), - } -} - -// HasHeader returns if a header with the key specified exists with one or -// more value. -func (e Encoder) HasHeader(key string) bool { - return len(e.header[key]) != 0 -} - -// SetURI returns a URIValue used for setting the given path key -func (e *Encoder) SetURI(key string) URIValue { - return newURIValue(&e.path, &e.rawPath, &e.pathBuffer, key) -} - -// SetQuery returns a QueryValue used for setting the given query key -func (e *Encoder) SetQuery(key string) QueryValue { - return NewQueryValue(e.query, key, false) -} - -// AddQuery returns a QueryValue used for appending the given query key -func (e *Encoder) AddQuery(key string) QueryValue { - return NewQueryValue(e.query, key, true) -} - -// HasQuery returns if a query with the key specified exists with one or -// more values. -func (e *Encoder) HasQuery(key string) bool { - return len(e.query.Get(key)) != 0 -} diff --git a/vendor/github.com/aws/smithy-go/encoding/httpbinding/header.go b/vendor/github.com/aws/smithy-go/encoding/httpbinding/header.go deleted file mode 100644 index f9256e175..000000000 --- a/vendor/github.com/aws/smithy-go/encoding/httpbinding/header.go +++ /dev/null @@ -1,122 +0,0 @@ -package httpbinding - -import ( - "encoding/base64" - "math" - "math/big" - "net/http" - "strconv" - "strings" -) - -// Headers is used to encode header keys using a provided prefix -type Headers struct { - header http.Header - prefix string -} - -// AddHeader returns a HeaderValue used to append values to prefix+key -func (h Headers) AddHeader(key string) HeaderValue { - return h.newHeaderValue(key, true) -} - -// SetHeader returns a HeaderValue used to set the value of prefix+key -func (h Headers) SetHeader(key string) HeaderValue { - return h.newHeaderValue(key, false) -} - -func (h Headers) newHeaderValue(key string, append bool) HeaderValue { - return newHeaderValue(h.header, h.prefix+strings.TrimSpace(key), append) -} - -// HeaderValue is used to encode values to an HTTP header -type HeaderValue struct { - header http.Header - key string - append bool -} - -func newHeaderValue(header http.Header, key string, append bool) HeaderValue { - return HeaderValue{header: header, key: strings.TrimSpace(key), append: append} -} - -func (h HeaderValue) modifyHeader(value string) { - if h.append { - h.header[h.key] = append(h.header[h.key], value) - } else { - h.header[h.key] = append(h.header[h.key][:0], value) - } -} - -// String encodes the value v as the header string value -func (h HeaderValue) String(v string) { - h.modifyHeader(v) -} - -// Byte encodes the value v as a query string value -func (h HeaderValue) Byte(v int8) { - h.Long(int64(v)) -} - -// Short encodes the value v as a query string value -func (h HeaderValue) Short(v int16) { - h.Long(int64(v)) -} - -// Integer encodes the value v as the header string value -func (h HeaderValue) Integer(v int32) { - h.Long(int64(v)) -} - -// Long encodes the value v as the header string value -func (h HeaderValue) Long(v int64) { - h.modifyHeader(strconv.FormatInt(v, 10)) -} - -// Boolean encodes the value v as a query string value -func (h HeaderValue) Boolean(v bool) { - h.modifyHeader(strconv.FormatBool(v)) -} - -// Float encodes the value v as a query string value -func (h HeaderValue) Float(v float32) { - h.float(float64(v), 32) -} - -// Double encodes the value v as a query string value -func (h HeaderValue) Double(v float64) { - h.float(v, 64) -} - -func (h HeaderValue) float(v float64, bitSize int) { - switch { - case math.IsNaN(v): - h.String(floatNaN) - case math.IsInf(v, 1): - h.String(floatInfinity) - case math.IsInf(v, -1): - h.String(floatNegInfinity) - default: - h.modifyHeader(strconv.FormatFloat(v, 'f', -1, bitSize)) - } -} - -// BigInteger encodes the value v as a query string value -func (h HeaderValue) BigInteger(v *big.Int) { - h.modifyHeader(v.String()) -} - -// BigDecimal encodes the value v as a query string value -func (h HeaderValue) BigDecimal(v *big.Float) { - if i, accuracy := v.Int64(); accuracy == big.Exact { - h.Long(i) - return - } - h.modifyHeader(v.Text('e', -1)) -} - -// Blob encodes the value v as a base64 header string value -func (h HeaderValue) Blob(v []byte) { - encodeToString := base64.StdEncoding.EncodeToString(v) - h.modifyHeader(encodeToString) -} diff --git a/vendor/github.com/aws/smithy-go/encoding/httpbinding/path_replace.go b/vendor/github.com/aws/smithy-go/encoding/httpbinding/path_replace.go deleted file mode 100644 index e78926c9a..000000000 --- a/vendor/github.com/aws/smithy-go/encoding/httpbinding/path_replace.go +++ /dev/null @@ -1,108 +0,0 @@ -package httpbinding - -import ( - "bytes" - "fmt" -) - -const ( - uriTokenStart = '{' - uriTokenStop = '}' - uriTokenSkip = '+' -) - -func bufCap(b []byte, n int) []byte { - if cap(b) < n { - return make([]byte, 0, n) - } - - return b[0:0] -} - -// replacePathElement replaces a single element in the path []byte. -// Escape is used to control whether the value will be escaped using Amazon path escape style. -func replacePathElement(path, fieldBuf []byte, key, val string, escape bool) ([]byte, []byte, error) { - fieldBuf = bufCap(fieldBuf, len(key)+3) // { [+] } - fieldBuf = append(fieldBuf, uriTokenStart) - fieldBuf = append(fieldBuf, key...) - - start := bytes.Index(path, fieldBuf) - end := start + len(fieldBuf) - if start < 0 || len(path[end:]) == 0 { - // TODO what to do about error? - return path, fieldBuf, fmt.Errorf("invalid path index, start=%d,end=%d. %s", start, end, path) - } - - encodeSep := true - if path[end] == uriTokenSkip { - // '+' token means do not escape slashes - encodeSep = false - end++ - } - - if escape { - val = EscapePath(val, encodeSep) - } - - if path[end] != uriTokenStop { - return path, fieldBuf, fmt.Errorf("invalid path element, does not contain token stop, %s", path) - } - end++ - - fieldBuf = bufCap(fieldBuf, len(val)) - fieldBuf = append(fieldBuf, val...) - - keyLen := end - start - valLen := len(fieldBuf) - - if keyLen == valLen { - copy(path[start:], fieldBuf) - return path, fieldBuf, nil - } - - newLen := len(path) + (valLen - keyLen) - if len(path) < newLen { - path = path[:cap(path)] - } - if cap(path) < newLen { - newURI := make([]byte, newLen) - copy(newURI, path) - path = newURI - } - - // shift - copy(path[start+valLen:], path[end:]) - path = path[:newLen] - copy(path[start:], fieldBuf) - - return path, fieldBuf, nil -} - -// EscapePath escapes part of a URL path in Amazon style. -func EscapePath(path string, encodeSep bool) string { - var buf bytes.Buffer - for i := 0; i < len(path); i++ { - c := path[i] - if noEscape[c] || (c == '/' && !encodeSep) { - buf.WriteByte(c) - } else { - fmt.Fprintf(&buf, "%%%02X", c) - } - } - return buf.String() -} - -var noEscape [256]bool - -func init() { - for i := 0; i < len(noEscape); i++ { - // AWS expects every character except these to be escaped - noEscape[i] = (i >= 'A' && i <= 'Z') || - (i >= 'a' && i <= 'z') || - (i >= '0' && i <= '9') || - i == '-' || - i == '.' || - i == '_' || - i == '~' - } -} diff --git a/vendor/github.com/aws/smithy-go/encoding/httpbinding/query.go b/vendor/github.com/aws/smithy-go/encoding/httpbinding/query.go deleted file mode 100644 index c2e7d0a20..000000000 --- a/vendor/github.com/aws/smithy-go/encoding/httpbinding/query.go +++ /dev/null @@ -1,107 +0,0 @@ -package httpbinding - -import ( - "encoding/base64" - "math" - "math/big" - "net/url" - "strconv" -) - -// QueryValue is used to encode query key values -type QueryValue struct { - query url.Values - key string - append bool -} - -// NewQueryValue creates a new QueryValue which enables encoding -// a query value into the given url.Values. -func NewQueryValue(query url.Values, key string, append bool) QueryValue { - return QueryValue{ - query: query, - key: key, - append: append, - } -} - -func (qv QueryValue) updateKey(value string) { - if qv.append { - qv.query.Add(qv.key, value) - } else { - qv.query.Set(qv.key, value) - } -} - -// Blob encodes v as a base64 query string value -func (qv QueryValue) Blob(v []byte) { - encodeToString := base64.StdEncoding.EncodeToString(v) - qv.updateKey(encodeToString) -} - -// Boolean encodes v as a query string value -func (qv QueryValue) Boolean(v bool) { - qv.updateKey(strconv.FormatBool(v)) -} - -// String encodes v as a query string value -func (qv QueryValue) String(v string) { - qv.updateKey(v) -} - -// Byte encodes v as a query string value -func (qv QueryValue) Byte(v int8) { - qv.Long(int64(v)) -} - -// Short encodes v as a query string value -func (qv QueryValue) Short(v int16) { - qv.Long(int64(v)) -} - -// Integer encodes v as a query string value -func (qv QueryValue) Integer(v int32) { - qv.Long(int64(v)) -} - -// Long encodes v as a query string value -func (qv QueryValue) Long(v int64) { - qv.updateKey(strconv.FormatInt(v, 10)) -} - -// Float encodes v as a query string value -func (qv QueryValue) Float(v float32) { - qv.float(float64(v), 32) -} - -// Double encodes v as a query string value -func (qv QueryValue) Double(v float64) { - qv.float(v, 64) -} - -func (qv QueryValue) float(v float64, bitSize int) { - switch { - case math.IsNaN(v): - qv.String(floatNaN) - case math.IsInf(v, 1): - qv.String(floatInfinity) - case math.IsInf(v, -1): - qv.String(floatNegInfinity) - default: - qv.updateKey(strconv.FormatFloat(v, 'f', -1, bitSize)) - } -} - -// BigInteger encodes v as a query string value -func (qv QueryValue) BigInteger(v *big.Int) { - qv.updateKey(v.String()) -} - -// BigDecimal encodes v as a query string value -func (qv QueryValue) BigDecimal(v *big.Float) { - if i, accuracy := v.Int64(); accuracy == big.Exact { - qv.Long(i) - return - } - qv.updateKey(v.Text('e', -1)) -} diff --git a/vendor/github.com/aws/smithy-go/encoding/httpbinding/uri.go b/vendor/github.com/aws/smithy-go/encoding/httpbinding/uri.go deleted file mode 100644 index f04e11984..000000000 --- a/vendor/github.com/aws/smithy-go/encoding/httpbinding/uri.go +++ /dev/null @@ -1,111 +0,0 @@ -package httpbinding - -import ( - "math" - "math/big" - "strconv" - "strings" -) - -// URIValue is used to encode named URI parameters -type URIValue struct { - path, rawPath, buffer *[]byte - - key string -} - -func newURIValue(path *[]byte, rawPath *[]byte, buffer *[]byte, key string) URIValue { - return URIValue{path: path, rawPath: rawPath, buffer: buffer, key: key} -} - -func (u URIValue) modifyURI(value string) (err error) { - *u.path, *u.buffer, err = replacePathElement(*u.path, *u.buffer, u.key, value, false) - if err != nil { - return err - } - *u.rawPath, *u.buffer, err = replacePathElement(*u.rawPath, *u.buffer, u.key, value, true) - return err -} - -// Boolean encodes v as a URI string value -func (u URIValue) Boolean(v bool) error { - return u.modifyURI(strconv.FormatBool(v)) -} - -// String encodes v as a URI string value -func (u URIValue) String(v string) error { - return u.modifyURI(v) -} - -// Byte encodes v as a URI string value -func (u URIValue) Byte(v int8) error { - return u.Long(int64(v)) -} - -// Short encodes v as a URI string value -func (u URIValue) Short(v int16) error { - return u.Long(int64(v)) -} - -// Integer encodes v as a URI string value -func (u URIValue) Integer(v int32) error { - return u.Long(int64(v)) -} - -// Long encodes v as a URI string value -func (u URIValue) Long(v int64) error { - return u.modifyURI(strconv.FormatInt(v, 10)) -} - -// Float encodes v as a query string value -func (u URIValue) Float(v float32) error { - return u.float(float64(v), 32) -} - -// Double encodes v as a query string value -func (u URIValue) Double(v float64) error { - return u.float(v, 64) -} - -func (u URIValue) float(v float64, bitSize int) error { - switch { - case math.IsNaN(v): - return u.String(floatNaN) - case math.IsInf(v, 1): - return u.String(floatInfinity) - case math.IsInf(v, -1): - return u.String(floatNegInfinity) - default: - return u.modifyURI(strconv.FormatFloat(v, 'f', -1, bitSize)) - } -} - -// BigInteger encodes v as a query string value -func (u URIValue) BigInteger(v *big.Int) error { - return u.modifyURI(v.String()) -} - -// BigDecimal encodes v as a query string value -func (u URIValue) BigDecimal(v *big.Float) error { - if i, accuracy := v.Int64(); accuracy == big.Exact { - return u.Long(i) - } - return u.modifyURI(v.Text('e', -1)) -} - -// SplitURI parses a Smithy HTTP binding trait URI -func SplitURI(uri string) (path, query string) { - queryStart := strings.IndexRune(uri, '?') - if queryStart == -1 { - path = uri - return path, query - } - - path = uri[:queryStart] - if queryStart+1 >= len(uri) { - return path, query - } - query = uri[queryStart+1:] - - return path, query -} diff --git a/vendor/github.com/aws/smithy-go/encoding/json/array.go b/vendor/github.com/aws/smithy-go/encoding/json/array.go deleted file mode 100644 index 7a232f660..000000000 --- a/vendor/github.com/aws/smithy-go/encoding/json/array.go +++ /dev/null @@ -1,35 +0,0 @@ -package json - -import ( - "bytes" -) - -// Array represents the encoding of a JSON Array -type Array struct { - w *bytes.Buffer - writeComma bool - scratch *[]byte -} - -func newArray(w *bytes.Buffer, scratch *[]byte) *Array { - w.WriteRune(leftBracket) - return &Array{w: w, scratch: scratch} -} - -// Value adds a new element to the JSON Array. -// Returns a Value type that is used to encode -// the array element. -func (a *Array) Value() Value { - if a.writeComma { - a.w.WriteRune(comma) - } else { - a.writeComma = true - } - - return newValue(a.w, a.scratch) -} - -// Close encodes the end of the JSON Array -func (a *Array) Close() { - a.w.WriteRune(rightBracket) -} diff --git a/vendor/github.com/aws/smithy-go/encoding/json/constants.go b/vendor/github.com/aws/smithy-go/encoding/json/constants.go deleted file mode 100644 index 91044092a..000000000 --- a/vendor/github.com/aws/smithy-go/encoding/json/constants.go +++ /dev/null @@ -1,15 +0,0 @@ -package json - -const ( - leftBrace = '{' - rightBrace = '}' - - leftBracket = '[' - rightBracket = ']' - - comma = ',' - quote = '"' - colon = ':' - - null = "null" -) diff --git a/vendor/github.com/aws/smithy-go/encoding/json/decoder_util.go b/vendor/github.com/aws/smithy-go/encoding/json/decoder_util.go deleted file mode 100644 index 7050c85b3..000000000 --- a/vendor/github.com/aws/smithy-go/encoding/json/decoder_util.go +++ /dev/null @@ -1,139 +0,0 @@ -package json - -import ( - "bytes" - "encoding/json" - "fmt" - "io" -) - -// DiscardUnknownField discards unknown fields from a decoder body. -// This function is useful while deserializing a JSON body with additional -// unknown information that should be discarded. -func DiscardUnknownField(decoder *json.Decoder) error { - // This deliberately does not share logic with CollectUnknownField, even - // though it could, because if we were to delegate to that then we'd incur - // extra allocations and general memory usage. - v, err := decoder.Token() - if err == io.EOF { - return nil - } - if err != nil { - return err - } - - if _, ok := v.(json.Delim); ok { - for decoder.More() { - err = DiscardUnknownField(decoder) - } - endToken, err := decoder.Token() - if err != nil { - return err - } - if _, ok := endToken.(json.Delim); !ok { - return fmt.Errorf("invalid JSON : expected json delimiter, found %T %v", - endToken, endToken) - } - } - - return nil -} - -// CollectUnknownField grabs the contents of unknown fields from the decoder body -// and returns them as a byte slice. This is useful for skipping unknown fields without -// completely discarding them. -func CollectUnknownField(decoder *json.Decoder) ([]byte, error) { - result, err := collectUnknownField(decoder) - if err != nil { - return nil, err - } - - buff := bytes.NewBuffer(nil) - encoder := json.NewEncoder(buff) - - if err := encoder.Encode(result); err != nil { - return nil, err - } - - return buff.Bytes(), nil -} - -func collectUnknownField(decoder *json.Decoder) (interface{}, error) { - // Grab the initial value. This could either be a concrete value like a string or a a - // delimiter. - token, err := decoder.Token() - if err == io.EOF { - return nil, nil - } - if err != nil { - return nil, err - } - - // If it's an array or object, we'll need to recurse. - delim, ok := token.(json.Delim) - if ok { - var result interface{} - if delim == '{' { - result, err = collectUnknownObject(decoder) - if err != nil { - return nil, err - } - } else { - result, err = collectUnknownArray(decoder) - if err != nil { - return nil, err - } - } - - // Discard the closing token. decoder.Token handles checking for matching delimiters - if _, err := decoder.Token(); err != nil { - return nil, err - } - return result, nil - } - - return token, nil -} - -func collectUnknownArray(decoder *json.Decoder) ([]interface{}, error) { - // We need to create an empty array here instead of a nil array, since by getting - // into this function at all we necessarily have seen a non-nil list. - array := []interface{}{} - - for decoder.More() { - value, err := collectUnknownField(decoder) - if err != nil { - return nil, err - } - array = append(array, value) - } - - return array, nil -} - -func collectUnknownObject(decoder *json.Decoder) (map[string]interface{}, error) { - object := make(map[string]interface{}) - - for decoder.More() { - key, err := collectUnknownField(decoder) - if err != nil { - return nil, err - } - - // Keys have to be strings, which is particularly important as the encoder - // won't except a map with interface{} keys - stringKey, ok := key.(string) - if !ok { - return nil, fmt.Errorf("expected string key, found %T", key) - } - - value, err := collectUnknownField(decoder) - if err != nil { - return nil, err - } - - object[stringKey] = value - } - - return object, nil -} diff --git a/vendor/github.com/aws/smithy-go/encoding/json/encoder.go b/vendor/github.com/aws/smithy-go/encoding/json/encoder.go deleted file mode 100644 index 8772953f1..000000000 --- a/vendor/github.com/aws/smithy-go/encoding/json/encoder.go +++ /dev/null @@ -1,30 +0,0 @@ -package json - -import ( - "bytes" -) - -// Encoder is JSON encoder that supports construction of JSON values -// using methods. -type Encoder struct { - w *bytes.Buffer - Value -} - -// NewEncoder returns a new JSON encoder -func NewEncoder() *Encoder { - writer := bytes.NewBuffer(nil) - scratch := make([]byte, 64) - - return &Encoder{w: writer, Value: newValue(writer, &scratch)} -} - -// String returns the String output of the JSON encoder -func (e Encoder) String() string { - return e.w.String() -} - -// Bytes returns the []byte slice of the JSON encoder -func (e Encoder) Bytes() []byte { - return e.w.Bytes() -} diff --git a/vendor/github.com/aws/smithy-go/encoding/json/escape.go b/vendor/github.com/aws/smithy-go/encoding/json/escape.go deleted file mode 100644 index d984d0cdc..000000000 --- a/vendor/github.com/aws/smithy-go/encoding/json/escape.go +++ /dev/null @@ -1,198 +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. - -// Copied and modified from Go 1.8 stdlib's encoding/json/#safeSet - -package json - -import ( - "bytes" - "unicode/utf8" -) - -// safeSet holds the value true if the ASCII character with the given array -// position can be represented inside a JSON string without any further -// escaping. -// -// All values are true except for the ASCII control characters (0-31), the -// double quote ("), and the backslash character ("\"). -var safeSet = [utf8.RuneSelf]bool{ - ' ': true, - '!': true, - '"': false, - '#': true, - '$': true, - '%': true, - '&': true, - '\'': true, - '(': true, - ')': true, - '*': true, - '+': true, - ',': true, - '-': true, - '.': true, - '/': true, - '0': true, - '1': true, - '2': true, - '3': true, - '4': true, - '5': true, - '6': true, - '7': true, - '8': true, - '9': true, - ':': true, - ';': true, - '<': true, - '=': true, - '>': true, - '?': true, - '@': true, - 'A': true, - 'B': true, - 'C': true, - 'D': true, - 'E': true, - 'F': true, - 'G': true, - 'H': true, - 'I': true, - 'J': true, - 'K': true, - 'L': true, - 'M': true, - 'N': true, - 'O': true, - 'P': true, - 'Q': true, - 'R': true, - 'S': true, - 'T': true, - 'U': true, - 'V': true, - 'W': true, - 'X': true, - 'Y': true, - 'Z': true, - '[': true, - '\\': false, - ']': true, - '^': true, - '_': true, - '`': true, - 'a': true, - 'b': true, - 'c': true, - 'd': true, - 'e': true, - 'f': true, - 'g': true, - 'h': true, - 'i': true, - 'j': true, - 'k': true, - 'l': true, - 'm': true, - 'n': true, - 'o': true, - 'p': true, - 'q': true, - 'r': true, - 's': true, - 't': true, - 'u': true, - 'v': true, - 'w': true, - 'x': true, - 'y': true, - 'z': true, - '{': true, - '|': true, - '}': true, - '~': true, - '\u007f': true, -} - -// copied from Go 1.8 stdlib's encoding/json/#hex -var hex = "0123456789abcdef" - -// escapeStringBytes escapes and writes the passed in string bytes to the dst -// buffer -// -// Copied and modifed from Go 1.8 stdlib's encodeing/json/#encodeState.stringBytes -func escapeStringBytes(e *bytes.Buffer, s []byte) { - e.WriteByte('"') - start := 0 - for i := 0; i < len(s); { - if b := s[i]; b < utf8.RuneSelf { - if safeSet[b] { - i++ - continue - } - if start < i { - e.Write(s[start:i]) - } - switch b { - case '\\', '"': - e.WriteByte('\\') - e.WriteByte(b) - case '\n': - e.WriteByte('\\') - e.WriteByte('n') - case '\r': - e.WriteByte('\\') - e.WriteByte('r') - case '\t': - e.WriteByte('\\') - e.WriteByte('t') - default: - // This encodes bytes < 0x20 except for \t, \n and \r. - // If escapeHTML is set, it also escapes <, >, and & - // because they can lead to security holes when - // user-controlled strings are rendered into JSON - // and served to some browsers. - e.WriteString(`\u00`) - e.WriteByte(hex[b>>4]) - e.WriteByte(hex[b&0xF]) - } - i++ - start = i - continue - } - c, size := utf8.DecodeRune(s[i:]) - if c == utf8.RuneError && size == 1 { - if start < i { - e.Write(s[start:i]) - } - e.WriteString(`\ufffd`) - i += size - start = i - continue - } - // U+2028 is LINE SEPARATOR. - // U+2029 is PARAGRAPH SEPARATOR. - // They are both technically valid characters in JSON strings, - // but don't work in JSONP, which has to be evaluated as JavaScript, - // and can lead to security holes there. It is valid JSON to - // escape them, so we do so unconditionally. - // See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion. - if c == '\u2028' || c == '\u2029' { - if start < i { - e.Write(s[start:i]) - } - e.WriteString(`\u202`) - e.WriteByte(hex[c&0xF]) - i += size - start = i - continue - } - i += size - } - if start < len(s) { - e.Write(s[start:]) - } - e.WriteByte('"') -} diff --git a/vendor/github.com/aws/smithy-go/encoding/json/object.go b/vendor/github.com/aws/smithy-go/encoding/json/object.go deleted file mode 100644 index 722346d03..000000000 --- a/vendor/github.com/aws/smithy-go/encoding/json/object.go +++ /dev/null @@ -1,40 +0,0 @@ -package json - -import ( - "bytes" -) - -// Object represents the encoding of a JSON Object type -type Object struct { - w *bytes.Buffer - writeComma bool - scratch *[]byte -} - -func newObject(w *bytes.Buffer, scratch *[]byte) *Object { - w.WriteRune(leftBrace) - return &Object{w: w, scratch: scratch} -} - -func (o *Object) writeKey(key string) { - escapeStringBytes(o.w, []byte(key)) - o.w.WriteRune(colon) -} - -// Key adds the given named key to the JSON object. -// Returns a Value encoder that should be used to encode -// a JSON value type. -func (o *Object) Key(name string) Value { - if o.writeComma { - o.w.WriteRune(comma) - } else { - o.writeComma = true - } - o.writeKey(name) - return newValue(o.w, o.scratch) -} - -// Close encodes the end of the JSON Object -func (o *Object) Close() { - o.w.WriteRune(rightBrace) -} diff --git a/vendor/github.com/aws/smithy-go/encoding/json/value.go b/vendor/github.com/aws/smithy-go/encoding/json/value.go deleted file mode 100644 index b41ff1e15..000000000 --- a/vendor/github.com/aws/smithy-go/encoding/json/value.go +++ /dev/null @@ -1,149 +0,0 @@ -package json - -import ( - "bytes" - "encoding/base64" - "math/big" - "strconv" - - "github.com/aws/smithy-go/encoding" -) - -// Value represents a JSON Value type -// JSON Value types: Object, Array, String, Number, Boolean, and Null -type Value struct { - w *bytes.Buffer - scratch *[]byte -} - -// newValue returns a new Value encoder -func newValue(w *bytes.Buffer, scratch *[]byte) Value { - return Value{w: w, scratch: scratch} -} - -// String encodes v as a JSON string -func (jv Value) String(v string) { - escapeStringBytes(jv.w, []byte(v)) -} - -// Byte encodes v as a JSON number -func (jv Value) Byte(v int8) { - jv.Long(int64(v)) -} - -// Short encodes v as a JSON number -func (jv Value) Short(v int16) { - jv.Long(int64(v)) -} - -// Integer encodes v as a JSON number -func (jv Value) Integer(v int32) { - jv.Long(int64(v)) -} - -// Long encodes v as a JSON number -func (jv Value) Long(v int64) { - *jv.scratch = strconv.AppendInt((*jv.scratch)[:0], v, 10) - jv.w.Write(*jv.scratch) -} - -// ULong encodes v as a JSON number -func (jv Value) ULong(v uint64) { - *jv.scratch = strconv.AppendUint((*jv.scratch)[:0], v, 10) - jv.w.Write(*jv.scratch) -} - -// Float encodes v as a JSON number -func (jv Value) Float(v float32) { - jv.float(float64(v), 32) -} - -// Double encodes v as a JSON number -func (jv Value) Double(v float64) { - jv.float(v, 64) -} - -func (jv Value) float(v float64, bits int) { - *jv.scratch = encoding.EncodeFloat((*jv.scratch)[:0], v, bits) - jv.w.Write(*jv.scratch) -} - -// Boolean encodes v as a JSON boolean -func (jv Value) Boolean(v bool) { - *jv.scratch = strconv.AppendBool((*jv.scratch)[:0], v) - jv.w.Write(*jv.scratch) -} - -// Base64EncodeBytes writes v as a base64 value in JSON string -func (jv Value) Base64EncodeBytes(v []byte) { - encodeByteSlice(jv.w, (*jv.scratch)[:0], v) -} - -// Write writes v directly to the JSON document -func (jv Value) Write(v []byte) { - jv.w.Write(v) -} - -// Array returns a new Array encoder -func (jv Value) Array() *Array { - return newArray(jv.w, jv.scratch) -} - -// Object returns a new Object encoder -func (jv Value) Object() *Object { - return newObject(jv.w, jv.scratch) -} - -// Null encodes a null JSON value -func (jv Value) Null() { - jv.w.WriteString(null) -} - -// BigInteger encodes v as JSON value -func (jv Value) BigInteger(v *big.Int) { - jv.w.Write([]byte(v.Text(10))) -} - -// BigDecimal encodes v as JSON value -func (jv Value) BigDecimal(v *big.Float) { - if i, accuracy := v.Int64(); accuracy == big.Exact { - jv.Long(i) - return - } - // TODO: Should this try to match ES6 ToString similar to stdlib JSON? - jv.w.Write([]byte(v.Text('e', -1))) -} - -// Based on encoding/json encodeByteSlice from the Go Standard Library -// https://golang.org/src/encoding/json/encode.go -func encodeByteSlice(w *bytes.Buffer, scratch []byte, v []byte) { - if v == nil { - w.WriteString(null) - return - } - - w.WriteRune(quote) - - encodedLen := base64.StdEncoding.EncodedLen(len(v)) - if encodedLen <= len(scratch) { - // If the encoded bytes fit in e.scratch, avoid an extra - // allocation and use the cheaper Encoding.Encode. - dst := scratch[:encodedLen] - base64.StdEncoding.Encode(dst, v) - w.Write(dst) - } else if encodedLen <= 1024 { - // The encoded bytes are short enough to allocate for, and - // Encoding.Encode is still cheaper. - dst := make([]byte, encodedLen) - base64.StdEncoding.Encode(dst, v) - w.Write(dst) - } else { - // The encoded bytes are too long to cheaply allocate, and - // Encoding.Encode is no longer noticeably cheaper. - enc := base64.NewEncoder(base64.StdEncoding, w) - enc.Write(v) - enc.Close() - } - - w.WriteRune(quote) -} diff --git a/vendor/github.com/aws/smithy-go/encoding/xml/array.go b/vendor/github.com/aws/smithy-go/encoding/xml/array.go deleted file mode 100644 index 508f3c997..000000000 --- a/vendor/github.com/aws/smithy-go/encoding/xml/array.go +++ /dev/null @@ -1,49 +0,0 @@ -package xml - -// arrayMemberWrapper is the default member wrapper tag name for XML Array type -var arrayMemberWrapper = StartElement{ - Name: Name{Local: "member"}, -} - -// Array represents the encoding of a XML array type -type Array struct { - w writer - scratch *[]byte - - // member start element is the array member wrapper start element - memberStartElement StartElement - - // isFlattened indicates if the array is a flattened array. - isFlattened bool -} - -// newArray returns an array encoder. -// It also takes in the member start element, array start element. -// It takes in a isFlattened bool, indicating that an array is flattened array. -// -// A wrapped array ["value1", "value2"] is represented as -// `value1value2`. - -// A flattened array `someList: ["value1", "value2"]` is represented as -// `value1value2`. -func newArray(w writer, scratch *[]byte, memberStartElement StartElement, arrayStartElement StartElement, isFlattened bool) *Array { - var memberWrapper = memberStartElement - if isFlattened { - memberWrapper = arrayStartElement - } - - return &Array{ - w: w, - scratch: scratch, - memberStartElement: memberWrapper, - isFlattened: isFlattened, - } -} - -// Member adds a new member to the XML array. -// It returns a Value encoder. -func (a *Array) Member() Value { - v := newValue(a.w, a.scratch, a.memberStartElement) - v.isFlattened = a.isFlattened - return v -} diff --git a/vendor/github.com/aws/smithy-go/encoding/xml/constants.go b/vendor/github.com/aws/smithy-go/encoding/xml/constants.go deleted file mode 100644 index ccee90a63..000000000 --- a/vendor/github.com/aws/smithy-go/encoding/xml/constants.go +++ /dev/null @@ -1,10 +0,0 @@ -package xml - -const ( - leftAngleBracket = '<' - rightAngleBracket = '>' - forwardSlash = '/' - colon = ':' - equals = '=' - quote = '"' -) diff --git a/vendor/github.com/aws/smithy-go/encoding/xml/doc.go b/vendor/github.com/aws/smithy-go/encoding/xml/doc.go deleted file mode 100644 index f9200093e..000000000 --- a/vendor/github.com/aws/smithy-go/encoding/xml/doc.go +++ /dev/null @@ -1,49 +0,0 @@ -/* -Package xml holds the XMl encoder utility. This utility is written in accordance to our design to delegate to -shape serializer function in which a xml.Value will be passed around. - -Resources followed: https://smithy.io/2.0/spec/protocol-traits.html#xml-bindings - -Member Element - -Member element should be used to encode xml shapes into xml elements except for flattened xml shapes. Member element -write their own element start tag. These elements should always be closed. - -Flattened Element - -Flattened element should be used to encode shapes marked with flattened trait into xml elements. Flattened element -do not write a start tag, and thus should not be closed. - -Simple types encoding - -All simple type methods on value such as String(), Long() etc; auto close the associated member element. - -Array - -Array returns the collection encoder. It has two modes, wrapped and flattened encoding. - -Wrapped arrays have two methods Array() and ArrayWithCustomName() which facilitate array member wrapping. -By default, a wrapped array members are wrapped with `member` named start element. - - appletree - -Flattened arrays rely on Value being marked as flattened. -If a shape is marked as flattened, Array() will use the shape element name as wrapper for array elements. - - appletree - -Map - -Map is the map encoder. It has two modes, wrapped and flattened encoding. - -Wrapped map has Array() method, which facilitate map member wrapping. -By default, a wrapped map members are wrapped with `entry` named start element. - - appletreesnowice - -Flattened map rely on Value being marked as flattened. -If a shape is marked as flattened, Map() will use the shape element name as wrapper for map entry elements. - - appletreesnowice -*/ -package xml diff --git a/vendor/github.com/aws/smithy-go/encoding/xml/element.go b/vendor/github.com/aws/smithy-go/encoding/xml/element.go deleted file mode 100644 index ae84e7999..000000000 --- a/vendor/github.com/aws/smithy-go/encoding/xml/element.go +++ /dev/null @@ -1,91 +0,0 @@ -// 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. - -// Copied and modified from Go 1.14 stdlib's encoding/xml - -package xml - -// A Name represents an XML name (Local) annotated -// with a name space identifier (Space). -// In tokens returned by Decoder.Token, the Space identifier -// is given as a canonical URL, not the short prefix used -// in the document being parsed. -type Name struct { - Space, Local string -} - -// An Attr represents an attribute in an XML element (Name=Value). -type Attr struct { - Name Name - Value string -} - -/* -NewAttribute returns a pointer to an attribute. -It takes in a local name aka attribute name, and value -representing the attribute value. -*/ -func NewAttribute(local, value string) Attr { - return Attr{ - Name: Name{ - Local: local, - }, - Value: value, - } -} - -/* -NewNamespaceAttribute returns a pointer to an attribute. -It takes in a local name aka attribute name, and value -representing the attribute value. - -NewNamespaceAttribute appends `xmlns:` in front of namespace -prefix. - -For creating a name space attribute representing -`xmlns:prefix="http://example.com`, the breakdown would be: -local = "prefix" -value = "http://example.com" -*/ -func NewNamespaceAttribute(local, value string) Attr { - attr := NewAttribute(local, value) - - // default name space identifier - attr.Name.Space = "xmlns" - return attr -} - -// A StartElement represents an XML start element. -type StartElement struct { - Name Name - Attr []Attr -} - -// Copy creates a new copy of StartElement. -func (e StartElement) Copy() StartElement { - attrs := make([]Attr, len(e.Attr)) - copy(attrs, e.Attr) - e.Attr = attrs - return e -} - -// End returns the corresponding XML end element. -func (e StartElement) End() EndElement { - return EndElement{e.Name} -} - -// returns true if start element local name is empty -func (e StartElement) isZero() bool { - return len(e.Name.Local) == 0 -} - -// An EndElement represents an XML end element. -type EndElement struct { - Name Name -} - -// returns true if end element local name is empty -func (e EndElement) isZero() bool { - return len(e.Name.Local) == 0 -} diff --git a/vendor/github.com/aws/smithy-go/encoding/xml/encoder.go b/vendor/github.com/aws/smithy-go/encoding/xml/encoder.go deleted file mode 100644 index 16fb3dddb..000000000 --- a/vendor/github.com/aws/smithy-go/encoding/xml/encoder.go +++ /dev/null @@ -1,51 +0,0 @@ -package xml - -// writer interface used by the xml encoder to write an encoded xml -// document in a writer. -type writer interface { - - // Write takes in a byte slice and returns number of bytes written and error - Write(p []byte) (n int, err error) - - // WriteRune takes in a rune and returns number of bytes written and error - WriteRune(r rune) (n int, err error) - - // WriteString takes in a string and returns number of bytes written and error - WriteString(s string) (n int, err error) - - // String method returns a string - String() string - - // Bytes return a byte slice. - Bytes() []byte -} - -// Encoder is an XML encoder that supports construction of XML values -// using methods. The encoder takes in a writer and maintains a scratch buffer. -type Encoder struct { - w writer - scratch *[]byte -} - -// NewEncoder returns an XML encoder -func NewEncoder(w writer) *Encoder { - scratch := make([]byte, 64) - - return &Encoder{w: w, scratch: &scratch} -} - -// String returns the string output of the XML encoder -func (e Encoder) String() string { - return e.w.String() -} - -// Bytes returns the []byte slice of the XML encoder -func (e Encoder) Bytes() []byte { - return e.w.Bytes() -} - -// RootElement builds a root element encoding -// It writes it's start element tag. The value should be closed. -func (e Encoder) RootElement(element StartElement) Value { - return newValue(e.w, e.scratch, element) -} diff --git a/vendor/github.com/aws/smithy-go/encoding/xml/error_utils.go b/vendor/github.com/aws/smithy-go/encoding/xml/error_utils.go deleted file mode 100644 index f3db6ccca..000000000 --- a/vendor/github.com/aws/smithy-go/encoding/xml/error_utils.go +++ /dev/null @@ -1,51 +0,0 @@ -package xml - -import ( - "encoding/xml" - "fmt" - "io" -) - -// ErrorComponents represents the error response fields -// that will be deserialized from an xml error response body -type ErrorComponents struct { - Code string - Message string -} - -// GetErrorResponseComponents returns the error fields from an xml error response body -func GetErrorResponseComponents(r io.Reader, noErrorWrapping bool) (ErrorComponents, error) { - if noErrorWrapping { - var errResponse noWrappedErrorResponse - if err := xml.NewDecoder(r).Decode(&errResponse); err != nil && err != io.EOF { - return ErrorComponents{}, fmt.Errorf("error while deserializing xml error response: %w", err) - } - return ErrorComponents{ - Code: errResponse.Code, - Message: errResponse.Message, - }, nil - } - - var errResponse wrappedErrorResponse - if err := xml.NewDecoder(r).Decode(&errResponse); err != nil && err != io.EOF { - return ErrorComponents{}, fmt.Errorf("error while deserializing xml error response: %w", err) - } - return ErrorComponents{ - Code: errResponse.Code, - Message: errResponse.Message, - }, nil -} - -// noWrappedErrorResponse represents the error response body with -// no internal ... -type wrappedErrorResponse struct { - Code string `xml:"Error>Code"` - Message string `xml:"Error>Message"` -} diff --git a/vendor/github.com/aws/smithy-go/encoding/xml/escape.go b/vendor/github.com/aws/smithy-go/encoding/xml/escape.go deleted file mode 100644 index 1c5479af6..000000000 --- a/vendor/github.com/aws/smithy-go/encoding/xml/escape.go +++ /dev/null @@ -1,137 +0,0 @@ -// 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. - -// Copied and modified from Go 1.14 stdlib's encoding/xml - -package xml - -import ( - "unicode/utf8" -) - -// Copied from Go 1.14 stdlib's encoding/xml -var ( - escQuot = []byte(""") // shorter than """ - escApos = []byte("'") // shorter than "'" - escAmp = []byte("&") - escLT = []byte("<") - escGT = []byte(">") - escTab = []byte(" ") - escNL = []byte(" ") - escCR = []byte(" ") - escFFFD = []byte("\uFFFD") // Unicode replacement character - - // Additional Escapes - escNextLine = []byte("…") - escLS = []byte("
") -) - -// Decide whether the given rune is in the XML Character Range, per -// the Char production of https://www.xml.com/axml/testaxml.htm, -// Section 2.2 Characters. -func isInCharacterRange(r rune) (inrange bool) { - return r == 0x09 || - r == 0x0A || - r == 0x0D || - r >= 0x20 && r <= 0xD7FF || - r >= 0xE000 && r <= 0xFFFD || - r >= 0x10000 && r <= 0x10FFFF -} - -// TODO: When do we need to escape the string? -// Based on encoding/xml escapeString from the Go Standard Library. -// https://golang.org/src/encoding/xml/xml.go -func escapeString(e writer, s string) { - var esc []byte - last := 0 - for i := 0; i < len(s); { - r, width := utf8.DecodeRuneInString(s[i:]) - i += width - switch r { - case '"': - esc = escQuot - case '\'': - esc = escApos - case '&': - esc = escAmp - case '<': - esc = escLT - case '>': - esc = escGT - case '\t': - esc = escTab - case '\n': - esc = escNL - case '\r': - esc = escCR - case '\u0085': - // Not escaped by stdlib - esc = escNextLine - case '\u2028': - // Not escaped by stdlib - esc = escLS - default: - if !isInCharacterRange(r) || (r == 0xFFFD && width == 1) { - esc = escFFFD - break - } - continue - } - e.WriteString(s[last : i-width]) - e.Write(esc) - last = i - } - e.WriteString(s[last:]) -} - -// escapeText writes to w the properly escaped XML equivalent -// of the plain text data s. If escapeNewline is true, newline -// characters will be escaped. -// -// Based on encoding/xml escapeText from the Go Standard Library. -// https://golang.org/src/encoding/xml/xml.go -func escapeText(e writer, s []byte) { - var esc []byte - last := 0 - for i := 0; i < len(s); { - r, width := utf8.DecodeRune(s[i:]) - i += width - switch r { - case '"': - esc = escQuot - case '\'': - esc = escApos - case '&': - esc = escAmp - case '<': - esc = escLT - case '>': - esc = escGT - case '\t': - esc = escTab - case '\n': - // This always escapes newline, which is different than stdlib's optional - // escape of new line. - esc = escNL - case '\r': - esc = escCR - case '\u0085': - // Not escaped by stdlib - esc = escNextLine - case '\u2028': - // Not escaped by stdlib - esc = escLS - default: - if !isInCharacterRange(r) || (r == 0xFFFD && width == 1) { - esc = escFFFD - break - } - continue - } - e.Write(s[last : i-width]) - e.Write(esc) - last = i - } - e.Write(s[last:]) -} diff --git a/vendor/github.com/aws/smithy-go/encoding/xml/map.go b/vendor/github.com/aws/smithy-go/encoding/xml/map.go deleted file mode 100644 index e42858965..000000000 --- a/vendor/github.com/aws/smithy-go/encoding/xml/map.go +++ /dev/null @@ -1,53 +0,0 @@ -package xml - -// mapEntryWrapper is the default member wrapper start element for XML Map entry -var mapEntryWrapper = StartElement{ - Name: Name{Local: "entry"}, -} - -// Map represents the encoding of a XML map type -type Map struct { - w writer - scratch *[]byte - - // member start element is the map entry wrapper start element - memberStartElement StartElement - - // isFlattened returns true if the map is a flattened map - isFlattened bool -} - -// newMap returns a map encoder which sets the default map -// entry wrapper to `entry`. -// -// A map `someMap : {{key:"abc", value:"123"}}` is represented as -// `abc123`. -func newMap(w writer, scratch *[]byte) *Map { - return &Map{ - w: w, - scratch: scratch, - memberStartElement: mapEntryWrapper, - } -} - -// newFlattenedMap returns a map encoder which sets the map -// entry wrapper to the passed in memberWrapper`. -// -// A flattened map `someMap : {{key:"abc", value:"123"}}` is represented as -// `abc123`. -func newFlattenedMap(w writer, scratch *[]byte, memberWrapper StartElement) *Map { - return &Map{ - w: w, - scratch: scratch, - memberStartElement: memberWrapper, - isFlattened: true, - } -} - -// Entry returns a Value encoder with map's element. -// It writes the member wrapper start tag for each entry. -func (m *Map) Entry() Value { - v := newValue(m.w, m.scratch, m.memberStartElement) - v.isFlattened = m.isFlattened - return v -} diff --git a/vendor/github.com/aws/smithy-go/encoding/xml/value.go b/vendor/github.com/aws/smithy-go/encoding/xml/value.go deleted file mode 100644 index 09434b2c0..000000000 --- a/vendor/github.com/aws/smithy-go/encoding/xml/value.go +++ /dev/null @@ -1,302 +0,0 @@ -package xml - -import ( - "encoding/base64" - "fmt" - "math/big" - "strconv" - - "github.com/aws/smithy-go/encoding" -) - -// Value represents an XML Value type -// XML Value types: Object, Array, Map, String, Number, Boolean. -type Value struct { - w writer - scratch *[]byte - - // xml start element is the associated start element for the Value - startElement StartElement - - // indicates if the Value represents a flattened shape - isFlattened bool -} - -// newFlattenedValue returns a Value encoder. newFlattenedValue does NOT write the start element tag -func newFlattenedValue(w writer, scratch *[]byte, startElement StartElement) Value { - return Value{ - w: w, - scratch: scratch, - startElement: startElement, - } -} - -// newValue writes the start element xml tag and returns a Value -func newValue(w writer, scratch *[]byte, startElement StartElement) Value { - writeStartElement(w, startElement) - return Value{w: w, scratch: scratch, startElement: startElement} -} - -// writeStartElement takes in a start element and writes it. -// It handles namespace, attributes in start element. -func writeStartElement(w writer, el StartElement) error { - if el.isZero() { - return fmt.Errorf("xml start element cannot be nil") - } - - w.WriteRune(leftAngleBracket) - - if len(el.Name.Space) != 0 { - escapeString(w, el.Name.Space) - w.WriteRune(colon) - } - escapeString(w, el.Name.Local) - for _, attr := range el.Attr { - w.WriteRune(' ') - writeAttribute(w, &attr) - } - - w.WriteRune(rightAngleBracket) - return nil -} - -// writeAttribute writes an attribute from a provided Attribute -// For a namespace attribute, the attr.Name.Space must be defined as "xmlns". -// https://www.w3.org/TR/REC-xml-names/#NT-DefaultAttName -func writeAttribute(w writer, attr *Attr) { - // if local, space both are not empty - if len(attr.Name.Space) != 0 && len(attr.Name.Local) != 0 { - escapeString(w, attr.Name.Space) - w.WriteRune(colon) - } - - // if prefix is empty, the default `xmlns` space should be used as prefix. - if len(attr.Name.Local) == 0 { - attr.Name.Local = attr.Name.Space - } - - escapeString(w, attr.Name.Local) - w.WriteRune(equals) - w.WriteRune(quote) - escapeString(w, attr.Value) - w.WriteRune(quote) -} - -// writeEndElement takes in a end element and writes it. -func writeEndElement(w writer, el EndElement) error { - if el.isZero() { - return fmt.Errorf("xml end element cannot be nil") - } - - w.WriteRune(leftAngleBracket) - w.WriteRune(forwardSlash) - - if len(el.Name.Space) != 0 { - escapeString(w, el.Name.Space) - w.WriteRune(colon) - } - escapeString(w, el.Name.Local) - w.WriteRune(rightAngleBracket) - - return nil -} - -// String encodes v as a XML string. -// It will auto close the parent xml element tag. -func (xv Value) String(v string) { - escapeString(xv.w, v) - xv.Close() -} - -// Byte encodes v as a XML number. -// It will auto close the parent xml element tag. -func (xv Value) Byte(v int8) { - xv.Long(int64(v)) -} - -// Short encodes v as a XML number. -// It will auto close the parent xml element tag. -func (xv Value) Short(v int16) { - xv.Long(int64(v)) -} - -// Integer encodes v as a XML number. -// It will auto close the parent xml element tag. -func (xv Value) Integer(v int32) { - xv.Long(int64(v)) -} - -// Long encodes v as a XML number. -// It will auto close the parent xml element tag. -func (xv Value) Long(v int64) { - *xv.scratch = strconv.AppendInt((*xv.scratch)[:0], v, 10) - xv.w.Write(*xv.scratch) - - xv.Close() -} - -// Float encodes v as a XML number. -// It will auto close the parent xml element tag. -func (xv Value) Float(v float32) { - xv.float(float64(v), 32) - xv.Close() -} - -// Double encodes v as a XML number. -// It will auto close the parent xml element tag. -func (xv Value) Double(v float64) { - xv.float(v, 64) - xv.Close() -} - -func (xv Value) float(v float64, bits int) { - *xv.scratch = encoding.EncodeFloat((*xv.scratch)[:0], v, bits) - xv.w.Write(*xv.scratch) -} - -// Boolean encodes v as a XML boolean. -// It will auto close the parent xml element tag. -func (xv Value) Boolean(v bool) { - *xv.scratch = strconv.AppendBool((*xv.scratch)[:0], v) - xv.w.Write(*xv.scratch) - - xv.Close() -} - -// Base64EncodeBytes writes v as a base64 value in XML string. -// It will auto close the parent xml element tag. -func (xv Value) Base64EncodeBytes(v []byte) { - encodeByteSlice(xv.w, (*xv.scratch)[:0], v) - xv.Close() -} - -// BigInteger encodes v big.Int as XML value. -// It will auto close the parent xml element tag. -func (xv Value) BigInteger(v *big.Int) { - xv.w.Write([]byte(v.Text(10))) - xv.Close() -} - -// BigDecimal encodes v big.Float as XML value. -// It will auto close the parent xml element tag. -func (xv Value) BigDecimal(v *big.Float) { - if i, accuracy := v.Int64(); accuracy == big.Exact { - xv.Long(i) - return - } - - xv.w.Write([]byte(v.Text('e', -1))) - xv.Close() -} - -// Write writes v directly to the xml document -// if escapeXMLText is set to true, write will escape text. -// It will auto close the parent xml element tag. -func (xv Value) Write(v []byte, escapeXMLText bool) { - // escape and write xml text - if escapeXMLText { - escapeText(xv.w, v) - } else { - // write xml directly - xv.w.Write(v) - } - - xv.Close() -} - -// MemberElement does member element encoding. It returns a Value. -// Member Element method should be used for all shapes except flattened shapes. -// -// A call to MemberElement will write nested element tags directly using the -// provided start element. The value returned by MemberElement should be closed. -func (xv Value) MemberElement(element StartElement) Value { - return newValue(xv.w, xv.scratch, element) -} - -// FlattenedElement returns flattened element encoding. It returns a Value. -// This method should be used for flattened shapes. -// -// Unlike MemberElement, flattened element will NOT write element tags -// directly for the associated start element. -// -// The value returned by the FlattenedElement does not need to be closed. -func (xv Value) FlattenedElement(element StartElement) Value { - v := newFlattenedValue(xv.w, xv.scratch, element) - v.isFlattened = true - return v -} - -// Array returns an array encoder. By default, the members of array are -// wrapped with `` element tag. -// If value is marked as flattened, the start element is used to wrap the members instead of -// the `` element. -func (xv Value) Array() *Array { - return newArray(xv.w, xv.scratch, arrayMemberWrapper, xv.startElement, xv.isFlattened) -} - -/* -ArrayWithCustomName returns an array encoder. - -It takes named start element as an argument, the named start element will used to wrap xml array entries. -for eg, `entry1` -Here `customName` named start element will be wrapped on each array member. -*/ -func (xv Value) ArrayWithCustomName(element StartElement) *Array { - return newArray(xv.w, xv.scratch, element, xv.startElement, xv.isFlattened) -} - -/* -Map returns a map encoder. By default, the map entries are -wrapped with `` element tag. - -If value is marked as flattened, the start element is used to wrap the entry instead of -the `` element. -*/ -func (xv Value) Map() *Map { - // flattened map - if xv.isFlattened { - return newFlattenedMap(xv.w, xv.scratch, xv.startElement) - } - - // un-flattened map - return newMap(xv.w, xv.scratch) -} - -// encodeByteSlice is modified copy of json encoder's encodeByteSlice. -// It is used to base64 encode a byte slice. -func encodeByteSlice(w writer, scratch []byte, v []byte) { - if v == nil { - return - } - - encodedLen := base64.StdEncoding.EncodedLen(len(v)) - if encodedLen <= len(scratch) { - // If the encoded bytes fit in e.scratch, avoid an extra - // allocation and use the cheaper Encoding.Encode. - dst := scratch[:encodedLen] - base64.StdEncoding.Encode(dst, v) - w.Write(dst) - } else if encodedLen <= 1024 { - // The encoded bytes are short enough to allocate for, and - // Encoding.Encode is still cheaper. - dst := make([]byte, encodedLen) - base64.StdEncoding.Encode(dst, v) - w.Write(dst) - } else { - // The encoded bytes are too long to cheaply allocate, and - // Encoding.Encode is no longer noticeably cheaper. - enc := base64.NewEncoder(base64.StdEncoding, w) - enc.Write(v) - enc.Close() - } -} - -// IsFlattened returns true if value is for flattened shape. -func (xv Value) IsFlattened() bool { - return xv.isFlattened -} - -// Close closes the value. -func (xv Value) Close() { - writeEndElement(xv.w, xv.startElement.End()) -} diff --git a/vendor/github.com/aws/smithy-go/encoding/xml/xml_decoder.go b/vendor/github.com/aws/smithy-go/encoding/xml/xml_decoder.go deleted file mode 100644 index dc4eebdff..000000000 --- a/vendor/github.com/aws/smithy-go/encoding/xml/xml_decoder.go +++ /dev/null @@ -1,154 +0,0 @@ -package xml - -import ( - "encoding/xml" - "fmt" - "strings" -) - -// NodeDecoder is a XML decoder wrapper that is responsible to decoding -// a single XML Node element and it's nested member elements. This wrapper decoder -// takes in the start element of the top level node being decoded. -type NodeDecoder struct { - Decoder *xml.Decoder - StartEl xml.StartElement -} - -// WrapNodeDecoder returns an initialized XMLNodeDecoder -func WrapNodeDecoder(decoder *xml.Decoder, startEl xml.StartElement) NodeDecoder { - return NodeDecoder{ - Decoder: decoder, - StartEl: startEl, - } -} - -// Token on a Node Decoder returns a xml StartElement. It returns a boolean that indicates the -// a token is the node decoder's end node token; and an error which indicates any error -// that occurred while retrieving the start element -func (d NodeDecoder) Token() (t xml.StartElement, done bool, err error) { - for { - token, e := d.Decoder.Token() - if e != nil { - return t, done, e - } - - // check if we reach end of the node being decoded - if el, ok := token.(xml.EndElement); ok { - return t, el == d.StartEl.End(), err - } - - if t, ok := token.(xml.StartElement); ok { - return restoreAttrNamespaces(t), false, err - } - - // skip token if it is a comment or preamble or empty space value due to indentation - // or if it's a value and is not expected - } -} - -// restoreAttrNamespaces update XML attributes to restore the short namespaces found within -// the raw XML document. -func restoreAttrNamespaces(node xml.StartElement) xml.StartElement { - if len(node.Attr) == 0 { - return node - } - - // Generate a mapping of XML namespace values to their short names. - ns := map[string]string{} - for _, a := range node.Attr { - if a.Name.Space == "xmlns" { - ns[a.Value] = a.Name.Local - break - } - } - - for i, a := range node.Attr { - if a.Name.Space == "xmlns" { - continue - } - // By default, xml.Decoder will fully resolve these namespaces. So if you had - // then by default the second attribute would have the `Name.Space` resolved to `baz`. But we need it to - // continue to resolve as `bar` so we can easily identify it later on. - if v, ok := ns[node.Attr[i].Name.Space]; ok { - node.Attr[i].Name.Space = v - } - } - return node -} - -// GetElement looks for the given tag name at the current level, and returns the element if found, and -// skipping over non-matching elements. Returns an error if the node is not found, or if an error occurs while walking -// the document. -func (d NodeDecoder) GetElement(name string) (t xml.StartElement, err error) { - for { - token, done, err := d.Token() - if err != nil { - return t, err - } - if done { - return t, fmt.Errorf("%s node not found", name) - } - switch { - case strings.EqualFold(name, token.Name.Local): - return token, nil - default: - err = d.Decoder.Skip() - if err != nil { - return t, err - } - } - } -} - -// Value provides an abstraction to retrieve char data value within an xml element. -// The method will return an error if it encounters a nested xml element instead of char data. -// This method should only be used to retrieve simple type or blob shape values as []byte. -func (d NodeDecoder) Value() (c []byte, err error) { - t, e := d.Decoder.Token() - if e != nil { - return c, e - } - - endElement := d.StartEl.End() - - switch ev := t.(type) { - case xml.CharData: - c = ev.Copy() - case xml.EndElement: // end tag or self-closing - if ev == endElement { - return []byte{}, err - } - return c, fmt.Errorf("expected value for %v element, got %T type %v instead", d.StartEl.Name.Local, t, t) - default: - return c, fmt.Errorf("expected value for %v element, got %T type %v instead", d.StartEl.Name.Local, t, t) - } - - t, e = d.Decoder.Token() - if e != nil { - return c, e - } - - if ev, ok := t.(xml.EndElement); ok { - if ev == endElement { - return c, err - } - } - - return c, fmt.Errorf("expected end element %v, got %T type %v instead", endElement, t, t) -} - -// FetchRootElement takes in a decoder and returns the first start element within the xml body. -// This function is useful in fetching the start element of an XML response and ignore the -// comments and preamble -func FetchRootElement(decoder *xml.Decoder) (startElement xml.StartElement, err error) { - for { - t, e := decoder.Token() - if e != nil { - return startElement, e - } - - if startElement, ok := t.(xml.StartElement); ok { - return startElement, err - } - } -} diff --git a/vendor/github.com/aws/smithy-go/endpoints/endpoint.go b/vendor/github.com/aws/smithy-go/endpoints/endpoint.go deleted file mode 100644 index a93528397..000000000 --- a/vendor/github.com/aws/smithy-go/endpoints/endpoint.go +++ /dev/null @@ -1,23 +0,0 @@ -package transport - -import ( - "net/http" - "net/url" - - "github.com/aws/smithy-go" -) - -// Endpoint is the endpoint object returned by Endpoint resolution V2 -type Endpoint struct { - // The complete URL minimally specfiying the scheme and host. - // May optionally specify the port and base path component. - URI url.URL - - // An optional set of headers to be sent using transport layer headers. - Headers http.Header - - // A grab-bag property map of endpoint attributes. The - // values present here are subject to change, or being add/removed at any - // time. - Properties smithy.Properties -} diff --git a/vendor/github.com/aws/smithy-go/errors.go b/vendor/github.com/aws/smithy-go/errors.go deleted file mode 100644 index d6948d020..000000000 --- a/vendor/github.com/aws/smithy-go/errors.go +++ /dev/null @@ -1,137 +0,0 @@ -package smithy - -import "fmt" - -// APIError provides the generic API and protocol agnostic error type all SDK -// generated exception types will implement. -type APIError interface { - error - - // ErrorCode returns the error code for the API exception. - ErrorCode() string - // ErrorMessage returns the error message for the API exception. - ErrorMessage() string - // ErrorFault returns the fault for the API exception. - ErrorFault() ErrorFault -} - -// GenericAPIError provides a generic concrete API error type that SDKs can use -// to deserialize error responses into. Should be used for unmodeled or untyped -// errors. -type GenericAPIError struct { - Code string - Message string - Fault ErrorFault -} - -// ErrorCode returns the error code for the API exception. -func (e *GenericAPIError) ErrorCode() string { return e.Code } - -// ErrorMessage returns the error message for the API exception. -func (e *GenericAPIError) ErrorMessage() string { return e.Message } - -// ErrorFault returns the fault for the API exception. -func (e *GenericAPIError) ErrorFault() ErrorFault { return e.Fault } - -func (e *GenericAPIError) Error() string { - return fmt.Sprintf("api error %s: %s", e.Code, e.Message) -} - -var _ APIError = (*GenericAPIError)(nil) - -// OperationError decorates an underlying error which occurred while invoking -// an operation with names of the operation and API. -type OperationError struct { - ServiceID string - OperationName string - Err error -} - -// Service returns the name of the API service the error occurred with. -func (e *OperationError) Service() string { return e.ServiceID } - -// Operation returns the name of the API operation the error occurred with. -func (e *OperationError) Operation() string { return e.OperationName } - -// Unwrap returns the nested error if any, or nil. -func (e *OperationError) Unwrap() error { return e.Err } - -func (e *OperationError) Error() string { - return fmt.Sprintf("operation error %s: %s, %v", e.ServiceID, e.OperationName, e.Err) -} - -// DeserializationError provides a wrapper for an error that occurs during -// deserialization. -type DeserializationError struct { - Err error // original error - Snapshot []byte -} - -// Error returns a formatted error for DeserializationError -func (e *DeserializationError) Error() string { - const msg = "deserialization failed" - if e.Err == nil { - return msg - } - return fmt.Sprintf("%s, %v", msg, e.Err) -} - -// Unwrap returns the underlying Error in DeserializationError -func (e *DeserializationError) Unwrap() error { return e.Err } - -// ErrorFault provides the type for a Smithy API error fault. -type ErrorFault int - -// ErrorFault enumeration values -const ( - FaultUnknown ErrorFault = iota - FaultServer - FaultClient -) - -func (f ErrorFault) String() string { - switch f { - case FaultServer: - return "server" - case FaultClient: - return "client" - default: - return "unknown" - } -} - -// SerializationError represents an error that occurred while attempting to serialize a request -type SerializationError struct { - Err error // original error -} - -// Error returns a formatted error for SerializationError -func (e *SerializationError) Error() string { - const msg = "serialization failed" - if e.Err == nil { - return msg - } - return fmt.Sprintf("%s: %v", msg, e.Err) -} - -// Unwrap returns the underlying Error in SerializationError -func (e *SerializationError) Unwrap() error { return e.Err } - -// CanceledError is the error that will be returned by an API request that was -// canceled. API operations given a Context may return this error when -// canceled. -type CanceledError struct { - Err error -} - -// CanceledError returns true to satisfy interfaces checking for canceled errors. -func (*CanceledError) CanceledError() bool { return true } - -// Unwrap returns the underlying error, if there was one. -func (e *CanceledError) Unwrap() error { - return e.Err -} - -func (e *CanceledError) Error() string { - return fmt.Sprintf("canceled, %v", e.Err) -} diff --git a/vendor/github.com/aws/smithy-go/go_module_metadata.go b/vendor/github.com/aws/smithy-go/go_module_metadata.go deleted file mode 100644 index 997c30924..000000000 --- a/vendor/github.com/aws/smithy-go/go_module_metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. - -package smithy - -// goModuleVersion is the tagged release for this module -const goModuleVersion = "1.14.2" diff --git a/vendor/github.com/aws/smithy-go/internal/sync/singleflight/LICENSE b/vendor/github.com/aws/smithy-go/internal/sync/singleflight/LICENSE deleted file mode 100644 index fe6a62006..000000000 --- a/vendor/github.com/aws/smithy-go/internal/sync/singleflight/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright (c) 2009 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 COPYIGHT 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/aws/smithy-go/internal/sync/singleflight/docs.go b/vendor/github.com/aws/smithy-go/internal/sync/singleflight/docs.go deleted file mode 100644 index 9c9d02b94..000000000 --- a/vendor/github.com/aws/smithy-go/internal/sync/singleflight/docs.go +++ /dev/null @@ -1,8 +0,0 @@ -// Package singleflight provides a duplicate function call suppression -// mechanism. This package is a fork of the Go golang.org/x/sync/singleflight -// package. The package is forked, because the package a part of the unstable -// and unversioned golang.org/x/sync module. -// -// https://github.com/golang/sync/tree/67f06af15bc961c363a7260195bcd53487529a21/singleflight - -package singleflight diff --git a/vendor/github.com/aws/smithy-go/internal/sync/singleflight/singleflight.go b/vendor/github.com/aws/smithy-go/internal/sync/singleflight/singleflight.go deleted file mode 100644 index e8a1b17d5..000000000 --- a/vendor/github.com/aws/smithy-go/internal/sync/singleflight/singleflight.go +++ /dev/null @@ -1,210 +0,0 @@ -// 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 singleflight - -import ( - "bytes" - "errors" - "fmt" - "runtime" - "runtime/debug" - "sync" -) - -// errGoexit indicates the runtime.Goexit was called in -// the user given function. -var errGoexit = errors.New("runtime.Goexit was called") - -// A panicError is an arbitrary value recovered from a panic -// with the stack trace during the execution of given function. -type panicError struct { - value interface{} - stack []byte -} - -// Error implements error interface. -func (p *panicError) Error() string { - return fmt.Sprintf("%v\n\n%s", p.value, p.stack) -} - -func newPanicError(v interface{}) error { - stack := debug.Stack() - - // The first line of the stack trace is of the form "goroutine N [status]:" - // but by the time the panic reaches Do the goroutine may no longer exist - // and its status will have changed. Trim out the misleading line. - if line := bytes.IndexByte(stack[:], '\n'); line >= 0 { - stack = stack[line+1:] - } - return &panicError{value: v, stack: stack} -} - -// call is an in-flight or completed singleflight.Do call -type call struct { - wg sync.WaitGroup - - // These fields are written once before the WaitGroup is done - // and are only read after the WaitGroup is done. - val interface{} - err error - - // forgotten indicates whether Forget was called with this call's key - // while the call was still in flight. - forgotten bool - - // These fields are read and written with the singleflight - // mutex held before the WaitGroup is done, and are read but - // not written after the WaitGroup is done. - dups int - chans []chan<- Result -} - -// Group represents a class of work and forms a namespace in -// which units of work can be executed with duplicate suppression. -type Group struct { - mu sync.Mutex // protects m - m map[string]*call // lazily initialized -} - -// Result holds the results of Do, so they can be passed -// on a channel. -type Result struct { - Val interface{} - Err error - Shared bool -} - -// Do executes and returns the results of the given function, making -// sure that only one execution is in-flight for a given key at a -// time. If a duplicate comes in, the duplicate caller waits for the -// original to complete and receives the same results. -// The return value shared indicates whether v was given to multiple callers. -func (g *Group) Do(key string, fn func() (interface{}, error)) (v interface{}, err error, shared bool) { - g.mu.Lock() - if g.m == nil { - g.m = make(map[string]*call) - } - if c, ok := g.m[key]; ok { - c.dups++ - g.mu.Unlock() - c.wg.Wait() - - if e, ok := c.err.(*panicError); ok { - panic(e) - } else if c.err == errGoexit { - runtime.Goexit() - } - return c.val, c.err, true - } - c := new(call) - c.wg.Add(1) - g.m[key] = c - g.mu.Unlock() - - g.doCall(c, key, fn) - return c.val, c.err, c.dups > 0 -} - -// DoChan is like Do but returns a channel that will receive the -// results when they are ready. -// -// The returned channel will not be closed. -func (g *Group) DoChan(key string, fn func() (interface{}, error)) <-chan Result { - ch := make(chan Result, 1) - g.mu.Lock() - if g.m == nil { - g.m = make(map[string]*call) - } - if c, ok := g.m[key]; ok { - c.dups++ - c.chans = append(c.chans, ch) - g.mu.Unlock() - return ch - } - c := &call{chans: []chan<- Result{ch}} - c.wg.Add(1) - g.m[key] = c - g.mu.Unlock() - - go g.doCall(c, key, fn) - - return ch -} - -// doCall handles the single call for a key. -func (g *Group) doCall(c *call, key string, fn func() (interface{}, error)) { - normalReturn := false - recovered := false - - // use double-defer to distinguish panic from runtime.Goexit, - // more details see https://golang.org/cl/134395 - defer func() { - // the given function invoked runtime.Goexit - if !normalReturn && !recovered { - c.err = errGoexit - } - - c.wg.Done() - g.mu.Lock() - defer g.mu.Unlock() - if !c.forgotten { - delete(g.m, key) - } - - if e, ok := c.err.(*panicError); ok { - // In order to prevent the waiting channels from being blocked forever, - // needs to ensure that this panic cannot be recovered. - if len(c.chans) > 0 { - go panic(e) - select {} // Keep this goroutine around so that it will appear in the crash dump. - } else { - panic(e) - } - } else if c.err == errGoexit { - // Already in the process of goexit, no need to call again - } else { - // Normal return - for _, ch := range c.chans { - ch <- Result{c.val, c.err, c.dups > 0} - } - } - }() - - func() { - defer func() { - if !normalReturn { - // Ideally, we would wait to take a stack trace until we've determined - // whether this is a panic or a runtime.Goexit. - // - // Unfortunately, the only way we can distinguish the two is to see - // whether the recover stopped the goroutine from terminating, and by - // the time we know that, the part of the stack trace relevant to the - // panic has been discarded. - if r := recover(); r != nil { - c.err = newPanicError(r) - } - } - }() - - c.val, c.err = fn() - normalReturn = true - }() - - if !normalReturn { - recovered = true - } -} - -// Forget tells the singleflight to forget about a key. Future calls -// to Do for this key will call the function rather than waiting for -// an earlier call to complete. -func (g *Group) Forget(key string) { - g.mu.Lock() - if c, ok := g.m[key]; ok { - c.forgotten = true - } - delete(g.m, key) - g.mu.Unlock() -} diff --git a/vendor/github.com/aws/smithy-go/io/byte.go b/vendor/github.com/aws/smithy-go/io/byte.go deleted file mode 100644 index f8417c15b..000000000 --- a/vendor/github.com/aws/smithy-go/io/byte.go +++ /dev/null @@ -1,12 +0,0 @@ -package io - -const ( - // Byte is 8 bits - Byte int64 = 1 - // KibiByte (KiB) is 1024 Bytes - KibiByte = Byte * 1024 - // MebiByte (MiB) is 1024 KiB - MebiByte = KibiByte * 1024 - // GibiByte (GiB) is 1024 MiB - GibiByte = MebiByte * 1024 -) diff --git a/vendor/github.com/aws/smithy-go/io/doc.go b/vendor/github.com/aws/smithy-go/io/doc.go deleted file mode 100644 index a6a33eaf5..000000000 --- a/vendor/github.com/aws/smithy-go/io/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package io provides utilities for Smithy generated API clients. -package io diff --git a/vendor/github.com/aws/smithy-go/io/reader.go b/vendor/github.com/aws/smithy-go/io/reader.go deleted file mode 100644 index 07063f296..000000000 --- a/vendor/github.com/aws/smithy-go/io/reader.go +++ /dev/null @@ -1,16 +0,0 @@ -package io - -import ( - "io" -) - -// ReadSeekNopCloser wraps an io.ReadSeeker with an additional Close method -// that does nothing. -type ReadSeekNopCloser struct { - io.ReadSeeker -} - -// Close does nothing. -func (ReadSeekNopCloser) Close() error { - return nil -} diff --git a/vendor/github.com/aws/smithy-go/io/ringbuffer.go b/vendor/github.com/aws/smithy-go/io/ringbuffer.go deleted file mode 100644 index 06b476add..000000000 --- a/vendor/github.com/aws/smithy-go/io/ringbuffer.go +++ /dev/null @@ -1,94 +0,0 @@ -package io - -import ( - "bytes" - "io" -) - -// RingBuffer struct satisfies io.ReadWrite interface. -// -// ReadBuffer is a revolving buffer data structure, which can be used to store snapshots of data in a -// revolving window. -type RingBuffer struct { - slice []byte - start int - end int - size int -} - -// NewRingBuffer method takes in a byte slice as an input and returns a RingBuffer. -func NewRingBuffer(slice []byte) *RingBuffer { - ringBuf := RingBuffer{ - slice: slice, - } - return &ringBuf -} - -// Write method inserts the elements in a byte slice, and returns the number of bytes written along with any error. -func (r *RingBuffer) Write(p []byte) (int, error) { - for _, b := range p { - // check if end points to invalid index, we need to circle back - if r.end == len(r.slice) { - r.end = 0 - } - // check if start points to invalid index, we need to circle back - if r.start == len(r.slice) { - r.start = 0 - } - // if ring buffer is filled, increment the start index - if r.size == len(r.slice) { - r.size-- - r.start++ - } - - r.slice[r.end] = b - r.end++ - r.size++ - } - return len(p), nil -} - -// Read copies the data on the ring buffer into the byte slice provided to the method. -// Returns the read count along with any error encountered while reading. -func (r *RingBuffer) Read(p []byte) (int, error) { - // readCount keeps track of the number of bytes read - var readCount int - for j := 0; j < len(p); j++ { - // if ring buffer is empty or completely read - // return EOF error. - if r.size == 0 { - return readCount, io.EOF - } - - if r.start == len(r.slice) { - r.start = 0 - } - - p[j] = r.slice[r.start] - readCount++ - // increment the start pointer for ring buffer - r.start++ - // decrement the size of ring buffer - r.size-- - } - return readCount, nil -} - -// Len returns the number of unread bytes in the buffer. -func (r *RingBuffer) Len() int { - return r.size -} - -// Bytes returns a copy of the RingBuffer's bytes. -func (r RingBuffer) Bytes() []byte { - var b bytes.Buffer - io.Copy(&b, &r) - return b.Bytes() -} - -// Reset resets the ring buffer. -func (r *RingBuffer) Reset() { - *r = RingBuffer{ - slice: r.slice, - } -} diff --git a/vendor/github.com/aws/smithy-go/local-mod-replace.sh b/vendor/github.com/aws/smithy-go/local-mod-replace.sh deleted file mode 100644 index 800bf3769..000000000 --- a/vendor/github.com/aws/smithy-go/local-mod-replace.sh +++ /dev/null @@ -1,39 +0,0 @@ -#1/usr/bin/env bash - -PROJECT_DIR="" -SMITHY_SOURCE_DIR=$(cd `dirname $0` && pwd) - -usage() { - echo "Usage: $0 [-s SMITHY_SOURCE_DIR] [-d PROJECT_DIR]" 1>&2 - exit 1 -} - -while getopts "hs:d:" options; do - case "${options}" in - s) - SMITHY_SOURCE_DIR=${OPTARG} - if [ "$SMITHY_SOURCE_DIR" == "" ]; then - echo "path to smithy-go source directory is required" || exit - usage - fi - ;; - d) - PROJECT_DIR=${OPTARG} - ;; - h) - usage - ;; - *) - usage - ;; - esac -done - -if [ "$PROJECT_DIR" != "" ]; then - cd $PROJECT_DIR || exit -fi - -go mod graph | awk '{print $1}' | cut -d '@' -f 1 | sort | uniq | grep "github.com/aws/smithy-go" | while read x; do - repPath=${x/github.com\/aws\/smithy-go/${SMITHY_SOURCE_DIR}} - echo -replace $x=$repPath -done | xargs go mod edit diff --git a/vendor/github.com/aws/smithy-go/logging/logger.go b/vendor/github.com/aws/smithy-go/logging/logger.go deleted file mode 100644 index 2071924bd..000000000 --- a/vendor/github.com/aws/smithy-go/logging/logger.go +++ /dev/null @@ -1,82 +0,0 @@ -package logging - -import ( - "context" - "io" - "log" -) - -// Classification is the type of the log entry's classification name. -type Classification string - -// Set of standard classifications that can be used by clients and middleware -const ( - Warn Classification = "WARN" - Debug Classification = "DEBUG" -) - -// Logger is an interface for logging entries at certain classifications. -type Logger interface { - // Logf is expected to support the standard fmt package "verbs". - Logf(classification Classification, format string, v ...interface{}) -} - -// LoggerFunc is a wrapper around a function to satisfy the Logger interface. -type LoggerFunc func(classification Classification, format string, v ...interface{}) - -// Logf delegates the logging request to the wrapped function. -func (f LoggerFunc) Logf(classification Classification, format string, v ...interface{}) { - f(classification, format, v...) -} - -// ContextLogger is an optional interface a Logger implementation may expose that provides -// the ability to create context aware log entries. -type ContextLogger interface { - WithContext(context.Context) Logger -} - -// WithContext will pass the provided context to logger if it implements the ContextLogger interface and return the resulting -// logger. Otherwise the logger will be returned as is. As a special case if a nil logger is provided, a Nop logger will -// be returned to the caller. -func WithContext(ctx context.Context, logger Logger) Logger { - if logger == nil { - return Nop{} - } - - cl, ok := logger.(ContextLogger) - if !ok { - return logger - } - - return cl.WithContext(ctx) -} - -// Nop is a Logger implementation that simply does not perform any logging. -type Nop struct{} - -// Logf simply returns without performing any action -func (n Nop) Logf(Classification, string, ...interface{}) { - return -} - -// StandardLogger is a Logger implementation that wraps the standard library logger, and delegates logging to it's -// Printf method. -type StandardLogger struct { - Logger *log.Logger -} - -// Logf logs the given classification and message to the underlying logger. -func (s StandardLogger) Logf(classification Classification, format string, v ...interface{}) { - if len(classification) != 0 { - format = string(classification) + " " + format - } - - s.Logger.Printf(format, v...) -} - -// NewStandardLogger returns a new StandardLogger -func NewStandardLogger(writer io.Writer) *StandardLogger { - return &StandardLogger{ - Logger: log.New(writer, "SDK ", log.LstdFlags), - } -} diff --git a/vendor/github.com/aws/smithy-go/middleware/doc.go b/vendor/github.com/aws/smithy-go/middleware/doc.go deleted file mode 100644 index 9858928a7..000000000 --- a/vendor/github.com/aws/smithy-go/middleware/doc.go +++ /dev/null @@ -1,67 +0,0 @@ -// Package middleware provides transport agnostic middleware for decorating SDK -// handlers. -// -// The Smithy middleware stack provides ordered behavior to be invoked on an -// underlying handler. The stack is separated into steps that are invoked in a -// static order. A step is a collection of middleware that are injected into a -// ordered list defined by the user. The user may add, insert, swap, and remove a -// step's middleware. When the stack is invoked the step middleware become static, -// and their order cannot be modified. -// -// A stack and its step middleware are **not** safe to modify concurrently. -// -// A stack will use the ordered list of middleware to decorate a underlying -// handler. A handler could be something like an HTTP Client that round trips an -// API operation over HTTP. -// -// Smithy Middleware Stack -// -// A Stack is a collection of middleware that wrap a handler. The stack can be -// broken down into discreet steps. Each step may contain zero or more middleware -// specific to that stack's step. -// -// A Stack Step is a predefined set of middleware that are invoked in a static -// order by the Stack. These steps represent fixed points in the middleware stack -// for organizing specific behavior, such as serialize and build. A Stack Step is -// composed of zero or more middleware that are specific to that step. A step may -// define its own set of input/output parameters the generic input/output -// parameters are cast from. A step calls its middleware recursively, before -// calling the next step in the stack returning the result or error of the step -// middleware decorating the underlying handler. -// -// * Initialize: Prepares the input, and sets any default parameters as needed, -// (e.g. idempotency token, and presigned URLs). -// -// * Serialize: Serializes the prepared input into a data structure that can be -// consumed by the target transport's message, (e.g. REST-JSON serialization). -// -// * Build: Adds additional metadata to the serialized transport message, (e.g. -// HTTP's Content-Length header, or body checksum). Decorations and -// modifications to the message should be copied to all message attempts. -// -// * Finalize: Performs final preparations needed before sending the message. The -// message should already be complete by this stage, and is only alternated to -// meet the expectations of the recipient, (e.g. Retry and AWS SigV4 request -// signing). -// -// * Deserialize: Reacts to the handler's response returned by the recipient of -// the request message. Deserializes the response into a structured type or -// error above stacks can react to. -// -// Adding Middleware to a Stack Step -// -// Middleware can be added to a step front or back, or relative, by name, to an -// existing middleware in that stack. If a middleware does not have a name, a -// unique name will be generated at the middleware and be added to the step. -// -// // Create middleware stack -// stack := middleware.NewStack() -// -// // Add middleware to stack steps -// stack.Initialize.Add(paramValidationMiddleware, middleware.After) -// stack.Serialize.Add(marshalOperationFoo, middleware.After) -// stack.Deserialize.Add(unmarshalOperationFoo, middleware.After) -// -// // Invoke middleware on handler. -// resp, err := stack.HandleMiddleware(ctx, req.Input, clientHandler) -package middleware diff --git a/vendor/github.com/aws/smithy-go/middleware/logging.go b/vendor/github.com/aws/smithy-go/middleware/logging.go deleted file mode 100644 index c2f0dbb6b..000000000 --- a/vendor/github.com/aws/smithy-go/middleware/logging.go +++ /dev/null @@ -1,46 +0,0 @@ -package middleware - -import ( - "context" - - "github.com/aws/smithy-go/logging" -) - -// loggerKey is the context value key for which the logger is associated with. -type loggerKey struct{} - -// GetLogger takes a context to retrieve a Logger from. If no logger is present on the context a logging.Nop logger -// is returned. If the logger retrieved from context supports the ContextLogger interface, the context will be passed -// to the WithContext method and the resulting logger will be returned. Otherwise the stored logger is returned as is. -func GetLogger(ctx context.Context) logging.Logger { - logger, ok := ctx.Value(loggerKey{}).(logging.Logger) - if !ok || logger == nil { - return logging.Nop{} - } - - return logging.WithContext(ctx, logger) -} - -// SetLogger sets the provided logger value on the provided ctx. -func SetLogger(ctx context.Context, logger logging.Logger) context.Context { - return context.WithValue(ctx, loggerKey{}, logger) -} - -type setLogger struct { - Logger logging.Logger -} - -// AddSetLoggerMiddleware adds a middleware that will add the provided logger to the middleware context. -func AddSetLoggerMiddleware(stack *Stack, logger logging.Logger) error { - return stack.Initialize.Add(&setLogger{Logger: logger}, After) -} - -func (a *setLogger) ID() string { - return "SetLogger" -} - -func (a *setLogger) HandleInitialize(ctx context.Context, in InitializeInput, next InitializeHandler) ( - out InitializeOutput, metadata Metadata, err error, -) { - return next.HandleInitialize(SetLogger(ctx, a.Logger), in) -} diff --git a/vendor/github.com/aws/smithy-go/middleware/metadata.go b/vendor/github.com/aws/smithy-go/middleware/metadata.go deleted file mode 100644 index 7bb7dbcf5..000000000 --- a/vendor/github.com/aws/smithy-go/middleware/metadata.go +++ /dev/null @@ -1,65 +0,0 @@ -package middleware - -// MetadataReader provides an interface for reading metadata from the -// underlying metadata container. -type MetadataReader interface { - Get(key interface{}) interface{} -} - -// Metadata provides storing and reading metadata values. Keys may be any -// comparable value type. Get and set will panic if key is not a comparable -// value type. -// -// Metadata uses lazy initialization, and Set method must be called as an -// addressable value, or pointer. Not doing so may cause key/value pair to not -// be set. -type Metadata struct { - values map[interface{}]interface{} -} - -// Get attempts to retrieve the value the key points to. Returns nil if the -// key was not found. -// -// Panics if key type is not comparable. -func (m Metadata) Get(key interface{}) interface{} { - return m.values[key] -} - -// Clone creates a shallow copy of Metadata entries, returning a new Metadata -// value with the original entries copied into it. -func (m Metadata) Clone() Metadata { - vs := make(map[interface{}]interface{}, len(m.values)) - for k, v := range m.values { - vs[k] = v - } - - return Metadata{ - values: vs, - } -} - -// Set stores the value pointed to by the key. If a value already exists at -// that key it will be replaced with the new value. -// -// Set method must be called as an addressable value, or pointer. If Set is not -// called as an addressable value or pointer, the key value pair being set may -// be lost. -// -// Panics if the key type is not comparable. -func (m *Metadata) Set(key, value interface{}) { - if m.values == nil { - m.values = map[interface{}]interface{}{} - } - m.values[key] = value -} - -// Has returns whether the key exists in the metadata. -// -// Panics if the key type is not comparable. -func (m Metadata) Has(key interface{}) bool { - if m.values == nil { - return false - } - _, ok := m.values[key] - return ok -} diff --git a/vendor/github.com/aws/smithy-go/middleware/middleware.go b/vendor/github.com/aws/smithy-go/middleware/middleware.go deleted file mode 100644 index 803b7c751..000000000 --- a/vendor/github.com/aws/smithy-go/middleware/middleware.go +++ /dev/null @@ -1,71 +0,0 @@ -package middleware - -import ( - "context" -) - -// Handler provides the interface for performing the logic to obtain an output, -// or error for the given input. -type Handler interface { - // Handle performs logic to obtain an output for the given input. Handler - // should be decorated with middleware to perform input specific behavior. - Handle(ctx context.Context, input interface{}) ( - output interface{}, metadata Metadata, err error, - ) -} - -// HandlerFunc provides a wrapper around a function pointer to be used as a -// middleware handler. -type HandlerFunc func(ctx context.Context, input interface{}) ( - output interface{}, metadata Metadata, err error, -) - -// Handle invokes the underlying function, returning the result. -func (fn HandlerFunc) Handle(ctx context.Context, input interface{}) ( - output interface{}, metadata Metadata, err error, -) { - return fn(ctx, input) -} - -// Middleware provides the interface to call handlers in a chain. -type Middleware interface { - // ID provides a unique identifier for the middleware. - ID() string - - // Performs the middleware's handling of the input, returning the output, - // or error. The middleware can invoke the next Handler if handling should - // continue. - HandleMiddleware(ctx context.Context, input interface{}, next Handler) ( - output interface{}, metadata Metadata, err error, - ) -} - -// decoratedHandler wraps a middleware in order to to call the next handler in -// the chain. -type decoratedHandler struct { - // The next handler to be called. - Next Handler - - // The current middleware decorating the handler. - With Middleware -} - -// Handle implements the Handler interface to handle a operation invocation. -func (m decoratedHandler) Handle(ctx context.Context, input interface{}) ( - output interface{}, metadata Metadata, err error, -) { - return m.With.HandleMiddleware(ctx, input, m.Next) -} - -// DecorateHandler decorates a handler with a middleware. Wrapping the handler -// with the middleware. -func DecorateHandler(h Handler, with ...Middleware) Handler { - for i := len(with) - 1; i >= 0; i-- { - h = decoratedHandler{ - Next: h, - With: with[i], - } - } - - return h -} diff --git a/vendor/github.com/aws/smithy-go/middleware/ordered_group.go b/vendor/github.com/aws/smithy-go/middleware/ordered_group.go deleted file mode 100644 index 4b195308c..000000000 --- a/vendor/github.com/aws/smithy-go/middleware/ordered_group.go +++ /dev/null @@ -1,268 +0,0 @@ -package middleware - -import "fmt" - -// RelativePosition provides specifying the relative position of a middleware -// in an ordered group. -type RelativePosition int - -// Relative position for middleware in steps. -const ( - After RelativePosition = iota - Before -) - -type ider interface { - ID() string -} - -// orderedIDs provides an ordered collection of items with relative ordering -// by name. -type orderedIDs struct { - order *relativeOrder - items map[string]ider -} - -const baseOrderedItems = 5 - -func newOrderedIDs() *orderedIDs { - return &orderedIDs{ - order: newRelativeOrder(), - items: make(map[string]ider, baseOrderedItems), - } -} - -// Add injects the item to the relative position of the item group. Returns an -// error if the item already exists. -func (g *orderedIDs) Add(m ider, pos RelativePosition) error { - id := m.ID() - if len(id) == 0 { - return fmt.Errorf("empty ID, ID must not be empty") - } - - if err := g.order.Add(pos, id); err != nil { - return err - } - - g.items[id] = m - return nil -} - -// Insert injects the item relative to an existing item id. Returns an error if -// the original item does not exist, or the item being added already exists. -func (g *orderedIDs) Insert(m ider, relativeTo string, pos RelativePosition) error { - if len(m.ID()) == 0 { - return fmt.Errorf("insert ID must not be empty") - } - if len(relativeTo) == 0 { - return fmt.Errorf("relative to ID must not be empty") - } - - if err := g.order.Insert(relativeTo, pos, m.ID()); err != nil { - return err - } - - g.items[m.ID()] = m - return nil -} - -// Get returns the ider identified by id. If ider is not present, returns false. -func (g *orderedIDs) Get(id string) (ider, bool) { - v, ok := g.items[id] - return v, ok -} - -// Swap removes the item by id, replacing it with the new item. Returns an error -// if the original item doesn't exist. -func (g *orderedIDs) Swap(id string, m ider) (ider, error) { - if len(id) == 0 { - return nil, fmt.Errorf("swap from ID must not be empty") - } - - iderID := m.ID() - if len(iderID) == 0 { - return nil, fmt.Errorf("swap to ID must not be empty") - } - - if err := g.order.Swap(id, iderID); err != nil { - return nil, err - } - - removed := g.items[id] - - delete(g.items, id) - g.items[iderID] = m - - return removed, nil -} - -// Remove removes the item by id. Returns an error if the item -// doesn't exist. -func (g *orderedIDs) Remove(id string) (ider, error) { - if len(id) == 0 { - return nil, fmt.Errorf("remove ID must not be empty") - } - - if err := g.order.Remove(id); err != nil { - return nil, err - } - - removed := g.items[id] - delete(g.items, id) - return removed, nil -} - -func (g *orderedIDs) List() []string { - items := g.order.List() - order := make([]string, len(items)) - copy(order, items) - return order -} - -// Clear removes all entries and slots. -func (g *orderedIDs) Clear() { - g.order.Clear() - g.items = map[string]ider{} -} - -// GetOrder returns the item in the order it should be invoked in. -func (g *orderedIDs) GetOrder() []interface{} { - order := g.order.List() - ordered := make([]interface{}, len(order)) - for i := 0; i < len(order); i++ { - ordered[i] = g.items[order[i]] - } - - return ordered -} - -// relativeOrder provides ordering of item -type relativeOrder struct { - order []string -} - -func newRelativeOrder() *relativeOrder { - return &relativeOrder{ - order: make([]string, 0, baseOrderedItems), - } -} - -// Add inserts an item into the order relative to the position provided. -func (s *relativeOrder) Add(pos RelativePosition, ids ...string) error { - if len(ids) == 0 { - return nil - } - - for _, id := range ids { - if _, ok := s.has(id); ok { - return fmt.Errorf("already exists, %v", id) - } - } - - switch pos { - case Before: - return s.insert(0, Before, ids...) - - case After: - s.order = append(s.order, ids...) - - default: - return fmt.Errorf("invalid position, %v", int(pos)) - } - - return nil -} - -// Insert injects an item before or after the relative item. Returns -// an error if the relative item does not exist. -func (s *relativeOrder) Insert(relativeTo string, pos RelativePosition, ids ...string) error { - if len(ids) == 0 { - return nil - } - - for _, id := range ids { - if _, ok := s.has(id); ok { - return fmt.Errorf("already exists, %v", id) - } - } - - i, ok := s.has(relativeTo) - if !ok { - return fmt.Errorf("not found, %v", relativeTo) - } - - return s.insert(i, pos, ids...) -} - -// Swap will replace the item id with the to item. Returns an -// error if the original item id does not exist. Allows swapping out an -// item for another item with the same id. -func (s *relativeOrder) Swap(id, to string) error { - i, ok := s.has(id) - if !ok { - return fmt.Errorf("not found, %v", id) - } - - if _, ok = s.has(to); ok && id != to { - return fmt.Errorf("already exists, %v", to) - } - - s.order[i] = to - return nil -} - -func (s *relativeOrder) Remove(id string) error { - i, ok := s.has(id) - if !ok { - return fmt.Errorf("not found, %v", id) - } - - s.order = append(s.order[:i], s.order[i+1:]...) - return nil -} - -func (s *relativeOrder) List() []string { - return s.order -} - -func (s *relativeOrder) Clear() { - s.order = s.order[0:0] -} - -func (s *relativeOrder) insert(i int, pos RelativePosition, ids ...string) error { - switch pos { - case Before: - n := len(ids) - var src []string - if n <= cap(s.order)-len(s.order) { - s.order = s.order[:len(s.order)+n] - src = s.order - } else { - src = s.order - s.order = make([]string, len(s.order)+n) - copy(s.order[:i], src[:i]) // only when allocating a new slice do we need to copy the front half - } - copy(s.order[i+n:], src[i:]) - copy(s.order[i:], ids) - case After: - if i == len(s.order)-1 || len(s.order) == 0 { - s.order = append(s.order, ids...) - } else { - s.order = append(s.order[:i+1], append(ids, s.order[i+1:]...)...) - } - - default: - return fmt.Errorf("invalid position, %v", int(pos)) - } - - return nil -} - -func (s *relativeOrder) has(id string) (i int, found bool) { - for i := 0; i < len(s.order); i++ { - if s.order[i] == id { - return i, true - } - } - return 0, false -} diff --git a/vendor/github.com/aws/smithy-go/middleware/stack.go b/vendor/github.com/aws/smithy-go/middleware/stack.go deleted file mode 100644 index 45ccb5b93..000000000 --- a/vendor/github.com/aws/smithy-go/middleware/stack.go +++ /dev/null @@ -1,209 +0,0 @@ -package middleware - -import ( - "context" - "io" - "strings" -) - -// Stack provides protocol and transport agnostic set of middleware split into -// distinct steps. Steps have specific transitions between them, that are -// managed by the individual step. -// -// Steps are composed as middleware around the underlying handler in the -// following order: -// -// Initialize -> Serialize -> Build -> Finalize -> Deserialize -> Handler -// -// Any middleware within the chain may choose to stop and return an error or -// response. Since the middleware decorate the handler like a call stack, each -// middleware will receive the result of the next middleware in the chain. -// Middleware that does not need to react to an input, or result must forward -// along the input down the chain, or return the result back up the chain. -// -// Initialize <- Serialize -> Build -> Finalize <- Deserialize <- Handler -type Stack struct { - // Initialize prepares the input, and sets any default parameters as - // needed, (e.g. idempotency token, and presigned URLs). - // - // Takes Input Parameters, and returns result or error. - // - // Receives result or error from Serialize step. - Initialize *InitializeStep - - // Serialize serializes the prepared input into a data structure that can be consumed - // by the target transport's message, (e.g. REST-JSON serialization) - // - // Converts Input Parameters into a Request, and returns the result or error. - // - // Receives result or error from Build step. - Serialize *SerializeStep - - // Build adds additional metadata to the serialized transport message - // (e.g. HTTP's Content-Length header, or body checksum). Decorations and - // modifications to the message should be copied to all message attempts. - // - // Takes Request, and returns result or error. - // - // Receives result or error from Finalize step. - Build *BuildStep - - // Finalize performs final preparations needed before sending the message. The - // message should already be complete by this stage, and is only alternated - // to meet the expectations of the recipient (e.g. Retry and AWS SigV4 - // request signing) - // - // Takes Request, and returns result or error. - // - // Receives result or error from Deserialize step. - Finalize *FinalizeStep - - // Deserialize reacts to the handler's response returned by the recipient of the request - // message. Deserializes the response into a structured type or error above - // stacks can react to. - // - // Should only forward Request to underlying handler. - // - // Takes Request, and returns result or error. - // - // Receives raw response, or error from underlying handler. - Deserialize *DeserializeStep - - id string -} - -// NewStack returns an initialize empty stack. -func NewStack(id string, newRequestFn func() interface{}) *Stack { - return &Stack{ - id: id, - Initialize: NewInitializeStep(), - Serialize: NewSerializeStep(newRequestFn), - Build: NewBuildStep(), - Finalize: NewFinalizeStep(), - Deserialize: NewDeserializeStep(), - } -} - -// ID returns the unique ID for the stack as a middleware. -func (s *Stack) ID() string { return s.id } - -// HandleMiddleware invokes the middleware stack decorating the next handler. -// Each step of stack will be invoked in order before calling the next step. -// With the next handler call last. -// -// The input value must be the input parameters of the operation being -// performed. -// -// Will return the result of the operation, or error. -func (s *Stack) HandleMiddleware(ctx context.Context, input interface{}, next Handler) ( - output interface{}, metadata Metadata, err error, -) { - h := DecorateHandler(next, - s.Initialize, - s.Serialize, - s.Build, - s.Finalize, - s.Deserialize, - ) - - return h.Handle(ctx, input) -} - -// List returns a list of all middleware in the stack by step. -func (s *Stack) List() []string { - var l []string - l = append(l, s.id) - - l = append(l, s.Initialize.ID()) - l = append(l, s.Initialize.List()...) - - l = append(l, s.Serialize.ID()) - l = append(l, s.Serialize.List()...) - - l = append(l, s.Build.ID()) - l = append(l, s.Build.List()...) - - l = append(l, s.Finalize.ID()) - l = append(l, s.Finalize.List()...) - - l = append(l, s.Deserialize.ID()) - l = append(l, s.Deserialize.List()...) - - return l -} - -func (s *Stack) String() string { - var b strings.Builder - - w := &indentWriter{w: &b} - - w.WriteLine(s.id) - w.Push() - - writeStepItems(w, s.Initialize) - writeStepItems(w, s.Serialize) - writeStepItems(w, s.Build) - writeStepItems(w, s.Finalize) - writeStepItems(w, s.Deserialize) - - return b.String() -} - -type stackStepper interface { - ID() string - List() []string -} - -func writeStepItems(w *indentWriter, s stackStepper) { - type lister interface { - List() []string - } - - w.WriteLine(s.ID()) - w.Push() - - defer w.Pop() - - // ignore stack to prevent circular iterations - if _, ok := s.(*Stack); ok { - return - } - - for _, id := range s.List() { - w.WriteLine(id) - } -} - -type stringWriter interface { - io.Writer - WriteString(string) (int, error) - WriteRune(rune) (int, error) -} - -type indentWriter struct { - w stringWriter - depth int -} - -const indentDepth = "\t\t\t\t\t\t\t\t\t\t" - -func (w *indentWriter) Push() { - w.depth++ -} - -func (w *indentWriter) Pop() { - w.depth-- - if w.depth < 0 { - w.depth = 0 - } -} - -func (w *indentWriter) WriteLine(v string) { - w.w.WriteString(indentDepth[:w.depth]) - - v = strings.ReplaceAll(v, "\n", "\\n") - v = strings.ReplaceAll(v, "\r", "\\r") - - w.w.WriteString(v) - w.w.WriteRune('\n') -} diff --git a/vendor/github.com/aws/smithy-go/middleware/stack_values.go b/vendor/github.com/aws/smithy-go/middleware/stack_values.go deleted file mode 100644 index ef96009ba..000000000 --- a/vendor/github.com/aws/smithy-go/middleware/stack_values.go +++ /dev/null @@ -1,100 +0,0 @@ -package middleware - -import ( - "context" - "reflect" - "strings" -) - -// WithStackValue adds a key value pair to the context that is intended to be -// scoped to a stack. Use ClearStackValues to get a new context with all stack -// values cleared. -func WithStackValue(ctx context.Context, key, value interface{}) context.Context { - md, _ := ctx.Value(stackValuesKey{}).(*stackValues) - - md = withStackValue(md, key, value) - return context.WithValue(ctx, stackValuesKey{}, md) -} - -// ClearStackValues returns a context without any stack values. -func ClearStackValues(ctx context.Context) context.Context { - return context.WithValue(ctx, stackValuesKey{}, nil) -} - -// GetStackValues returns the value pointed to by the key within the stack -// values, if it is present. -func GetStackValue(ctx context.Context, key interface{}) interface{} { - md, _ := ctx.Value(stackValuesKey{}).(*stackValues) - if md == nil { - return nil - } - - return md.Value(key) -} - -type stackValuesKey struct{} - -type stackValues struct { - key interface{} - value interface{} - parent *stackValues -} - -func withStackValue(parent *stackValues, key, value interface{}) *stackValues { - if key == nil { - panic("nil key") - } - if !reflect.TypeOf(key).Comparable() { - panic("key is not comparable") - } - return &stackValues{key: key, value: value, parent: parent} -} - -func (m *stackValues) Value(key interface{}) interface{} { - if key == m.key { - return m.value - } - - if m.parent == nil { - return nil - } - - return m.parent.Value(key) -} - -func (c *stackValues) String() string { - var str strings.Builder - - cc := c - for cc == nil { - str.WriteString("(" + - reflect.TypeOf(c.key).String() + - ": " + - stringify(cc.value) + - ")") - if cc.parent != nil { - str.WriteString(" -> ") - } - cc = cc.parent - } - str.WriteRune('}') - - return str.String() -} - -type stringer interface { - String() string -} - -// stringify tries a bit to stringify v, without using fmt, since we don't -// want context depending on the unicode tables. This is only used by -// *valueCtx.String(). -func stringify(v interface{}) string { - switch s := v.(type) { - case stringer: - return s.String() - case string: - return s - } - return "" -} diff --git a/vendor/github.com/aws/smithy-go/middleware/step_build.go b/vendor/github.com/aws/smithy-go/middleware/step_build.go deleted file mode 100644 index 7e1d94cae..000000000 --- a/vendor/github.com/aws/smithy-go/middleware/step_build.go +++ /dev/null @@ -1,211 +0,0 @@ -package middleware - -import ( - "context" -) - -// BuildInput provides the input parameters for the BuildMiddleware to consume. -// BuildMiddleware may modify the Request value before forwarding the input -// along to the next BuildHandler. -type BuildInput struct { - Request interface{} -} - -// BuildOutput provides the result returned by the next BuildHandler. -type BuildOutput struct { - Result interface{} -} - -// BuildHandler provides the interface for the next handler the -// BuildMiddleware will call in the middleware chain. -type BuildHandler interface { - HandleBuild(ctx context.Context, in BuildInput) ( - out BuildOutput, metadata Metadata, err error, - ) -} - -// BuildMiddleware provides the interface for middleware specific to the -// serialize step. Delegates to the next BuildHandler for further -// processing. -type BuildMiddleware interface { - // Unique ID for the middleware in theBuildStep. The step does not allow - // duplicate IDs. - ID() string - - // Invokes the middleware behavior which must delegate to the next handler - // for the middleware chain to continue. The method must return a result or - // error to its caller. - HandleBuild(ctx context.Context, in BuildInput, next BuildHandler) ( - out BuildOutput, metadata Metadata, err error, - ) -} - -// BuildMiddlewareFunc returns a BuildMiddleware with the unique ID provided, -// and the func to be invoked. -func BuildMiddlewareFunc(id string, fn func(context.Context, BuildInput, BuildHandler) (BuildOutput, Metadata, error)) BuildMiddleware { - return buildMiddlewareFunc{ - id: id, - fn: fn, - } -} - -type buildMiddlewareFunc struct { - // Unique ID for the middleware. - id string - - // Middleware function to be called. - fn func(context.Context, BuildInput, BuildHandler) (BuildOutput, Metadata, error) -} - -// ID returns the unique ID for the middleware. -func (s buildMiddlewareFunc) ID() string { return s.id } - -// HandleBuild invokes the middleware Fn. -func (s buildMiddlewareFunc) HandleBuild(ctx context.Context, in BuildInput, next BuildHandler) ( - out BuildOutput, metadata Metadata, err error, -) { - return s.fn(ctx, in, next) -} - -var _ BuildMiddleware = (buildMiddlewareFunc{}) - -// BuildStep provides the ordered grouping of BuildMiddleware to be invoked on -// a handler. -type BuildStep struct { - ids *orderedIDs -} - -// NewBuildStep returns a BuildStep ready to have middleware for -// initialization added to it. -func NewBuildStep() *BuildStep { - return &BuildStep{ - ids: newOrderedIDs(), - } -} - -var _ Middleware = (*BuildStep)(nil) - -// ID returns the unique name of the step as a middleware. -func (s *BuildStep) ID() string { - return "Build stack step" -} - -// HandleMiddleware invokes the middleware by decorating the next handler -// provided. Returns the result of the middleware and handler being invoked. -// -// Implements Middleware interface. -func (s *BuildStep) HandleMiddleware(ctx context.Context, in interface{}, next Handler) ( - out interface{}, metadata Metadata, err error, -) { - order := s.ids.GetOrder() - - var h BuildHandler = buildWrapHandler{Next: next} - for i := len(order) - 1; i >= 0; i-- { - h = decoratedBuildHandler{ - Next: h, - With: order[i].(BuildMiddleware), - } - } - - sIn := BuildInput{ - Request: in, - } - - res, metadata, err := h.HandleBuild(ctx, sIn) - return res.Result, metadata, err -} - -// Get retrieves the middleware identified by id. If the middleware is not present, returns false. -func (s *BuildStep) Get(id string) (BuildMiddleware, bool) { - get, ok := s.ids.Get(id) - if !ok { - return nil, false - } - return get.(BuildMiddleware), ok -} - -// Add injects the middleware to the relative position of the middleware group. -// Returns an error if the middleware already exists. -func (s *BuildStep) Add(m BuildMiddleware, pos RelativePosition) error { - return s.ids.Add(m, pos) -} - -// Insert injects the middleware relative to an existing middleware id. -// Returns an error if the original middleware does not exist, or the middleware -// being added already exists. -func (s *BuildStep) Insert(m BuildMiddleware, relativeTo string, pos RelativePosition) error { - return s.ids.Insert(m, relativeTo, pos) -} - -// Swap removes the middleware by id, replacing it with the new middleware. -// Returns the middleware removed, or an error if the middleware to be removed -// doesn't exist. -func (s *BuildStep) Swap(id string, m BuildMiddleware) (BuildMiddleware, error) { - removed, err := s.ids.Swap(id, m) - if err != nil { - return nil, err - } - - return removed.(BuildMiddleware), nil -} - -// Remove removes the middleware by id. Returns error if the middleware -// doesn't exist. -func (s *BuildStep) Remove(id string) (BuildMiddleware, error) { - removed, err := s.ids.Remove(id) - if err != nil { - return nil, err - } - - return removed.(BuildMiddleware), nil -} - -// List returns a list of the middleware in the step. -func (s *BuildStep) List() []string { - return s.ids.List() -} - -// Clear removes all middleware in the step. -func (s *BuildStep) Clear() { - s.ids.Clear() -} - -type buildWrapHandler struct { - Next Handler -} - -var _ BuildHandler = (*buildWrapHandler)(nil) - -// Implements BuildHandler, converts types and delegates to underlying -// generic handler. -func (w buildWrapHandler) HandleBuild(ctx context.Context, in BuildInput) ( - out BuildOutput, metadata Metadata, err error, -) { - res, metadata, err := w.Next.Handle(ctx, in.Request) - return BuildOutput{ - Result: res, - }, metadata, err -} - -type decoratedBuildHandler struct { - Next BuildHandler - With BuildMiddleware -} - -var _ BuildHandler = (*decoratedBuildHandler)(nil) - -func (h decoratedBuildHandler) HandleBuild(ctx context.Context, in BuildInput) ( - out BuildOutput, metadata Metadata, err error, -) { - return h.With.HandleBuild(ctx, in, h.Next) -} - -// BuildHandlerFunc provides a wrapper around a function to be used as a build middleware handler. -type BuildHandlerFunc func(context.Context, BuildInput) (BuildOutput, Metadata, error) - -// HandleBuild invokes the wrapped function with the provided arguments. -func (b BuildHandlerFunc) HandleBuild(ctx context.Context, in BuildInput) (BuildOutput, Metadata, error) { - return b(ctx, in) -} - -var _ BuildHandler = BuildHandlerFunc(nil) diff --git a/vendor/github.com/aws/smithy-go/middleware/step_deserialize.go b/vendor/github.com/aws/smithy-go/middleware/step_deserialize.go deleted file mode 100644 index 448607215..000000000 --- a/vendor/github.com/aws/smithy-go/middleware/step_deserialize.go +++ /dev/null @@ -1,217 +0,0 @@ -package middleware - -import ( - "context" -) - -// DeserializeInput provides the input parameters for the DeserializeInput to -// consume. DeserializeMiddleware should not modify the Request, and instead -// forward it along to the next DeserializeHandler. -type DeserializeInput struct { - Request interface{} -} - -// DeserializeOutput provides the result returned by the next -// DeserializeHandler. The DeserializeMiddleware should deserialize the -// RawResponse into a Result that can be consumed by middleware higher up in -// the stack. -type DeserializeOutput struct { - RawResponse interface{} - Result interface{} -} - -// DeserializeHandler provides the interface for the next handler the -// DeserializeMiddleware will call in the middleware chain. -type DeserializeHandler interface { - HandleDeserialize(ctx context.Context, in DeserializeInput) ( - out DeserializeOutput, metadata Metadata, err error, - ) -} - -// DeserializeMiddleware provides the interface for middleware specific to the -// serialize step. Delegates to the next DeserializeHandler for further -// processing. -type DeserializeMiddleware interface { - // ID returns a unique ID for the middleware in the DeserializeStep. The step does not - // allow duplicate IDs. - ID() string - - // HandleDeserialize invokes the middleware behavior which must delegate to the next handler - // for the middleware chain to continue. The method must return a result or - // error to its caller. - HandleDeserialize(ctx context.Context, in DeserializeInput, next DeserializeHandler) ( - out DeserializeOutput, metadata Metadata, err error, - ) -} - -// DeserializeMiddlewareFunc returns a DeserializeMiddleware with the unique ID -// provided, and the func to be invoked. -func DeserializeMiddlewareFunc(id string, fn func(context.Context, DeserializeInput, DeserializeHandler) (DeserializeOutput, Metadata, error)) DeserializeMiddleware { - return deserializeMiddlewareFunc{ - id: id, - fn: fn, - } -} - -type deserializeMiddlewareFunc struct { - // Unique ID for the middleware. - id string - - // Middleware function to be called. - fn func(context.Context, DeserializeInput, DeserializeHandler) ( - DeserializeOutput, Metadata, error, - ) -} - -// ID returns the unique ID for the middleware. -func (s deserializeMiddlewareFunc) ID() string { return s.id } - -// HandleDeserialize invokes the middleware Fn. -func (s deserializeMiddlewareFunc) HandleDeserialize(ctx context.Context, in DeserializeInput, next DeserializeHandler) ( - out DeserializeOutput, metadata Metadata, err error, -) { - return s.fn(ctx, in, next) -} - -var _ DeserializeMiddleware = (deserializeMiddlewareFunc{}) - -// DeserializeStep provides the ordered grouping of DeserializeMiddleware to be -// invoked on a handler. -type DeserializeStep struct { - ids *orderedIDs -} - -// NewDeserializeStep returns a DeserializeStep ready to have middleware for -// initialization added to it. -func NewDeserializeStep() *DeserializeStep { - return &DeserializeStep{ - ids: newOrderedIDs(), - } -} - -var _ Middleware = (*DeserializeStep)(nil) - -// ID returns the unique ID of the step as a middleware. -func (s *DeserializeStep) ID() string { - return "Deserialize stack step" -} - -// HandleMiddleware invokes the middleware by decorating the next handler -// provided. Returns the result of the middleware and handler being invoked. -// -// Implements Middleware interface. -func (s *DeserializeStep) HandleMiddleware(ctx context.Context, in interface{}, next Handler) ( - out interface{}, metadata Metadata, err error, -) { - order := s.ids.GetOrder() - - var h DeserializeHandler = deserializeWrapHandler{Next: next} - for i := len(order) - 1; i >= 0; i-- { - h = decoratedDeserializeHandler{ - Next: h, - With: order[i].(DeserializeMiddleware), - } - } - - sIn := DeserializeInput{ - Request: in, - } - - res, metadata, err := h.HandleDeserialize(ctx, sIn) - return res.Result, metadata, err -} - -// Get retrieves the middleware identified by id. If the middleware is not present, returns false. -func (s *DeserializeStep) Get(id string) (DeserializeMiddleware, bool) { - get, ok := s.ids.Get(id) - if !ok { - return nil, false - } - return get.(DeserializeMiddleware), ok -} - -// Add injects the middleware to the relative position of the middleware group. -// Returns an error if the middleware already exists. -func (s *DeserializeStep) Add(m DeserializeMiddleware, pos RelativePosition) error { - return s.ids.Add(m, pos) -} - -// Insert injects the middleware relative to an existing middleware ID. -// Returns error if the original middleware does not exist, or the middleware -// being added already exists. -func (s *DeserializeStep) Insert(m DeserializeMiddleware, relativeTo string, pos RelativePosition) error { - return s.ids.Insert(m, relativeTo, pos) -} - -// Swap removes the middleware by id, replacing it with the new middleware. -// Returns the middleware removed, or error if the middleware to be removed -// doesn't exist. -func (s *DeserializeStep) Swap(id string, m DeserializeMiddleware) (DeserializeMiddleware, error) { - removed, err := s.ids.Swap(id, m) - if err != nil { - return nil, err - } - - return removed.(DeserializeMiddleware), nil -} - -// Remove removes the middleware by id. Returns error if the middleware -// doesn't exist. -func (s *DeserializeStep) Remove(id string) (DeserializeMiddleware, error) { - removed, err := s.ids.Remove(id) - if err != nil { - return nil, err - } - - return removed.(DeserializeMiddleware), nil -} - -// List returns a list of the middleware in the step. -func (s *DeserializeStep) List() []string { - return s.ids.List() -} - -// Clear removes all middleware in the step. -func (s *DeserializeStep) Clear() { - s.ids.Clear() -} - -type deserializeWrapHandler struct { - Next Handler -} - -var _ DeserializeHandler = (*deserializeWrapHandler)(nil) - -// HandleDeserialize implements DeserializeHandler, converts types and delegates to underlying -// generic handler. -func (w deserializeWrapHandler) HandleDeserialize(ctx context.Context, in DeserializeInput) ( - out DeserializeOutput, metadata Metadata, err error, -) { - resp, metadata, err := w.Next.Handle(ctx, in.Request) - return DeserializeOutput{ - RawResponse: resp, - }, metadata, err -} - -type decoratedDeserializeHandler struct { - Next DeserializeHandler - With DeserializeMiddleware -} - -var _ DeserializeHandler = (*decoratedDeserializeHandler)(nil) - -func (h decoratedDeserializeHandler) HandleDeserialize(ctx context.Context, in DeserializeInput) ( - out DeserializeOutput, metadata Metadata, err error, -) { - return h.With.HandleDeserialize(ctx, in, h.Next) -} - -// DeserializeHandlerFunc provides a wrapper around a function to be used as a deserialize middleware handler. -type DeserializeHandlerFunc func(context.Context, DeserializeInput) (DeserializeOutput, Metadata, error) - -// HandleDeserialize invokes the wrapped function with the given arguments. -func (d DeserializeHandlerFunc) HandleDeserialize(ctx context.Context, in DeserializeInput) (DeserializeOutput, Metadata, error) { - return d(ctx, in) -} - -var _ DeserializeHandler = DeserializeHandlerFunc(nil) diff --git a/vendor/github.com/aws/smithy-go/middleware/step_finalize.go b/vendor/github.com/aws/smithy-go/middleware/step_finalize.go deleted file mode 100644 index 065e3885d..000000000 --- a/vendor/github.com/aws/smithy-go/middleware/step_finalize.go +++ /dev/null @@ -1,211 +0,0 @@ -package middleware - -import "context" - -// FinalizeInput provides the input parameters for the FinalizeMiddleware to -// consume. FinalizeMiddleware may modify the Request value before forwarding -// the FinalizeInput along to the next next FinalizeHandler. -type FinalizeInput struct { - Request interface{} -} - -// FinalizeOutput provides the result returned by the next FinalizeHandler. -type FinalizeOutput struct { - Result interface{} -} - -// FinalizeHandler provides the interface for the next handler the -// FinalizeMiddleware will call in the middleware chain. -type FinalizeHandler interface { - HandleFinalize(ctx context.Context, in FinalizeInput) ( - out FinalizeOutput, metadata Metadata, err error, - ) -} - -// FinalizeMiddleware provides the interface for middleware specific to the -// serialize step. Delegates to the next FinalizeHandler for further -// processing. -type FinalizeMiddleware interface { - // ID returns a unique ID for the middleware in the FinalizeStep. The step does not - // allow duplicate IDs. - ID() string - - // HandleFinalize invokes the middleware behavior which must delegate to the next handler - // for the middleware chain to continue. The method must return a result or - // error to its caller. - HandleFinalize(ctx context.Context, in FinalizeInput, next FinalizeHandler) ( - out FinalizeOutput, metadata Metadata, err error, - ) -} - -// FinalizeMiddlewareFunc returns a FinalizeMiddleware with the unique ID -// provided, and the func to be invoked. -func FinalizeMiddlewareFunc(id string, fn func(context.Context, FinalizeInput, FinalizeHandler) (FinalizeOutput, Metadata, error)) FinalizeMiddleware { - return finalizeMiddlewareFunc{ - id: id, - fn: fn, - } -} - -type finalizeMiddlewareFunc struct { - // Unique ID for the middleware. - id string - - // Middleware function to be called. - fn func(context.Context, FinalizeInput, FinalizeHandler) ( - FinalizeOutput, Metadata, error, - ) -} - -// ID returns the unique ID for the middleware. -func (s finalizeMiddlewareFunc) ID() string { return s.id } - -// HandleFinalize invokes the middleware Fn. -func (s finalizeMiddlewareFunc) HandleFinalize(ctx context.Context, in FinalizeInput, next FinalizeHandler) ( - out FinalizeOutput, metadata Metadata, err error, -) { - return s.fn(ctx, in, next) -} - -var _ FinalizeMiddleware = (finalizeMiddlewareFunc{}) - -// FinalizeStep provides the ordered grouping of FinalizeMiddleware to be -// invoked on a handler. -type FinalizeStep struct { - ids *orderedIDs -} - -// NewFinalizeStep returns a FinalizeStep ready to have middleware for -// initialization added to it. -func NewFinalizeStep() *FinalizeStep { - return &FinalizeStep{ - ids: newOrderedIDs(), - } -} - -var _ Middleware = (*FinalizeStep)(nil) - -// ID returns the unique id of the step as a middleware. -func (s *FinalizeStep) ID() string { - return "Finalize stack step" -} - -// HandleMiddleware invokes the middleware by decorating the next handler -// provided. Returns the result of the middleware and handler being invoked. -// -// Implements Middleware interface. -func (s *FinalizeStep) HandleMiddleware(ctx context.Context, in interface{}, next Handler) ( - out interface{}, metadata Metadata, err error, -) { - order := s.ids.GetOrder() - - var h FinalizeHandler = finalizeWrapHandler{Next: next} - for i := len(order) - 1; i >= 0; i-- { - h = decoratedFinalizeHandler{ - Next: h, - With: order[i].(FinalizeMiddleware), - } - } - - sIn := FinalizeInput{ - Request: in, - } - - res, metadata, err := h.HandleFinalize(ctx, sIn) - return res.Result, metadata, err -} - -// Get retrieves the middleware identified by id. If the middleware is not present, returns false. -func (s *FinalizeStep) Get(id string) (FinalizeMiddleware, bool) { - get, ok := s.ids.Get(id) - if !ok { - return nil, false - } - return get.(FinalizeMiddleware), ok -} - -// Add injects the middleware to the relative position of the middleware group. -// Returns an error if the middleware already exists. -func (s *FinalizeStep) Add(m FinalizeMiddleware, pos RelativePosition) error { - return s.ids.Add(m, pos) -} - -// Insert injects the middleware relative to an existing middleware ID. -// Returns error if the original middleware does not exist, or the middleware -// being added already exists. -func (s *FinalizeStep) Insert(m FinalizeMiddleware, relativeTo string, pos RelativePosition) error { - return s.ids.Insert(m, relativeTo, pos) -} - -// Swap removes the middleware by id, replacing it with the new middleware. -// Returns the middleware removed, or error if the middleware to be removed -// doesn't exist. -func (s *FinalizeStep) Swap(id string, m FinalizeMiddleware) (FinalizeMiddleware, error) { - removed, err := s.ids.Swap(id, m) - if err != nil { - return nil, err - } - - return removed.(FinalizeMiddleware), nil -} - -// Remove removes the middleware by id. Returns error if the middleware -// doesn't exist. -func (s *FinalizeStep) Remove(id string) (FinalizeMiddleware, error) { - removed, err := s.ids.Remove(id) - if err != nil { - return nil, err - } - - return removed.(FinalizeMiddleware), nil -} - -// List returns a list of the middleware in the step. -func (s *FinalizeStep) List() []string { - return s.ids.List() -} - -// Clear removes all middleware in the step. -func (s *FinalizeStep) Clear() { - s.ids.Clear() -} - -type finalizeWrapHandler struct { - Next Handler -} - -var _ FinalizeHandler = (*finalizeWrapHandler)(nil) - -// HandleFinalize implements FinalizeHandler, converts types and delegates to underlying -// generic handler. -func (w finalizeWrapHandler) HandleFinalize(ctx context.Context, in FinalizeInput) ( - out FinalizeOutput, metadata Metadata, err error, -) { - res, metadata, err := w.Next.Handle(ctx, in.Request) - return FinalizeOutput{ - Result: res, - }, metadata, err -} - -type decoratedFinalizeHandler struct { - Next FinalizeHandler - With FinalizeMiddleware -} - -var _ FinalizeHandler = (*decoratedFinalizeHandler)(nil) - -func (h decoratedFinalizeHandler) HandleFinalize(ctx context.Context, in FinalizeInput) ( - out FinalizeOutput, metadata Metadata, err error, -) { - return h.With.HandleFinalize(ctx, in, h.Next) -} - -// FinalizeHandlerFunc provides a wrapper around a function to be used as a finalize middleware handler. -type FinalizeHandlerFunc func(context.Context, FinalizeInput) (FinalizeOutput, Metadata, error) - -// HandleFinalize invokes the wrapped function with the given arguments. -func (f FinalizeHandlerFunc) HandleFinalize(ctx context.Context, in FinalizeInput) (FinalizeOutput, Metadata, error) { - return f(ctx, in) -} - -var _ FinalizeHandler = FinalizeHandlerFunc(nil) diff --git a/vendor/github.com/aws/smithy-go/middleware/step_initialize.go b/vendor/github.com/aws/smithy-go/middleware/step_initialize.go deleted file mode 100644 index fe359144d..000000000 --- a/vendor/github.com/aws/smithy-go/middleware/step_initialize.go +++ /dev/null @@ -1,211 +0,0 @@ -package middleware - -import "context" - -// InitializeInput wraps the input parameters for the InitializeMiddlewares to -// consume. InitializeMiddleware may modify the parameter value before -// forwarding it along to the next InitializeHandler. -type InitializeInput struct { - Parameters interface{} -} - -// InitializeOutput provides the result returned by the next InitializeHandler. -type InitializeOutput struct { - Result interface{} -} - -// InitializeHandler provides the interface for the next handler the -// InitializeMiddleware will call in the middleware chain. -type InitializeHandler interface { - HandleInitialize(ctx context.Context, in InitializeInput) ( - out InitializeOutput, metadata Metadata, err error, - ) -} - -// InitializeMiddleware provides the interface for middleware specific to the -// initialize step. Delegates to the next InitializeHandler for further -// processing. -type InitializeMiddleware interface { - // ID returns a unique ID for the middleware in the InitializeStep. The step does not - // allow duplicate IDs. - ID() string - - // HandleInitialize invokes the middleware behavior which must delegate to the next handler - // for the middleware chain to continue. The method must return a result or - // error to its caller. - HandleInitialize(ctx context.Context, in InitializeInput, next InitializeHandler) ( - out InitializeOutput, metadata Metadata, err error, - ) -} - -// InitializeMiddlewareFunc returns a InitializeMiddleware with the unique ID provided, -// and the func to be invoked. -func InitializeMiddlewareFunc(id string, fn func(context.Context, InitializeInput, InitializeHandler) (InitializeOutput, Metadata, error)) InitializeMiddleware { - return initializeMiddlewareFunc{ - id: id, - fn: fn, - } -} - -type initializeMiddlewareFunc struct { - // Unique ID for the middleware. - id string - - // Middleware function to be called. - fn func(context.Context, InitializeInput, InitializeHandler) ( - InitializeOutput, Metadata, error, - ) -} - -// ID returns the unique ID for the middleware. -func (s initializeMiddlewareFunc) ID() string { return s.id } - -// HandleInitialize invokes the middleware Fn. -func (s initializeMiddlewareFunc) HandleInitialize(ctx context.Context, in InitializeInput, next InitializeHandler) ( - out InitializeOutput, metadata Metadata, err error, -) { - return s.fn(ctx, in, next) -} - -var _ InitializeMiddleware = (initializeMiddlewareFunc{}) - -// InitializeStep provides the ordered grouping of InitializeMiddleware to be -// invoked on a handler. -type InitializeStep struct { - ids *orderedIDs -} - -// NewInitializeStep returns an InitializeStep ready to have middleware for -// initialization added to it. -func NewInitializeStep() *InitializeStep { - return &InitializeStep{ - ids: newOrderedIDs(), - } -} - -var _ Middleware = (*InitializeStep)(nil) - -// ID returns the unique ID of the step as a middleware. -func (s *InitializeStep) ID() string { - return "Initialize stack step" -} - -// HandleMiddleware invokes the middleware by decorating the next handler -// provided. Returns the result of the middleware and handler being invoked. -// -// Implements Middleware interface. -func (s *InitializeStep) HandleMiddleware(ctx context.Context, in interface{}, next Handler) ( - out interface{}, metadata Metadata, err error, -) { - order := s.ids.GetOrder() - - var h InitializeHandler = initializeWrapHandler{Next: next} - for i := len(order) - 1; i >= 0; i-- { - h = decoratedInitializeHandler{ - Next: h, - With: order[i].(InitializeMiddleware), - } - } - - sIn := InitializeInput{ - Parameters: in, - } - - res, metadata, err := h.HandleInitialize(ctx, sIn) - return res.Result, metadata, err -} - -// Get retrieves the middleware identified by id. If the middleware is not present, returns false. -func (s *InitializeStep) Get(id string) (InitializeMiddleware, bool) { - get, ok := s.ids.Get(id) - if !ok { - return nil, false - } - return get.(InitializeMiddleware), ok -} - -// Add injects the middleware to the relative position of the middleware group. -// Returns an error if the middleware already exists. -func (s *InitializeStep) Add(m InitializeMiddleware, pos RelativePosition) error { - return s.ids.Add(m, pos) -} - -// Insert injects the middleware relative to an existing middleware ID. -// Returns error if the original middleware does not exist, or the middleware -// being added already exists. -func (s *InitializeStep) Insert(m InitializeMiddleware, relativeTo string, pos RelativePosition) error { - return s.ids.Insert(m, relativeTo, pos) -} - -// Swap removes the middleware by id, replacing it with the new middleware. -// Returns the middleware removed, or error if the middleware to be removed -// doesn't exist. -func (s *InitializeStep) Swap(id string, m InitializeMiddleware) (InitializeMiddleware, error) { - removed, err := s.ids.Swap(id, m) - if err != nil { - return nil, err - } - - return removed.(InitializeMiddleware), nil -} - -// Remove removes the middleware by id. Returns error if the middleware -// doesn't exist. -func (s *InitializeStep) Remove(id string) (InitializeMiddleware, error) { - removed, err := s.ids.Remove(id) - if err != nil { - return nil, err - } - - return removed.(InitializeMiddleware), nil -} - -// List returns a list of the middleware in the step. -func (s *InitializeStep) List() []string { - return s.ids.List() -} - -// Clear removes all middleware in the step. -func (s *InitializeStep) Clear() { - s.ids.Clear() -} - -type initializeWrapHandler struct { - Next Handler -} - -var _ InitializeHandler = (*initializeWrapHandler)(nil) - -// HandleInitialize implements InitializeHandler, converts types and delegates to underlying -// generic handler. -func (w initializeWrapHandler) HandleInitialize(ctx context.Context, in InitializeInput) ( - out InitializeOutput, metadata Metadata, err error, -) { - res, metadata, err := w.Next.Handle(ctx, in.Parameters) - return InitializeOutput{ - Result: res, - }, metadata, err -} - -type decoratedInitializeHandler struct { - Next InitializeHandler - With InitializeMiddleware -} - -var _ InitializeHandler = (*decoratedInitializeHandler)(nil) - -func (h decoratedInitializeHandler) HandleInitialize(ctx context.Context, in InitializeInput) ( - out InitializeOutput, metadata Metadata, err error, -) { - return h.With.HandleInitialize(ctx, in, h.Next) -} - -// InitializeHandlerFunc provides a wrapper around a function to be used as an initialize middleware handler. -type InitializeHandlerFunc func(context.Context, InitializeInput) (InitializeOutput, Metadata, error) - -// HandleInitialize calls the wrapped function with the provided arguments. -func (i InitializeHandlerFunc) HandleInitialize(ctx context.Context, in InitializeInput) (InitializeOutput, Metadata, error) { - return i(ctx, in) -} - -var _ InitializeHandler = InitializeHandlerFunc(nil) diff --git a/vendor/github.com/aws/smithy-go/middleware/step_serialize.go b/vendor/github.com/aws/smithy-go/middleware/step_serialize.go deleted file mode 100644 index 114bafced..000000000 --- a/vendor/github.com/aws/smithy-go/middleware/step_serialize.go +++ /dev/null @@ -1,219 +0,0 @@ -package middleware - -import "context" - -// SerializeInput provides the input parameters for the SerializeMiddleware to -// consume. SerializeMiddleware may modify the Request value before forwarding -// SerializeInput along to the next SerializeHandler. The Parameters member -// should not be modified by SerializeMiddleware, InitializeMiddleware should -// be responsible for modifying the provided Parameter value. -type SerializeInput struct { - Parameters interface{} - Request interface{} -} - -// SerializeOutput provides the result returned by the next SerializeHandler. -type SerializeOutput struct { - Result interface{} -} - -// SerializeHandler provides the interface for the next handler the -// SerializeMiddleware will call in the middleware chain. -type SerializeHandler interface { - HandleSerialize(ctx context.Context, in SerializeInput) ( - out SerializeOutput, metadata Metadata, err error, - ) -} - -// SerializeMiddleware provides the interface for middleware specific to the -// serialize step. Delegates to the next SerializeHandler for further -// processing. -type SerializeMiddleware interface { - // ID returns a unique ID for the middleware in the SerializeStep. The step does not - // allow duplicate IDs. - ID() string - - // HandleSerialize invokes the middleware behavior which must delegate to the next handler - // for the middleware chain to continue. The method must return a result or - // error to its caller. - HandleSerialize(ctx context.Context, in SerializeInput, next SerializeHandler) ( - out SerializeOutput, metadata Metadata, err error, - ) -} - -// SerializeMiddlewareFunc returns a SerializeMiddleware with the unique ID -// provided, and the func to be invoked. -func SerializeMiddlewareFunc(id string, fn func(context.Context, SerializeInput, SerializeHandler) (SerializeOutput, Metadata, error)) SerializeMiddleware { - return serializeMiddlewareFunc{ - id: id, - fn: fn, - } -} - -type serializeMiddlewareFunc struct { - // Unique ID for the middleware. - id string - - // Middleware function to be called. - fn func(context.Context, SerializeInput, SerializeHandler) ( - SerializeOutput, Metadata, error, - ) -} - -// ID returns the unique ID for the middleware. -func (s serializeMiddlewareFunc) ID() string { return s.id } - -// HandleSerialize invokes the middleware Fn. -func (s serializeMiddlewareFunc) HandleSerialize(ctx context.Context, in SerializeInput, next SerializeHandler) ( - out SerializeOutput, metadata Metadata, err error, -) { - return s.fn(ctx, in, next) -} - -var _ SerializeMiddleware = (serializeMiddlewareFunc{}) - -// SerializeStep provides the ordered grouping of SerializeMiddleware to be -// invoked on a handler. -type SerializeStep struct { - newRequest func() interface{} - ids *orderedIDs -} - -// NewSerializeStep returns a SerializeStep ready to have middleware for -// initialization added to it. The newRequest func parameter is used to -// initialize the transport specific request for the stack SerializeStep to -// serialize the input parameters into. -func NewSerializeStep(newRequest func() interface{}) *SerializeStep { - return &SerializeStep{ - ids: newOrderedIDs(), - newRequest: newRequest, - } -} - -var _ Middleware = (*SerializeStep)(nil) - -// ID returns the unique ID of the step as a middleware. -func (s *SerializeStep) ID() string { - return "Serialize stack step" -} - -// HandleMiddleware invokes the middleware by decorating the next handler -// provided. Returns the result of the middleware and handler being invoked. -// -// Implements Middleware interface. -func (s *SerializeStep) HandleMiddleware(ctx context.Context, in interface{}, next Handler) ( - out interface{}, metadata Metadata, err error, -) { - order := s.ids.GetOrder() - - var h SerializeHandler = serializeWrapHandler{Next: next} - for i := len(order) - 1; i >= 0; i-- { - h = decoratedSerializeHandler{ - Next: h, - With: order[i].(SerializeMiddleware), - } - } - - sIn := SerializeInput{ - Parameters: in, - Request: s.newRequest(), - } - - res, metadata, err := h.HandleSerialize(ctx, sIn) - return res.Result, metadata, err -} - -// Get retrieves the middleware identified by id. If the middleware is not present, returns false. -func (s *SerializeStep) Get(id string) (SerializeMiddleware, bool) { - get, ok := s.ids.Get(id) - if !ok { - return nil, false - } - return get.(SerializeMiddleware), ok -} - -// Add injects the middleware to the relative position of the middleware group. -// Returns an error if the middleware already exists. -func (s *SerializeStep) Add(m SerializeMiddleware, pos RelativePosition) error { - return s.ids.Add(m, pos) -} - -// Insert injects the middleware relative to an existing middleware ID. -// Returns error if the original middleware does not exist, or the middleware -// being added already exists. -func (s *SerializeStep) Insert(m SerializeMiddleware, relativeTo string, pos RelativePosition) error { - return s.ids.Insert(m, relativeTo, pos) -} - -// Swap removes the middleware by id, replacing it with the new middleware. -// Returns the middleware removed, or error if the middleware to be removed -// doesn't exist. -func (s *SerializeStep) Swap(id string, m SerializeMiddleware) (SerializeMiddleware, error) { - removed, err := s.ids.Swap(id, m) - if err != nil { - return nil, err - } - - return removed.(SerializeMiddleware), nil -} - -// Remove removes the middleware by id. Returns error if the middleware -// doesn't exist. -func (s *SerializeStep) Remove(id string) (SerializeMiddleware, error) { - removed, err := s.ids.Remove(id) - if err != nil { - return nil, err - } - - return removed.(SerializeMiddleware), nil -} - -// List returns a list of the middleware in the step. -func (s *SerializeStep) List() []string { - return s.ids.List() -} - -// Clear removes all middleware in the step. -func (s *SerializeStep) Clear() { - s.ids.Clear() -} - -type serializeWrapHandler struct { - Next Handler -} - -var _ SerializeHandler = (*serializeWrapHandler)(nil) - -// Implements SerializeHandler, converts types and delegates to underlying -// generic handler. -func (w serializeWrapHandler) HandleSerialize(ctx context.Context, in SerializeInput) ( - out SerializeOutput, metadata Metadata, err error, -) { - res, metadata, err := w.Next.Handle(ctx, in.Request) - return SerializeOutput{ - Result: res, - }, metadata, err -} - -type decoratedSerializeHandler struct { - Next SerializeHandler - With SerializeMiddleware -} - -var _ SerializeHandler = (*decoratedSerializeHandler)(nil) - -func (h decoratedSerializeHandler) HandleSerialize(ctx context.Context, in SerializeInput) ( - out SerializeOutput, metadata Metadata, err error, -) { - return h.With.HandleSerialize(ctx, in, h.Next) -} - -// SerializeHandlerFunc provides a wrapper around a function to be used as a serialize middleware handler. -type SerializeHandlerFunc func(context.Context, SerializeInput) (SerializeOutput, Metadata, error) - -// HandleSerialize calls the wrapped function with the provided arguments. -func (s SerializeHandlerFunc) HandleSerialize(ctx context.Context, in SerializeInput) (SerializeOutput, Metadata, error) { - return s(ctx, in) -} - -var _ SerializeHandler = SerializeHandlerFunc(nil) diff --git a/vendor/github.com/aws/smithy-go/modman.toml b/vendor/github.com/aws/smithy-go/modman.toml deleted file mode 100644 index 20295cdd2..000000000 --- a/vendor/github.com/aws/smithy-go/modman.toml +++ /dev/null @@ -1,11 +0,0 @@ -[dependencies] - "github.com/google/go-cmp" = "v0.5.8" - "github.com/jmespath/go-jmespath" = "v0.4.0" - -[modules] - - [modules.codegen] - no_tag = true - - [modules."codegen/smithy-go-codegen/build/test-generated/go/internal/testmodule"] - no_tag = true diff --git a/vendor/github.com/aws/smithy-go/properties.go b/vendor/github.com/aws/smithy-go/properties.go deleted file mode 100644 index 17d659c53..000000000 --- a/vendor/github.com/aws/smithy-go/properties.go +++ /dev/null @@ -1,52 +0,0 @@ -package smithy - -// PropertiesReader provides an interface for reading metadata from the -// underlying metadata container. -type PropertiesReader interface { - Get(key interface{}) interface{} -} - -// Properties provides storing and reading metadata values. Keys may be any -// comparable value type. Get and set will panic if key is not a comparable -// value type. -// -// Properties uses lazy initialization, and Set method must be called as an -// addressable value, or pointer. Not doing so may cause key/value pair to not -// be set. -type Properties struct { - values map[interface{}]interface{} -} - -// Get attempts to retrieve the value the key points to. Returns nil if the -// key was not found. -// -// Panics if key type is not comparable. -func (m *Properties) Get(key interface{}) interface{} { - return m.values[key] -} - -// Set stores the value pointed to by the key. If a value already exists at -// that key it will be replaced with the new value. -// -// Set method must be called as an addressable value, or pointer. If Set is not -// called as an addressable value or pointer, the key value pair being set may -// be lost. -// -// Panics if the key type is not comparable. -func (m *Properties) Set(key, value interface{}) { - if m.values == nil { - m.values = map[interface{}]interface{}{} - } - m.values[key] = value -} - -// Has returns whether the key exists in the metadata. -// -// Panics if the key type is not comparable. -func (m *Properties) Has(key interface{}) bool { - if m.values == nil { - return false - } - _, ok := m.values[key] - return ok -} diff --git a/vendor/github.com/aws/smithy-go/ptr/doc.go b/vendor/github.com/aws/smithy-go/ptr/doc.go deleted file mode 100644 index bc1f69961..000000000 --- a/vendor/github.com/aws/smithy-go/ptr/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -// Package ptr provides utilities for converting scalar literal type values to and from pointers inline. -package ptr - -//go:generate go run -tags codegen generate.go -//go:generate gofmt -w -s . diff --git a/vendor/github.com/aws/smithy-go/ptr/from_ptr.go b/vendor/github.com/aws/smithy-go/ptr/from_ptr.go deleted file mode 100644 index a2845bb2c..000000000 --- a/vendor/github.com/aws/smithy-go/ptr/from_ptr.go +++ /dev/null @@ -1,601 +0,0 @@ -// Code generated by smithy-go/ptr/generate.go DO NOT EDIT. -package ptr - -import ( - "time" -) - -// ToBool returns bool value dereferenced if the passed -// in pointer was not nil. Returns a bool zero value if the -// pointer was nil. -func ToBool(p *bool) (v bool) { - if p == nil { - return v - } - - return *p -} - -// ToBoolSlice returns a slice of bool values, that are -// dereferenced if the passed in pointer was not nil. Returns a bool -// zero value if the pointer was nil. -func ToBoolSlice(vs []*bool) []bool { - ps := make([]bool, len(vs)) - for i, v := range vs { - ps[i] = ToBool(v) - } - - return ps -} - -// ToBoolMap returns a map of bool values, that are -// dereferenced if the passed in pointer was not nil. The bool -// zero value is used if the pointer was nil. -func ToBoolMap(vs map[string]*bool) map[string]bool { - ps := make(map[string]bool, len(vs)) - for k, v := range vs { - ps[k] = ToBool(v) - } - - return ps -} - -// ToByte returns byte value dereferenced if the passed -// in pointer was not nil. Returns a byte zero value if the -// pointer was nil. -func ToByte(p *byte) (v byte) { - if p == nil { - return v - } - - return *p -} - -// ToByteSlice returns a slice of byte values, that are -// dereferenced if the passed in pointer was not nil. Returns a byte -// zero value if the pointer was nil. -func ToByteSlice(vs []*byte) []byte { - ps := make([]byte, len(vs)) - for i, v := range vs { - ps[i] = ToByte(v) - } - - return ps -} - -// ToByteMap returns a map of byte values, that are -// dereferenced if the passed in pointer was not nil. The byte -// zero value is used if the pointer was nil. -func ToByteMap(vs map[string]*byte) map[string]byte { - ps := make(map[string]byte, len(vs)) - for k, v := range vs { - ps[k] = ToByte(v) - } - - return ps -} - -// ToString returns string value dereferenced if the passed -// in pointer was not nil. Returns a string zero value if the -// pointer was nil. -func ToString(p *string) (v string) { - if p == nil { - return v - } - - return *p -} - -// ToStringSlice returns a slice of string values, that are -// dereferenced if the passed in pointer was not nil. Returns a string -// zero value if the pointer was nil. -func ToStringSlice(vs []*string) []string { - ps := make([]string, len(vs)) - for i, v := range vs { - ps[i] = ToString(v) - } - - return ps -} - -// ToStringMap returns a map of string values, that are -// dereferenced if the passed in pointer was not nil. The string -// zero value is used if the pointer was nil. -func ToStringMap(vs map[string]*string) map[string]string { - ps := make(map[string]string, len(vs)) - for k, v := range vs { - ps[k] = ToString(v) - } - - return ps -} - -// ToInt returns int value dereferenced if the passed -// in pointer was not nil. Returns a int zero value if the -// pointer was nil. -func ToInt(p *int) (v int) { - if p == nil { - return v - } - - return *p -} - -// ToIntSlice returns a slice of int values, that are -// dereferenced if the passed in pointer was not nil. Returns a int -// zero value if the pointer was nil. -func ToIntSlice(vs []*int) []int { - ps := make([]int, len(vs)) - for i, v := range vs { - ps[i] = ToInt(v) - } - - return ps -} - -// ToIntMap returns a map of int values, that are -// dereferenced if the passed in pointer was not nil. The int -// zero value is used if the pointer was nil. -func ToIntMap(vs map[string]*int) map[string]int { - ps := make(map[string]int, len(vs)) - for k, v := range vs { - ps[k] = ToInt(v) - } - - return ps -} - -// ToInt8 returns int8 value dereferenced if the passed -// in pointer was not nil. Returns a int8 zero value if the -// pointer was nil. -func ToInt8(p *int8) (v int8) { - if p == nil { - return v - } - - return *p -} - -// ToInt8Slice returns a slice of int8 values, that are -// dereferenced if the passed in pointer was not nil. Returns a int8 -// zero value if the pointer was nil. -func ToInt8Slice(vs []*int8) []int8 { - ps := make([]int8, len(vs)) - for i, v := range vs { - ps[i] = ToInt8(v) - } - - return ps -} - -// ToInt8Map returns a map of int8 values, that are -// dereferenced if the passed in pointer was not nil. The int8 -// zero value is used if the pointer was nil. -func ToInt8Map(vs map[string]*int8) map[string]int8 { - ps := make(map[string]int8, len(vs)) - for k, v := range vs { - ps[k] = ToInt8(v) - } - - return ps -} - -// ToInt16 returns int16 value dereferenced if the passed -// in pointer was not nil. Returns a int16 zero value if the -// pointer was nil. -func ToInt16(p *int16) (v int16) { - if p == nil { - return v - } - - return *p -} - -// ToInt16Slice returns a slice of int16 values, that are -// dereferenced if the passed in pointer was not nil. Returns a int16 -// zero value if the pointer was nil. -func ToInt16Slice(vs []*int16) []int16 { - ps := make([]int16, len(vs)) - for i, v := range vs { - ps[i] = ToInt16(v) - } - - return ps -} - -// ToInt16Map returns a map of int16 values, that are -// dereferenced if the passed in pointer was not nil. The int16 -// zero value is used if the pointer was nil. -func ToInt16Map(vs map[string]*int16) map[string]int16 { - ps := make(map[string]int16, len(vs)) - for k, v := range vs { - ps[k] = ToInt16(v) - } - - return ps -} - -// ToInt32 returns int32 value dereferenced if the passed -// in pointer was not nil. Returns a int32 zero value if the -// pointer was nil. -func ToInt32(p *int32) (v int32) { - if p == nil { - return v - } - - return *p -} - -// ToInt32Slice returns a slice of int32 values, that are -// dereferenced if the passed in pointer was not nil. Returns a int32 -// zero value if the pointer was nil. -func ToInt32Slice(vs []*int32) []int32 { - ps := make([]int32, len(vs)) - for i, v := range vs { - ps[i] = ToInt32(v) - } - - return ps -} - -// ToInt32Map returns a map of int32 values, that are -// dereferenced if the passed in pointer was not nil. The int32 -// zero value is used if the pointer was nil. -func ToInt32Map(vs map[string]*int32) map[string]int32 { - ps := make(map[string]int32, len(vs)) - for k, v := range vs { - ps[k] = ToInt32(v) - } - - return ps -} - -// ToInt64 returns int64 value dereferenced if the passed -// in pointer was not nil. Returns a int64 zero value if the -// pointer was nil. -func ToInt64(p *int64) (v int64) { - if p == nil { - return v - } - - return *p -} - -// ToInt64Slice returns a slice of int64 values, that are -// dereferenced if the passed in pointer was not nil. Returns a int64 -// zero value if the pointer was nil. -func ToInt64Slice(vs []*int64) []int64 { - ps := make([]int64, len(vs)) - for i, v := range vs { - ps[i] = ToInt64(v) - } - - return ps -} - -// ToInt64Map returns a map of int64 values, that are -// dereferenced if the passed in pointer was not nil. The int64 -// zero value is used if the pointer was nil. -func ToInt64Map(vs map[string]*int64) map[string]int64 { - ps := make(map[string]int64, len(vs)) - for k, v := range vs { - ps[k] = ToInt64(v) - } - - return ps -} - -// ToUint returns uint value dereferenced if the passed -// in pointer was not nil. Returns a uint zero value if the -// pointer was nil. -func ToUint(p *uint) (v uint) { - if p == nil { - return v - } - - return *p -} - -// ToUintSlice returns a slice of uint values, that are -// dereferenced if the passed in pointer was not nil. Returns a uint -// zero value if the pointer was nil. -func ToUintSlice(vs []*uint) []uint { - ps := make([]uint, len(vs)) - for i, v := range vs { - ps[i] = ToUint(v) - } - - return ps -} - -// ToUintMap returns a map of uint values, that are -// dereferenced if the passed in pointer was not nil. The uint -// zero value is used if the pointer was nil. -func ToUintMap(vs map[string]*uint) map[string]uint { - ps := make(map[string]uint, len(vs)) - for k, v := range vs { - ps[k] = ToUint(v) - } - - return ps -} - -// ToUint8 returns uint8 value dereferenced if the passed -// in pointer was not nil. Returns a uint8 zero value if the -// pointer was nil. -func ToUint8(p *uint8) (v uint8) { - if p == nil { - return v - } - - return *p -} - -// ToUint8Slice returns a slice of uint8 values, that are -// dereferenced if the passed in pointer was not nil. Returns a uint8 -// zero value if the pointer was nil. -func ToUint8Slice(vs []*uint8) []uint8 { - ps := make([]uint8, len(vs)) - for i, v := range vs { - ps[i] = ToUint8(v) - } - - return ps -} - -// ToUint8Map returns a map of uint8 values, that are -// dereferenced if the passed in pointer was not nil. The uint8 -// zero value is used if the pointer was nil. -func ToUint8Map(vs map[string]*uint8) map[string]uint8 { - ps := make(map[string]uint8, len(vs)) - for k, v := range vs { - ps[k] = ToUint8(v) - } - - return ps -} - -// ToUint16 returns uint16 value dereferenced if the passed -// in pointer was not nil. Returns a uint16 zero value if the -// pointer was nil. -func ToUint16(p *uint16) (v uint16) { - if p == nil { - return v - } - - return *p -} - -// ToUint16Slice returns a slice of uint16 values, that are -// dereferenced if the passed in pointer was not nil. Returns a uint16 -// zero value if the pointer was nil. -func ToUint16Slice(vs []*uint16) []uint16 { - ps := make([]uint16, len(vs)) - for i, v := range vs { - ps[i] = ToUint16(v) - } - - return ps -} - -// ToUint16Map returns a map of uint16 values, that are -// dereferenced if the passed in pointer was not nil. The uint16 -// zero value is used if the pointer was nil. -func ToUint16Map(vs map[string]*uint16) map[string]uint16 { - ps := make(map[string]uint16, len(vs)) - for k, v := range vs { - ps[k] = ToUint16(v) - } - - return ps -} - -// ToUint32 returns uint32 value dereferenced if the passed -// in pointer was not nil. Returns a uint32 zero value if the -// pointer was nil. -func ToUint32(p *uint32) (v uint32) { - if p == nil { - return v - } - - return *p -} - -// ToUint32Slice returns a slice of uint32 values, that are -// dereferenced if the passed in pointer was not nil. Returns a uint32 -// zero value if the pointer was nil. -func ToUint32Slice(vs []*uint32) []uint32 { - ps := make([]uint32, len(vs)) - for i, v := range vs { - ps[i] = ToUint32(v) - } - - return ps -} - -// ToUint32Map returns a map of uint32 values, that are -// dereferenced if the passed in pointer was not nil. The uint32 -// zero value is used if the pointer was nil. -func ToUint32Map(vs map[string]*uint32) map[string]uint32 { - ps := make(map[string]uint32, len(vs)) - for k, v := range vs { - ps[k] = ToUint32(v) - } - - return ps -} - -// ToUint64 returns uint64 value dereferenced if the passed -// in pointer was not nil. Returns a uint64 zero value if the -// pointer was nil. -func ToUint64(p *uint64) (v uint64) { - if p == nil { - return v - } - - return *p -} - -// ToUint64Slice returns a slice of uint64 values, that are -// dereferenced if the passed in pointer was not nil. Returns a uint64 -// zero value if the pointer was nil. -func ToUint64Slice(vs []*uint64) []uint64 { - ps := make([]uint64, len(vs)) - for i, v := range vs { - ps[i] = ToUint64(v) - } - - return ps -} - -// ToUint64Map returns a map of uint64 values, that are -// dereferenced if the passed in pointer was not nil. The uint64 -// zero value is used if the pointer was nil. -func ToUint64Map(vs map[string]*uint64) map[string]uint64 { - ps := make(map[string]uint64, len(vs)) - for k, v := range vs { - ps[k] = ToUint64(v) - } - - return ps -} - -// ToFloat32 returns float32 value dereferenced if the passed -// in pointer was not nil. Returns a float32 zero value if the -// pointer was nil. -func ToFloat32(p *float32) (v float32) { - if p == nil { - return v - } - - return *p -} - -// ToFloat32Slice returns a slice of float32 values, that are -// dereferenced if the passed in pointer was not nil. Returns a float32 -// zero value if the pointer was nil. -func ToFloat32Slice(vs []*float32) []float32 { - ps := make([]float32, len(vs)) - for i, v := range vs { - ps[i] = ToFloat32(v) - } - - return ps -} - -// ToFloat32Map returns a map of float32 values, that are -// dereferenced if the passed in pointer was not nil. The float32 -// zero value is used if the pointer was nil. -func ToFloat32Map(vs map[string]*float32) map[string]float32 { - ps := make(map[string]float32, len(vs)) - for k, v := range vs { - ps[k] = ToFloat32(v) - } - - return ps -} - -// ToFloat64 returns float64 value dereferenced if the passed -// in pointer was not nil. Returns a float64 zero value if the -// pointer was nil. -func ToFloat64(p *float64) (v float64) { - if p == nil { - return v - } - - return *p -} - -// ToFloat64Slice returns a slice of float64 values, that are -// dereferenced if the passed in pointer was not nil. Returns a float64 -// zero value if the pointer was nil. -func ToFloat64Slice(vs []*float64) []float64 { - ps := make([]float64, len(vs)) - for i, v := range vs { - ps[i] = ToFloat64(v) - } - - return ps -} - -// ToFloat64Map returns a map of float64 values, that are -// dereferenced if the passed in pointer was not nil. The float64 -// zero value is used if the pointer was nil. -func ToFloat64Map(vs map[string]*float64) map[string]float64 { - ps := make(map[string]float64, len(vs)) - for k, v := range vs { - ps[k] = ToFloat64(v) - } - - return ps -} - -// ToTime returns time.Time value dereferenced if the passed -// in pointer was not nil. Returns a time.Time zero value if the -// pointer was nil. -func ToTime(p *time.Time) (v time.Time) { - if p == nil { - return v - } - - return *p -} - -// ToTimeSlice returns a slice of time.Time values, that are -// dereferenced if the passed in pointer was not nil. Returns a time.Time -// zero value if the pointer was nil. -func ToTimeSlice(vs []*time.Time) []time.Time { - ps := make([]time.Time, len(vs)) - for i, v := range vs { - ps[i] = ToTime(v) - } - - return ps -} - -// ToTimeMap returns a map of time.Time values, that are -// dereferenced if the passed in pointer was not nil. The time.Time -// zero value is used if the pointer was nil. -func ToTimeMap(vs map[string]*time.Time) map[string]time.Time { - ps := make(map[string]time.Time, len(vs)) - for k, v := range vs { - ps[k] = ToTime(v) - } - - return ps -} - -// ToDuration returns time.Duration value dereferenced if the passed -// in pointer was not nil. Returns a time.Duration zero value if the -// pointer was nil. -func ToDuration(p *time.Duration) (v time.Duration) { - if p == nil { - return v - } - - return *p -} - -// ToDurationSlice returns a slice of time.Duration values, that are -// dereferenced if the passed in pointer was not nil. Returns a time.Duration -// zero value if the pointer was nil. -func ToDurationSlice(vs []*time.Duration) []time.Duration { - ps := make([]time.Duration, len(vs)) - for i, v := range vs { - ps[i] = ToDuration(v) - } - - return ps -} - -// ToDurationMap returns a map of time.Duration values, that are -// dereferenced if the passed in pointer was not nil. The time.Duration -// zero value is used if the pointer was nil. -func ToDurationMap(vs map[string]*time.Duration) map[string]time.Duration { - ps := make(map[string]time.Duration, len(vs)) - for k, v := range vs { - ps[k] = ToDuration(v) - } - - return ps -} diff --git a/vendor/github.com/aws/smithy-go/ptr/gen_scalars.go b/vendor/github.com/aws/smithy-go/ptr/gen_scalars.go deleted file mode 100644 index 97f01011e..000000000 --- a/vendor/github.com/aws/smithy-go/ptr/gen_scalars.go +++ /dev/null @@ -1,83 +0,0 @@ -//go:build codegen -// +build codegen - -package ptr - -import "strings" - -func GetScalars() Scalars { - return Scalars{ - {Type: "bool"}, - {Type: "byte"}, - {Type: "string"}, - {Type: "int"}, - {Type: "int8"}, - {Type: "int16"}, - {Type: "int32"}, - {Type: "int64"}, - {Type: "uint"}, - {Type: "uint8"}, - {Type: "uint16"}, - {Type: "uint32"}, - {Type: "uint64"}, - {Type: "float32"}, - {Type: "float64"}, - {Type: "Time", Import: &Import{Path: "time"}}, - {Type: "Duration", Import: &Import{Path: "time"}}, - } -} - -// Import provides the import path and optional alias -type Import struct { - Path string - Alias string -} - -// Package returns the Go package name for the import. Returns alias if set. -func (i Import) Package() string { - if v := i.Alias; len(v) != 0 { - return v - } - - if v := i.Path; len(v) != 0 { - parts := strings.Split(v, "/") - pkg := parts[len(parts)-1] - return pkg - } - - return "" -} - -// Scalar provides the definition of a type to generate pointer utilities for. -type Scalar struct { - Type string - Import *Import -} - -// Name returns the exported function name for the type. -func (t Scalar) Name() string { - return strings.Title(t.Type) -} - -// Symbol returns the scalar's Go symbol with path if needed. -func (t Scalar) Symbol() string { - if t.Import != nil { - return t.Import.Package() + "." + t.Type - } - return t.Type -} - -// Scalars is a list of scalars. -type Scalars []Scalar - -// Imports returns all imports for the scalars. -func (ts Scalars) Imports() []*Import { - imports := []*Import{} - for _, t := range ts { - if v := t.Import; v != nil { - imports = append(imports, v) - } - } - - return imports -} diff --git a/vendor/github.com/aws/smithy-go/ptr/to_ptr.go b/vendor/github.com/aws/smithy-go/ptr/to_ptr.go deleted file mode 100644 index 0bfbbecbd..000000000 --- a/vendor/github.com/aws/smithy-go/ptr/to_ptr.go +++ /dev/null @@ -1,499 +0,0 @@ -// Code generated by smithy-go/ptr/generate.go DO NOT EDIT. -package ptr - -import ( - "time" -) - -// Bool returns a pointer value for the bool value passed in. -func Bool(v bool) *bool { - return &v -} - -// BoolSlice returns a slice of bool pointers from the values -// passed in. -func BoolSlice(vs []bool) []*bool { - ps := make([]*bool, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// BoolMap returns a map of bool pointers from the values -// passed in. -func BoolMap(vs map[string]bool) map[string]*bool { - ps := make(map[string]*bool, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Byte returns a pointer value for the byte value passed in. -func Byte(v byte) *byte { - return &v -} - -// ByteSlice returns a slice of byte pointers from the values -// passed in. -func ByteSlice(vs []byte) []*byte { - ps := make([]*byte, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// ByteMap returns a map of byte pointers from the values -// passed in. -func ByteMap(vs map[string]byte) map[string]*byte { - ps := make(map[string]*byte, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// String returns a pointer value for the string value passed in. -func String(v string) *string { - return &v -} - -// StringSlice returns a slice of string pointers from the values -// passed in. -func StringSlice(vs []string) []*string { - ps := make([]*string, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// StringMap returns a map of string pointers from the values -// passed in. -func StringMap(vs map[string]string) map[string]*string { - ps := make(map[string]*string, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Int returns a pointer value for the int value passed in. -func Int(v int) *int { - return &v -} - -// IntSlice returns a slice of int pointers from the values -// passed in. -func IntSlice(vs []int) []*int { - ps := make([]*int, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// IntMap returns a map of int pointers from the values -// passed in. -func IntMap(vs map[string]int) map[string]*int { - ps := make(map[string]*int, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Int8 returns a pointer value for the int8 value passed in. -func Int8(v int8) *int8 { - return &v -} - -// Int8Slice returns a slice of int8 pointers from the values -// passed in. -func Int8Slice(vs []int8) []*int8 { - ps := make([]*int8, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// Int8Map returns a map of int8 pointers from the values -// passed in. -func Int8Map(vs map[string]int8) map[string]*int8 { - ps := make(map[string]*int8, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Int16 returns a pointer value for the int16 value passed in. -func Int16(v int16) *int16 { - return &v -} - -// Int16Slice returns a slice of int16 pointers from the values -// passed in. -func Int16Slice(vs []int16) []*int16 { - ps := make([]*int16, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// Int16Map returns a map of int16 pointers from the values -// passed in. -func Int16Map(vs map[string]int16) map[string]*int16 { - ps := make(map[string]*int16, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Int32 returns a pointer value for the int32 value passed in. -func Int32(v int32) *int32 { - return &v -} - -// Int32Slice returns a slice of int32 pointers from the values -// passed in. -func Int32Slice(vs []int32) []*int32 { - ps := make([]*int32, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// Int32Map returns a map of int32 pointers from the values -// passed in. -func Int32Map(vs map[string]int32) map[string]*int32 { - ps := make(map[string]*int32, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Int64 returns a pointer value for the int64 value passed in. -func Int64(v int64) *int64 { - return &v -} - -// Int64Slice returns a slice of int64 pointers from the values -// passed in. -func Int64Slice(vs []int64) []*int64 { - ps := make([]*int64, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// Int64Map returns a map of int64 pointers from the values -// passed in. -func Int64Map(vs map[string]int64) map[string]*int64 { - ps := make(map[string]*int64, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Uint returns a pointer value for the uint value passed in. -func Uint(v uint) *uint { - return &v -} - -// UintSlice returns a slice of uint pointers from the values -// passed in. -func UintSlice(vs []uint) []*uint { - ps := make([]*uint, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// UintMap returns a map of uint pointers from the values -// passed in. -func UintMap(vs map[string]uint) map[string]*uint { - ps := make(map[string]*uint, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Uint8 returns a pointer value for the uint8 value passed in. -func Uint8(v uint8) *uint8 { - return &v -} - -// Uint8Slice returns a slice of uint8 pointers from the values -// passed in. -func Uint8Slice(vs []uint8) []*uint8 { - ps := make([]*uint8, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// Uint8Map returns a map of uint8 pointers from the values -// passed in. -func Uint8Map(vs map[string]uint8) map[string]*uint8 { - ps := make(map[string]*uint8, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Uint16 returns a pointer value for the uint16 value passed in. -func Uint16(v uint16) *uint16 { - return &v -} - -// Uint16Slice returns a slice of uint16 pointers from the values -// passed in. -func Uint16Slice(vs []uint16) []*uint16 { - ps := make([]*uint16, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// Uint16Map returns a map of uint16 pointers from the values -// passed in. -func Uint16Map(vs map[string]uint16) map[string]*uint16 { - ps := make(map[string]*uint16, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Uint32 returns a pointer value for the uint32 value passed in. -func Uint32(v uint32) *uint32 { - return &v -} - -// Uint32Slice returns a slice of uint32 pointers from the values -// passed in. -func Uint32Slice(vs []uint32) []*uint32 { - ps := make([]*uint32, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// Uint32Map returns a map of uint32 pointers from the values -// passed in. -func Uint32Map(vs map[string]uint32) map[string]*uint32 { - ps := make(map[string]*uint32, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Uint64 returns a pointer value for the uint64 value passed in. -func Uint64(v uint64) *uint64 { - return &v -} - -// Uint64Slice returns a slice of uint64 pointers from the values -// passed in. -func Uint64Slice(vs []uint64) []*uint64 { - ps := make([]*uint64, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// Uint64Map returns a map of uint64 pointers from the values -// passed in. -func Uint64Map(vs map[string]uint64) map[string]*uint64 { - ps := make(map[string]*uint64, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Float32 returns a pointer value for the float32 value passed in. -func Float32(v float32) *float32 { - return &v -} - -// Float32Slice returns a slice of float32 pointers from the values -// passed in. -func Float32Slice(vs []float32) []*float32 { - ps := make([]*float32, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// Float32Map returns a map of float32 pointers from the values -// passed in. -func Float32Map(vs map[string]float32) map[string]*float32 { - ps := make(map[string]*float32, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Float64 returns a pointer value for the float64 value passed in. -func Float64(v float64) *float64 { - return &v -} - -// Float64Slice returns a slice of float64 pointers from the values -// passed in. -func Float64Slice(vs []float64) []*float64 { - ps := make([]*float64, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// Float64Map returns a map of float64 pointers from the values -// passed in. -func Float64Map(vs map[string]float64) map[string]*float64 { - ps := make(map[string]*float64, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Time returns a pointer value for the time.Time value passed in. -func Time(v time.Time) *time.Time { - return &v -} - -// TimeSlice returns a slice of time.Time pointers from the values -// passed in. -func TimeSlice(vs []time.Time) []*time.Time { - ps := make([]*time.Time, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// TimeMap returns a map of time.Time pointers from the values -// passed in. -func TimeMap(vs map[string]time.Time) map[string]*time.Time { - ps := make(map[string]*time.Time, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Duration returns a pointer value for the time.Duration value passed in. -func Duration(v time.Duration) *time.Duration { - return &v -} - -// DurationSlice returns a slice of time.Duration pointers from the values -// passed in. -func DurationSlice(vs []time.Duration) []*time.Duration { - ps := make([]*time.Duration, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// DurationMap returns a map of time.Duration pointers from the values -// passed in. -func DurationMap(vs map[string]time.Duration) map[string]*time.Duration { - ps := make(map[string]*time.Duration, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} diff --git a/vendor/github.com/aws/smithy-go/rand/doc.go b/vendor/github.com/aws/smithy-go/rand/doc.go deleted file mode 100644 index f8b25d562..000000000 --- a/vendor/github.com/aws/smithy-go/rand/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package rand provides utilities for creating and working with random value -// generators. -package rand diff --git a/vendor/github.com/aws/smithy-go/rand/rand.go b/vendor/github.com/aws/smithy-go/rand/rand.go deleted file mode 100644 index 9c479f62b..000000000 --- a/vendor/github.com/aws/smithy-go/rand/rand.go +++ /dev/null @@ -1,31 +0,0 @@ -package rand - -import ( - "crypto/rand" - "fmt" - "io" - "math/big" -) - -func init() { - Reader = rand.Reader -} - -// Reader provides a random reader that can reset during testing. -var Reader io.Reader - -// Int63n returns a int64 between zero and value of max, read from an io.Reader source. -func Int63n(reader io.Reader, max int64) (int64, error) { - bi, err := rand.Int(reader, big.NewInt(max)) - if err != nil { - return 0, fmt.Errorf("failed to read random value, %w", err) - } - - return bi.Int64(), nil -} - -// CryptoRandInt63n returns a random int64 between zero and value of max -// obtained from the crypto rand source. -func CryptoRandInt63n(max int64) (int64, error) { - return Int63n(Reader, max) -} diff --git a/vendor/github.com/aws/smithy-go/rand/uuid.go b/vendor/github.com/aws/smithy-go/rand/uuid.go deleted file mode 100644 index dc81cbc68..000000000 --- a/vendor/github.com/aws/smithy-go/rand/uuid.go +++ /dev/null @@ -1,87 +0,0 @@ -package rand - -import ( - "encoding/hex" - "io" -) - -const dash byte = '-' - -// UUIDIdempotencyToken provides a utility to get idempotency tokens in the -// UUID format. -type UUIDIdempotencyToken struct { - uuid *UUID -} - -// NewUUIDIdempotencyToken returns a idempotency token provider returning -// tokens in the UUID random format using the reader provided. -func NewUUIDIdempotencyToken(r io.Reader) *UUIDIdempotencyToken { - return &UUIDIdempotencyToken{uuid: NewUUID(r)} -} - -// GetIdempotencyToken returns a random UUID value for Idempotency token. -func (u UUIDIdempotencyToken) GetIdempotencyToken() (string, error) { - return u.uuid.GetUUID() -} - -// UUID provides computing random UUID version 4 values from a random source -// reader. -type UUID struct { - randSrc io.Reader -} - -// NewUUID returns an initialized UUID value that can be used to retrieve -// random UUID version 4 values. -func NewUUID(r io.Reader) *UUID { - return &UUID{randSrc: r} -} - -// GetUUID returns a random UUID version 4 string representation sourced from the random reader the -// UUID was created with. Returns an error if unable to compute the UUID. -func (r *UUID) GetUUID() (string, error) { - var b [16]byte - if _, err := io.ReadFull(r.randSrc, b[:]); err != nil { - return "", err - } - r.makeUUIDv4(b[:]) - return format(b), nil -} - -// GetBytes returns a byte slice containing a random UUID version 4 sourced from the random reader the -// UUID was created with. Returns an error if unable to compute the UUID. -func (r *UUID) GetBytes() (u []byte, err error) { - u = make([]byte, 16) - if _, err = io.ReadFull(r.randSrc, u); err != nil { - return u, err - } - r.makeUUIDv4(u) - return u, nil -} - -func (r *UUID) makeUUIDv4(u []byte) { - // 13th character is "4" - u[6] = (u[6] & 0x0f) | 0x40 // Version 4 - // 17th character is "8", "9", "a", or "b" - u[8] = (u[8] & 0x3f) | 0x80 // Variant most significant bits are 10x where x can be either 1 or 0 -} - -// Format returns the canonical text representation of a UUID. -// This implementation is optimized to not use fmt. -// Example: 82e42f16-b6cc-4d5b-95f5-d403c4befd3d -func format(u [16]byte) string { - // https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_.28random.29 - - var scratch [36]byte - - hex.Encode(scratch[:8], u[0:4]) - scratch[8] = dash - hex.Encode(scratch[9:13], u[4:6]) - scratch[13] = dash - hex.Encode(scratch[14:18], u[6:8]) - scratch[18] = dash - hex.Encode(scratch[19:23], u[8:10]) - scratch[23] = dash - hex.Encode(scratch[24:], u[10:]) - - return string(scratch[:]) -} diff --git a/vendor/github.com/aws/smithy-go/time/time.go b/vendor/github.com/aws/smithy-go/time/time.go deleted file mode 100644 index b552a09f8..000000000 --- a/vendor/github.com/aws/smithy-go/time/time.go +++ /dev/null @@ -1,134 +0,0 @@ -package time - -import ( - "context" - "fmt" - "math/big" - "strings" - "time" -) - -const ( - // dateTimeFormat is a IMF-fixdate formatted RFC3339 section 5.6 - dateTimeFormatInput = "2006-01-02T15:04:05.999999999Z" - dateTimeFormatInputNoZ = "2006-01-02T15:04:05.999999999" - dateTimeFormatOutput = "2006-01-02T15:04:05.999Z" - - // httpDateFormat is a date time defined by RFC 7231#section-7.1.1.1 - // IMF-fixdate with no UTC offset. - httpDateFormat = "Mon, 02 Jan 2006 15:04:05 GMT" - // Additional formats needed for compatibility. - httpDateFormatSingleDigitDay = "Mon, _2 Jan 2006 15:04:05 GMT" - httpDateFormatSingleDigitDayTwoDigitYear = "Mon, _2 Jan 06 15:04:05 GMT" -) - -var millisecondFloat = big.NewFloat(1e3) - -// FormatDateTime formats value as a date-time, (RFC3339 section 5.6) -// -// Example: 1985-04-12T23:20:50.52Z -func FormatDateTime(value time.Time) string { - return value.UTC().Format(dateTimeFormatOutput) -} - -// ParseDateTime parses a string as a date-time, (RFC3339 section 5.6) -// -// Example: 1985-04-12T23:20:50.52Z -func ParseDateTime(value string) (time.Time, error) { - return tryParse(value, - dateTimeFormatInput, - dateTimeFormatInputNoZ, - time.RFC3339Nano, - time.RFC3339, - ) -} - -// FormatHTTPDate formats value as a http-date, (RFC 7231#section-7.1.1.1 IMF-fixdate) -// -// Example: Tue, 29 Apr 2014 18:30:38 GMT -func FormatHTTPDate(value time.Time) string { - return value.UTC().Format(httpDateFormat) -} - -// ParseHTTPDate parses a string as a http-date, (RFC 7231#section-7.1.1.1 IMF-fixdate) -// -// Example: Tue, 29 Apr 2014 18:30:38 GMT -func ParseHTTPDate(value string) (time.Time, error) { - return tryParse(value, - httpDateFormat, - httpDateFormatSingleDigitDay, - httpDateFormatSingleDigitDayTwoDigitYear, - time.RFC850, - time.ANSIC, - ) -} - -// FormatEpochSeconds returns value as a Unix time in seconds with with decimal precision -// -// Example: 1515531081.123 -func FormatEpochSeconds(value time.Time) float64 { - ms := value.UnixNano() / int64(time.Millisecond) - return float64(ms) / 1e3 -} - -// ParseEpochSeconds returns value as a Unix time in seconds with with decimal precision -// -// Example: 1515531081.123 -func ParseEpochSeconds(value float64) time.Time { - f := big.NewFloat(value) - f = f.Mul(f, millisecondFloat) - i, _ := f.Int64() - // Offset to `UTC` because time.Unix returns the time value based on system - // local setting. - return time.Unix(0, i*1e6).UTC() -} - -func tryParse(v string, formats ...string) (time.Time, error) { - var errs parseErrors - for _, f := range formats { - t, err := time.Parse(f, v) - if err != nil { - errs = append(errs, parseError{ - Format: f, - Err: err, - }) - continue - } - return t, nil - } - - return time.Time{}, fmt.Errorf("unable to parse time string, %w", errs) -} - -type parseErrors []parseError - -func (es parseErrors) Error() string { - var s strings.Builder - for _, e := range es { - fmt.Fprintf(&s, "\n * %q: %v", e.Format, e.Err) - } - - return "parse errors:" + s.String() -} - -type parseError struct { - Format string - Err error -} - -// SleepWithContext will wait for the timer duration to expire, or until the context -// is canceled. Whichever happens first. If the context is canceled the -// Context's error will be returned. -func SleepWithContext(ctx context.Context, dur time.Duration) error { - t := time.NewTimer(dur) - defer t.Stop() - - select { - case <-t.C: - break - case <-ctx.Done(): - return ctx.Err() - } - - return nil -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/checksum_middleware.go b/vendor/github.com/aws/smithy-go/transport/http/checksum_middleware.go deleted file mode 100644 index bc4ad6e79..000000000 --- a/vendor/github.com/aws/smithy-go/transport/http/checksum_middleware.go +++ /dev/null @@ -1,70 +0,0 @@ -package http - -import ( - "context" - "fmt" - - "github.com/aws/smithy-go/middleware" -) - -const contentMD5Header = "Content-Md5" - -// contentMD5Checksum provides a middleware to compute and set -// content-md5 checksum for a http request -type contentMD5Checksum struct { -} - -// AddContentChecksumMiddleware adds checksum middleware to middleware's -// build step. -func AddContentChecksumMiddleware(stack *middleware.Stack) error { - // This middleware must be executed before request body is set. - return stack.Build.Add(&contentMD5Checksum{}, middleware.Before) -} - -// ID returns the identifier for the checksum middleware -func (m *contentMD5Checksum) ID() string { return "ContentChecksum" } - -// HandleBuild adds behavior to compute md5 checksum and add content-md5 header -// on http request -func (m *contentMD5Checksum) HandleBuild( - ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler, -) ( - out middleware.BuildOutput, metadata middleware.Metadata, err error, -) { - req, ok := in.Request.(*Request) - if !ok { - return out, metadata, fmt.Errorf("unknown request type %T", req) - } - - // if Content-MD5 header is already present, return - if v := req.Header.Get(contentMD5Header); len(v) != 0 { - return next.HandleBuild(ctx, in) - } - - // fetch the request stream. - stream := req.GetStream() - // compute checksum if payload is explicit - if stream != nil { - if !req.IsStreamSeekable() { - return out, metadata, fmt.Errorf( - "unseekable stream is not supported for computing md5 checksum") - } - - v, err := computeMD5Checksum(stream) - if err != nil { - return out, metadata, fmt.Errorf("error computing md5 checksum, %w", err) - } - - // reset the request stream - if err := req.RewindStream(); err != nil { - return out, metadata, fmt.Errorf( - "error rewinding request stream after computing md5 checksum, %w", err) - } - - // set the 'Content-MD5' header - req.Header.Set(contentMD5Header, string(v)) - } - - // set md5 header value - return next.HandleBuild(ctx, in) -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/client.go b/vendor/github.com/aws/smithy-go/transport/http/client.go deleted file mode 100644 index e691c69bf..000000000 --- a/vendor/github.com/aws/smithy-go/transport/http/client.go +++ /dev/null @@ -1,120 +0,0 @@ -package http - -import ( - "context" - "fmt" - "net/http" - - smithy "github.com/aws/smithy-go" - "github.com/aws/smithy-go/middleware" -) - -// ClientDo provides the interface for custom HTTP client implementations. -type ClientDo interface { - Do(*http.Request) (*http.Response, error) -} - -// ClientDoFunc provides a helper to wrap a function as an HTTP client for -// round tripping requests. -type ClientDoFunc func(*http.Request) (*http.Response, error) - -// Do will invoke the underlying func, returning the result. -func (fn ClientDoFunc) Do(r *http.Request) (*http.Response, error) { - return fn(r) -} - -// ClientHandler wraps a client that implements the HTTP Do method. Standard -// implementation is http.Client. -type ClientHandler struct { - client ClientDo -} - -// NewClientHandler returns an initialized middleware handler for the client. -func NewClientHandler(client ClientDo) ClientHandler { - return ClientHandler{ - client: client, - } -} - -// Handle implements the middleware Handler interface, that will invoke the -// underlying HTTP client. Requires the input to be a Smithy *Request. Returns -// a smithy *Response, or error if the request failed. -func (c ClientHandler) Handle(ctx context.Context, input interface{}) ( - out interface{}, metadata middleware.Metadata, err error, -) { - req, ok := input.(*Request) - if !ok { - return nil, metadata, fmt.Errorf("expect Smithy http.Request value as input, got unsupported type %T", input) - } - - builtRequest := req.Build(ctx) - if err := ValidateEndpointHost(builtRequest.Host); err != nil { - return nil, metadata, err - } - - resp, err := c.client.Do(builtRequest) - if resp == nil { - // Ensure a http response value is always present to prevent unexpected - // panics. - resp = &http.Response{ - Header: http.Header{}, - Body: http.NoBody, - } - } - if err != nil { - err = &RequestSendError{Err: err} - - // Override the error with a context canceled error, if that was canceled. - select { - case <-ctx.Done(): - err = &smithy.CanceledError{Err: ctx.Err()} - default: - } - } - - // HTTP RoundTripper *should* close the request body. But this may not happen in a timely manner. - // So instead Smithy *Request Build wraps the body to be sent in a safe closer that will clear the - // stream reference so that it can be safely reused. - if builtRequest.Body != nil { - _ = builtRequest.Body.Close() - } - - return &Response{Response: resp}, metadata, err -} - -// RequestSendError provides a generic request transport error. This error -// should wrap errors making HTTP client requests. -// -// The ClientHandler will wrap the HTTP client's error if the client request -// fails, and did not fail because of context canceled. -type RequestSendError struct { - Err error -} - -// ConnectionError returns that the error is related to not being able to send -// the request, or receive a response from the service. -func (e *RequestSendError) ConnectionError() bool { - return true -} - -// Unwrap returns the underlying error, if there was one. -func (e *RequestSendError) Unwrap() error { - return e.Err -} - -func (e *RequestSendError) Error() string { - return fmt.Sprintf("request send failed, %v", e.Err) -} - -// NopClient provides a client that ignores the request, and returns an empty -// successful HTTP response value. -type NopClient struct{} - -// Do ignores the request and returns a 200 status empty response. -func (NopClient) Do(r *http.Request) (*http.Response, error) { - return &http.Response{ - StatusCode: 200, - Header: http.Header{}, - Body: http.NoBody, - }, nil -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/doc.go b/vendor/github.com/aws/smithy-go/transport/http/doc.go deleted file mode 100644 index 07366ac85..000000000 --- a/vendor/github.com/aws/smithy-go/transport/http/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -/* -Package http provides the HTTP transport client and request/response types -needed to round trip API operation calls with an service. -*/ -package http diff --git a/vendor/github.com/aws/smithy-go/transport/http/headerlist.go b/vendor/github.com/aws/smithy-go/transport/http/headerlist.go deleted file mode 100644 index cbc9deb4d..000000000 --- a/vendor/github.com/aws/smithy-go/transport/http/headerlist.go +++ /dev/null @@ -1,163 +0,0 @@ -package http - -import ( - "fmt" - "strconv" - "strings" - "unicode" -) - -func splitHeaderListValues(vs []string, splitFn func(string) ([]string, error)) ([]string, error) { - values := make([]string, 0, len(vs)) - - for i := 0; i < len(vs); i++ { - parts, err := splitFn(vs[i]) - if err != nil { - return nil, err - } - values = append(values, parts...) - } - - return values, nil -} - -// SplitHeaderListValues attempts to split the elements of the slice by commas, -// and return a list of all values separated. Returns error if unable to -// separate the values. -func SplitHeaderListValues(vs []string) ([]string, error) { - return splitHeaderListValues(vs, quotedCommaSplit) -} - -func quotedCommaSplit(v string) (parts []string, err error) { - v = strings.TrimSpace(v) - - expectMore := true - for i := 0; i < len(v); i++ { - if unicode.IsSpace(rune(v[i])) { - continue - } - expectMore = false - - // leading space in part is ignored. - // Start of value must be non-space, or quote. - // - // - If quote, enter quoted mode, find next non-escaped quote to - // terminate the value. - // - Otherwise, find next comma to terminate value. - - remaining := v[i:] - - var value string - var valueLen int - if remaining[0] == '"' { - //------------------------------ - // Quoted value - //------------------------------ - var j int - var skipQuote bool - for j += 1; j < len(remaining); j++ { - if remaining[j] == '\\' || (remaining[j] != '\\' && skipQuote) { - skipQuote = !skipQuote - continue - } - if remaining[j] == '"' { - break - } - } - if j == len(remaining) || j == 1 { - return nil, fmt.Errorf("value %v missing closing double quote", - remaining) - } - valueLen = j + 1 - - tail := remaining[valueLen:] - var k int - for ; k < len(tail); k++ { - if !unicode.IsSpace(rune(tail[k])) && tail[k] != ',' { - return nil, fmt.Errorf("value %v has non-space trailing characters", - remaining) - } - if tail[k] == ',' { - expectMore = true - break - } - } - value = remaining[:valueLen] - value, err = strconv.Unquote(value) - if err != nil { - return nil, fmt.Errorf("failed to unquote value %v, %w", value, err) - } - - // Pad valueLen to include trailing space(s) so `i` is updated correctly. - valueLen += k - - } else { - //------------------------------ - // Unquoted value - //------------------------------ - - // Index of the next comma is the length of the value, or end of string. - valueLen = strings.Index(remaining, ",") - if valueLen != -1 { - expectMore = true - } else { - valueLen = len(remaining) - } - value = strings.TrimSpace(remaining[:valueLen]) - } - - i += valueLen - parts = append(parts, value) - - } - - if expectMore { - parts = append(parts, "") - } - - return parts, nil -} - -// SplitHTTPDateTimestampHeaderListValues attempts to split the HTTP-Date -// timestamp values in the slice by commas, and return a list of all values -// separated. The split is aware of the HTTP-Date timestamp format, and will skip -// comma within the timestamp value. Returns an error if unable to split the -// timestamp values. -func SplitHTTPDateTimestampHeaderListValues(vs []string) ([]string, error) { - return splitHeaderListValues(vs, splitHTTPDateHeaderValue) -} - -func splitHTTPDateHeaderValue(v string) ([]string, error) { - if n := strings.Count(v, ","); n <= 1 { - // Nothing to do if only contains a no, or single HTTPDate value - return []string{v}, nil - } else if n%2 == 0 { - return nil, fmt.Errorf("invalid timestamp HTTPDate header comma separations, %q", v) - } - - var parts []string - var i, j int - - var doSplit bool - for ; i < len(v); i++ { - if v[i] == ',' { - if doSplit { - doSplit = false - parts = append(parts, strings.TrimSpace(v[j:i])) - j = i + 1 - } else { - // Skip the first comma in the timestamp value since that - // separates the day from the rest of the timestamp. - // - // Tue, 17 Dec 2019 23:48:18 GMT - doSplit = true - } - } - } - // Add final part - if j < len(v) { - parts = append(parts, strings.TrimSpace(v[j:])) - } - - return parts, nil -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/host.go b/vendor/github.com/aws/smithy-go/transport/http/host.go deleted file mode 100644 index 6b290fec0..000000000 --- a/vendor/github.com/aws/smithy-go/transport/http/host.go +++ /dev/null @@ -1,89 +0,0 @@ -package http - -import ( - "fmt" - "net" - "strconv" - "strings" -) - -// ValidateEndpointHost validates that the host string passed in is a valid RFC -// 3986 host. Returns error if the host is not valid. -func ValidateEndpointHost(host string) error { - var errors strings.Builder - var hostname string - var port string - var err error - - if strings.Contains(host, ":") { - hostname, port, err = net.SplitHostPort(host) - if err != nil { - errors.WriteString(fmt.Sprintf("\n endpoint %v, failed to parse, got ", host)) - errors.WriteString(err.Error()) - } - - if !ValidPortNumber(port) { - errors.WriteString(fmt.Sprintf("port number should be in range [0-65535], got %v", port)) - } - } else { - hostname = host - } - - labels := strings.Split(hostname, ".") - for i, label := range labels { - if i == len(labels)-1 && len(label) == 0 { - // Allow trailing dot for FQDN hosts. - continue - } - - if !ValidHostLabel(label) { - errors.WriteString("\nendpoint host domain labels must match \"[a-zA-Z0-9-]{1,63}\", but found: ") - errors.WriteString(label) - } - } - - if len(hostname) == 0 && len(port) != 0 { - errors.WriteString("\nendpoint host with port must not be empty") - } - - if len(hostname) > 255 { - errors.WriteString(fmt.Sprintf("\nendpoint host must be less than 255 characters, but was %d", len(hostname))) - } - - if len(errors.String()) > 0 { - return fmt.Errorf("invalid endpoint host%s", errors.String()) - } - return nil -} - -// ValidPortNumber returns whether the port is valid RFC 3986 port. -func ValidPortNumber(port string) bool { - i, err := strconv.Atoi(port) - if err != nil { - return false - } - - if i < 0 || i > 65535 { - return false - } - return true -} - -// ValidHostLabel returns whether the label is a valid RFC 3986 host abel. -func ValidHostLabel(label string) bool { - if l := len(label); l == 0 || l > 63 { - return false - } - for _, r := range label { - switch { - case r >= '0' && r <= '9': - case r >= 'A' && r <= 'Z': - case r >= 'a' && r <= 'z': - case r == '-': - default: - return false - } - } - - return true -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/internal/io/safe.go b/vendor/github.com/aws/smithy-go/transport/http/internal/io/safe.go deleted file mode 100644 index 941a8d6b5..000000000 --- a/vendor/github.com/aws/smithy-go/transport/http/internal/io/safe.go +++ /dev/null @@ -1,75 +0,0 @@ -package io - -import ( - "io" - "sync" -) - -// NewSafeReadCloser returns a new safeReadCloser that wraps readCloser. -func NewSafeReadCloser(readCloser io.ReadCloser) io.ReadCloser { - sr := &safeReadCloser{ - readCloser: readCloser, - } - - if _, ok := readCloser.(io.WriterTo); ok { - return &safeWriteToReadCloser{safeReadCloser: sr} - } - - return sr -} - -// safeWriteToReadCloser wraps a safeReadCloser but exposes a WriteTo interface implementation. This will panic -// if the underlying io.ReadClose does not support WriteTo. Use NewSafeReadCloser to ensure the proper handling of this -// type. -type safeWriteToReadCloser struct { - *safeReadCloser -} - -// WriteTo implements the io.WriteTo interface. -func (r *safeWriteToReadCloser) WriteTo(w io.Writer) (int64, error) { - r.safeReadCloser.mtx.Lock() - defer r.safeReadCloser.mtx.Unlock() - - if r.safeReadCloser.closed { - return 0, io.EOF - } - - return r.safeReadCloser.readCloser.(io.WriterTo).WriteTo(w) -} - -// safeReadCloser wraps a io.ReadCloser and presents an io.ReadCloser interface. When Close is called on safeReadCloser -// the underlying Close method will be executed, and then the reference to the reader will be dropped. This type -// is meant to be used with the net/http library which will retain a reference to the request body for the lifetime -// of a goroutine connection. Wrapping in this manner will ensure that no data race conditions are falsely reported. -// This type is thread-safe. -type safeReadCloser struct { - readCloser io.ReadCloser - closed bool - mtx sync.Mutex -} - -// Read reads up to len(p) bytes into p from the underlying read. If the reader is closed io.EOF will be returned. -func (r *safeReadCloser) Read(p []byte) (n int, err error) { - r.mtx.Lock() - defer r.mtx.Unlock() - if r.closed { - return 0, io.EOF - } - - return r.readCloser.Read(p) -} - -// Close calls the underlying io.ReadCloser's Close method, removes the reference to the reader, and returns any error -// reported from Close. Subsequent calls to Close will always return a nil error. -func (r *safeReadCloser) Close() error { - r.mtx.Lock() - defer r.mtx.Unlock() - if r.closed { - return nil - } - - r.closed = true - rc := r.readCloser - r.readCloser = nil - return rc.Close() -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/md5_checksum.go b/vendor/github.com/aws/smithy-go/transport/http/md5_checksum.go deleted file mode 100644 index 5d6a4b23a..000000000 --- a/vendor/github.com/aws/smithy-go/transport/http/md5_checksum.go +++ /dev/null @@ -1,25 +0,0 @@ -package http - -import ( - "crypto/md5" - "encoding/base64" - "fmt" - "io" -) - -// computeMD5Checksum computes base64 md5 checksum of an io.Reader's contents. -// Returns the byte slice of md5 checksum and an error. -func computeMD5Checksum(r io.Reader) ([]byte, error) { - h := md5.New() - // copy errors may be assumed to be from the body. - _, err := io.Copy(h, r) - if err != nil { - return nil, fmt.Errorf("failed to read body: %w", err) - } - - // encode the md5 checksum in base64. - sum := h.Sum(nil) - sum64 := make([]byte, base64.StdEncoding.EncodedLen(len(sum))) - base64.StdEncoding.Encode(sum64, sum) - return sum64, nil -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/middleware_close_response_body.go b/vendor/github.com/aws/smithy-go/transport/http/middleware_close_response_body.go deleted file mode 100644 index 1d3b218a1..000000000 --- a/vendor/github.com/aws/smithy-go/transport/http/middleware_close_response_body.go +++ /dev/null @@ -1,79 +0,0 @@ -package http - -import ( - "context" - "github.com/aws/smithy-go/logging" - "github.com/aws/smithy-go/middleware" - "io" - "io/ioutil" -) - -// AddErrorCloseResponseBodyMiddleware adds the middleware to automatically -// close the response body of an operation request if the request response -// failed. -func AddErrorCloseResponseBodyMiddleware(stack *middleware.Stack) error { - return stack.Deserialize.Insert(&errorCloseResponseBodyMiddleware{}, "OperationDeserializer", middleware.Before) -} - -type errorCloseResponseBodyMiddleware struct{} - -func (*errorCloseResponseBodyMiddleware) ID() string { - return "ErrorCloseResponseBody" -} - -func (m *errorCloseResponseBodyMiddleware) HandleDeserialize( - ctx context.Context, input middleware.DeserializeInput, next middleware.DeserializeHandler, -) ( - output middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err := next.HandleDeserialize(ctx, input) - if err != nil { - if resp, ok := out.RawResponse.(*Response); ok && resp != nil && resp.Body != nil { - // Consume the full body to prevent TCP connection resets on some platforms - _, _ = io.Copy(ioutil.Discard, resp.Body) - // Do not validate that the response closes successfully. - resp.Body.Close() - } - } - - return out, metadata, err -} - -// AddCloseResponseBodyMiddleware adds the middleware to automatically close -// the response body of an operation request, after the response had been -// deserialized. -func AddCloseResponseBodyMiddleware(stack *middleware.Stack) error { - return stack.Deserialize.Insert(&closeResponseBody{}, "OperationDeserializer", middleware.Before) -} - -type closeResponseBody struct{} - -func (*closeResponseBody) ID() string { - return "CloseResponseBody" -} - -func (m *closeResponseBody) HandleDeserialize( - ctx context.Context, input middleware.DeserializeInput, next middleware.DeserializeHandler, -) ( - output middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err := next.HandleDeserialize(ctx, input) - if err != nil { - return out, metadata, err - } - - if resp, ok := out.RawResponse.(*Response); ok { - // Consume the full body to prevent TCP connection resets on some platforms - _, copyErr := io.Copy(ioutil.Discard, resp.Body) - if copyErr != nil { - middleware.GetLogger(ctx).Logf(logging.Warn, "failed to discard remaining HTTP response body, this may affect connection reuse") - } - - closeErr := resp.Body.Close() - if closeErr != nil { - middleware.GetLogger(ctx).Logf(logging.Warn, "failed to close HTTP response body, this may affect connection reuse") - } - } - - return out, metadata, err -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/middleware_content_length.go b/vendor/github.com/aws/smithy-go/transport/http/middleware_content_length.go deleted file mode 100644 index 9969389bb..000000000 --- a/vendor/github.com/aws/smithy-go/transport/http/middleware_content_length.go +++ /dev/null @@ -1,84 +0,0 @@ -package http - -import ( - "context" - "fmt" - - "github.com/aws/smithy-go/middleware" -) - -// ComputeContentLength provides a middleware to set the content-length -// header for the length of a serialize request body. -type ComputeContentLength struct { -} - -// AddComputeContentLengthMiddleware adds ComputeContentLength to the middleware -// stack's Build step. -func AddComputeContentLengthMiddleware(stack *middleware.Stack) error { - return stack.Build.Add(&ComputeContentLength{}, middleware.After) -} - -// ID returns the identifier for the ComputeContentLength. -func (m *ComputeContentLength) ID() string { return "ComputeContentLength" } - -// HandleBuild adds the length of the serialized request to the HTTP header -// if the length can be determined. -func (m *ComputeContentLength) HandleBuild( - ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler, -) ( - out middleware.BuildOutput, metadata middleware.Metadata, err error, -) { - req, ok := in.Request.(*Request) - if !ok { - return out, metadata, fmt.Errorf("unknown request type %T", req) - } - - // do nothing if request content-length was set to 0 or above. - if req.ContentLength >= 0 { - return next.HandleBuild(ctx, in) - } - - // attempt to compute stream length - if n, ok, err := req.StreamLength(); err != nil { - return out, metadata, fmt.Errorf( - "failed getting length of request stream, %w", err) - } else if ok { - req.ContentLength = n - } - - return next.HandleBuild(ctx, in) -} - -// validateContentLength provides a middleware to validate the content-length -// is valid (greater than zero), for the serialized request payload. -type validateContentLength struct{} - -// ValidateContentLengthHeader adds middleware that validates request content-length -// is set to value greater than zero. -func ValidateContentLengthHeader(stack *middleware.Stack) error { - return stack.Build.Add(&validateContentLength{}, middleware.After) -} - -// ID returns the identifier for the ComputeContentLength. -func (m *validateContentLength) ID() string { return "ValidateContentLength" } - -// HandleBuild adds the length of the serialized request to the HTTP header -// if the length can be determined. -func (m *validateContentLength) HandleBuild( - ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler, -) ( - out middleware.BuildOutput, metadata middleware.Metadata, err error, -) { - req, ok := in.Request.(*Request) - if !ok { - return out, metadata, fmt.Errorf("unknown request type %T", req) - } - - // if request content-length was set to less than 0, return an error - if req.ContentLength < 0 { - return out, metadata, fmt.Errorf( - "content length for payload is required and must be at least 0") - } - - return next.HandleBuild(ctx, in) -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/middleware_headers.go b/vendor/github.com/aws/smithy-go/transport/http/middleware_headers.go deleted file mode 100644 index eac32b4ba..000000000 --- a/vendor/github.com/aws/smithy-go/transport/http/middleware_headers.go +++ /dev/null @@ -1,167 +0,0 @@ -package http - -import ( - "context" - "fmt" - - "github.com/aws/smithy-go/middleware" -) - -type isContentTypeAutoSet struct{} - -// SetIsContentTypeDefaultValue returns a Context specifying if the request's -// content-type header was set to a default value. -func SetIsContentTypeDefaultValue(ctx context.Context, isDefault bool) context.Context { - return context.WithValue(ctx, isContentTypeAutoSet{}, isDefault) -} - -// GetIsContentTypeDefaultValue returns if the content-type HTTP header on the -// request is a default value that was auto assigned by an operation -// serializer. Allows middleware post serialization to know if the content-type -// was auto set to a default value or not. -// -// Also returns false if the Context value was never updated to include if -// content-type was set to a default value. -func GetIsContentTypeDefaultValue(ctx context.Context) bool { - v, _ := ctx.Value(isContentTypeAutoSet{}).(bool) - return v -} - -// AddNoPayloadDefaultContentTypeRemover Adds the DefaultContentTypeRemover -// middleware to the stack after the operation serializer. This middleware will -// remove the content-type header from the request if it was set as a default -// value, and no request payload is present. -// -// Returns error if unable to add the middleware. -func AddNoPayloadDefaultContentTypeRemover(stack *middleware.Stack) (err error) { - err = stack.Serialize.Insert(removeDefaultContentType{}, - "OperationSerializer", middleware.After) - if err != nil { - return fmt.Errorf("failed to add %s serialize middleware, %w", - removeDefaultContentType{}.ID(), err) - } - - return nil -} - -// RemoveNoPayloadDefaultContentTypeRemover removes the -// DefaultContentTypeRemover middleware from the stack. Returns an error if -// unable to remove the middleware. -func RemoveNoPayloadDefaultContentTypeRemover(stack *middleware.Stack) (err error) { - _, err = stack.Serialize.Remove(removeDefaultContentType{}.ID()) - if err != nil { - return fmt.Errorf("failed to remove %s serialize middleware, %w", - removeDefaultContentType{}.ID(), err) - - } - return nil -} - -// removeDefaultContentType provides after serialization middleware that will -// remove the content-type header from an HTTP request if the header was set as -// a default value by the operation serializer, and there is no request payload. -type removeDefaultContentType struct{} - -// ID returns the middleware ID -func (removeDefaultContentType) ID() string { return "RemoveDefaultContentType" } - -// HandleSerialize implements the serialization middleware. -func (removeDefaultContentType) HandleSerialize( - ctx context.Context, input middleware.SerializeInput, next middleware.SerializeHandler, -) ( - out middleware.SerializeOutput, meta middleware.Metadata, err error, -) { - req, ok := input.Request.(*Request) - if !ok { - return out, meta, fmt.Errorf( - "unexpected request type %T for removeDefaultContentType middleware", - input.Request) - } - - if GetIsContentTypeDefaultValue(ctx) && req.GetStream() == nil { - req.Header.Del("Content-Type") - input.Request = req - } - - return next.HandleSerialize(ctx, input) -} - -type headerValue struct { - header string - value string - append bool -} - -type headerValueHelper struct { - headerValues []headerValue -} - -func (h *headerValueHelper) addHeaderValue(value headerValue) { - h.headerValues = append(h.headerValues, value) -} - -func (h *headerValueHelper) ID() string { - return "HTTPHeaderHelper" -} - -func (h *headerValueHelper) HandleBuild(ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler) (out middleware.BuildOutput, metadata middleware.Metadata, err error) { - req, ok := in.Request.(*Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - for _, value := range h.headerValues { - if value.append { - req.Header.Add(value.header, value.value) - } else { - req.Header.Set(value.header, value.value) - } - } - - return next.HandleBuild(ctx, in) -} - -func getOrAddHeaderValueHelper(stack *middleware.Stack) (*headerValueHelper, error) { - id := (*headerValueHelper)(nil).ID() - m, ok := stack.Build.Get(id) - if !ok { - m = &headerValueHelper{} - err := stack.Build.Add(m, middleware.After) - if err != nil { - return nil, err - } - } - - requestUserAgent, ok := m.(*headerValueHelper) - if !ok { - return nil, fmt.Errorf("%T for %s middleware did not match expected type", m, id) - } - - return requestUserAgent, nil -} - -// AddHeaderValue returns a stack mutator that adds the header value pair to header. -// Appends to any existing values if present. -func AddHeaderValue(header string, value string) func(stack *middleware.Stack) error { - return func(stack *middleware.Stack) error { - helper, err := getOrAddHeaderValueHelper(stack) - if err != nil { - return err - } - helper.addHeaderValue(headerValue{header: header, value: value, append: true}) - return nil - } -} - -// SetHeaderValue returns a stack mutator that adds the header value pair to header. -// Replaces any existing values if present. -func SetHeaderValue(header string, value string) func(stack *middleware.Stack) error { - return func(stack *middleware.Stack) error { - helper, err := getOrAddHeaderValueHelper(stack) - if err != nil { - return err - } - helper.addHeaderValue(headerValue{header: header, value: value, append: false}) - return nil - } -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/middleware_http_logging.go b/vendor/github.com/aws/smithy-go/transport/http/middleware_http_logging.go deleted file mode 100644 index d5909b0a2..000000000 --- a/vendor/github.com/aws/smithy-go/transport/http/middleware_http_logging.go +++ /dev/null @@ -1,75 +0,0 @@ -package http - -import ( - "context" - "fmt" - "net/http/httputil" - - "github.com/aws/smithy-go/logging" - "github.com/aws/smithy-go/middleware" -) - -// RequestResponseLogger is a deserialize middleware that will log the request and response HTTP messages and optionally -// their respective bodies. Will not perform any logging if none of the options are set. -type RequestResponseLogger struct { - LogRequest bool - LogRequestWithBody bool - - LogResponse bool - LogResponseWithBody bool -} - -// ID is the middleware identifier. -func (r *RequestResponseLogger) ID() string { - return "RequestResponseLogger" -} - -// HandleDeserialize will log the request and response HTTP messages if configured accordingly. -func (r *RequestResponseLogger) HandleDeserialize( - ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler, -) ( - out middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - logger := middleware.GetLogger(ctx) - - if r.LogRequest || r.LogRequestWithBody { - smithyRequest, ok := in.Request.(*Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in) - } - - rc := smithyRequest.Build(ctx) - reqBytes, err := httputil.DumpRequestOut(rc, r.LogRequestWithBody) - if err != nil { - return out, metadata, err - } - - logger.Logf(logging.Debug, "Request\n%v", string(reqBytes)) - - if r.LogRequestWithBody { - smithyRequest, err = smithyRequest.SetStream(rc.Body) - if err != nil { - return out, metadata, err - } - in.Request = smithyRequest - } - } - - out, metadata, err = next.HandleDeserialize(ctx, in) - - if (err == nil) && (r.LogResponse || r.LogResponseWithBody) { - smithyResponse, ok := out.RawResponse.(*Response) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", out.RawResponse) - } - - respBytes, err := httputil.DumpResponse(smithyResponse.Response, r.LogResponseWithBody) - if err != nil { - return out, metadata, fmt.Errorf("failed to dump response %w", err) - } - - logger.Logf(logging.Debug, "Response\n%v", string(respBytes)) - } - - return out, metadata, err -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/middleware_metadata.go b/vendor/github.com/aws/smithy-go/transport/http/middleware_metadata.go deleted file mode 100644 index d6079b259..000000000 --- a/vendor/github.com/aws/smithy-go/transport/http/middleware_metadata.go +++ /dev/null @@ -1,51 +0,0 @@ -package http - -import ( - "context" - - "github.com/aws/smithy-go/middleware" -) - -type ( - hostnameImmutableKey struct{} - hostPrefixDisableKey struct{} -) - -// GetHostnameImmutable retrieves whether the endpoint hostname should be considered -// immutable or not. -// -// Scoped to stack values. Use middleware#ClearStackValues to clear all stack -// values. -func GetHostnameImmutable(ctx context.Context) (v bool) { - v, _ = middleware.GetStackValue(ctx, hostnameImmutableKey{}).(bool) - return v -} - -// SetHostnameImmutable sets or modifies whether the request's endpoint hostname -// should be considered immutable or not. -// -// Scoped to stack values. Use middleware#ClearStackValues to clear all stack -// values. -func SetHostnameImmutable(ctx context.Context, value bool) context.Context { - return middleware.WithStackValue(ctx, hostnameImmutableKey{}, value) -} - -// IsEndpointHostPrefixDisabled retrieves whether the hostname prefixing is -// disabled. -// -// Scoped to stack values. Use middleware#ClearStackValues to clear all stack -// values. -func IsEndpointHostPrefixDisabled(ctx context.Context) (v bool) { - v, _ = middleware.GetStackValue(ctx, hostPrefixDisableKey{}).(bool) - return v -} - -// DisableEndpointHostPrefix sets or modifies whether the request's endpoint host -// prefixing should be disabled. If value is true, endpoint host prefixing -// will be disabled. -// -// Scoped to stack values. Use middleware#ClearStackValues to clear all stack -// values. -func DisableEndpointHostPrefix(ctx context.Context, value bool) context.Context { - return middleware.WithStackValue(ctx, hostPrefixDisableKey{}, value) -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/middleware_min_proto.go b/vendor/github.com/aws/smithy-go/transport/http/middleware_min_proto.go deleted file mode 100644 index 326cb8a6c..000000000 --- a/vendor/github.com/aws/smithy-go/transport/http/middleware_min_proto.go +++ /dev/null @@ -1,79 +0,0 @@ -package http - -import ( - "context" - "fmt" - "github.com/aws/smithy-go/middleware" - "strings" -) - -// MinimumProtocolError is an error type indicating that the established connection did not meet the expected minimum -// HTTP protocol version. -type MinimumProtocolError struct { - proto string - expectedProtoMajor int - expectedProtoMinor int -} - -// Error returns the error message. -func (m *MinimumProtocolError) Error() string { - return fmt.Sprintf("operation requires minimum HTTP protocol of HTTP/%d.%d, but was %s", - m.expectedProtoMajor, m.expectedProtoMinor, m.proto) -} - -// RequireMinimumProtocol is a deserialization middleware that asserts that the established HTTP connection -// meets the minimum major ad minor version. -type RequireMinimumProtocol struct { - ProtoMajor int - ProtoMinor int -} - -// AddRequireMinimumProtocol adds the RequireMinimumProtocol middleware to the stack using the provided minimum -// protocol major and minor version. -func AddRequireMinimumProtocol(stack *middleware.Stack, major, minor int) error { - return stack.Deserialize.Insert(&RequireMinimumProtocol{ - ProtoMajor: major, - ProtoMinor: minor, - }, "OperationDeserializer", middleware.Before) -} - -// ID returns the middleware identifier string. -func (r *RequireMinimumProtocol) ID() string { - return "RequireMinimumProtocol" -} - -// HandleDeserialize asserts that the established connection is a HTTP connection with the minimum major and minor -// protocol version. -func (r *RequireMinimumProtocol) HandleDeserialize( - ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler, -) ( - out middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err = next.HandleDeserialize(ctx, in) - if err != nil { - return out, metadata, err - } - - response, ok := out.RawResponse.(*Response) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type: %T", out.RawResponse) - } - - if !strings.HasPrefix(response.Proto, "HTTP") { - return out, metadata, &MinimumProtocolError{ - proto: response.Proto, - expectedProtoMajor: r.ProtoMajor, - expectedProtoMinor: r.ProtoMinor, - } - } - - if response.ProtoMajor < r.ProtoMajor || response.ProtoMinor < r.ProtoMinor { - return out, metadata, &MinimumProtocolError{ - proto: response.Proto, - expectedProtoMajor: r.ProtoMajor, - expectedProtoMinor: r.ProtoMinor, - } - } - - return out, metadata, err -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/request.go b/vendor/github.com/aws/smithy-go/transport/http/request.go deleted file mode 100644 index 7177d6f95..000000000 --- a/vendor/github.com/aws/smithy-go/transport/http/request.go +++ /dev/null @@ -1,189 +0,0 @@ -package http - -import ( - "context" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "strings" - - iointernal "github.com/aws/smithy-go/transport/http/internal/io" -) - -// Request provides the HTTP specific request structure for HTTP specific -// middleware steps to use to serialize input, and send an operation's request. -type Request struct { - *http.Request - stream io.Reader - isStreamSeekable bool - streamStartPos int64 -} - -// NewStackRequest returns an initialized request ready to be populated with the -// HTTP request details. Returns empty interface so the function can be used as -// a parameter to the Smithy middleware Stack constructor. -func NewStackRequest() interface{} { - return &Request{ - Request: &http.Request{ - URL: &url.URL{}, - Header: http.Header{}, - ContentLength: -1, // default to unknown length - }, - } -} - -// IsHTTPS returns if the request is HTTPS. Returns false if no endpoint URL is set. -func (r *Request) IsHTTPS() bool { - if r.URL == nil { - return false - } - return strings.EqualFold(r.URL.Scheme, "https") -} - -// Clone returns a deep copy of the Request for the new context. A reference to -// the Stream is copied, but the underlying stream is not copied. -func (r *Request) Clone() *Request { - rc := *r - rc.Request = rc.Request.Clone(context.TODO()) - return &rc -} - -// StreamLength returns the number of bytes of the serialized stream attached -// to the request and ok set. If the length cannot be determined, an error will -// be returned. -func (r *Request) StreamLength() (size int64, ok bool, err error) { - return streamLength(r.stream, r.isStreamSeekable, r.streamStartPos) -} - -func streamLength(stream io.Reader, seekable bool, startPos int64) (size int64, ok bool, err error) { - if stream == nil { - return 0, true, nil - } - - if l, ok := stream.(interface{ Len() int }); ok { - return int64(l.Len()), true, nil - } - - if !seekable { - return 0, false, nil - } - - s := stream.(io.Seeker) - endOffset, err := s.Seek(0, io.SeekEnd) - if err != nil { - return 0, false, err - } - - // The reason to seek to streamStartPos instead of 0 is to ensure that the - // SDK only sends the stream from the starting position the user's - // application provided it to the SDK at. For example application opens a - // file, and wants to skip the first N bytes uploading the rest. The - // application would move the file's offset N bytes, then hand it off to - // the SDK to send the remaining. The SDK should respect that initial offset. - _, err = s.Seek(startPos, io.SeekStart) - if err != nil { - return 0, false, err - } - - return endOffset - startPos, true, nil -} - -// RewindStream will rewind the io.Reader to the relative start position if it -// is an io.Seeker. -func (r *Request) RewindStream() error { - // If there is no stream there is nothing to rewind. - if r.stream == nil { - return nil - } - - if !r.isStreamSeekable { - return fmt.Errorf("request stream is not seekable") - } - _, err := r.stream.(io.Seeker).Seek(r.streamStartPos, io.SeekStart) - return err -} - -// GetStream returns the request stream io.Reader if a stream is set. If no -// stream is present nil will be returned. -func (r *Request) GetStream() io.Reader { - return r.stream -} - -// IsStreamSeekable returns whether the stream is seekable. -func (r *Request) IsStreamSeekable() bool { - return r.isStreamSeekable -} - -// SetStream returns a clone of the request with the stream set to the provided -// reader. May return an error if the provided reader is seekable but returns -// an error. -func (r *Request) SetStream(reader io.Reader) (rc *Request, err error) { - rc = r.Clone() - - if reader == http.NoBody { - reader = nil - } - - var isStreamSeekable bool - var streamStartPos int64 - switch v := reader.(type) { - case io.Seeker: - n, err := v.Seek(0, io.SeekCurrent) - if err != nil { - return r, err - } - isStreamSeekable = true - streamStartPos = n - default: - // If the stream length can be determined, and is determined to be empty, - // use a nil stream to prevent confusion between empty vs not-empty - // streams. - length, ok, err := streamLength(reader, false, 0) - if err != nil { - return nil, err - } else if ok && length == 0 { - reader = nil - } - } - - rc.stream = reader - rc.isStreamSeekable = isStreamSeekable - rc.streamStartPos = streamStartPos - - return rc, err -} - -// Build returns a build standard HTTP request value from the Smithy request. -// The request's stream is wrapped in a safe container that allows it to be -// reused for subsequent attempts. -func (r *Request) Build(ctx context.Context) *http.Request { - req := r.Request.Clone(ctx) - - if r.stream == nil && req.ContentLength == -1 { - req.ContentLength = 0 - } - - switch stream := r.stream.(type) { - case *io.PipeReader: - req.Body = ioutil.NopCloser(stream) - req.ContentLength = -1 - default: - // HTTP Client Request must only have a non-nil body if the - // ContentLength is explicitly unknown (-1) or non-zero. The HTTP - // Client will interpret a non-nil body and ContentLength 0 as - // "unknown". This is unwanted behavior. - if req.ContentLength != 0 && r.stream != nil { - req.Body = iointernal.NewSafeReadCloser(ioutil.NopCloser(stream)) - } - } - - return req -} - -// RequestCloner is a function that can take an input request type and clone the request -// for use in a subsequent retry attempt. -func RequestCloner(v interface{}) interface{} { - return v.(*Request).Clone() -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/response.go b/vendor/github.com/aws/smithy-go/transport/http/response.go deleted file mode 100644 index 0c13bfcc8..000000000 --- a/vendor/github.com/aws/smithy-go/transport/http/response.go +++ /dev/null @@ -1,34 +0,0 @@ -package http - -import ( - "fmt" - "net/http" -) - -// Response provides the HTTP specific response structure for HTTP specific -// middleware steps to use to deserialize the response from an operation call. -type Response struct { - *http.Response -} - -// ResponseError provides the HTTP centric error type wrapping the underlying -// error with the HTTP response value. -type ResponseError struct { - Response *Response - Err error -} - -// HTTPStatusCode returns the HTTP response status code received from the service. -func (e *ResponseError) HTTPStatusCode() int { return e.Response.StatusCode } - -// HTTPResponse returns the HTTP response received from the service. -func (e *ResponseError) HTTPResponse() *Response { return e.Response } - -// Unwrap returns the nested error if any, or nil. -func (e *ResponseError) Unwrap() error { return e.Err } - -func (e *ResponseError) Error() string { - return fmt.Sprintf( - "http response error StatusCode: %d, %v", - e.Response.StatusCode, e.Err) -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/time.go b/vendor/github.com/aws/smithy-go/transport/http/time.go deleted file mode 100644 index 607b196a8..000000000 --- a/vendor/github.com/aws/smithy-go/transport/http/time.go +++ /dev/null @@ -1,13 +0,0 @@ -package http - -import ( - "time" - - smithytime "github.com/aws/smithy-go/time" -) - -// ParseTime parses a time string like the HTTP Date header. This uses a more -// relaxed rule set for date parsing compared to the standard library. -func ParseTime(text string) (t time.Time, err error) { - return smithytime.ParseHTTPDate(text) -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/url.go b/vendor/github.com/aws/smithy-go/transport/http/url.go deleted file mode 100644 index 60a5fc100..000000000 --- a/vendor/github.com/aws/smithy-go/transport/http/url.go +++ /dev/null @@ -1,44 +0,0 @@ -package http - -import "strings" - -// JoinPath returns an absolute URL path composed of the two paths provided. -// Enforces that the returned path begins with '/'. If added path is empty the -// returned path suffix will match the first parameter suffix. -func JoinPath(a, b string) string { - if len(a) == 0 { - a = "/" - } else if a[0] != '/' { - a = "/" + a - } - - if len(b) != 0 && b[0] == '/' { - b = b[1:] - } - - if len(b) != 0 && len(a) > 1 && a[len(a)-1] != '/' { - a = a + "/" - } - - return a + b -} - -// JoinRawQuery returns an absolute raw query expression. Any duplicate '&' -// will be collapsed to single separator between values. -func JoinRawQuery(a, b string) string { - a = strings.TrimFunc(a, isAmpersand) - b = strings.TrimFunc(b, isAmpersand) - - if len(a) == 0 { - return b - } - if len(b) == 0 { - return a - } - - return a + "&" + b -} - -func isAmpersand(v rune) bool { - return v == '&' -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/user_agent.go b/vendor/github.com/aws/smithy-go/transport/http/user_agent.go deleted file mode 100644 index 71a7e0d8a..000000000 --- a/vendor/github.com/aws/smithy-go/transport/http/user_agent.go +++ /dev/null @@ -1,37 +0,0 @@ -package http - -import ( - "strings" -) - -// UserAgentBuilder is a builder for a HTTP User-Agent string. -type UserAgentBuilder struct { - sb strings.Builder -} - -// NewUserAgentBuilder returns a new UserAgentBuilder. -func NewUserAgentBuilder() *UserAgentBuilder { - return &UserAgentBuilder{sb: strings.Builder{}} -} - -// AddKey adds the named component/product to the agent string -func (u *UserAgentBuilder) AddKey(key string) { - u.appendTo(key) -} - -// AddKeyValue adds the named key to the agent string with the given value. -func (u *UserAgentBuilder) AddKeyValue(key, value string) { - u.appendTo(key + "/" + value) -} - -// Build returns the constructed User-Agent string. May be called multiple times. -func (u *UserAgentBuilder) Build() string { - return u.sb.String() -} - -func (u *UserAgentBuilder) appendTo(value string) { - if u.sb.Len() > 0 { - u.sb.WriteRune(' ') - } - u.sb.WriteString(value) -} diff --git a/vendor/github.com/aws/smithy-go/validation.go b/vendor/github.com/aws/smithy-go/validation.go deleted file mode 100644 index b5eedc1f9..000000000 --- a/vendor/github.com/aws/smithy-go/validation.go +++ /dev/null @@ -1,140 +0,0 @@ -package smithy - -import ( - "bytes" - "fmt" - "strings" -) - -// An InvalidParamsError provides wrapping of invalid parameter errors found when -// validating API operation input parameters. -type InvalidParamsError struct { - // Context is the base context of the invalid parameter group. - Context string - errs []InvalidParamError -} - -// Add adds a new invalid parameter error to the collection of invalid -// parameters. The context of the invalid parameter will be updated to reflect -// this collection. -func (e *InvalidParamsError) Add(err InvalidParamError) { - err.SetContext(e.Context) - e.errs = append(e.errs, err) -} - -// AddNested adds the invalid parameter errors from another InvalidParamsError -// value into this collection. The nested errors will have their nested context -// updated and base context to reflect the merging. -// -// Use for nested validations errors. -func (e *InvalidParamsError) AddNested(nestedCtx string, nested InvalidParamsError) { - for _, err := range nested.errs { - err.SetContext(e.Context) - err.AddNestedContext(nestedCtx) - e.errs = append(e.errs, err) - } -} - -// Len returns the number of invalid parameter errors -func (e *InvalidParamsError) Len() int { - return len(e.errs) -} - -// Error returns the string formatted form of the invalid parameters. -func (e InvalidParamsError) Error() string { - w := &bytes.Buffer{} - fmt.Fprintf(w, "%d validation error(s) found.\n", len(e.errs)) - - for _, err := range e.errs { - fmt.Fprintf(w, "- %s\n", err.Error()) - } - - return w.String() -} - -// Errs returns a slice of the invalid parameters -func (e InvalidParamsError) Errs() []error { - errs := make([]error, len(e.errs)) - for i := 0; i < len(errs); i++ { - errs[i] = e.errs[i] - } - - return errs -} - -// An InvalidParamError represents an invalid parameter error type. -type InvalidParamError interface { - error - - // Field name the error occurred on. - Field() string - - // SetContext updates the context of the error. - SetContext(string) - - // AddNestedContext updates the error's context to include a nested level. - AddNestedContext(string) -} - -type invalidParamError struct { - context string - nestedContext string - field string - reason string -} - -// Error returns the string version of the invalid parameter error. -func (e invalidParamError) Error() string { - return fmt.Sprintf("%s, %s.", e.reason, e.Field()) -} - -// Field Returns the field and context the error occurred. -func (e invalidParamError) Field() string { - sb := &strings.Builder{} - sb.WriteString(e.context) - if sb.Len() > 0 { - if len(e.nestedContext) == 0 || (len(e.nestedContext) > 0 && e.nestedContext[:1] != "[") { - sb.WriteRune('.') - } - } - if len(e.nestedContext) > 0 { - sb.WriteString(e.nestedContext) - sb.WriteRune('.') - } - sb.WriteString(e.field) - return sb.String() -} - -// SetContext updates the base context of the error. -func (e *invalidParamError) SetContext(ctx string) { - e.context = ctx -} - -// AddNestedContext prepends a context to the field's path. -func (e *invalidParamError) AddNestedContext(ctx string) { - if len(e.nestedContext) == 0 { - e.nestedContext = ctx - return - } - // Check if our nested context is an index into a slice or map - if e.nestedContext[:1] != "[" { - e.nestedContext = fmt.Sprintf("%s.%s", ctx, e.nestedContext) - return - } - e.nestedContext = ctx + e.nestedContext -} - -// An ParamRequiredError represents an required parameter error. -type ParamRequiredError struct { - invalidParamError -} - -// NewErrParamRequired creates a new required parameter error. -func NewErrParamRequired(field string) *ParamRequiredError { - return &ParamRequiredError{ - invalidParamError{ - field: field, - reason: fmt.Sprintf("missing required field"), - }, - } -} diff --git a/vendor/github.com/buger/goterm/.gitignore b/vendor/github.com/buger/goterm/.gitignore deleted file mode 100644 index 986544fb0..000000000 --- a/vendor/github.com/buger/goterm/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -*.swp -.idea \ No newline at end of file diff --git a/vendor/github.com/buger/goterm/LICENSE b/vendor/github.com/buger/goterm/LICENSE deleted file mode 100644 index ac25aeb7d..000000000 --- a/vendor/github.com/buger/goterm/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2016 Leonid Bugaev - -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/buger/goterm/README.md b/vendor/github.com/buger/goterm/README.md deleted file mode 100644 index fc74e2105..000000000 --- a/vendor/github.com/buger/goterm/README.md +++ /dev/null @@ -1,119 +0,0 @@ -## Description - -This library provides basic building blocks for building advanced console UIs. - -Initially created for [Gor](http://github.com/buger/gor). - -Full API documentation: http://godoc.org/github.com/buger/goterm - -## Basic usage - -Full screen console app, printing current time: - -```go -import ( - tm "github.com/buger/goterm" - "time" -) - -func main() { - tm.Clear() // Clear current screen - - for { - // By moving cursor to top-left position we ensure that console output - // will be overwritten each time, instead of adding new. - tm.MoveCursor(1,1) - - tm.Println("Current Time:", time.Now().Format(time.RFC1123)) - - tm.Flush() // Call it every time at the end of rendering - - time.Sleep(time.Second) - } -} -``` - -This can be seen in [examples/time_example.go](examples/time_example.go). To -run it yourself, go into your `$GOPATH/src/github.com/buger/goterm` directory -and run `go run ./examples/time_example.go` - - -Print red bold message on white background: - -```go -tm.Println(tm.Background(tm.Color(tm.Bold("Important header"), tm.RED), tm.WHITE)) -``` - - -Create box and move it to center of the screen: - -```go -tm.Clear() - -// Create Box with 30% width of current screen, and height of 20 lines -box := tm.NewBox(30|tm.PCT, 20, 0) - -// Add some content to the box -// Note that you can add ANY content, even tables -fmt.Fprint(box, "Some box content") - -// Move Box to approx center of the screen -tm.Print(tm.MoveTo(box.String(), 40|tm.PCT, 40|tm.PCT)) - -tm.Flush() -``` - -This can be found in [examples/box_example.go](examples/box_example.go). - -Draw table: - -```go -// Based on http://golang.org/pkg/text/tabwriter -totals := tm.NewTable(0, 10, 5, ' ', 0) -fmt.Fprintf(totals, "Time\tStarted\tActive\tFinished\n") -fmt.Fprintf(totals, "%s\t%d\t%d\t%d\n", "All", started, started-finished, finished) -tm.Println(totals) -tm.Flush() -``` - -This can be found in [examples/table_example.go](examples/table_example.go). - -## Line charts - -Chart example: - -![screen shot 2013-07-09 at 5 05 37 pm](https://f.cloud.github.com/assets/14009/767676/e3dd35aa-e887-11e2-9cd2-f6451eb26adc.png) - - -```go - import ( - tm "github.com/buger/goterm" - ) - - chart := tm.NewLineChart(100, 20) - - data := new(tm.DataTable) - data.AddColumn("Time") - data.AddColumn("Sin(x)") - data.AddColumn("Cos(x+1)") - - for i := 0.1; i < 10; i += 0.1 { - data.AddRow(i, math.Sin(i), math.Cos(i+1)) - } - - tm.Println(chart.Draw(data)) -``` - -This can be found in [examples/chart_example.go](examples/chart_example.go). - -Drawing 2 separate graphs in different scales. Each graph have its own Y axe. - -```go -chart.Flags = tm.DRAW_INDEPENDENT -``` - -Drawing graph with relative scale (Grapwh draw starting from min value instead of zero) - -```go -chart.Flags = tm.DRAW_RELATIVE -``` diff --git a/vendor/github.com/buger/goterm/box.go b/vendor/github.com/buger/goterm/box.go deleted file mode 100644 index 4a119c552..000000000 --- a/vendor/github.com/buger/goterm/box.go +++ /dev/null @@ -1,176 +0,0 @@ -package goterm - -import ( - "bytes" - "regexp" - "strings" - _ "unicode/utf8" -) - -const DEFAULT_BORDER = "- │ ┌ ┐ └ ┘" - -// Box allows you to create independent parts of screen, with its own buffer and borders. -// Can be used for creating modal windows -// -// Generates boxes likes this: -// ┌--------┐ -// │hello │ -// │world │ -// │ │ -// └--------┘ -// -type Box struct { - Buf *bytes.Buffer - - Width int - Height int - - // To get even padding: PaddingX ~= PaddingY*4 - PaddingX int - PaddingY int - - // Should contain 6 border pieces separated by spaces - // - // Example border: - // "- │ ┌ ┐ └ ┘" - Border string - - Flags int // Not used now -} - -// Create new Box. -// Width and height can be relative: -// -// // Create box with 50% with of current screen and 10 lines height -// box := tm.NewBox(50|tm.PCT, 10, 0) -// -func NewBox(width, height int, flags int) *Box { - width, height = GetXY(width, height) - - box := new(Box) - box.Buf = new(bytes.Buffer) - box.Width = width - box.Height = height - box.Border = DEFAULT_BORDER - box.PaddingX = 1 - box.PaddingY = 0 - box.Flags = flags - - return box -} - -func (b *Box) Write(p []byte) (int, error) { - return b.Buf.Write(p) -} - -var ANSI_RE = regexp.MustCompile(`\\0\d+\[\d+(?:;\d+)?m`) - -// String renders Box -func (b *Box) String() (out string) { - borders := strings.Split(b.Border, " ") - lines := strings.Split(b.Buf.String(), "\n") - - // Border + padding - prefix := borders[1] + strings.Repeat(" ", b.PaddingX) - suffix := strings.Repeat(" ", b.PaddingX) + borders[1] - - offset := b.PaddingY + 1 // 1 is border width - - // Content width without borders and padding - contentWidth := b.Width - (b.PaddingX+1)*2 - for y := 0; y < b.Height; y++ { - var line string - - switch { - // Draw borders for first line - case y == 0: - line = borders[2] + strings.Repeat(borders[0], b.Width-2) + borders[3] - - // Draw borders for last line - case y == (b.Height - 1): - line = borders[4] + strings.Repeat(borders[0], b.Width-2) + borders[5] - - // Draw top and bottom padding - case y <= b.PaddingY || y >= (b.Height-b.PaddingY): - line = borders[1] + strings.Repeat(" ", b.Width-2) + borders[1] - - // Render content - default: - if len(lines) > y-offset { - line = lines[y-offset] - } else { - line = "" - } - - r := []rune(line) - - lastAnsii := "" - withoutAnsii := []rune{} - withOffset := []rune{} - i := 0 - - for { - if i >= len(r) { - break - } - - if r[i] == 27 { - lastAnsii = "" - withOffset = append(withOffset, r[i]) - lastAnsii += string(r[i]) - i++ - for { - - i++ - if i > len(r) { - break - } - - withOffset = append(withOffset, r[i]) - lastAnsii += string(r[i]) - - if r[i] == 'm' { - i++ - break - } - } - } - - if i >= len(r) { - break - } - - withoutAnsii = append(withoutAnsii, r[i]) - - if len(withoutAnsii) <= contentWidth { - withOffset = append(withOffset, r[i]) - } - - i++ - } - - if len(withoutAnsii) > contentWidth { - // If line is too large limit it - line = string(withOffset) - } else { - // If line is too small enlarge it by adding spaces - line += strings.Repeat(" ", contentWidth-len(withoutAnsii)) - } - - if lastAnsii != "" { - line += RESET - } - - line = prefix + line + suffix - } - - // Don't add newline for last element - if y != b.Height-1 { - line += "\n" - } - - out += line - } - - return out -} diff --git a/vendor/github.com/buger/goterm/plot.go b/vendor/github.com/buger/goterm/plot.go deleted file mode 100644 index 504358cbe..000000000 --- a/vendor/github.com/buger/goterm/plot.go +++ /dev/null @@ -1,329 +0,0 @@ -package goterm - -import ( - "fmt" - "math" - "strings" - "unicode/utf8" -) - -const ( - AXIS_LEFT = iota - AXIS_RIGHT -) - -const ( - DRAW_INDEPENDENT = 1 << iota - DRAW_RELATIVE -) - -type DataTable struct { - columns []string - - rows [][]float64 -} - -func (d *DataTable) AddColumn(name string) { - d.columns = append(d.columns, name) -} - -func (d *DataTable) AddRow(elms ...float64) { - d.rows = append(d.rows, elms) -} - -type Chart interface { - Draw(data DataTable, flags int) string -} - -type LineChart struct { - Buf []string - chartBuf []string - - data *DataTable - - Width int - Height int - - chartHeight int - chartWidth int - - paddingX int - - paddingY int - - Flags int -} - -func genBuf(size int) []string { - buf := make([]string, size) - - for i := 0; i < size; i++ { - buf[i] = " " - } - - return buf -} - -// Format float -func ff(num interface{}) string { - return fmt.Sprintf("%.1f", num) -} - -func NewLineChart(width, height int) *LineChart { - chart := new(LineChart) - chart.Width = width - chart.Height = height - chart.Buf = genBuf(width * height) - - // axis lines + axies text - chart.paddingY = 2 - - return chart -} - -func (c *LineChart) DrawAxes(maxX, minX, maxY, minY float64, index int) { - side := AXIS_LEFT - - if c.Flags&DRAW_INDEPENDENT != 0 { - if index%2 == 0 { - side = AXIS_RIGHT - } - - c.DrawLine(c.paddingX-1, 1, c.Width-c.paddingX, 1, "-") - } else { - c.DrawLine(c.paddingX-1, 1, c.Width-1, 1, "-") - } - - if side == AXIS_LEFT { - c.DrawLine(c.paddingX-1, 1, c.paddingX-1, c.Height-1, "│") - } else { - c.DrawLine(c.Width-c.paddingX, 1, c.Width-c.paddingX, c.Height-1, "│") - } - - left := 0 - if side == AXIS_RIGHT { - left = c.Width - c.paddingX + 1 - } - - if c.Flags&DRAW_RELATIVE != 0 { - c.writeText(ff(minY), left, 1) - } else { - if minY > 0 { - c.writeText("0", left, 1) - } else { - c.writeText(ff(minY), left, 1) - } - } - - c.writeText(ff(maxY), left, c.Height-1) - - c.writeText(ff(minX), c.paddingX, 0) - - x_col := c.data.columns[0] - c.writeText(c.data.columns[0], c.Width/2-utf8.RuneCountInString(x_col)/2, 1) - - if c.Flags&DRAW_INDEPENDENT != 0 || len(c.data.columns) < 3 { - col := c.data.columns[index] - - for idx, char := range strings.Split(col, "") { - start_from := c.Height/2 + len(col)/2 - idx - - if side == AXIS_LEFT { - c.writeText(char, c.paddingX-1, start_from) - } else { - c.writeText(char, c.Width-c.paddingX, start_from) - } - } - } - - if c.Flags&DRAW_INDEPENDENT != 0 { - c.writeText(ff(maxX), c.Width-c.paddingX-len(ff(maxX)), 0) - } else { - c.writeText(ff(maxX), c.Width-len(ff(maxX)), 0) - } -} - -func (c *LineChart) writeText(text string, x, y int) { - coord := y*c.Width + x - - for idx, char := range strings.Split(text, "") { - c.Buf[coord+idx] = char - } -} - -func (c *LineChart) Draw(data *DataTable) (out string) { - var scaleY, scaleX float64 - - c.data = data - - if c.Flags&DRAW_INDEPENDENT != 0 && len(data.columns) > 3 { - fmt.Println("Error: Can't use DRAW_INDEPENDENT for more then 2 graphs") - return "" - } - - charts := len(data.columns) - 1 - - prevPoint := [2]int{-1, -1} - - maxX, minX, maxY, minY := getBoundaryValues(data, -1) - - c.paddingX = int(math.Max(float64(len(ff(minY))), float64(len(ff(maxY))))) + 1 - - c.chartHeight = c.Height - c.paddingY - - if c.Flags&DRAW_INDEPENDENT != 0 { - c.chartWidth = c.Width - 2*c.paddingX - } else { - c.chartWidth = c.Width - c.paddingX - 1 - } - - scaleX = float64(c.chartWidth) / (maxX - minX) - - if c.Flags&DRAW_RELATIVE != 0 || minY < 0 { - scaleY = float64(c.chartHeight) / (maxY - minY) - } else { - scaleY = float64(c.chartHeight) / maxY - } - - for i := 1; i < charts+1; i++ { - if c.Flags&DRAW_INDEPENDENT != 0 { - maxX, minX, maxY, minY = getBoundaryValues(data, i) - - scaleX = float64(c.chartWidth-1) / (maxX - minX) - scaleY = float64(c.chartHeight) / maxY - - if c.Flags&DRAW_RELATIVE != 0 || minY < 0 { - scaleY = float64(c.chartHeight) / (maxY - minY) - } - } - - symbol := Color("•", i) - - c_data := getChartData(data, i) - - for _, point := range c_data { - x := int((point[0]-minX)*scaleX) + c.paddingX - y := int((point[1])*scaleY) + c.paddingY - - if c.Flags&DRAW_RELATIVE != 0 || minY < 0 { - y = int((point[1]-minY)*scaleY) + c.paddingY - } - - if prevPoint[0] == -1 { - prevPoint[0] = x - prevPoint[1] = y - } - - if prevPoint[0] <= x { - c.DrawLine(prevPoint[0], prevPoint[1], x, y, symbol) - } - - prevPoint[0] = x - prevPoint[1] = y - } - - c.DrawAxes(maxX, minX, maxY, minY, i) - } - - for row := c.Height - 1; row >= 0; row-- { - out += strings.Join(c.Buf[row*c.Width:(row+1)*c.Width], "") + "\n" - } - - return -} - -func (c *LineChart) DrawLine(x0, y0, x1, y1 int, symbol string) { - drawLine(x0, y0, x1, y1, func(x, y int) { - coord := y*c.Width + x - - if coord > 0 && coord < len(c.Buf) { - c.Buf[coord] = symbol - } - }) -} - -func getBoundaryValues(data *DataTable, index int) (maxX, minX, maxY, minY float64) { - maxX = math.Inf(-1) - minX = math.Inf(1) - maxY = math.Inf(-1) - minY = math.Inf(1) - - for _, r := range data.rows { - maxX = math.Max(maxX, r[0]) - minX = math.Min(minX, r[0]) - - for idx, c := range r { - if idx > 0 { - if index == -1 || index == idx { - maxY = math.Max(maxY, c) - minY = math.Min(minY, c) - } - } - } - } - - if maxY > 0 { - maxY = maxY * 1.1 - } else { - maxY = maxY * 0.9 - } - - if minY > 0 { - minY = minY * 0.9 - } else { - minY = minY * 1.1 - } - - return -} - -// DataTable can contain data for multiple graphs, we need to extract only 1 -func getChartData(data *DataTable, index int) (out [][]float64) { - for _, r := range data.rows { - out = append(out, []float64{r[0], r[index]}) - } - - return -} - -// Algorithm for drawing line between two points -// -// http://en.wikipedia.org/wiki/Bresenham's_line_algorithm -func drawLine(x0, y0, x1, y1 int, plot func(int, int)) { - dx := x1 - x0 - if dx < 0 { - dx = -dx - } - dy := y1 - y0 - if dy < 0 { - dy = -dy - } - var sx, sy int - if x0 < x1 { - sx = 1 - } else { - sx = -1 - } - if y0 < y1 { - sy = 1 - } else { - sy = -1 - } - err := dx - dy - - for { - plot(x0, y0) - if x0 == x1 && y0 == y1 { - break - } - e2 := 2 * err - if e2 > -dy { - err -= dy - x0 += sx - } - if e2 < dx { - err += dx - y0 += sy - } - } -} diff --git a/vendor/github.com/buger/goterm/table.go b/vendor/github.com/buger/goterm/table.go deleted file mode 100644 index d8dae55ce..000000000 --- a/vendor/github.com/buger/goterm/table.go +++ /dev/null @@ -1,34 +0,0 @@ -package goterm - -import ( - "bytes" - "text/tabwriter" -) - -// Tabwriter with own buffer: -// -// totals := tm.NewTable(0, 10, 5, ' ', 0) -// fmt.Fprintf(totals, "Time\tStarted\tActive\tFinished\n") -// fmt.Fprintf(totals, "%s\t%d\t%d\t%d\n", "All", started, started-finished, finished) -// tm.Println(totals) -// -// Based on http://golang.org/pkg/text/tabwriter -type Table struct { - tabwriter.Writer - - Buf *bytes.Buffer -} - -// Same as here http://golang.org/pkg/text/tabwriter/#Writer.Init -func NewTable(minwidth, tabwidth, padding int, padchar byte, flags uint) *Table { - tbl := new(Table) - tbl.Buf = new(bytes.Buffer) - tbl.Init(tbl.Buf, minwidth, tabwidth, padding, padchar, flags) - - return tbl -} - -func (t *Table) String() string { - t.Flush() - return t.Buf.String() -} diff --git a/vendor/github.com/buger/goterm/terminal.go b/vendor/github.com/buger/goterm/terminal.go deleted file mode 100644 index d1e82085e..000000000 --- a/vendor/github.com/buger/goterm/terminal.go +++ /dev/null @@ -1,249 +0,0 @@ -// Provides basic bulding blocks for advanced console UI -// -// Coordinate system: -// -// 1/1---X----> -// | -// Y -// | -// v -// -// Documentation for ANSI codes: http://en.wikipedia.org/wiki/ANSI_escape_code#Colors -// -// Inspired by: http://www.darkcoding.net/software/pretty-command-line-console-output-on-unix-in-python-and-go-lang/ -package goterm - -import ( - "bufio" - "bytes" - "fmt" - "os" - "strings" -) - -// Reset all custom styles -const RESET = "\033[0m" - -// Reset to default color -const RESET_COLOR = "\033[32m" - -// Return cursor to start of line and clean it -const RESET_LINE = "\r\033[K" - -// List of possible colors -const ( - BLACK = iota - RED - GREEN - YELLOW - BLUE - MAGENTA - CYAN - WHITE -) - -var Output *bufio.Writer = bufio.NewWriter(os.Stdout) - -func getColor(code int) string { - return fmt.Sprintf("\033[3%dm", code) -} - -func getBgColor(code int) string { - return fmt.Sprintf("\033[4%dm", code) -} - -// Set percent flag: num | PCT -// -// Check percent flag: num & PCT -// -// Reset percent flag: num & 0xFF -const shift = uint(^uint(0)>>63) << 4 -const PCT = 0x8000 << shift - -type winsize struct { - Row uint16 - Col uint16 - Xpixel uint16 - Ypixel uint16 -} - -// Global screen buffer -// Its not recommended write to buffer dirrectly, use package Print,Printf,Println fucntions instead. -var Screen *bytes.Buffer = new(bytes.Buffer) - -// GetXY gets relative or absolute coordinates -// To get relative, set PCT flag to number: -// -// // Get 10% of total width to `x` and 20 to y -// x, y = tm.GetXY(10|tm.PCT, 20) -// -func GetXY(x int, y int) (int, int) { - if y == -1 { - y = CurrentHeight() + 1 - } - - if x&PCT != 0 { - x = int((x & 0xFF) * Width() / 100) - } - - if y&PCT != 0 { - y = int((y & 0xFF) * Height() / 100) - } - - return x, y -} - -type sf func(int, string) string - -// Apply given transformation func for each line in string -func applyTransform(str string, transform sf) (out string) { - out = "" - - for idx, line := range strings.Split(str, "\n") { - out += transform(idx, line) - } - - return -} - -// Clear screen -func Clear() { - Output.WriteString("\033[2J") -} - -// Move cursor to given position -func MoveCursor(x int, y int) { - fmt.Fprintf(Screen, "\033[%d;%dH", y, x) -} - -// Move cursor up relative the current position -func MoveCursorUp(bias int) { - fmt.Fprintf(Screen, "\033[%dA", bias) -} - -// Move cursor down relative the current position -func MoveCursorDown(bias int) { - fmt.Fprintf(Screen, "\033[%dB", bias) -} - -// Move cursor forward relative the current position -func MoveCursorForward(bias int) { - fmt.Fprintf(Screen, "\033[%dC", bias) -} - -// Move cursor backward relative the current position -func MoveCursorBackward(bias int) { - fmt.Fprintf(Screen, "\033[%dD", bias) -} - -// Move string to possition -func MoveTo(str string, x int, y int) (out string) { - x, y = GetXY(x, y) - - return applyTransform(str, func(idx int, line string) string { - return fmt.Sprintf("\033[%d;%dH%s", y+idx, x, line) - }) -} - -// ResetLine returns carrier to start of line -func ResetLine(str string) (out string) { - return applyTransform(str, func(idx int, line string) string { - return fmt.Sprintf("%s%s", RESET_LINE, line) - }) -} - -// Make bold -func Bold(str string) string { - return applyTransform(str, func(idx int, line string) string { - return fmt.Sprintf("\033[1m%s\033[0m", line) - }) -} - -// Apply given color to string: -// -// tm.Color("RED STRING", tm.RED) -// -func Color(str string, color int) string { - return applyTransform(str, func(idx int, line string) string { - return fmt.Sprintf("%s%s%s", getColor(color), line, RESET) - }) -} - -func Highlight(str, substr string, color int) string { - hiSubstr := Color(substr, color) - return strings.Replace(str, substr, hiSubstr, -1) -} - -func HighlightRegion(str string, from, to, color int) string { - return str[:from] + Color(str[from:to], color) + str[to:] -} - -// Change background color of string: -// -// tm.Background("string", tm.RED) -// -func Background(str string, color int) string { - return applyTransform(str, func(idx int, line string) string { - return fmt.Sprintf("%s%s%s", getBgColor(color), line, RESET) - }) -} - -// Width gets console width -func Width() int { - ws, err := getWinsize() - - if err != nil { - return -1 - } - - return int(ws.Col) -} - -// CurrentHeight gets current height. Line count in Screen buffer. -func CurrentHeight() int { - return strings.Count(Screen.String(), "\n") -} - -// Flush buffer and ensure that it will not overflow screen -func Flush() { - for idx, str := range strings.SplitAfter(Screen.String(), "\n") { - if idx > Height() { - return - } - - Output.WriteString(str) - } - - Output.Flush() - Screen.Reset() -} - -func Print(a ...interface{}) (n int, err error) { - return fmt.Fprint(Screen, a...) -} - -func Println(a ...interface{}) (n int, err error) { - return fmt.Fprintln(Screen, a...) -} - -func Printf(format string, a ...interface{}) (n int, err error) { - return fmt.Fprintf(Screen, format, a...) -} - -func Context(data string, idx, max int) string { - var start, end int - - if len(data[:idx]) < (max / 2) { - start = 0 - } else { - start = idx - max/2 - } - - if len(data)-idx < (max / 2) { - end = len(data) - 1 - } else { - end = idx + max/2 - } - - return data[start:end] -} diff --git a/vendor/github.com/buger/goterm/terminal_nosysioctl.go b/vendor/github.com/buger/goterm/terminal_nosysioctl.go deleted file mode 100644 index f4f4d5efc..000000000 --- a/vendor/github.com/buger/goterm/terminal_nosysioctl.go +++ /dev/null @@ -1,22 +0,0 @@ -//go:build plan9 || solaris -// +build plan9 solaris - -package goterm - -func getWinsize() (*winsize, error) { - ws := new(winsize) - - ws.Col = 80 - ws.Row = 24 - - return ws, nil -} - -// Height gets console height -func Height() int { - ws, err := getWinsize() - if err != nil { - return -1 - } - return int(ws.Row) -} diff --git a/vendor/github.com/buger/goterm/terminal_sysioctl.go b/vendor/github.com/buger/goterm/terminal_sysioctl.go deleted file mode 100644 index 8b48b405c..000000000 --- a/vendor/github.com/buger/goterm/terminal_sysioctl.go +++ /dev/null @@ -1,36 +0,0 @@ -//go:build !windows && !plan9 && !solaris -// +build !windows,!plan9,!solaris - -package goterm - -import ( - "errors" - "math" - "os" - - "golang.org/x/sys/unix" -) - -func getWinsize() (*unix.Winsize, error) { - - ws, err := unix.IoctlGetWinsize(int(os.Stdout.Fd()), unix.TIOCGWINSZ) - if err != nil { - return nil, os.NewSyscallError("GetWinsize", err) - } - - return ws, nil -} - -// Height gets console height -func Height() int { - ws, err := getWinsize() - if err != nil { - // returns math.MinInt32 if we could not retrieve the height of console window, - // like VSCode debugging console - if errors.Is(err, unix.EOPNOTSUPP) { - return math.MinInt32 - } - return -1 - } - return int(ws.Row) -} diff --git a/vendor/github.com/buger/goterm/terminal_windows.go b/vendor/github.com/buger/goterm/terminal_windows.go deleted file mode 100644 index e8236b697..000000000 --- a/vendor/github.com/buger/goterm/terminal_windows.go +++ /dev/null @@ -1,40 +0,0 @@ -//go:build windows -// +build windows - -package goterm - -import ( - "errors" - "math" - "os" - - "golang.org/x/sys/windows" -) - -func getWinsize() (*winsize, error) { - ws := new(winsize) - fd := os.Stdout.Fd() - var info windows.ConsoleScreenBufferInfo - if err := windows.GetConsoleScreenBufferInfo(windows.Handle(fd), &info); err != nil { - return nil, err - } - - ws.Col = uint16(info.Window.Right - info.Window.Left + 1) - ws.Row = uint16(info.Window.Bottom - info.Window.Top + 1) - - return ws, nil -} - -// Height gets console height -func Height() int { - ws, err := getWinsize() - if err != nil { - // returns math.MinInt32 if we could not retrieve the height of console window, - // like VSCode debugging console - if errors.Is(err, windows.WSAEOPNOTSUPP) { - return math.MinInt32 - } - return -1 - } - return int(ws.Row) -} diff --git a/vendor/github.com/compose-spec/compose-go/LICENSE b/vendor/github.com/compose-spec/compose-go/LICENSE deleted file mode 100644 index 9c8e20ab8..000000000 --- a/vendor/github.com/compose-spec/compose-go/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2013-2017 Docker, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - https://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/compose-spec/compose-go/NOTICE b/vendor/github.com/compose-spec/compose-go/NOTICE deleted file mode 100644 index 9c2755477..000000000 --- a/vendor/github.com/compose-spec/compose-go/NOTICE +++ /dev/null @@ -1,2 +0,0 @@ -The Compose Specification -Copyright 2020 The Compose Specification Authors diff --git a/vendor/github.com/compose-spec/compose-go/cli/options.go b/vendor/github.com/compose-spec/compose-go/cli/options.go deleted file mode 100644 index 332ea3b5b..000000000 --- a/vendor/github.com/compose-spec/compose-go/cli/options.go +++ /dev/null @@ -1,475 +0,0 @@ -/* - Copyright 2020 The Compose Specification 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 cli - -import ( - "context" - "io" - "os" - "path/filepath" - "strings" - - "github.com/pkg/errors" - "github.com/sirupsen/logrus" - - "github.com/compose-spec/compose-go/consts" - "github.com/compose-spec/compose-go/dotenv" - "github.com/compose-spec/compose-go/errdefs" - "github.com/compose-spec/compose-go/loader" - "github.com/compose-spec/compose-go/types" - "github.com/compose-spec/compose-go/utils" -) - -// ProjectOptions provides common configuration for loading a project. -type ProjectOptions struct { - ctx context.Context - - // Name is a valid Compose project name to be used or empty. - // - // If empty, the project loader will automatically infer a reasonable - // project name if possible. - Name string - - // WorkingDir is a file path to use as the project directory or empty. - // - // If empty, the project loader will automatically infer a reasonable - // working directory if possible. - WorkingDir string - - // ConfigPaths are file paths to one or more Compose files. - // - // These are applied in order by the loader following the merge logic - // as described in the spec. - // - // The first entry is required and is the primary Compose file. - // For convenience, WithConfigFileEnv and WithDefaultConfigPath - // are provided to populate this in a predictable manner. - ConfigPaths []string - - // Environment are additional environment variables to make available - // for interpolation. - // - // NOTE: For security, the loader does not automatically expose any - // process environment variables. For convenience, WithOsEnv can be - // used if appropriate. - Environment types.Mapping - - // EnvFiles are file paths to ".env" files with additional environment - // variable data. - // - // These are loaded in-order, so it is possible to override variables or - // in subsequent files. - // - // This field is optional, but any file paths that are included here must - // exist or an error will be returned during load. - EnvFiles []string - - loadOptions []func(*loader.Options) -} - -type ProjectOptionsFn func(*ProjectOptions) error - -// NewProjectOptions creates ProjectOptions -func NewProjectOptions(configs []string, opts ...ProjectOptionsFn) (*ProjectOptions, error) { - options := &ProjectOptions{ - ConfigPaths: configs, - Environment: map[string]string{}, - } - for _, o := range opts { - err := o(options) - if err != nil { - return nil, err - } - } - return options, nil -} - -// WithName defines ProjectOptions' name -func WithName(name string) ProjectOptionsFn { - return func(o *ProjectOptions) error { - // a project (once loaded) cannot have an empty name - // however, on the options object, the name is optional: if unset, - // a name will be inferred by the loader, so it's legal to set the - // name to an empty string here - if name != loader.NormalizeProjectName(name) { - return loader.InvalidProjectNameErr(name) - } - o.Name = name - return nil - } -} - -// WithWorkingDirectory defines ProjectOptions' working directory -func WithWorkingDirectory(wd string) ProjectOptionsFn { - return func(o *ProjectOptions) error { - if wd == "" { - return nil - } - abs, err := filepath.Abs(wd) - if err != nil { - return err - } - o.WorkingDir = abs - return nil - } -} - -// WithConfigFileEnv allow to set compose config file paths by COMPOSE_FILE environment variable -func WithConfigFileEnv(o *ProjectOptions) error { - if len(o.ConfigPaths) > 0 { - return nil - } - sep := o.Environment[consts.ComposePathSeparator] - if sep == "" { - sep = string(os.PathListSeparator) - } - f, ok := o.Environment[consts.ComposeFilePath] - if ok { - paths, err := absolutePaths(strings.Split(f, sep)) - o.ConfigPaths = paths - return err - } - return nil -} - -// WithDefaultConfigPath searches for default config files from working directory -func WithDefaultConfigPath(o *ProjectOptions) error { - if len(o.ConfigPaths) > 0 { - return nil - } - pwd, err := o.GetWorkingDir() - if err != nil { - return err - } - for { - candidates := findFiles(DefaultFileNames, pwd) - if len(candidates) > 0 { - winner := candidates[0] - if len(candidates) > 1 { - logrus.Warnf("Found multiple config files with supported names: %s", strings.Join(candidates, ", ")) - logrus.Warnf("Using %s", winner) - } - o.ConfigPaths = append(o.ConfigPaths, winner) - - overrides := findFiles(DefaultOverrideFileNames, pwd) - if len(overrides) > 0 { - if len(overrides) > 1 { - logrus.Warnf("Found multiple override files with supported names: %s", strings.Join(overrides, ", ")) - logrus.Warnf("Using %s", overrides[0]) - } - o.ConfigPaths = append(o.ConfigPaths, overrides[0]) - } - return nil - } - parent := filepath.Dir(pwd) - if parent == pwd { - // no config file found, but that's not a blocker if caller only needs project name - return nil - } - pwd = parent - } -} - -// WithEnv defines a key=value set of variables used for compose file interpolation -func WithEnv(env []string) ProjectOptionsFn { - return func(o *ProjectOptions) error { - for k, v := range utils.GetAsEqualsMap(env) { - o.Environment[k] = v - } - return nil - } -} - -// WithDiscardEnvFile sets discards the `env_file` section after resolving to -// the `environment` section -func WithDiscardEnvFile(o *ProjectOptions) error { - o.loadOptions = append(o.loadOptions, loader.WithDiscardEnvFiles) - return nil -} - -// WithLoadOptions provides a hook to control how compose files are loaded -func WithLoadOptions(loadOptions ...func(*loader.Options)) ProjectOptionsFn { - return func(o *ProjectOptions) error { - o.loadOptions = append(o.loadOptions, loadOptions...) - return nil - } -} - -// WithDefaultProfiles uses the provided profiles (if any), and falls back to -// profiles specified via the COMPOSE_PROFILES environment variable otherwise. -func WithDefaultProfiles(profile ...string) ProjectOptionsFn { - if len(profile) == 0 { - profile = strings.Split(os.Getenv(consts.ComposeProfiles), ",") - } - return WithProfiles(profile) -} - -// WithProfiles sets profiles to be activated -func WithProfiles(profiles []string) ProjectOptionsFn { - return func(o *ProjectOptions) error { - o.loadOptions = append(o.loadOptions, loader.WithProfiles(profiles)) - return nil - } -} - -// WithOsEnv imports environment variables from OS -func WithOsEnv(o *ProjectOptions) error { - for k, v := range utils.GetAsEqualsMap(os.Environ()) { - if _, set := o.Environment[k]; set { - continue - } - o.Environment[k] = v - } - return nil -} - -// WithEnvFile sets an alternate env file. -// -// Deprecated: use WithEnvFiles instead. -func WithEnvFile(file string) ProjectOptionsFn { - var files []string - if file != "" { - files = []string{file} - } - return WithEnvFiles(files...) -} - -// WithEnvFiles set alternate env files -func WithEnvFiles(file ...string) ProjectOptionsFn { - return func(options *ProjectOptions) error { - options.EnvFiles = file - return nil - } -} - -// WithDotEnv imports environment variables from .env file -func WithDotEnv(o *ProjectOptions) error { - wd, err := o.GetWorkingDir() - if err != nil { - return err - } - envMap, err := dotenv.GetEnvFromFile(o.Environment, wd, o.EnvFiles) - if err != nil { - return err - } - o.Environment.Merge(envMap) - return nil -} - -// WithInterpolation set ProjectOptions to enable/skip interpolation -func WithInterpolation(interpolation bool) ProjectOptionsFn { - return func(o *ProjectOptions) error { - o.loadOptions = append(o.loadOptions, func(options *loader.Options) { - options.SkipInterpolation = !interpolation - }) - return nil - } -} - -// WithNormalization set ProjectOptions to enable/skip normalization -func WithNormalization(normalization bool) ProjectOptionsFn { - return func(o *ProjectOptions) error { - o.loadOptions = append(o.loadOptions, func(options *loader.Options) { - options.SkipNormalization = !normalization - }) - return nil - } -} - -// WithConsistency set ProjectOptions to enable/skip consistency -func WithConsistency(consistency bool) ProjectOptionsFn { - return func(o *ProjectOptions) error { - o.loadOptions = append(o.loadOptions, func(options *loader.Options) { - options.SkipConsistencyCheck = !consistency - }) - return nil - } -} - -// WithResolvedPaths set ProjectOptions to enable paths resolution -func WithResolvedPaths(resolve bool) ProjectOptionsFn { - return func(o *ProjectOptions) error { - o.loadOptions = append(o.loadOptions, func(options *loader.Options) { - options.ResolvePaths = resolve - }) - return nil - } -} - -// WithContext sets the context used to load model and resources -func WithContext(ctx context.Context) ProjectOptionsFn { - return func(o *ProjectOptions) error { - o.ctx = ctx - return nil - } -} - -// WithResourceLoader register support for ResourceLoader to manage remote resources -func WithResourceLoader(r loader.ResourceLoader) ProjectOptionsFn { - return func(o *ProjectOptions) error { - o.loadOptions = append(o.loadOptions, func(options *loader.Options) { - options.ResourceLoaders = append(options.ResourceLoaders, r) - }) - return nil - } -} - -// DefaultFileNames defines the Compose file names for auto-discovery (in order of preference) -var DefaultFileNames = []string{"compose.yaml", "compose.yml", "docker-compose.yml", "docker-compose.yaml"} - -// DefaultOverrideFileNames defines the Compose override file names for auto-discovery (in order of preference) -var DefaultOverrideFileNames = []string{"compose.override.yml", "compose.override.yaml", "docker-compose.override.yml", "docker-compose.override.yaml"} - -func (o ProjectOptions) GetWorkingDir() (string, error) { - if o.WorkingDir != "" { - return o.WorkingDir, nil - } - for _, path := range o.ConfigPaths { - if path != "-" { - absPath, err := filepath.Abs(path) - if err != nil { - return "", err - } - return filepath.Dir(absPath), nil - } - } - return os.Getwd() -} - -// ProjectFromOptions load a compose project based on command line options -func ProjectFromOptions(options *ProjectOptions) (*types.Project, error) { - configPaths, err := getConfigPathsFromOptions(options) - if err != nil { - return nil, err - } - - var configs []types.ConfigFile - for _, f := range configPaths { - var b []byte - if f == "-" { - b, err = io.ReadAll(os.Stdin) - if err != nil { - return nil, err - } - } else { - f, err := filepath.Abs(f) - if err != nil { - return nil, err - } - b, err = os.ReadFile(f) - if err != nil { - return nil, err - } - } - configs = append(configs, types.ConfigFile{ - Filename: f, - Content: b, - }) - } - - workingDir, err := options.GetWorkingDir() - if err != nil { - return nil, err - } - absWorkingDir, err := filepath.Abs(workingDir) - if err != nil { - return nil, err - } - - options.loadOptions = append(options.loadOptions, - withNamePrecedenceLoad(absWorkingDir, options), - withConvertWindowsPaths(options)) - - ctx := options.ctx - if ctx == nil { - ctx = context.Background() - } - - project, err := loader.LoadWithContext(ctx, types.ConfigDetails{ - ConfigFiles: configs, - WorkingDir: workingDir, - Environment: options.Environment, - }, options.loadOptions...) - if err != nil { - return nil, err - } - - project.ComposeFiles = configPaths - return project, nil -} - -func withNamePrecedenceLoad(absWorkingDir string, options *ProjectOptions) func(*loader.Options) { - return func(opts *loader.Options) { - if options.Name != "" { - opts.SetProjectName(options.Name, true) - } else if nameFromEnv, ok := options.Environment[consts.ComposeProjectName]; ok && nameFromEnv != "" { - opts.SetProjectName(nameFromEnv, true) - } else { - opts.SetProjectName( - loader.NormalizeProjectName(filepath.Base(absWorkingDir)), - false, - ) - } - } -} - -func withConvertWindowsPaths(options *ProjectOptions) func(*loader.Options) { - return func(o *loader.Options) { - if o.ResolvePaths { - o.ConvertWindowsPaths = utils.StringToBool(options.Environment["COMPOSE_CONVERT_WINDOWS_PATHS"]) - } - } -} - -// getConfigPathsFromOptions retrieves the config files for project based on project options -func getConfigPathsFromOptions(options *ProjectOptions) ([]string, error) { - if len(options.ConfigPaths) != 0 { - return absolutePaths(options.ConfigPaths) - } - return nil, errors.Wrap(errdefs.ErrNotFound, "no configuration file provided") -} - -func findFiles(names []string, pwd string) []string { - candidates := []string{} - for _, n := range names { - f := filepath.Join(pwd, n) - if _, err := os.Stat(f); err == nil { - candidates = append(candidates, f) - } - } - return candidates -} - -func absolutePaths(p []string) ([]string, error) { - var paths []string - for _, f := range p { - if f == "-" { - paths = append(paths, f) - continue - } - abs, err := filepath.Abs(f) - if err != nil { - return nil, err - } - f = abs - if _, err := os.Stat(f); err != nil { - return nil, err - } - paths = append(paths, f) - } - return paths, nil -} diff --git a/vendor/github.com/compose-spec/compose-go/consts/consts.go b/vendor/github.com/compose-spec/compose-go/consts/consts.go deleted file mode 100644 index 76bdb82e1..000000000 --- a/vendor/github.com/compose-spec/compose-go/consts/consts.go +++ /dev/null @@ -1,24 +0,0 @@ -/* - Copyright 2020 The Compose Specification 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 consts - -const ( - ComposeProjectName = "COMPOSE_PROJECT_NAME" - ComposePathSeparator = "COMPOSE_PATH_SEPARATOR" - ComposeFilePath = "COMPOSE_FILE" - ComposeProfiles = "COMPOSE_PROFILES" -) diff --git a/vendor/github.com/compose-spec/compose-go/dotenv/LICENSE b/vendor/github.com/compose-spec/compose-go/dotenv/LICENSE deleted file mode 100644 index 9390caf66..000000000 --- a/vendor/github.com/compose-spec/compose-go/dotenv/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2013 John Barton - -MIT License - -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/compose-spec/compose-go/dotenv/env.go b/vendor/github.com/compose-spec/compose-go/dotenv/env.go deleted file mode 100644 index c8a538bcb..000000000 --- a/vendor/github.com/compose-spec/compose-go/dotenv/env.go +++ /dev/null @@ -1,84 +0,0 @@ -/* - Copyright 2020 The Compose Specification 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 dotenv - -import ( - "bytes" - "os" - "path/filepath" - - "github.com/pkg/errors" -) - -func GetEnvFromFile(currentEnv map[string]string, workingDir string, filenames []string) (map[string]string, error) { - envMap := make(map[string]string) - - dotEnvFiles := filenames - if len(dotEnvFiles) == 0 { - dotEnvFiles = append(dotEnvFiles, filepath.Join(workingDir, ".env")) - } - for _, dotEnvFile := range dotEnvFiles { - abs, err := filepath.Abs(dotEnvFile) - if err != nil { - return envMap, err - } - dotEnvFile = abs - - s, err := os.Stat(dotEnvFile) - if os.IsNotExist(err) { - if len(filenames) == 0 { - return envMap, nil - } - return envMap, errors.Errorf("Couldn't find env file: %s", dotEnvFile) - } - if err != nil { - return envMap, err - } - - if s.IsDir() { - if len(filenames) == 0 { - return envMap, nil - } - return envMap, errors.Errorf("%s is a directory", dotEnvFile) - } - - b, err := os.ReadFile(dotEnvFile) - if os.IsNotExist(err) { - return nil, errors.Errorf("Couldn't read env file: %s", dotEnvFile) - } - if err != nil { - return envMap, err - } - - env, err := ParseWithLookup(bytes.NewReader(b), func(k string) (string, bool) { - v, ok := currentEnv[k] - if ok { - return v, true - } - v, ok = envMap[k] - return v, ok - }) - if err != nil { - return envMap, errors.Wrapf(err, "failed to read %s", dotEnvFile) - } - for k, v := range env { - envMap[k] = v - } - } - - return envMap, nil -} diff --git a/vendor/github.com/compose-spec/compose-go/dotenv/godotenv.go b/vendor/github.com/compose-spec/compose-go/dotenv/godotenv.go deleted file mode 100644 index 9b95c990e..000000000 --- a/vendor/github.com/compose-spec/compose-go/dotenv/godotenv.go +++ /dev/null @@ -1,175 +0,0 @@ -// Package dotenv is a go port of the ruby dotenv library (https://github.com/bkeepers/dotenv) -// -// Examples/readme can be found on the github page at https://github.com/joho/godotenv -// -// The TL;DR is that you make a .env file that looks something like -// -// SOME_ENV_VAR=somevalue -// -// and then in your go code you can call -// -// godotenv.Load() -// -// and all the env vars declared in .env will be available through os.Getenv("SOME_ENV_VAR") -package dotenv - -import ( - "bytes" - "io" - "os" - "regexp" - "strings" - - "github.com/compose-spec/compose-go/template" -) - -var utf8BOM = []byte("\uFEFF") - -var startsWithDigitRegex = regexp.MustCompile(`^\s*\d.*`) // Keys starting with numbers are ignored - -// LookupFn represents a lookup function to resolve variables from -type LookupFn func(string) (string, bool) - -var noLookupFn = func(s string) (string, bool) { - return "", false -} - -// Parse reads an env file from io.Reader, returning a map of keys and values. -func Parse(r io.Reader) (map[string]string, error) { - return ParseWithLookup(r, nil) -} - -// ParseWithLookup reads an env file from io.Reader, returning a map of keys and values. -func ParseWithLookup(r io.Reader, lookupFn LookupFn) (map[string]string, error) { - data, err := io.ReadAll(r) - if err != nil { - return nil, err - } - - // seek past the UTF-8 BOM if it exists (particularly on Windows, some - // editors tend to add it, and it'll cause parsing to fail) - data = bytes.TrimPrefix(data, utf8BOM) - - return UnmarshalBytesWithLookup(data, lookupFn) -} - -// Load will read your env file(s) and load them into ENV for this process. -// -// Call this function as close as possible to the start of your program (ideally in main). -// -// If you call Load without any args it will default to loading .env in the current path. -// -// You can otherwise tell it which files to load (there can be more than one) like: -// -// godotenv.Load("fileone", "filetwo") -// -// It's important to note that it WILL NOT OVERRIDE an env variable that already exists - consider the .env file to set dev vars or sensible defaults -func Load(filenames ...string) error { - return load(false, filenames...) -} - -func load(overload bool, filenames ...string) error { - filenames = filenamesOrDefault(filenames) - for _, filename := range filenames { - err := loadFile(filename, overload) - if err != nil { - return err - } - } - return nil -} - -// ReadWithLookup gets all env vars from the files and/or lookup function and return values as -// a map rather than automatically writing values into env -func ReadWithLookup(lookupFn LookupFn, filenames ...string) (map[string]string, error) { - filenames = filenamesOrDefault(filenames) - envMap := make(map[string]string) - - for _, filename := range filenames { - individualEnvMap, individualErr := readFile(filename, lookupFn) - - if individualErr != nil { - return envMap, individualErr - } - - for key, value := range individualEnvMap { - if startsWithDigitRegex.MatchString(key) { - continue - } - envMap[key] = value - } - } - - return envMap, nil -} - -// Read all env (with same file loading semantics as Load) but return values as -// a map rather than automatically writing values into env -func Read(filenames ...string) (map[string]string, error) { - return ReadWithLookup(nil, filenames...) -} - -// UnmarshalBytesWithLookup parses env file from byte slice of chars, returning a map of keys and values. -func UnmarshalBytesWithLookup(src []byte, lookupFn LookupFn) (map[string]string, error) { - return UnmarshalWithLookup(string(src), lookupFn) -} - -// UnmarshalWithLookup parses env file from string, returning a map of keys and values. -func UnmarshalWithLookup(src string, lookupFn LookupFn) (map[string]string, error) { - out := make(map[string]string) - err := newParser().parse(src, out, lookupFn) - return out, err -} - -func filenamesOrDefault(filenames []string) []string { - if len(filenames) == 0 { - return []string{".env"} - } - return filenames -} - -func loadFile(filename string, overload bool) error { - envMap, err := readFile(filename, nil) - if err != nil { - return err - } - - currentEnv := map[string]bool{} - rawEnv := os.Environ() - for _, rawEnvLine := range rawEnv { - key := strings.Split(rawEnvLine, "=")[0] - currentEnv[key] = true - } - - for key, value := range envMap { - if !currentEnv[key] || overload { - _ = os.Setenv(key, value) - } - } - - return nil -} - -func readFile(filename string, lookupFn LookupFn) (map[string]string, error) { - file, err := os.Open(filename) - if err != nil { - return nil, err - } - defer file.Close() - - return ParseWithLookup(file, lookupFn) -} - -func expandVariables(value string, envMap map[string]string, lookupFn LookupFn) (string, error) { - retVal, err := template.Substitute(value, func(k string) (string, bool) { - if v, ok := lookupFn(k); ok { - return v, true - } - v, ok := envMap[k] - return v, ok - }) - if err != nil { - return value, err - } - return retVal, nil -} diff --git a/vendor/github.com/compose-spec/compose-go/dotenv/parser.go b/vendor/github.com/compose-spec/compose-go/dotenv/parser.go deleted file mode 100644 index aec72a880..000000000 --- a/vendor/github.com/compose-spec/compose-go/dotenv/parser.go +++ /dev/null @@ -1,271 +0,0 @@ -package dotenv - -import ( - "errors" - "fmt" - "regexp" - "strconv" - "strings" - "unicode" -) - -const ( - charComment = '#' - prefixSingleQuote = '\'' - prefixDoubleQuote = '"' -) - -var ( - escapeSeqRegex = regexp.MustCompile(`(\\(?:[abcfnrtv$"\\]|0\d{0,3}))`) - exportRegex = regexp.MustCompile(`^export\s+`) -) - -type parser struct { - line int -} - -func newParser() *parser { - return &parser{ - line: 1, - } -} - -func (p *parser) parse(src string, out map[string]string, lookupFn LookupFn) error { - cutset := src - if lookupFn == nil { - lookupFn = noLookupFn - } - for { - cutset = p.getStatementStart(cutset) - if cutset == "" { - // reached end of file - break - } - - key, left, inherited, err := p.locateKeyName(cutset) - if err != nil { - return err - } - if strings.Contains(key, " ") { - return fmt.Errorf("line %d: key cannot contain a space", p.line) - } - - if inherited { - value, ok := lookupFn(key) - if ok { - out[key] = value - } - cutset = left - continue - } - - value, left, err := p.extractVarValue(left, out, lookupFn) - if err != nil { - return err - } - - out[key] = value - cutset = left - } - - return nil -} - -// getStatementPosition returns position of statement begin. -// -// It skips any comment line or non-whitespace character. -func (p *parser) getStatementStart(src string) string { - pos := p.indexOfNonSpaceChar(src) - if pos == -1 { - return "" - } - - src = src[pos:] - if src[0] != charComment { - return src - } - - // skip comment section - pos = strings.IndexFunc(src, isCharFunc('\n')) - if pos == -1 { - return "" - } - return p.getStatementStart(src[pos:]) -} - -// locateKeyName locates and parses key name and returns rest of slice -func (p *parser) locateKeyName(src string) (string, string, bool, error) { - var key string - var inherited bool - // trim "export" and space at beginning - src = strings.TrimLeftFunc(exportRegex.ReplaceAllString(src, ""), isSpace) - - // locate key name end and validate it in single loop - offset := 0 -loop: - for i, rune := range src { - if isSpace(rune) { - continue - } - - switch rune { - case '=', ':', '\n': - // library also supports yaml-style value declaration - key = string(src[0:i]) - offset = i + 1 - inherited = rune == '\n' - break loop - case '_', '.', '-', '[', ']': - default: - // variable name should match [A-Za-z0-9_.-] - if unicode.IsLetter(rune) || unicode.IsNumber(rune) { - continue - } - - return "", "", inherited, fmt.Errorf( - `line %d: unexpected character %q in variable name %q`, - p.line, string(rune), strings.Split(src, "\n")[0]) - } - } - - if src == "" { - return "", "", inherited, errors.New("zero length string") - } - - // trim whitespace - key = strings.TrimRightFunc(key, unicode.IsSpace) - cutset := strings.TrimLeftFunc(src[offset:], isSpace) - return key, cutset, inherited, nil -} - -// extractVarValue extracts variable value and returns rest of slice -func (p *parser) extractVarValue(src string, envMap map[string]string, lookupFn LookupFn) (string, string, error) { - quote, isQuoted := hasQuotePrefix(src) - if !isQuoted { - // unquoted value - read until new line - value, rest, _ := strings.Cut(src, "\n") - p.line++ - - // Remove inline comments on unquoted lines - value, _, _ = strings.Cut(value, " #") - value = strings.TrimRightFunc(value, unicode.IsSpace) - retVal, err := expandVariables(string(value), envMap, lookupFn) - return retVal, rest, err - } - - previousCharIsEscape := false - // lookup quoted string terminator - for i := 1; i < len(src); i++ { - if src[i] == '\n' { - p.line++ - } - if char := src[i]; char != quote { - if !previousCharIsEscape && char == '\\' { - previousCharIsEscape = true - } else { - previousCharIsEscape = false - } - continue - } - - // skip escaped quote symbol (\" or \', depends on quote) - if previousCharIsEscape { - previousCharIsEscape = false - continue - } - - // trim quotes - value := string(src[1:i]) - if quote == prefixDoubleQuote { - // expand standard shell escape sequences & then interpolate - // variables on the result - retVal, err := expandVariables(expandEscapes(value), envMap, lookupFn) - if err != nil { - return "", "", err - } - value = retVal - } - - return value, src[i+1:], nil - } - - // return formatted error if quoted string is not terminated - valEndIndex := strings.IndexFunc(src, isCharFunc('\n')) - if valEndIndex == -1 { - valEndIndex = len(src) - } - - return "", "", fmt.Errorf("line %d: unterminated quoted value %s", p.line, src[:valEndIndex]) -} - -func expandEscapes(str string) string { - out := escapeSeqRegex.ReplaceAllStringFunc(str, func(match string) string { - if match == `\$` { - // `\$` is not a Go escape sequence, the expansion parser uses - // the special `$$` syntax - // both `FOO=\$bar` and `FOO=$$bar` are valid in an env file and - // will result in FOO w/ literal value of "$bar" (no interpolation) - return "$$" - } - - if strings.HasPrefix(match, `\0`) { - // octal escape sequences in Go are not prefixed with `\0`, so - // rewrite the prefix, e.g. `\0123` -> `\123` -> literal value "S" - match = strings.Replace(match, `\0`, `\`, 1) - } - - // use Go to unquote (unescape) the literal - // see https://go.dev/ref/spec#Rune_literals - // - // NOTE: Go supports ADDITIONAL escapes like `\x` & `\u` & `\U`! - // These are NOT supported, which is why we use a regex to find - // only matches we support and then use `UnquoteChar` instead of a - // `Unquote` on the entire value - v, _, _, err := strconv.UnquoteChar(match, '"') - if err != nil { - return match - } - return string(v) - }) - return out -} - -func (p *parser) indexOfNonSpaceChar(src string) int { - return strings.IndexFunc(src, func(r rune) bool { - if r == '\n' { - p.line++ - } - return !unicode.IsSpace(r) - }) -} - -// hasQuotePrefix reports whether charset starts with single or double quote and returns quote character -func hasQuotePrefix(src string) (byte, bool) { - if src == "" { - return 0, false - } - - switch quote := src[0]; quote { - case prefixDoubleQuote, prefixSingleQuote: - return quote, true // isQuoted - default: - return 0, false - } -} - -func isCharFunc(char rune) func(rune) bool { - return func(v rune) bool { - return v == char - } -} - -// isSpace reports whether the rune is a space character but not line break character -// -// this differs from unicode.IsSpace, which also applies line break as space -func isSpace(r rune) bool { - switch r { - case '\t', '\v', '\f', '\r', ' ', 0x85, 0xA0: - return true - } - return false -} diff --git a/vendor/github.com/compose-spec/compose-go/errdefs/errors.go b/vendor/github.com/compose-spec/compose-go/errdefs/errors.go deleted file mode 100644 index a54407007..000000000 --- a/vendor/github.com/compose-spec/compose-go/errdefs/errors.go +++ /dev/null @@ -1,53 +0,0 @@ -/* - Copyright 2020 The Compose Specification 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 errdefs - -import "errors" - -var ( - // ErrNotFound is returned when an object is not found - ErrNotFound = errors.New("not found") - - // ErrInvalid is returned when a compose project is invalid - ErrInvalid = errors.New("invalid compose project") - - // ErrUnsupported is returned when a compose project uses an unsupported attribute - ErrUnsupported = errors.New("unsupported attribute") - - // ErrIncompatible is returned when a compose project uses an incompatible attribute - ErrIncompatible = errors.New("incompatible attribute") -) - -// IsNotFoundError returns true if the unwrapped error is ErrNotFound -func IsNotFoundError(err error) bool { - return errors.Is(err, ErrNotFound) -} - -// IsInvalidError returns true if the unwrapped error is ErrInvalid -func IsInvalidError(err error) bool { - return errors.Is(err, ErrInvalid) -} - -// IsUnsupportedError returns true if the unwrapped error is ErrUnsupported -func IsUnsupportedError(err error) bool { - return errors.Is(err, ErrUnsupported) -} - -// IsUnsupportedError returns true if the unwrapped error is ErrIncompatible -func IsIncompatibleError(err error) bool { - return errors.Is(err, ErrIncompatible) -} diff --git a/vendor/github.com/compose-spec/compose-go/interpolation/interpolation.go b/vendor/github.com/compose-spec/compose-go/interpolation/interpolation.go deleted file mode 100644 index 305730838..000000000 --- a/vendor/github.com/compose-spec/compose-go/interpolation/interpolation.go +++ /dev/null @@ -1,132 +0,0 @@ -/* - Copyright 2020 The Compose Specification 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 interpolation - -import ( - "os" - - "github.com/compose-spec/compose-go/template" - "github.com/compose-spec/compose-go/tree" - "github.com/pkg/errors" -) - -// Options supported by Interpolate -type Options struct { - // LookupValue from a key - LookupValue LookupValue - // TypeCastMapping maps key paths to functions to cast to a type - TypeCastMapping map[tree.Path]Cast - // Substitution function to use - Substitute func(string, template.Mapping) (string, error) -} - -// LookupValue is a function which maps from variable names to values. -// Returns the value as a string and a bool indicating whether -// the value is present, to distinguish between an empty string -// and the absence of a value. -type LookupValue func(key string) (string, bool) - -// Cast a value to a new type, or return an error if the value can't be cast -type Cast func(value string) (interface{}, error) - -// Interpolate replaces variables in a string with the values from a mapping -func Interpolate(config map[string]interface{}, opts Options) (map[string]interface{}, error) { - if opts.LookupValue == nil { - opts.LookupValue = os.LookupEnv - } - if opts.TypeCastMapping == nil { - opts.TypeCastMapping = make(map[tree.Path]Cast) - } - if opts.Substitute == nil { - opts.Substitute = template.Substitute - } - - out := map[string]interface{}{} - - for key, value := range config { - interpolatedValue, err := recursiveInterpolate(value, tree.NewPath(key), opts) - if err != nil { - return out, err - } - out[key] = interpolatedValue - } - - return out, nil -} - -func recursiveInterpolate(value interface{}, path tree.Path, opts Options) (interface{}, error) { - switch value := value.(type) { - case string: - newValue, err := opts.Substitute(value, template.Mapping(opts.LookupValue)) - if err != nil { - return value, newPathError(path, err) - } - caster, ok := opts.getCasterForPath(path) - if !ok { - return newValue, nil - } - casted, err := caster(newValue) - return casted, newPathError(path, errors.Wrap(err, "failed to cast to expected type")) - - case map[string]interface{}: - out := map[string]interface{}{} - for key, elem := range value { - interpolatedElem, err := recursiveInterpolate(elem, path.Next(key), opts) - if err != nil { - return nil, err - } - out[key] = interpolatedElem - } - return out, nil - - case []interface{}: - out := make([]interface{}, len(value)) - for i, elem := range value { - interpolatedElem, err := recursiveInterpolate(elem, path.Next(tree.PathMatchList), opts) - if err != nil { - return nil, err - } - out[i] = interpolatedElem - } - return out, nil - - default: - return value, nil - } -} - -func newPathError(path tree.Path, err error) error { - switch err := err.(type) { - case nil: - return nil - case *template.InvalidTemplateError: - return errors.Errorf( - "invalid interpolation format for %s.\nYou may need to escape any $ with another $.\n%s", - path, err.Template) - default: - return errors.Wrapf(err, "error while interpolating %s", path) - } -} - -func (o Options) getCasterForPath(path tree.Path) (Cast, bool) { - for pattern, caster := range o.TypeCastMapping { - if path.Matches(pattern) { - return caster, true - } - } - return nil, false -} diff --git a/vendor/github.com/compose-spec/compose-go/loader/example1.env b/vendor/github.com/compose-spec/compose-go/loader/example1.env deleted file mode 100644 index 61716e93b..000000000 --- a/vendor/github.com/compose-spec/compose-go/loader/example1.env +++ /dev/null @@ -1,10 +0,0 @@ -# passed through -FOO=foo_from_env_file -ENV.WITH.DOT=ok -ENV_WITH_UNDERSCORE=ok - -# overridden in example2.env -BAR=bar_from_env_file - -# overridden in full-example.yml -BAZ=baz_from_env_file diff --git a/vendor/github.com/compose-spec/compose-go/loader/example2.env b/vendor/github.com/compose-spec/compose-go/loader/example2.env deleted file mode 100644 index f47d1e614..000000000 --- a/vendor/github.com/compose-spec/compose-go/loader/example2.env +++ /dev/null @@ -1,4 +0,0 @@ -BAR=bar_from_env_file_2 - -# overridden in configDetails.Environment -QUX=quz_from_env_file_2 diff --git a/vendor/github.com/compose-spec/compose-go/loader/full-example.yml b/vendor/github.com/compose-spec/compose-go/loader/full-example.yml deleted file mode 100644 index 24d954578..000000000 --- a/vendor/github.com/compose-spec/compose-go/loader/full-example.yml +++ /dev/null @@ -1,450 +0,0 @@ -name: full_example_project_name -services: - - bar: - build: - dockerfile_inline: | - FROM alpine - RUN echo "hello" > /world.txt - - foo: - annotations: - - com.example.foo=bar - build: - context: ./dir - dockerfile: Dockerfile - args: - foo: bar - ssh: - - default - target: foo - network: foo - cache_from: - - foo - - bar - labels: [FOO=BAR] - additional_contexts: - foo: ./bar - secrets: - - secret1 - - source: secret2 - target: my_secret - uid: '103' - gid: '103' - mode: 0440 - tags: - - foo:v1.0.0 - - docker.io/username/foo:my-other-tag - - ${COMPOSE_PROJECT_NAME}:1.0.0 - platforms: - - linux/amd64 - - linux/arm64 - - - cap_add: - - ALL - - cap_drop: - - NET_ADMIN - - SYS_ADMIN - - cgroup_parent: m-executor-abcd - - # String or list - command: bundle exec thin -p 3000 - # command: ["bundle", "exec", "thin", "-p", "3000"] - - configs: - - config1 - - source: config2 - target: /my_config - uid: '103' - gid: '103' - mode: 0440 - - container_name: my-web-container - - depends_on: - - db - - redis - - deploy: - mode: replicated - replicas: 6 - labels: [FOO=BAR] - rollback_config: - parallelism: 3 - delay: 10s - failure_action: continue - monitor: 60s - max_failure_ratio: 0.3 - order: start-first - update_config: - parallelism: 3 - delay: 10s - failure_action: continue - monitor: 60s - max_failure_ratio: 0.3 - order: start-first - resources: - limits: - cpus: '0.001' - memory: 50M - reservations: - cpus: '0.0001' - memory: 20M - generic_resources: - - discrete_resource_spec: - kind: 'gpu' - value: 2 - - discrete_resource_spec: - kind: 'ssd' - value: 1 - restart_policy: - condition: on-failure - delay: 5s - max_attempts: 3 - window: 120s - placement: - constraints: [node=foo] - max_replicas_per_node: 5 - preferences: - - spread: node.labels.az - endpoint_mode: dnsrr - - device_cgroup_rules: - - "c 1:3 mr" - - "a 7:* rmw" - - devices: - - "/dev/ttyUSB0:/dev/ttyUSB0" - - # String or list - # dns: 8.8.8.8 - dns: - - 8.8.8.8 - - 9.9.9.9 - - # String or list - # dns_search: example.com - dns_search: - - dc1.example.com - - dc2.example.com - - domainname: foo.com - - # String or list - # entrypoint: /code/entrypoint.sh -p 3000 - entrypoint: ["/code/entrypoint.sh", "-p", "3000"] - - # String or list - # env_file: .env - env_file: - - ./example1.env - - ./example2.env - - # Mapping or list - # Mapping values can be strings, numbers or null - # Booleans are not allowed - must be quoted - environment: - BAZ: baz_from_service_def - QUX: - # environment: - # - RACK_ENV=development - # - SHOW=true - # - SESSION_SECRET - - # Items can be strings or numbers - expose: - - "3000" - - 8000 - - external_links: - - redis_1 - - project_db_1:mysql - - project_db_1:postgresql - - # Mapping or list - # Mapping values must be strings - # extra_hosts: - # somehost: "162.242.195.82" - # otherhost: "50.31.209.229" - extra_hosts: - - "otherhost:50.31.209.229" - - "somehost:162.242.195.82" - - hostname: foo - - healthcheck: - test: echo "hello world" - interval: 10s - timeout: 1s - retries: 5 - start_period: 15s - start_interval: 5s - - # Any valid image reference - repo, tag, id, sha - image: redis - # image: ubuntu:14.04 - # image: tutum/influxdb - # image: example-registry.com:4000/postgresql - # image: a4bc65fd - # image: busybox@sha256:38a203e1986cf79639cfb9b2e1d6e773de84002feea2d4eb006b52004ee8502d - - ipc: host - - uts: host - - # Mapping or list - # Mapping values can be strings, numbers or null - labels: - com.example.description: "Accounting webapp" - com.example.number: 42 - com.example.empty-label: - # labels: - # - "com.example.description=Accounting webapp" - # - "com.example.number=42" - # - "com.example.empty-label" - - links: - - db - - db:database - - redis - - logging: - driver: syslog - options: - syslog-address: "tcp://192.168.0.42:123" - - mac_address: 02:42:ac:11:65:43 - - # network_mode: "bridge" - # network_mode: "host" - # network_mode: "none" - # Use the network mode of an arbitrary container from another service - # network_mode: "service:db" - # Use the network mode of another container, specified by name or id - # network_mode: "container:some-container" - network_mode: "container:0cfeab0f748b9a743dc3da582046357c6ef497631c1a016d28d2bf9b4f899f7b" - - networks: - some-network: - aliases: - - alias1 - - alias3 - other-network: - ipv4_address: 172.16.238.10 - ipv6_address: 2001:3984:3989::10 - other-other-network: - - pid: "host" - - ports: - - 3000 - - "3001-3005" - - "8000:8000" - - "9090-9091:8080-8081" - - "49100:22" - - "127.0.0.1:8001:8001" - - "127.0.0.1:5000-5010:5000-5010" - - privileged: true - - read_only: true - - restart: always - - secrets: - - secret1 - - source: secret2 - target: my_secret - uid: '103' - gid: '103' - mode: 0440 - - security_opt: - - label=level:s0:c100,c200 - - label=type:svirt_apache_t - - stdin_open: true - - stop_grace_period: 20s - - stop_signal: SIGUSR1 - - sysctls: - net.core.somaxconn: 1024 - net.ipv4.tcp_syncookies: 0 - - # String or list - # tmpfs: /run - tmpfs: - - /run - - /tmp - - tty: true - - ulimits: - # Single number or mapping with soft + hard limits - nproc: 65535 - nofile: - soft: 20000 - hard: 40000 - - user: someone - - volumes: - # Just specify a path and let the Engine create a volume - - /var/lib/mysql - # Specify an absolute path mapping - - /opt/data:/var/lib/mysql - # Path on the host, relative to the Compose file - - .:/code - - ./static:/var/www/html - # User-relative path - - ~/configs:/etc/configs:ro - # Named volume - - datavolume:/var/lib/mysql - - type: bind - source: ./opt - target: /opt - consistency: cached - - type: tmpfs - target: /opt - tmpfs: - size: 10000 - - working_dir: /code - x-bar: baz - x-foo: bar - -networks: - # Entries can be null, which specifies simply that a network - # called "{project name}_some-network" should be created and - # use the default driver - some-network: - - other-network: - driver: overlay - - driver_opts: - # Values can be strings or numbers - foo: "bar" - baz: 1 - - ipam: - driver: overlay - # driver_opts: - # # Values can be strings or numbers - # com.docker.network.enable_ipv6: "true" - # com.docker.network.numeric_value: 1 - config: - - subnet: 172.28.0.0/16 - ip_range: 172.28.5.0/24 - gateway: 172.28.5.254 - aux_addresses: - host1: 172.28.1.5 - host2: 172.28.1.6 - host3: 172.28.1.7 - - subnet: 2001:3984:3989::/64 - gateway: 2001:3984:3989::1 - - labels: - foo: bar - - external-network: - # Specifies that a pre-existing network called "external-network" - # can be referred to within this file as "external-network" - external: true - - other-external-network: - # Specifies that a pre-existing network called "my-cool-network" - # can be referred to within this file as "other-external-network" - external: - name: my-cool-network - x-bar: baz - x-foo: bar - -volumes: - # Entries can be null, which specifies simply that a volume - # called "{project name}_some-volume" should be created and - # use the default driver - some-volume: - - other-volume: - driver: flocker - - driver_opts: - # Values can be strings or numbers - foo: "bar" - baz: 1 - labels: - foo: bar - - another-volume: - name: "user_specified_name" - driver: vsphere - - driver_opts: - # Values can be strings or numbers - foo: "bar" - baz: 1 - - external-volume: - # Specifies that a pre-existing volume called "external-volume" - # can be referred to within this file as "external-volume" - external: true - - other-external-volume: - # Specifies that a pre-existing volume called "my-cool-volume" - # can be referred to within this file as "other-external-volume" - # This example uses the deprecated "volume.external.name" (replaced by "volume.name") - external: - name: my-cool-volume - - external-volume3: - # Specifies that a pre-existing volume called "this-is-volume3" - # can be referred to within this file as "external-volume3" - name: this-is-volume3 - external: true - x-bar: baz - x-foo: bar - -configs: - config1: - file: ./config_data - labels: - foo: bar - config2: - external: - name: my_config - config3: - external: true - config4: - name: foo - file: ~/config_data - x-bar: baz - x-foo: bar - -secrets: - secret1: - file: ./secret_data - labels: - foo: bar - secret2: - external: - name: my_secret - secret3: - external: true - secret4: - name: bar - environment: BAR - x-bar: baz - x-foo: bar - secret5: - file: /abs/secret_data -x-bar: baz -x-foo: bar -x-nested: - bar: baz - foo: bar diff --git a/vendor/github.com/compose-spec/compose-go/loader/include.go b/vendor/github.com/compose-spec/compose-go/loader/include.go deleted file mode 100644 index ea7841446..000000000 --- a/vendor/github.com/compose-spec/compose-go/loader/include.go +++ /dev/null @@ -1,148 +0,0 @@ -/* - Copyright 2020 The Compose Specification 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 loader - -import ( - "context" - "fmt" - "path/filepath" - - "github.com/compose-spec/compose-go/dotenv" - interp "github.com/compose-spec/compose-go/interpolation" - "github.com/compose-spec/compose-go/types" - "github.com/pkg/errors" -) - -// LoadIncludeConfig parse the require config from raw yaml -func LoadIncludeConfig(source []interface{}) ([]types.IncludeConfig, error) { - var requires []types.IncludeConfig - err := Transform(source, &requires) - return requires, err -} - -var transformIncludeConfig TransformerFunc = func(data interface{}) (interface{}, error) { - switch value := data.(type) { - case string: - return map[string]interface{}{"path": value}, nil - case map[string]interface{}: - return value, nil - default: - return data, errors.Errorf("invalid type %T for `include` configuration", value) - } -} - -func loadInclude(ctx context.Context, filename string, configDetails types.ConfigDetails, model *types.Config, options *Options, loaded []string) (*types.Config, map[string][]types.IncludeConfig, error) { - included := make(map[string][]types.IncludeConfig) - for _, r := range model.Include { - included[filename] = append(included[filename], r) - - for i, p := range r.Path { - for _, loader := range options.ResourceLoaders { - if loader.Accept(p) { - path, err := loader.Load(ctx, p) - if err != nil { - return nil, nil, err - } - p = path - break - } - } - r.Path[i] = absPath(configDetails.WorkingDir, p) - } - if r.ProjectDirectory == "" { - r.ProjectDirectory = filepath.Dir(r.Path[0]) - } - - loadOptions := options.clone() - loadOptions.SetProjectName(model.Name, true) - loadOptions.ResolvePaths = true - loadOptions.SkipNormalization = true - loadOptions.SkipConsistencyCheck = true - - envFromFile, err := dotenv.GetEnvFromFile(configDetails.Environment, r.ProjectDirectory, r.EnvFile) - if err != nil { - return nil, nil, err - } - - config := types.ConfigDetails{ - WorkingDir: r.ProjectDirectory, - ConfigFiles: types.ToConfigFiles(r.Path), - Environment: configDetails.Environment.Clone().Merge(envFromFile), - } - loadOptions.Interpolate = &interp.Options{ - Substitute: options.Interpolate.Substitute, - LookupValue: config.LookupEnv, - TypeCastMapping: options.Interpolate.TypeCastMapping, - } - imported, err := load(ctx, config, loadOptions, loaded) - if err != nil { - return nil, nil, err - } - for k, v := range imported.IncludeReferences { - included[k] = append(included[k], v...) - } - - err = importResources(model, imported, r.Path) - if err != nil { - return nil, nil, err - } - } - model.Include = nil - return model, included, nil -} - -// importResources import into model all resources defined by imported, and report error on conflict -func importResources(model *types.Config, imported *types.Project, path []string) error { - services := mapByName(model.Services) - for _, service := range imported.Services { - if _, ok := services[service.Name]; ok { - return fmt.Errorf("imported compose file %s defines conflicting service %s", path, service.Name) - } - model.Services = append(model.Services, service) - } - for _, service := range imported.DisabledServices { - if _, ok := services[service.Name]; ok { - return fmt.Errorf("imported compose file %s defines conflicting service %s", path, service.Name) - } - model.Services = append(model.Services, service) - } - for n, network := range imported.Networks { - if _, ok := model.Networks[n]; ok { - return fmt.Errorf("imported compose file %s defines conflicting network %s", path, n) - } - model.Networks[n] = network - } - for n, volume := range imported.Volumes { - if _, ok := model.Volumes[n]; ok { - return fmt.Errorf("imported compose file %s defines conflicting volume %s", path, n) - } - model.Volumes[n] = volume - } - for n, secret := range imported.Secrets { - if _, ok := model.Secrets[n]; ok { - return fmt.Errorf("imported compose file %s defines conflicting secret %s", path, n) - } - model.Secrets[n] = secret - } - for n, config := range imported.Configs { - if _, ok := model.Configs[n]; ok { - return fmt.Errorf("imported compose file %s defines conflicting config %s", path, n) - } - model.Configs[n] = config - } - return nil -} diff --git a/vendor/github.com/compose-spec/compose-go/loader/interpolate.go b/vendor/github.com/compose-spec/compose-go/loader/interpolate.go deleted file mode 100644 index aae6dc3a4..000000000 --- a/vendor/github.com/compose-spec/compose-go/loader/interpolate.go +++ /dev/null @@ -1,132 +0,0 @@ -/* - Copyright 2020 The Compose Specification 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 loader - -import ( - "strconv" - "strings" - - interp "github.com/compose-spec/compose-go/interpolation" - "github.com/compose-spec/compose-go/tree" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" -) - -var interpolateTypeCastMapping = map[tree.Path]interp.Cast{ - servicePath("configs", tree.PathMatchList, "mode"): toInt, - servicePath("cpu_count"): toInt64, - servicePath("cpu_percent"): toFloat, - servicePath("cpu_period"): toInt64, - servicePath("cpu_quota"): toInt64, - servicePath("cpu_rt_period"): toInt64, - servicePath("cpu_rt_runtime"): toInt64, - servicePath("cpus"): toFloat32, - servicePath("cpu_shares"): toInt64, - servicePath("init"): toBoolean, - servicePath("deploy", "replicas"): toInt, - servicePath("deploy", "update_config", "parallelism"): toInt, - servicePath("deploy", "update_config", "max_failure_ratio"): toFloat, - servicePath("deploy", "rollback_config", "parallelism"): toInt, - servicePath("deploy", "rollback_config", "max_failure_ratio"): toFloat, - servicePath("deploy", "restart_policy", "max_attempts"): toInt, - servicePath("deploy", "placement", "max_replicas_per_node"): toInt, - servicePath("healthcheck", "retries"): toInt, - servicePath("healthcheck", "disable"): toBoolean, - servicePath("mem_limit"): toUnitBytes, - servicePath("mem_reservation"): toUnitBytes, - servicePath("memswap_limit"): toUnitBytes, - servicePath("mem_swappiness"): toUnitBytes, - servicePath("oom_kill_disable"): toBoolean, - servicePath("oom_score_adj"): toInt64, - servicePath("pids_limit"): toInt64, - servicePath("ports", tree.PathMatchList, "target"): toInt, - servicePath("privileged"): toBoolean, - servicePath("read_only"): toBoolean, - servicePath("scale"): toInt, - servicePath("secrets", tree.PathMatchList, "mode"): toInt, - servicePath("shm_size"): toUnitBytes, - servicePath("stdin_open"): toBoolean, - servicePath("stop_grace_period"): toDuration, - servicePath("tty"): toBoolean, - servicePath("ulimits", tree.PathMatchAll): toInt, - servicePath("ulimits", tree.PathMatchAll, "hard"): toInt, - servicePath("ulimits", tree.PathMatchAll, "soft"): toInt, - servicePath("volumes", tree.PathMatchList, "read_only"): toBoolean, - servicePath("volumes", tree.PathMatchList, "volume", "nocopy"): toBoolean, - servicePath("volumes", tree.PathMatchList, "tmpfs", "size"): toUnitBytes, - iPath("networks", tree.PathMatchAll, "external"): toBoolean, - iPath("networks", tree.PathMatchAll, "internal"): toBoolean, - iPath("networks", tree.PathMatchAll, "attachable"): toBoolean, - iPath("networks", tree.PathMatchAll, "enable_ipv6"): toBoolean, - iPath("volumes", tree.PathMatchAll, "external"): toBoolean, - iPath("secrets", tree.PathMatchAll, "external"): toBoolean, - iPath("configs", tree.PathMatchAll, "external"): toBoolean, -} - -func iPath(parts ...string) tree.Path { - return tree.NewPath(parts...) -} - -func servicePath(parts ...string) tree.Path { - return iPath(append([]string{"services", tree.PathMatchAll}, parts...)...) -} - -func toInt(value string) (interface{}, error) { - return strconv.Atoi(value) -} - -func toInt64(value string) (interface{}, error) { - return strconv.ParseInt(value, 10, 64) -} - -func toUnitBytes(value string) (interface{}, error) { - return transformSize(value) -} - -func toDuration(value string) (interface{}, error) { - return transformStringToDuration(value) -} - -func toFloat(value string) (interface{}, error) { - return strconv.ParseFloat(value, 64) -} - -func toFloat32(value string) (interface{}, error) { - f, err := strconv.ParseFloat(value, 32) - if err != nil { - return nil, err - } - return float32(f), nil -} - -// should match http://yaml.org/type/bool.html -func toBoolean(value string) (interface{}, error) { - switch strings.ToLower(value) { - case "true": - return true, nil - case "false": - return false, nil - case "y", "yes", "on": - logrus.Warnf("%q for boolean is not supported by YAML 1.2, please use `true`", value) - return true, nil - case "n", "no", "off": - logrus.Warnf("%q for boolean is not supported by YAML 1.2, please use `false`", value) - return false, nil - default: - return nil, errors.Errorf("invalid boolean: %s", value) - } -} diff --git a/vendor/github.com/compose-spec/compose-go/loader/loader.go b/vendor/github.com/compose-spec/compose-go/loader/loader.go deleted file mode 100644 index 205dcd673..000000000 --- a/vendor/github.com/compose-spec/compose-go/loader/loader.go +++ /dev/null @@ -1,1369 +0,0 @@ -/* - Copyright 2020 The Compose Specification 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 loader - -import ( - "bytes" - "context" - "fmt" - "io" - "os" - paths "path" - "path/filepath" - "reflect" - "regexp" - "strconv" - "strings" - "time" - - "github.com/compose-spec/compose-go/consts" - interp "github.com/compose-spec/compose-go/interpolation" - "github.com/compose-spec/compose-go/schema" - "github.com/compose-spec/compose-go/template" - "github.com/compose-spec/compose-go/types" - "github.com/docker/go-units" - "github.com/mattn/go-shellwords" - "github.com/mitchellh/mapstructure" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" - "gopkg.in/yaml.v3" -) - -// Options supported by Load -type Options struct { - // Skip schema validation - SkipValidation bool - // Skip interpolation - SkipInterpolation bool - // Skip normalization - SkipNormalization bool - // Resolve paths - ResolvePaths bool - // Convert Windows paths - ConvertWindowsPaths bool - // Skip consistency check - SkipConsistencyCheck bool - // Skip extends - SkipExtends bool - // SkipInclude will ignore `include` and only load model from file(s) set by ConfigDetails - SkipInclude bool - // Interpolation options - Interpolate *interp.Options - // Discard 'env_file' entries after resolving to 'environment' section - discardEnvFiles bool - // Set project projectName - projectName string - // Indicates when the projectName was imperatively set or guessed from path - projectNameImperativelySet bool - // Profiles set profiles to enable - Profiles []string - // ResourceLoaders manages support for remote resources - ResourceLoaders []ResourceLoader -} - -// ResourceLoader is a plugable remote resource resolver -type ResourceLoader interface { - // Accept returns `true` is the resource reference matches ResourceLoader supported protocol(s) - Accept(path string) bool - // Load returns the path to a local copy of remote resource identified by `path`. - Load(ctx context.Context, path string) (string, error) -} - -func (o *Options) clone() *Options { - return &Options{ - SkipValidation: o.SkipValidation, - SkipInterpolation: o.SkipInterpolation, - SkipNormalization: o.SkipNormalization, - ResolvePaths: o.ResolvePaths, - ConvertWindowsPaths: o.ConvertWindowsPaths, - SkipConsistencyCheck: o.SkipConsistencyCheck, - SkipExtends: o.SkipExtends, - SkipInclude: o.SkipInclude, - Interpolate: o.Interpolate, - discardEnvFiles: o.discardEnvFiles, - projectName: o.projectName, - projectNameImperativelySet: o.projectNameImperativelySet, - Profiles: o.Profiles, - ResourceLoaders: o.ResourceLoaders, - } -} - -func (o *Options) SetProjectName(name string, imperativelySet bool) { - o.projectName = name - o.projectNameImperativelySet = imperativelySet -} - -func (o Options) GetProjectName() (string, bool) { - return o.projectName, o.projectNameImperativelySet -} - -// serviceRef identifies a reference to a service. It's used to detect cyclic -// references in "extends". -type serviceRef struct { - filename string - service string -} - -type cycleTracker struct { - loaded []serviceRef -} - -func (ct *cycleTracker) Add(filename, service string) error { - toAdd := serviceRef{filename: filename, service: service} - for _, loaded := range ct.loaded { - if toAdd == loaded { - // Create an error message of the form: - // Circular reference: - // service-a in docker-compose.yml - // extends service-b in docker-compose.yml - // extends service-a in docker-compose.yml - errLines := []string{ - "Circular reference:", - fmt.Sprintf(" %s in %s", ct.loaded[0].service, ct.loaded[0].filename), - } - for _, service := range append(ct.loaded[1:], toAdd) { - errLines = append(errLines, fmt.Sprintf(" extends %s in %s", service.service, service.filename)) - } - - return errors.New(strings.Join(errLines, "\n")) - } - } - - ct.loaded = append(ct.loaded, toAdd) - return nil -} - -// WithDiscardEnvFiles sets the Options to discard the `env_file` section after resolving to -// the `environment` section -func WithDiscardEnvFiles(opts *Options) { - opts.discardEnvFiles = true -} - -// WithSkipValidation sets the Options to skip validation when loading sections -func WithSkipValidation(opts *Options) { - opts.SkipValidation = true -} - -// WithProfiles sets profiles to be activated -func WithProfiles(profiles []string) func(*Options) { - return func(opts *Options) { - opts.Profiles = profiles - } -} - -// ParseYAML reads the bytes from a file, parses the bytes into a mapping -// structure, and returns it. -func ParseYAML(source []byte) (map[string]interface{}, error) { - r := bytes.NewReader(source) - decoder := yaml.NewDecoder(r) - m, _, err := parseYAML(decoder) - return m, err -} - -// PostProcessor is used to tweak compose model based on metadata extracted during yaml Unmarshal phase -// that hardly can be implemented using go-yaml and mapstructure -type PostProcessor interface { - yaml.Unmarshaler - - // Apply changes to compose model based on recorder metadata - Apply(config *types.Config) error -} - -func parseYAML(decoder *yaml.Decoder) (map[string]interface{}, PostProcessor, error) { - var cfg interface{} - processor := ResetProcessor{target: &cfg} - - if err := decoder.Decode(&processor); err != nil { - return nil, nil, err - } - stringMap, ok := cfg.(map[string]interface{}) - if ok { - converted, err := convertToStringKeysRecursive(stringMap, "") - if err != nil { - return nil, nil, err - } - return converted.(map[string]interface{}), &processor, nil - } - cfgMap, ok := cfg.(map[interface{}]interface{}) - if !ok { - return nil, nil, errors.Errorf("Top-level object must be a mapping") - } - converted, err := convertToStringKeysRecursive(cfgMap, "") - if err != nil { - return nil, nil, err - } - return converted.(map[string]interface{}), &processor, nil -} - -// Load reads a ConfigDetails and returns a fully loaded configuration. -// Deprecated: use LoadWithContext. -func Load(configDetails types.ConfigDetails, options ...func(*Options)) (*types.Project, error) { - return LoadWithContext(context.Background(), configDetails, options...) -} - -// LoadWithContext reads a ConfigDetails and returns a fully loaded configuration -func LoadWithContext(ctx context.Context, configDetails types.ConfigDetails, options ...func(*Options)) (*types.Project, error) { - if len(configDetails.ConfigFiles) < 1 { - return nil, errors.Errorf("No files specified") - } - - opts := &Options{ - Interpolate: &interp.Options{ - Substitute: template.Substitute, - LookupValue: configDetails.LookupEnv, - TypeCastMapping: interpolateTypeCastMapping, - }, - ResolvePaths: true, - } - - for _, op := range options { - op(opts) - } - - projectName, err := projectName(configDetails, opts) - if err != nil { - return nil, err - } - opts.projectName = projectName - return load(ctx, configDetails, opts, nil) -} - -func load(ctx context.Context, configDetails types.ConfigDetails, opts *Options, loaded []string) (*types.Project, error) { - var model *types.Config - - mainFile := configDetails.ConfigFiles[0].Filename - for _, f := range loaded { - if f == mainFile { - loaded = append(loaded, mainFile) - return nil, errors.Errorf("include cycle detected:\n%s\n include %s", loaded[0], strings.Join(loaded[1:], "\n include ")) - } - } - loaded = append(loaded, mainFile) - - includeRefs := make(map[string][]types.IncludeConfig) - first := true - for _, file := range configDetails.ConfigFiles { - var postProcessor PostProcessor - configDict := file.Config - - processYaml := func() error { - if !opts.SkipValidation { - if err := schema.Validate(configDict); err != nil { - return fmt.Errorf("validating %s: %w", file.Filename, err) - } - } - - configDict = groupXFieldsIntoExtensions(configDict) - - cfg, err := loadSections(ctx, file.Filename, configDict, configDetails, opts) - if err != nil { - return err - } - - if !opts.SkipInclude { - var included map[string][]types.IncludeConfig - cfg, included, err = loadInclude(ctx, file.Filename, configDetails, cfg, opts, loaded) - if err != nil { - return err - } - for k, v := range included { - includeRefs[k] = append(includeRefs[k], v...) - } - } - - if first { - first = false - model = cfg - return nil - } - merged, err := merge([]*types.Config{model, cfg}) - if err != nil { - return err - } - if postProcessor != nil { - err = postProcessor.Apply(merged) - if err != nil { - return err - } - } - model = merged - return nil - } - - if configDict == nil { - if len(file.Content) == 0 { - content, err := os.ReadFile(file.Filename) - if err != nil { - return nil, err - } - file.Content = content - } - - r := bytes.NewReader(file.Content) - decoder := yaml.NewDecoder(r) - for { - dict, p, err := parseConfig(decoder, opts) - if err != nil { - if err != io.EOF { - return nil, fmt.Errorf("parsing %s: %w", file.Filename, err) - } - break - } - configDict = dict - postProcessor = p - - if err := processYaml(); err != nil { - return nil, err - } - } - } else { - if err := processYaml(); err != nil { - return nil, err - } - } - } - - project := &types.Project{ - Name: opts.projectName, - WorkingDir: configDetails.WorkingDir, - Services: model.Services, - Networks: model.Networks, - Volumes: model.Volumes, - Secrets: model.Secrets, - Configs: model.Configs, - Environment: configDetails.Environment, - Extensions: model.Extensions, - } - - if len(includeRefs) != 0 { - project.IncludeReferences = includeRefs - } - - if !opts.SkipNormalization { - err := Normalize(project) - if err != nil { - return nil, err - } - } - - if opts.ResolvePaths { - err := ResolveRelativePaths(project) - if err != nil { - return nil, err - } - } - - if opts.ConvertWindowsPaths { - for i, service := range project.Services { - for j, volume := range service.Volumes { - service.Volumes[j] = convertVolumePath(volume) - } - project.Services[i] = service - } - } - - if !opts.SkipConsistencyCheck { - err := checkConsistency(project) - if err != nil { - return nil, err - } - } - - project.ApplyProfiles(opts.Profiles) - - err := project.ResolveServicesEnvironment(opts.discardEnvFiles) - - return project, err -} - -func InvalidProjectNameErr(v string) error { - return fmt.Errorf( - "invalid project name %q: must consist only of lowercase alphanumeric characters, hyphens, and underscores as well as start with a letter or number", - v, - ) -} - -// projectName determines the canonical name to use for the project considering -// the loader Options as well as `name` fields in Compose YAML fields (which -// also support interpolation). -// -// TODO(milas): restructure loading so that we don't need to re-parse the YAML -// here, as it's both wasteful and makes this code error-prone. -func projectName(details types.ConfigDetails, opts *Options) (string, error) { - projectName, projectNameImperativelySet := opts.GetProjectName() - - // if user did NOT provide a name explicitly, then see if one is defined - // in any of the config files - if !projectNameImperativelySet { - var pjNameFromConfigFile string - for _, configFile := range details.ConfigFiles { - yml, err := ParseYAML(configFile.Content) - if err != nil { - // HACK: the way that loading is currently structured, this is - // a duplicative parse just for the `name`. if it fails, we - // give up but don't return the error, knowing that it'll get - // caught downstream for us - return "", nil - } - if val, ok := yml["name"]; ok && val != "" { - sVal, ok := val.(string) - if !ok { - // HACK: see above - this is a temporary parsed version - // that hasn't been schema-validated, but we don't want - // to be the ones to actually report that, so give up, - // knowing that it'll get caught downstream for us - return "", nil - } - pjNameFromConfigFile = sVal - } - } - if !opts.SkipInterpolation { - interpolated, err := interp.Interpolate( - map[string]interface{}{"name": pjNameFromConfigFile}, - *opts.Interpolate, - ) - if err != nil { - return "", err - } - pjNameFromConfigFile = interpolated["name"].(string) - } - pjNameFromConfigFile = NormalizeProjectName(pjNameFromConfigFile) - if pjNameFromConfigFile != "" { - projectName = pjNameFromConfigFile - } - } - - if projectName == "" { - return "", errors.New("project name must not be empty") - } - - if NormalizeProjectName(projectName) != projectName { - return "", InvalidProjectNameErr(projectName) - } - - // TODO(milas): this should probably ALWAYS set (overriding any existing) - if _, ok := details.Environment[consts.ComposeProjectName]; !ok && projectName != "" { - details.Environment[consts.ComposeProjectName] = projectName - } - return projectName, nil -} - -func NormalizeProjectName(s string) string { - r := regexp.MustCompile("[a-z0-9_-]") - s = strings.ToLower(s) - s = strings.Join(r.FindAllString(s, -1), "") - return strings.TrimLeft(s, "_-") -} - -func parseConfig(decoder *yaml.Decoder, opts *Options) (map[string]interface{}, PostProcessor, error) { - yml, postProcessor, err := parseYAML(decoder) - if err != nil { - return nil, nil, err - } - if !opts.SkipInterpolation { - interpolated, err := interp.Interpolate(yml, *opts.Interpolate) - return interpolated, postProcessor, err - } - return yml, postProcessor, err -} - -const extensions = "#extensions" // Using # prefix, we prevent risk to conflict with an actual yaml key - -func groupXFieldsIntoExtensions(dict map[string]interface{}) map[string]interface{} { - extras := map[string]interface{}{} - for key, value := range dict { - if strings.HasPrefix(key, "x-") { - extras[key] = value - delete(dict, key) - } - if d, ok := value.(map[string]interface{}); ok { - dict[key] = groupXFieldsIntoExtensions(d) - } - } - if len(extras) > 0 { - dict[extensions] = extras - } - return dict -} - -func loadSections(ctx context.Context, filename string, config map[string]interface{}, configDetails types.ConfigDetails, opts *Options) (*types.Config, error) { - var err error - cfg := types.Config{ - Filename: filename, - } - name := "" - if n, ok := config["name"]; ok { - name, ok = n.(string) - if !ok { - return nil, errors.New("project name must be a string") - } - } - cfg.Name = name - cfg.Services, err = LoadServices(ctx, filename, getSection(config, "services"), configDetails.WorkingDir, configDetails.LookupEnv, opts) - if err != nil { - return nil, err - } - cfg.Networks, err = LoadNetworks(getSection(config, "networks")) - if err != nil { - return nil, err - } - cfg.Volumes, err = LoadVolumes(getSection(config, "volumes")) - if err != nil { - return nil, err - } - cfg.Secrets, err = LoadSecrets(getSection(config, "secrets")) - if err != nil { - return nil, err - } - cfg.Configs, err = LoadConfigObjs(getSection(config, "configs")) - if err != nil { - return nil, err - } - cfg.Include, err = LoadIncludeConfig(getSequence(config, "include")) - if err != nil { - return nil, err - } - extensions := getSection(config, extensions) - if len(extensions) > 0 { - cfg.Extensions = extensions - } - return &cfg, nil -} - -func getSection(config map[string]interface{}, key string) map[string]interface{} { - section, ok := config[key] - if !ok { - return make(map[string]interface{}) - } - return section.(map[string]interface{}) -} - -func getSequence(config map[string]interface{}, key string) []interface{} { - section, ok := config[key] - if !ok { - return make([]interface{}, 0) - } - return section.([]interface{}) -} - -// ForbiddenPropertiesError is returned when there are properties in the Compose -// file that are forbidden. -type ForbiddenPropertiesError struct { - Properties map[string]string -} - -func (e *ForbiddenPropertiesError) Error() string { - return "Configuration contains forbidden properties" -} - -// Transform converts the source into the target struct with compose types transformer -// and the specified transformers if any. -func Transform(source interface{}, target interface{}, additionalTransformers ...Transformer) error { - data := mapstructure.Metadata{} - config := &mapstructure.DecoderConfig{ - DecodeHook: mapstructure.ComposeDecodeHookFunc( - createTransformHook(additionalTransformers...), - mapstructure.StringToTimeDurationHookFunc()), - Result: target, - TagName: "yaml", - Metadata: &data, - } - decoder, err := mapstructure.NewDecoder(config) - if err != nil { - return err - } - return decoder.Decode(source) -} - -// TransformerFunc defines a function to perform the actual transformation -type TransformerFunc func(interface{}) (interface{}, error) - -// Transformer defines a map to type transformer -type Transformer struct { - TypeOf reflect.Type - Func TransformerFunc -} - -func createTransformHook(additionalTransformers ...Transformer) mapstructure.DecodeHookFuncType { - transforms := map[reflect.Type]func(interface{}) (interface{}, error){ - reflect.TypeOf(types.External{}): transformExternal, - reflect.TypeOf(types.HealthCheckTest{}): transformHealthCheckTest, - reflect.TypeOf(types.ShellCommand{}): transformShellCommand, - reflect.TypeOf(types.StringList{}): transformStringList, - reflect.TypeOf(map[string]string{}): transformMapStringString, - reflect.TypeOf(types.UlimitsConfig{}): transformUlimits, - reflect.TypeOf(types.UnitBytes(0)): transformSize, - reflect.TypeOf([]types.ServicePortConfig{}): transformServicePort, - reflect.TypeOf(types.ServiceSecretConfig{}): transformFileReferenceConfig, - reflect.TypeOf(types.ServiceConfigObjConfig{}): transformFileReferenceConfig, - reflect.TypeOf(types.StringOrNumberList{}): transformStringOrNumberList, - reflect.TypeOf(map[string]*types.ServiceNetworkConfig{}): transformServiceNetworkMap, - reflect.TypeOf(types.Mapping{}): transformMappingOrListFunc("=", false), - reflect.TypeOf(types.MappingWithEquals{}): transformMappingOrListFunc("=", true), - reflect.TypeOf(types.Labels{}): transformMappingOrListFunc("=", false), - reflect.TypeOf(types.MappingWithColon{}): transformMappingOrListFunc(":", false), - reflect.TypeOf(types.HostsList{}): transformMappingOrListFunc(":", false), - reflect.TypeOf(types.ServiceVolumeConfig{}): transformServiceVolumeConfig, - reflect.TypeOf(types.BuildConfig{}): transformBuildConfig, - reflect.TypeOf(types.Duration(0)): transformStringToDuration, - reflect.TypeOf(types.DependsOnConfig{}): transformDependsOnConfig, - reflect.TypeOf(types.ExtendsConfig{}): transformExtendsConfig, - reflect.TypeOf(types.DeviceRequest{}): transformServiceDeviceRequest, - reflect.TypeOf(types.SSHConfig{}): transformSSHConfig, - reflect.TypeOf(types.IncludeConfig{}): transformIncludeConfig, - } - - for _, transformer := range additionalTransformers { - transforms[transformer.TypeOf] = transformer.Func - } - - return func(_ reflect.Type, target reflect.Type, data interface{}) (interface{}, error) { - transform, ok := transforms[target] - if !ok { - return data, nil - } - return transform(data) - } -} - -// keys need to be converted to strings for jsonschema -func convertToStringKeysRecursive(value interface{}, keyPrefix string) (interface{}, error) { - if mapping, ok := value.(map[string]interface{}); ok { - for key, entry := range mapping { - var newKeyPrefix string - if keyPrefix == "" { - newKeyPrefix = key - } else { - newKeyPrefix = fmt.Sprintf("%s.%s", keyPrefix, key) - } - convertedEntry, err := convertToStringKeysRecursive(entry, newKeyPrefix) - if err != nil { - return nil, err - } - mapping[key] = convertedEntry - } - return mapping, nil - } - if mapping, ok := value.(map[interface{}]interface{}); ok { - dict := make(map[string]interface{}) - for key, entry := range mapping { - str, ok := key.(string) - if !ok { - return nil, formatInvalidKeyError(keyPrefix, key) - } - var newKeyPrefix string - if keyPrefix == "" { - newKeyPrefix = str - } else { - newKeyPrefix = fmt.Sprintf("%s.%s", keyPrefix, str) - } - convertedEntry, err := convertToStringKeysRecursive(entry, newKeyPrefix) - if err != nil { - return nil, err - } - dict[str] = convertedEntry - } - return dict, nil - } - if list, ok := value.([]interface{}); ok { - var convertedList []interface{} - for index, entry := range list { - newKeyPrefix := fmt.Sprintf("%s[%d]", keyPrefix, index) - convertedEntry, err := convertToStringKeysRecursive(entry, newKeyPrefix) - if err != nil { - return nil, err - } - convertedList = append(convertedList, convertedEntry) - } - return convertedList, nil - } - return value, nil -} - -func formatInvalidKeyError(keyPrefix string, key interface{}) error { - var location string - if keyPrefix == "" { - location = "at top level" - } else { - location = fmt.Sprintf("in %s", keyPrefix) - } - return errors.Errorf("Non-string key %s: %#v", location, key) -} - -// LoadServices produces a ServiceConfig map from a compose file Dict -// the servicesDict is not validated if directly used. Use Load() to enable validation -func LoadServices(ctx context.Context, filename string, servicesDict map[string]interface{}, workingDir string, lookupEnv template.Mapping, opts *Options) ([]types.ServiceConfig, error) { - var services []types.ServiceConfig - - x, ok := servicesDict[extensions] - if ok { - // as a top-level attribute, "services" doesn't support extensions, and a service can be named `x-foo` - for k, v := range x.(map[string]interface{}) { - servicesDict[k] = v - } - delete(servicesDict, extensions) - } - - for name := range servicesDict { - serviceConfig, err := loadServiceWithExtends(ctx, filename, name, servicesDict, workingDir, lookupEnv, opts, &cycleTracker{}) - if err != nil { - return nil, err - } - - services = append(services, *serviceConfig) - } - - return services, nil -} - -func loadServiceWithExtends(ctx context.Context, filename, name string, servicesDict map[string]interface{}, workingDir string, lookupEnv template.Mapping, opts *Options, ct *cycleTracker) (*types.ServiceConfig, error) { - if err := ct.Add(filename, name); err != nil { - return nil, err - } - - target, ok := servicesDict[name] - if !ok { - return nil, fmt.Errorf("cannot extend service %q in %s: service not found", name, filename) - } - - if target == nil { - target = map[string]interface{}{} - } - - serviceConfig, err := LoadService(name, target.(map[string]interface{})) - if err != nil { - return nil, err - } - - if serviceConfig.Extends != nil && !opts.SkipExtends { - baseServiceName := serviceConfig.Extends.Service - var baseService *types.ServiceConfig - file := serviceConfig.Extends.File - if file == "" { - baseService, err = loadServiceWithExtends(ctx, filename, baseServiceName, servicesDict, workingDir, lookupEnv, opts, ct) - if err != nil { - return nil, err - } - } else { - for _, loader := range opts.ResourceLoaders { - if loader.Accept(file) { - path, err := loader.Load(ctx, file) - if err != nil { - return nil, err - } - file = path - break - } - } - // Resolve the path to the imported file, and load it. - baseFilePath := absPath(workingDir, file) - - b, err := os.ReadFile(baseFilePath) - if err != nil { - return nil, err - } - - r := bytes.NewReader(b) - decoder := yaml.NewDecoder(r) - - baseFile, _, err := parseConfig(decoder, opts) - if err != nil { - return nil, err - } - - baseFileServices := getSection(baseFile, "services") - baseService, err = loadServiceWithExtends(ctx, baseFilePath, baseServiceName, baseFileServices, filepath.Dir(baseFilePath), lookupEnv, opts, ct) - if err != nil { - return nil, err - } - - // Make paths relative to the importing Compose file. Note that we - // make the paths relative to `file` rather than `baseFilePath` so - // that the resulting paths won't be absolute if `file` isn't an - // absolute path. - - baseFileParent := filepath.Dir(file) - ResolveServiceRelativePaths(baseFileParent, baseService) - } - - serviceConfig, err = _merge(baseService, serviceConfig) - if err != nil { - return nil, err - } - serviceConfig.Extends = nil - } - - return serviceConfig, nil -} - -// LoadService produces a single ServiceConfig from a compose file Dict -// the serviceDict is not validated if directly used. Use Load() to enable validation -func LoadService(name string, serviceDict map[string]interface{}) (*types.ServiceConfig, error) { - serviceConfig := &types.ServiceConfig{ - Scale: 1, - } - if err := Transform(serviceDict, serviceConfig); err != nil { - return nil, err - } - serviceConfig.Name = name - - for i, volume := range serviceConfig.Volumes { - if volume.Type != types.VolumeTypeBind { - continue - } - if volume.Source == "" { - return nil, errors.New(`invalid mount config for type "bind": field Source must not be empty`) - } - - serviceConfig.Volumes[i] = volume - } - - return serviceConfig, nil -} - -// Windows paths, c:\\my\\path\\shiny, need to be changed to be compatible with -// the Engine. Volume paths are expected to be linux style /c/my/path/shiny/ -func convertVolumePath(volume types.ServiceVolumeConfig) types.ServiceVolumeConfig { - volumeName := strings.ToLower(filepath.VolumeName(volume.Source)) - if len(volumeName) != 2 { - return volume - } - - convertedSource := fmt.Sprintf("/%c%s", volumeName[0], volume.Source[len(volumeName):]) - convertedSource = strings.ReplaceAll(convertedSource, "\\", "/") - - volume.Source = convertedSource - return volume -} - -func resolveMaybeUnixPath(workingDir string, path string) string { - filePath := expandUser(path) - // Check if source is an absolute path (either Unix or Windows), to - // handle a Windows client with a Unix daemon or vice-versa. - // - // Note that this is not required for Docker for Windows when specifying - // a local Windows path, because Docker for Windows translates the Windows - // path into a valid path within the VM. - if !paths.IsAbs(filePath) && !isAbs(filePath) { - filePath = absPath(workingDir, filePath) - } - return filePath -} - -// TODO: make this more robust -func expandUser(path string) string { - if strings.HasPrefix(path, "~") { - home, err := os.UserHomeDir() - if err != nil { - logrus.Warn("cannot expand '~', because the environment lacks HOME") - return path - } - return filepath.Join(home, path[1:]) - } - return path -} - -func transformUlimits(data interface{}) (interface{}, error) { - switch value := data.(type) { - case int: - return types.UlimitsConfig{Single: value}, nil - case map[string]interface{}: - ulimit := types.UlimitsConfig{} - if v, ok := value["soft"]; ok { - ulimit.Soft = v.(int) - } - if v, ok := value["hard"]; ok { - ulimit.Hard = v.(int) - } - return ulimit, nil - default: - return data, errors.Errorf("invalid type %T for ulimits", value) - } -} - -// LoadNetworks produces a NetworkConfig map from a compose file Dict -// the source Dict is not validated if directly used. Use Load() to enable validation -func LoadNetworks(source map[string]interface{}) (map[string]types.NetworkConfig, error) { - networks := make(map[string]types.NetworkConfig) - err := Transform(source, &networks) - if err != nil { - return networks, err - } - for name, network := range networks { - if !network.External.External { - continue - } - switch { - case network.External.Name != "": - if network.Name != "" { - return nil, errors.Errorf("network %s: network.external.name and network.name conflict; only use network.name", name) - } - logrus.Warnf("network %s: network.external.name is deprecated. Please set network.name with external: true", name) - network.Name = network.External.Name - network.External.Name = "" - case network.Name == "": - network.Name = name - } - networks[name] = network - } - return networks, nil -} - -func externalVolumeError(volume, key string) error { - return errors.Errorf( - "conflicting parameters \"external\" and %q specified for volume %q", - key, volume) -} - -// LoadVolumes produces a VolumeConfig map from a compose file Dict -// the source Dict is not validated if directly used. Use Load() to enable validation -func LoadVolumes(source map[string]interface{}) (map[string]types.VolumeConfig, error) { - volumes := make(map[string]types.VolumeConfig) - if err := Transform(source, &volumes); err != nil { - return volumes, err - } - - for name, volume := range volumes { - if !volume.External.External { - continue - } - switch { - case volume.Driver != "": - return nil, externalVolumeError(name, "driver") - case len(volume.DriverOpts) > 0: - return nil, externalVolumeError(name, "driver_opts") - case len(volume.Labels) > 0: - return nil, externalVolumeError(name, "labels") - case volume.External.Name != "": - if volume.Name != "" { - return nil, errors.Errorf("volume %s: volume.external.name and volume.name conflict; only use volume.name", name) - } - logrus.Warnf("volume %s: volume.external.name is deprecated in favor of volume.name", name) - volume.Name = volume.External.Name - volume.External.Name = "" - case volume.Name == "": - volume.Name = name - } - volumes[name] = volume - } - return volumes, nil -} - -// LoadSecrets produces a SecretConfig map from a compose file Dict -// the source Dict is not validated if directly used. Use Load() to enable validation -func LoadSecrets(source map[string]interface{}) (map[string]types.SecretConfig, error) { - secrets := make(map[string]types.SecretConfig) - if err := Transform(source, &secrets); err != nil { - return secrets, err - } - for name, secret := range secrets { - obj, err := loadFileObjectConfig(name, "secret", types.FileObjectConfig(secret)) - if err != nil { - return nil, err - } - secrets[name] = types.SecretConfig(obj) - } - return secrets, nil -} - -// LoadConfigObjs produces a ConfigObjConfig map from a compose file Dict -// the source Dict is not validated if directly used. Use Load() to enable validation -func LoadConfigObjs(source map[string]interface{}) (map[string]types.ConfigObjConfig, error) { - configs := make(map[string]types.ConfigObjConfig) - if err := Transform(source, &configs); err != nil { - return configs, err - } - for name, config := range configs { - obj, err := loadFileObjectConfig(name, "config", types.FileObjectConfig(config)) - if err != nil { - return nil, err - } - configs[name] = types.ConfigObjConfig(obj) - } - return configs, nil -} - -func loadFileObjectConfig(name string, objType string, obj types.FileObjectConfig) (types.FileObjectConfig, error) { - // if "external: true" - switch { - case obj.External.External: - // handle deprecated external.name - if obj.External.Name != "" { - if obj.Name != "" { - return obj, errors.Errorf("%[1]s %[2]s: %[1]s.external.name and %[1]s.name conflict; only use %[1]s.name", objType, name) - } - logrus.Warnf("%[1]s %[2]s: %[1]s.external.name is deprecated in favor of %[1]s.name", objType, name) - obj.Name = obj.External.Name - obj.External.Name = "" - } else if obj.Name == "" { - obj.Name = name - } - // if not "external: true" - case obj.Driver != "": - if obj.File != "" { - return obj, errors.Errorf("%[1]s %[2]s: %[1]s.driver and %[1]s.file conflict; only use %[1]s.driver", objType, name) - } - } - - return obj, nil -} - -var transformMapStringString TransformerFunc = func(data interface{}) (interface{}, error) { - switch value := data.(type) { - case map[string]interface{}: - return toMapStringString(value, false), nil - case map[string]string: - return value, nil - default: - return data, errors.Errorf("invalid type %T for map[string]string", value) - } -} - -var transformExternal TransformerFunc = func(data interface{}) (interface{}, error) { - switch value := data.(type) { - case bool: - return map[string]interface{}{"external": value}, nil - case map[string]interface{}: - return map[string]interface{}{"external": true, "name": value["name"]}, nil - default: - return data, errors.Errorf("invalid type %T for external", value) - } -} - -var transformServicePort TransformerFunc = func(data interface{}) (interface{}, error) { - switch entries := data.(type) { - case []interface{}: - // We process the list instead of individual items here. - // The reason is that one entry might be mapped to multiple ServicePortConfig. - // Therefore we take an input of a list and return an output of a list. - var ports []interface{} - for _, entry := range entries { - switch value := entry.(type) { - case int: - parsed, err := types.ParsePortConfig(fmt.Sprint(value)) - if err != nil { - return data, err - } - for _, v := range parsed { - ports = append(ports, v) - } - case string: - parsed, err := types.ParsePortConfig(value) - if err != nil { - return data, err - } - for _, v := range parsed { - ports = append(ports, v) - } - case map[string]interface{}: - published := value["published"] - if v, ok := published.(int); ok { - value["published"] = strconv.Itoa(v) - } - ports = append(ports, groupXFieldsIntoExtensions(value)) - default: - return data, errors.Errorf("invalid type %T for port", value) - } - } - return ports, nil - default: - return data, errors.Errorf("invalid type %T for port", entries) - } -} - -var transformServiceDeviceRequest TransformerFunc = func(data interface{}) (interface{}, error) { - switch value := data.(type) { - case map[string]interface{}: - count, ok := value["count"] - if ok { - switch val := count.(type) { - case int: - return value, nil - case string: - if strings.ToLower(val) == "all" { - value["count"] = -1 - return value, nil - } - i, err := strconv.ParseInt(val, 10, 64) - if err == nil { - value["count"] = i - return value, nil - } - return data, errors.Errorf("invalid string value for 'count' (the only value allowed is 'all' or a number)") - default: - return data, errors.Errorf("invalid type %T for device count", val) - } - } - return data, nil - default: - return data, errors.Errorf("invalid type %T for resource reservation", value) - } -} - -var transformFileReferenceConfig TransformerFunc = func(data interface{}) (interface{}, error) { - switch value := data.(type) { - case string: - return map[string]interface{}{"source": value}, nil - case map[string]interface{}: - if target, ok := value["target"]; ok { - value["target"] = cleanTarget(target.(string)) - } - return groupXFieldsIntoExtensions(value), nil - default: - return data, errors.Errorf("invalid type %T for secret", value) - } -} - -func cleanTarget(target string) string { - if target == "" { - return "" - } - return paths.Clean(target) -} - -var transformBuildConfig TransformerFunc = func(data interface{}) (interface{}, error) { - switch value := data.(type) { - case string: - return map[string]interface{}{"context": value}, nil - case map[string]interface{}: - return groupXFieldsIntoExtensions(data.(map[string]interface{})), nil - default: - return data, errors.Errorf("invalid type %T for service build", value) - } -} - -var transformDependsOnConfig TransformerFunc = func(data interface{}) (interface{}, error) { - switch value := data.(type) { - case []interface{}: - transformed := map[string]interface{}{} - for _, serviceIntf := range value { - service, ok := serviceIntf.(string) - if !ok { - return data, errors.Errorf("invalid type %T for service depends_on element, expected string", value) - } - transformed[service] = map[string]interface{}{"condition": types.ServiceConditionStarted, "required": true} - } - return transformed, nil - case map[string]interface{}: - transformed := map[string]interface{}{} - for service, val := range value { - dependsConfigIntf, ok := val.(map[string]interface{}) - if !ok { - return data, errors.Errorf("invalid type %T for service depends_on element", value) - } - if _, ok := dependsConfigIntf["required"]; !ok { - dependsConfigIntf["required"] = true - } - transformed[service] = dependsConfigIntf - } - return groupXFieldsIntoExtensions(transformed), nil - default: - return data, errors.Errorf("invalid type %T for service depends_on", value) - } -} - -var transformExtendsConfig TransformerFunc = func(value interface{}) (interface{}, error) { - switch value.(type) { - case string: - return map[string]interface{}{"service": value}, nil - case map[string]interface{}: - return value, nil - default: - return value, errors.Errorf("invalid type %T for extends", value) - } -} - -var transformServiceVolumeConfig TransformerFunc = func(data interface{}) (interface{}, error) { - switch value := data.(type) { - case string: - volume, err := ParseVolume(value) - volume.Target = cleanTarget(volume.Target) - return volume, err - case map[string]interface{}: - data := groupXFieldsIntoExtensions(data.(map[string]interface{})) - if target, ok := data["target"]; ok { - data["target"] = cleanTarget(target.(string)) - } - return data, nil - default: - return data, errors.Errorf("invalid type %T for service volume", value) - } -} - -var transformServiceNetworkMap TransformerFunc = func(value interface{}) (interface{}, error) { - if list, ok := value.([]interface{}); ok { - mapValue := map[interface{}]interface{}{} - for _, name := range list { - mapValue[name] = nil - } - return mapValue, nil - } - return value, nil -} - -var transformSSHConfig TransformerFunc = func(data interface{}) (interface{}, error) { - switch value := data.(type) { - case map[string]interface{}: - var result []types.SSHKey - for key, val := range value { - if val == nil { - val = "" - } - result = append(result, types.SSHKey{ID: key, Path: val.(string)}) - } - return result, nil - case []interface{}: - var result []types.SSHKey - for _, v := range value { - key, val := transformValueToMapEntry(v.(string), "=", false) - result = append(result, types.SSHKey{ID: key, Path: val.(string)}) - } - return result, nil - case string: - return ParseShortSSHSyntax(value) - } - return nil, errors.Errorf("expected a sting, map or a list, got %T: %#v", data, data) -} - -// ParseShortSSHSyntax parse short syntax for SSH authentications -func ParseShortSSHSyntax(value string) ([]types.SSHKey, error) { - if value == "" { - value = "default" - } - key, val := transformValueToMapEntry(value, "=", false) - result := []types.SSHKey{{ID: key, Path: val.(string)}} - return result, nil -} - -var transformStringOrNumberList TransformerFunc = func(value interface{}) (interface{}, error) { - list := value.([]interface{}) - result := make([]string, len(list)) - for i, item := range list { - result[i] = fmt.Sprint(item) - } - return result, nil -} - -var transformStringList TransformerFunc = func(data interface{}) (interface{}, error) { - switch value := data.(type) { - case string: - return []string{value}, nil - case []interface{}: - return value, nil - default: - return data, errors.Errorf("invalid type %T for string list", value) - } -} - -func transformMappingOrListFunc(sep string, allowNil bool) TransformerFunc { - return func(data interface{}) (interface{}, error) { - return transformMappingOrList(data, sep, allowNil) - } -} - -func transformMappingOrList(mappingOrList interface{}, sep string, allowNil bool) (interface{}, error) { - switch value := mappingOrList.(type) { - case map[string]interface{}: - return toMapStringString(value, allowNil), nil - case []interface{}: - result := make(map[string]interface{}) - for _, value := range value { - key, val := transformValueToMapEntry(value.(string), sep, allowNil) - result[key] = val - } - return result, nil - } - return nil, errors.Errorf("expected a map or a list, got %T: %#v", mappingOrList, mappingOrList) -} - -func transformValueToMapEntry(value string, separator string, allowNil bool) (string, interface{}) { - parts := strings.SplitN(value, separator, 2) - key := parts[0] - switch { - case len(parts) == 1 && allowNil: - return key, nil - case len(parts) == 1 && !allowNil: - return key, "" - default: - return key, parts[1] - } -} - -var transformShellCommand TransformerFunc = func(value interface{}) (interface{}, error) { - if str, ok := value.(string); ok { - return shellwords.Parse(str) - } - return value, nil -} - -var transformHealthCheckTest TransformerFunc = func(data interface{}) (interface{}, error) { - switch value := data.(type) { - case string: - return append([]string{"CMD-SHELL"}, value), nil - case []interface{}: - return value, nil - default: - return value, errors.Errorf("invalid type %T for healthcheck.test", value) - } -} - -var transformSize TransformerFunc = func(value interface{}) (interface{}, error) { - switch value := value.(type) { - case int: - return int64(value), nil - case int64, types.UnitBytes: - return value, nil - case string: - return units.RAMInBytes(value) - default: - return value, errors.Errorf("invalid type for size %T", value) - } -} - -var transformStringToDuration TransformerFunc = func(value interface{}) (interface{}, error) { - switch value := value.(type) { - case string: - d, err := time.ParseDuration(value) - if err != nil { - return value, err - } - return types.Duration(d), nil - case types.Duration: - return value, nil - default: - return value, errors.Errorf("invalid type %T for duration", value) - } -} - -func toMapStringString(value map[string]interface{}, allowNil bool) map[string]interface{} { - output := make(map[string]interface{}) - for key, value := range value { - output[key] = toString(value, allowNil) - } - return output -} - -func toString(value interface{}, allowNil bool) interface{} { - switch { - case value != nil: - return fmt.Sprint(value) - case allowNil: - return nil - default: - return "" - } -} diff --git a/vendor/github.com/compose-spec/compose-go/loader/merge.go b/vendor/github.com/compose-spec/compose-go/loader/merge.go deleted file mode 100644 index 3c4848e07..000000000 --- a/vendor/github.com/compose-spec/compose-go/loader/merge.go +++ /dev/null @@ -1,378 +0,0 @@ -/* - Copyright 2020 The Compose Specification 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 loader - -import ( - "reflect" - "sort" - - "github.com/compose-spec/compose-go/types" - "github.com/imdario/mergo" - "github.com/pkg/errors" -) - -type specials struct { - m map[reflect.Type]func(dst, src reflect.Value) error -} - -var serviceSpecials = &specials{ - m: map[reflect.Type]func(dst, src reflect.Value) error{ - reflect.TypeOf(&types.LoggingConfig{}): safelyMerge(mergeLoggingConfig), - reflect.TypeOf(&types.UlimitsConfig{}): safelyMerge(mergeUlimitsConfig), - reflect.TypeOf([]types.ServiceVolumeConfig{}): mergeSlice(toServiceVolumeConfigsMap, toServiceVolumeConfigsSlice), - reflect.TypeOf([]types.ServicePortConfig{}): mergeSlice(toServicePortConfigsMap, toServicePortConfigsSlice), - reflect.TypeOf([]types.ServiceSecretConfig{}): mergeSlice(toServiceSecretConfigsMap, toServiceSecretConfigsSlice), - reflect.TypeOf([]types.ServiceConfigObjConfig{}): mergeSlice(toServiceConfigObjConfigsMap, toSServiceConfigObjConfigsSlice), - reflect.TypeOf(&types.UlimitsConfig{}): mergeUlimitsConfig, - }, -} - -func (s *specials) Transformer(t reflect.Type) func(dst, src reflect.Value) error { - // TODO this is a workaround waiting for imdario/mergo#131 - if t.Kind() == reflect.Pointer && t.Elem().Kind() == reflect.Bool { - return func(dst, src reflect.Value) error { - if dst.CanSet() && !src.IsNil() { - dst.Set(src) - } - return nil - } - } - if fn, ok := s.m[t]; ok { - return fn - } - return nil -} - -func merge(configs []*types.Config) (*types.Config, error) { - base := configs[0] - for _, override := range configs[1:] { - var err error - base.Name = mergeNames(base.Name, override.Name) - base.Services, err = mergeServices(base.Services, override.Services) - if err != nil { - return base, errors.Wrapf(err, "cannot merge services from %s", override.Filename) - } - base.Volumes, err = mergeVolumes(base.Volumes, override.Volumes) - if err != nil { - return base, errors.Wrapf(err, "cannot merge volumes from %s", override.Filename) - } - base.Networks, err = mergeNetworks(base.Networks, override.Networks) - if err != nil { - return base, errors.Wrapf(err, "cannot merge networks from %s", override.Filename) - } - base.Secrets, err = mergeSecrets(base.Secrets, override.Secrets) - if err != nil { - return base, errors.Wrapf(err, "cannot merge secrets from %s", override.Filename) - } - base.Configs, err = mergeConfigs(base.Configs, override.Configs) - if err != nil { - return base, errors.Wrapf(err, "cannot merge configs from %s", override.Filename) - } - base.Extensions, err = mergeExtensions(base.Extensions, override.Extensions) - if err != nil { - return base, errors.Wrapf(err, "cannot merge extensions from %s", override.Filename) - } - } - return base, nil -} - -func mergeNames(base, override string) string { - if override != "" { - return override - } - return base -} - -func mergeServices(base, override []types.ServiceConfig) ([]types.ServiceConfig, error) { - baseServices := mapByName(base) - overrideServices := mapByName(override) - for name, overrideService := range overrideServices { - overrideService := overrideService - if baseService, ok := baseServices[name]; ok { - merged, err := _merge(&baseService, &overrideService) - if err != nil { - return nil, errors.Wrapf(err, "cannot merge service %s", name) - } - baseServices[name] = *merged - continue - } - baseServices[name] = overrideService - } - services := []types.ServiceConfig{} - for _, baseService := range baseServices { - services = append(services, baseService) - } - sort.Slice(services, func(i, j int) bool { return services[i].Name < services[j].Name }) - return services, nil -} - -func _merge(baseService *types.ServiceConfig, overrideService *types.ServiceConfig) (*types.ServiceConfig, error) { - if err := mergo.Merge(baseService, overrideService, - mergo.WithAppendSlice, - mergo.WithOverride, - mergo.WithTransformers(serviceSpecials)); err != nil { - return nil, err - } - if overrideService.Command != nil { - baseService.Command = overrideService.Command - } - if overrideService.HealthCheck != nil && overrideService.HealthCheck.Test != nil { - baseService.HealthCheck.Test = overrideService.HealthCheck.Test - } - if overrideService.Entrypoint != nil { - baseService.Entrypoint = overrideService.Entrypoint - } - if baseService.Environment != nil { - baseService.Environment.OverrideBy(overrideService.Environment) - } else { - baseService.Environment = overrideService.Environment - } - baseService.Expose = unique(baseService.Expose) - return baseService, nil -} - -func unique(slice []string) []string { - if slice == nil { - return nil - } - uniqMap := make(map[string]struct{}) - var uniqSlice []string - for _, v := range slice { - if _, ok := uniqMap[v]; !ok { - uniqSlice = append(uniqSlice, v) - uniqMap[v] = struct{}{} - } - } - return uniqSlice -} - -func toServiceSecretConfigsMap(s interface{}) (map[interface{}]interface{}, error) { - secrets, ok := s.([]types.ServiceSecretConfig) - if !ok { - return nil, errors.Errorf("not a serviceSecretConfig: %v", s) - } - m := map[interface{}]interface{}{} - for _, secret := range secrets { - m[secret.Source] = secret - } - return m, nil -} - -func toServiceConfigObjConfigsMap(s interface{}) (map[interface{}]interface{}, error) { - secrets, ok := s.([]types.ServiceConfigObjConfig) - if !ok { - return nil, errors.Errorf("not a serviceSecretConfig: %v", s) - } - m := map[interface{}]interface{}{} - for _, secret := range secrets { - m[secret.Source] = secret - } - return m, nil -} - -func toServicePortConfigsMap(s interface{}) (map[interface{}]interface{}, error) { - ports, ok := s.([]types.ServicePortConfig) - if !ok { - return nil, errors.Errorf("not a servicePortConfig slice: %v", s) - } - m := map[interface{}]interface{}{} - type port struct { - target uint32 - published string - ip string - protocol string - } - - for _, p := range ports { - mergeKey := port{ - target: p.Target, - published: p.Published, - ip: p.HostIP, - protocol: p.Protocol, - } - m[mergeKey] = p - } - return m, nil -} - -func toServiceVolumeConfigsMap(s interface{}) (map[interface{}]interface{}, error) { - volumes, ok := s.([]types.ServiceVolumeConfig) - if !ok { - return nil, errors.Errorf("not a ServiceVolumeConfig slice: %v", s) - } - m := map[interface{}]interface{}{} - for _, v := range volumes { - m[v.Target] = v - } - return m, nil -} - -func toServiceSecretConfigsSlice(dst reflect.Value, m map[interface{}]interface{}) error { - var s []types.ServiceSecretConfig - for _, v := range m { - s = append(s, v.(types.ServiceSecretConfig)) - } - sort.Slice(s, func(i, j int) bool { return s[i].Source < s[j].Source }) - dst.Set(reflect.ValueOf(s)) - return nil -} - -func toSServiceConfigObjConfigsSlice(dst reflect.Value, m map[interface{}]interface{}) error { - var s []types.ServiceConfigObjConfig - for _, v := range m { - s = append(s, v.(types.ServiceConfigObjConfig)) - } - sort.Slice(s, func(i, j int) bool { return s[i].Source < s[j].Source }) - dst.Set(reflect.ValueOf(s)) - return nil -} - -func toServicePortConfigsSlice(dst reflect.Value, m map[interface{}]interface{}) error { - var s []types.ServicePortConfig - for _, v := range m { - s = append(s, v.(types.ServicePortConfig)) - } - sort.Slice(s, func(i, j int) bool { - if s[i].Target != s[j].Target { - return s[i].Target < s[j].Target - } - if s[i].Published != s[j].Published { - return s[i].Published < s[j].Published - } - if s[i].HostIP != s[j].HostIP { - return s[i].HostIP < s[j].HostIP - } - return s[i].Protocol < s[j].Protocol - }) - dst.Set(reflect.ValueOf(s)) - return nil -} - -func toServiceVolumeConfigsSlice(dst reflect.Value, m map[interface{}]interface{}) error { - var s []types.ServiceVolumeConfig - for _, v := range m { - s = append(s, v.(types.ServiceVolumeConfig)) - } - sort.Slice(s, func(i, j int) bool { return s[i].Target < s[j].Target }) - dst.Set(reflect.ValueOf(s)) - return nil -} - -type toMapFn func(s interface{}) (map[interface{}]interface{}, error) -type writeValueFromMapFn func(reflect.Value, map[interface{}]interface{}) error - -func safelyMerge(mergeFn func(dst, src reflect.Value) error) func(dst, src reflect.Value) error { - return func(dst, src reflect.Value) error { - if src.IsNil() { - return nil - } - if dst.IsNil() { - dst.Set(src) - return nil - } - return mergeFn(dst, src) - } -} - -func mergeSlice(toMap toMapFn, writeValue writeValueFromMapFn) func(dst, src reflect.Value) error { - return func(dst, src reflect.Value) error { - dstMap, err := sliceToMap(toMap, dst) - if err != nil { - return err - } - srcMap, err := sliceToMap(toMap, src) - if err != nil { - return err - } - if err := mergo.Map(&dstMap, srcMap, mergo.WithOverride); err != nil { - return err - } - return writeValue(dst, dstMap) - } -} - -func sliceToMap(toMap toMapFn, v reflect.Value) (map[interface{}]interface{}, error) { - // check if valid - if !v.IsValid() { - return nil, errors.Errorf("invalid value : %+v", v) - } - return toMap(v.Interface()) -} - -func mergeLoggingConfig(dst, src reflect.Value) error { - // Same driver, merging options - if getLoggingDriver(dst.Elem()) == getLoggingDriver(src.Elem()) || - getLoggingDriver(dst.Elem()) == "" || getLoggingDriver(src.Elem()) == "" { - if getLoggingDriver(dst.Elem()) == "" { - dst.Elem().FieldByName("Driver").SetString(getLoggingDriver(src.Elem())) - } - dstOptions := dst.Elem().FieldByName("Options").Interface().(map[string]string) - srcOptions := src.Elem().FieldByName("Options").Interface().(map[string]string) - return mergo.Merge(&dstOptions, srcOptions, mergo.WithOverride) - } - // Different driver, override with src - dst.Set(src) - return nil -} - -// nolint: unparam -func mergeUlimitsConfig(dst, src reflect.Value) error { - if src.Interface() != reflect.Zero(reflect.TypeOf(src.Interface())).Interface() { - dst.Elem().Set(src.Elem()) - } - return nil -} - -func getLoggingDriver(v reflect.Value) string { - return v.FieldByName("Driver").String() -} - -func mapByName(services []types.ServiceConfig) map[string]types.ServiceConfig { - m := map[string]types.ServiceConfig{} - for _, service := range services { - m[service.Name] = service - } - return m -} - -func mergeVolumes(base, override map[string]types.VolumeConfig) (map[string]types.VolumeConfig, error) { - err := mergo.Map(&base, &override, mergo.WithOverride) - return base, err -} - -func mergeNetworks(base, override map[string]types.NetworkConfig) (map[string]types.NetworkConfig, error) { - err := mergo.Map(&base, &override, mergo.WithOverride) - return base, err -} - -func mergeSecrets(base, override map[string]types.SecretConfig) (map[string]types.SecretConfig, error) { - err := mergo.Map(&base, &override, mergo.WithOverride) - return base, err -} - -func mergeConfigs(base, override map[string]types.ConfigObjConfig) (map[string]types.ConfigObjConfig, error) { - err := mergo.Map(&base, &override, mergo.WithOverride) - return base, err -} - -func mergeExtensions(base, override map[string]interface{}) (map[string]interface{}, error) { - if base == nil { - base = map[string]interface{}{} - } - err := mergo.Map(&base, &override, mergo.WithOverride) - return base, err -} diff --git a/vendor/github.com/compose-spec/compose-go/loader/normalize.go b/vendor/github.com/compose-spec/compose-go/loader/normalize.go deleted file mode 100644 index 58863b5fa..000000000 --- a/vendor/github.com/compose-spec/compose-go/loader/normalize.go +++ /dev/null @@ -1,335 +0,0 @@ -/* - Copyright 2020 The Compose Specification 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 loader - -import ( - "fmt" - "strings" - - "github.com/compose-spec/compose-go/errdefs" - "github.com/compose-spec/compose-go/types" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" -) - -// Normalize compose project by moving deprecated attributes to their canonical position and injecting implicit defaults -func Normalize(project *types.Project) error { - if project.Networks == nil { - project.Networks = make(map[string]types.NetworkConfig) - } - - // If not declared explicitly, Compose model involves an implicit "default" network - if _, ok := project.Networks["default"]; !ok { - project.Networks["default"] = types.NetworkConfig{} - } - - if err := relocateExternalName(project); err != nil { - return err - } - - for i, s := range project.Services { - if len(s.Networks) == 0 && s.NetworkMode == "" { - // Service without explicit network attachment are implicitly exposed on default network - s.Networks = map[string]*types.ServiceNetworkConfig{"default": nil} - } - - if s.PullPolicy == types.PullPolicyIfNotPresent { - s.PullPolicy = types.PullPolicyMissing - } - - fn := func(s string) (string, bool) { - v, ok := project.Environment[s] - return v, ok - } - - if s.Build != nil { - if s.Build.Context == "" { - s.Build.Context = "." - } - if s.Build.Dockerfile == "" && s.Build.DockerfileInline == "" { - s.Build.Dockerfile = "Dockerfile" - } - s.Build.Args = s.Build.Args.Resolve(fn) - } - s.Environment = s.Environment.Resolve(fn) - - for _, link := range s.Links { - parts := strings.Split(link, ":") - if len(parts) == 2 { - link = parts[0] - } - s.DependsOn = setIfMissing(s.DependsOn, link, types.ServiceDependency{ - Condition: types.ServiceConditionStarted, - Restart: true, - Required: true, - }) - } - - for _, namespace := range []string{s.NetworkMode, s.Ipc, s.Pid, s.Uts, s.Cgroup} { - if strings.HasPrefix(namespace, types.ServicePrefix) { - name := namespace[len(types.ServicePrefix):] - s.DependsOn = setIfMissing(s.DependsOn, name, types.ServiceDependency{ - Condition: types.ServiceConditionStarted, - Restart: true, - Required: true, - }) - } - } - - for _, vol := range s.VolumesFrom { - if !strings.HasPrefix(vol, types.ContainerPrefix) { - spec := strings.Split(vol, ":") - s.DependsOn = setIfMissing(s.DependsOn, spec[0], types.ServiceDependency{ - Condition: types.ServiceConditionStarted, - Restart: false, - Required: true, - }) - } - } - - err := relocateLogDriver(&s) - if err != nil { - return err - } - - err = relocateLogOpt(&s) - if err != nil { - return err - } - - err = relocateDockerfile(&s) - if err != nil { - return err - } - - err = relocateScale(&s) - if err != nil { - return err - } - - inferImplicitDependencies(&s) - - project.Services[i] = s - } - - setNameFromKey(project) - - return nil -} - -// IsServiceDependency check the relation set by ref refers to a service -func IsServiceDependency(ref string) (string, bool) { - if strings.HasPrefix( - ref, - types.ServicePrefix, - ) { - return ref[len(types.ServicePrefix):], true - } - return "", false -} - -func inferImplicitDependencies(service *types.ServiceConfig) { - var dependencies []string - - maybeReferences := []string{ - service.NetworkMode, - service.Ipc, - service.Pid, - service.Uts, - service.Cgroup, - } - for _, ref := range maybeReferences { - if dep, ok := IsServiceDependency(ref); ok { - dependencies = append(dependencies, dep) - } - } - - for _, vol := range service.VolumesFrom { - spec := strings.Split(vol, ":") - if len(spec) == 0 { - continue - } - if spec[0] == "container" { - continue - } - dependencies = append(dependencies, spec[0]) - } - - for _, link := range service.Links { - dependencies = append(dependencies, strings.Split(link, ":")[0]) - } - - if len(dependencies) > 0 && service.DependsOn == nil { - service.DependsOn = make(types.DependsOnConfig) - } - - for _, d := range dependencies { - if _, ok := service.DependsOn[d]; !ok { - service.DependsOn[d] = types.ServiceDependency{ - Condition: types.ServiceConditionStarted, - Required: true, - } - } - } -} - -// setIfMissing adds a ServiceDependency for service if not already defined -func setIfMissing(d types.DependsOnConfig, service string, dep types.ServiceDependency) types.DependsOnConfig { - if d == nil { - d = types.DependsOnConfig{} - } - if _, ok := d[service]; !ok { - d[service] = dep - } - return d -} - -func relocateScale(s *types.ServiceConfig) error { - scale := uint64(s.Scale) - if scale > 1 { - logrus.Warn("`scale` is deprecated. Use the `deploy.replicas` element") - if s.Deploy == nil { - s.Deploy = &types.DeployConfig{} - } - if s.Deploy.Replicas != nil && *s.Deploy.Replicas != scale { - return errors.Wrap(errdefs.ErrInvalid, "can't use both 'scale' (deprecated) and 'deploy.replicas'") - } - s.Deploy.Replicas = &scale - } - return nil -} - -// Resources with no explicit name are actually named by their key in map -func setNameFromKey(project *types.Project) { - for i, n := range project.Networks { - if n.Name == "" { - n.Name = fmt.Sprintf("%s_%s", project.Name, i) - project.Networks[i] = n - } - } - - for i, v := range project.Volumes { - if v.Name == "" { - v.Name = fmt.Sprintf("%s_%s", project.Name, i) - project.Volumes[i] = v - } - } - - for i, c := range project.Configs { - if c.Name == "" { - c.Name = fmt.Sprintf("%s_%s", project.Name, i) - project.Configs[i] = c - } - } - - for i, s := range project.Secrets { - if s.Name == "" { - s.Name = fmt.Sprintf("%s_%s", project.Name, i) - project.Secrets[i] = s - } - } -} - -func relocateExternalName(project *types.Project) error { - for i, n := range project.Networks { - if n.External.Name != "" { - if n.Name != "" { - return errors.Wrap(errdefs.ErrInvalid, "can't use both 'networks.external.name' (deprecated) and 'networks.name'") - } - n.Name = n.External.Name - } - project.Networks[i] = n - } - - for i, v := range project.Volumes { - if v.External.Name != "" { - if v.Name != "" { - return errors.Wrap(errdefs.ErrInvalid, "can't use both 'volumes.external.name' (deprecated) and 'volumes.name'") - } - v.Name = v.External.Name - } - project.Volumes[i] = v - } - - for i, s := range project.Secrets { - if s.External.Name != "" { - if s.Name != "" { - return errors.Wrap(errdefs.ErrInvalid, "can't use both 'secrets.external.name' (deprecated) and 'secrets.name'") - } - s.Name = s.External.Name - } - project.Secrets[i] = s - } - - for i, c := range project.Configs { - if c.External.Name != "" { - if c.Name != "" { - return errors.Wrap(errdefs.ErrInvalid, "can't use both 'configs.external.name' (deprecated) and 'configs.name'") - } - c.Name = c.External.Name - } - project.Configs[i] = c - } - return nil -} - -func relocateLogOpt(s *types.ServiceConfig) error { - if len(s.LogOpt) != 0 { - logrus.Warn("`log_opts` is deprecated. Use the `logging` element") - if s.Logging == nil { - s.Logging = &types.LoggingConfig{} - } - for k, v := range s.LogOpt { - if _, ok := s.Logging.Options[k]; !ok { - s.Logging.Options[k] = v - } else { - return errors.Wrap(errdefs.ErrInvalid, "can't use both 'log_opt' (deprecated) and 'logging.options'") - } - } - } - return nil -} - -func relocateLogDriver(s *types.ServiceConfig) error { - if s.LogDriver != "" { - logrus.Warn("`log_driver` is deprecated. Use the `logging` element") - if s.Logging == nil { - s.Logging = &types.LoggingConfig{} - } - if s.Logging.Driver == "" { - s.Logging.Driver = s.LogDriver - } else { - return errors.Wrap(errdefs.ErrInvalid, "can't use both 'log_driver' (deprecated) and 'logging.driver'") - } - } - return nil -} - -func relocateDockerfile(s *types.ServiceConfig) error { - if s.Dockerfile != "" { - logrus.Warn("`dockerfile` is deprecated. Use the `build` element") - if s.Build == nil { - s.Build = &types.BuildConfig{} - } - if s.Dockerfile == "" { - s.Build.Dockerfile = s.Dockerfile - } else { - return errors.Wrap(errdefs.ErrInvalid, "can't use both 'dockerfile' (deprecated) and 'build.dockerfile'") - } - } - return nil -} diff --git a/vendor/github.com/compose-spec/compose-go/loader/null.go b/vendor/github.com/compose-spec/compose-go/loader/null.go deleted file mode 100644 index 648aacde4..000000000 --- a/vendor/github.com/compose-spec/compose-go/loader/null.go +++ /dev/null @@ -1,159 +0,0 @@ -/* - Copyright 2020 The Compose Specification 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 loader - -import ( - "fmt" - "reflect" - "strconv" - "strings" - - "github.com/compose-spec/compose-go/tree" - "github.com/compose-spec/compose-go/types" - "gopkg.in/yaml.v3" -) - -type ResetProcessor struct { - target interface{} - paths []tree.Path -} - -// UnmarshalYAML implement yaml.Unmarshaler -func (p *ResetProcessor) UnmarshalYAML(value *yaml.Node) error { - resolved, err := p.resolveReset(value, tree.NewPath()) - if err != nil { - return err - } - return resolved.Decode(p.target) -} - -// resolveReset detects `!reset` tag being set on yaml nodes and record position in the yaml tree -func (p *ResetProcessor) resolveReset(node *yaml.Node, path tree.Path) (*yaml.Node, error) { - if node.Tag == "!reset" { - p.paths = append(p.paths, path) - } - switch node.Kind { - case yaml.SequenceNode: - var err error - for idx, v := range node.Content { - next := path.Next(strconv.Itoa(idx)) - node.Content[idx], err = p.resolveReset(v, next) - if err != nil { - return nil, err - } - } - case yaml.MappingNode: - var err error - var key string - for idx, v := range node.Content { - if idx%2 == 0 { - key = v.Value - } else { - node.Content[idx], err = p.resolveReset(v, path.Next(key)) - if err != nil { - return nil, err - } - } - } - } - return node, nil -} - -// Apply finds the go attributes matching recorded paths and reset them to zero value -func (p *ResetProcessor) Apply(target *types.Config) error { - return p.applyNullOverrides(reflect.ValueOf(target), tree.NewPath()) -} - -// applyNullOverrides set val to Zero if it matches any of the recorded paths -func (p *ResetProcessor) applyNullOverrides(val reflect.Value, path tree.Path) error { - val = reflect.Indirect(val) - if !val.IsValid() { - return nil - } - typ := val.Type() - switch { - case path == "services": - // Project.Services is a slice in compose-go, but a mapping in yaml - for i := 0; i < val.Len(); i++ { - service := val.Index(i) - name := service.FieldByName("Name") - next := path.Next(name.String()) - err := p.applyNullOverrides(service, next) - if err != nil { - return err - } - } - case typ.Kind() == reflect.Map: - iter := val.MapRange() - KEYS: - for iter.Next() { - k := iter.Key() - next := path.Next(k.String()) - for _, pattern := range p.paths { - if next.Matches(pattern) { - val.SetMapIndex(k, reflect.Value{}) - continue KEYS - } - } - return p.applyNullOverrides(iter.Value(), next) - } - case typ.Kind() == reflect.Slice: - ITER: - for i := 0; i < val.Len(); i++ { - next := path.Next(fmt.Sprintf("[%d]", i)) - for _, pattern := range p.paths { - if next.Matches(pattern) { - - continue ITER - } - } - // TODO(ndeloof) support removal from sequence - return p.applyNullOverrides(val.Index(i), next) - } - - case typ.Kind() == reflect.Struct: - FIELDS: - for i := 0; i < typ.NumField(); i++ { - field := typ.Field(i) - name := field.Name - attr := strings.ToLower(name) - tag := field.Tag.Get("yaml") - tag = strings.Split(tag, ",")[0] - if tag != "" && tag != "-" { - attr = tag - } - next := path.Next(attr) - f := val.Field(i) - for _, pattern := range p.paths { - if next.Matches(pattern) { - f := f - if !f.CanSet() { - return fmt.Errorf("can't override attribute %s", name) - } - // f.SetZero() requires go 1.20 - f.Set(reflect.Zero(f.Type())) - continue FIELDS - } - } - err := p.applyNullOverrides(f, next) - if err != nil { - return err - } - } - } - return nil -} diff --git a/vendor/github.com/compose-spec/compose-go/loader/paths.go b/vendor/github.com/compose-spec/compose-go/loader/paths.go deleted file mode 100644 index 61e79f011..000000000 --- a/vendor/github.com/compose-spec/compose-go/loader/paths.go +++ /dev/null @@ -1,165 +0,0 @@ -/* - Copyright 2020 The Compose Specification 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 loader - -import ( - "os" - "path/filepath" - "strings" - - "github.com/compose-spec/compose-go/types" -) - -// ResolveRelativePaths resolves relative paths based on project WorkingDirectory -func ResolveRelativePaths(project *types.Project) error { - absWorkingDir, err := filepath.Abs(project.WorkingDir) - if err != nil { - return err - } - project.WorkingDir = absWorkingDir - - absComposeFiles, err := absComposeFiles(project.ComposeFiles) - if err != nil { - return err - } - project.ComposeFiles = absComposeFiles - - for i, s := range project.Services { - ResolveServiceRelativePaths(project.WorkingDir, &s) - project.Services[i] = s - } - - for i, obj := range project.Configs { - if obj.File != "" { - obj.File = absPath(project.WorkingDir, obj.File) - project.Configs[i] = obj - } - } - - for i, obj := range project.Secrets { - if obj.File != "" { - obj.File = resolveMaybeUnixPath(project.WorkingDir, obj.File) - project.Secrets[i] = obj - } - } - - for name, config := range project.Volumes { - if config.Driver == "local" && config.DriverOpts["o"] == "bind" { - // This is actually a bind mount - config.DriverOpts["device"] = resolveMaybeUnixPath(project.WorkingDir, config.DriverOpts["device"]) - project.Volumes[name] = config - } - } - - // don't coerce a nil map to an empty map - if project.IncludeReferences != nil { - absIncludes := make(map[string][]types.IncludeConfig, len(project.IncludeReferences)) - for filename, config := range project.IncludeReferences { - filename = absPath(project.WorkingDir, filename) - absConfigs := make([]types.IncludeConfig, len(config)) - for i, c := range config { - absConfigs[i] = types.IncludeConfig{ - Path: resolvePaths(project.WorkingDir, c.Path), - ProjectDirectory: absPath(project.WorkingDir, c.ProjectDirectory), - EnvFile: resolvePaths(project.WorkingDir, c.EnvFile), - } - } - absIncludes[filename] = absConfigs - } - project.IncludeReferences = absIncludes - } - - return nil -} - -func ResolveServiceRelativePaths(workingDir string, s *types.ServiceConfig) { - if s.Build != nil { - if !isRemoteContext(s.Build.Context) { - s.Build.Context = absPath(workingDir, s.Build.Context) - } - for name, path := range s.Build.AdditionalContexts { - if strings.Contains(path, "://") { // `docker-image://` or any builder specific context type - continue - } - if isRemoteContext(path) { - continue - } - s.Build.AdditionalContexts[name] = absPath(workingDir, path) - } - } - for j, f := range s.EnvFile { - s.EnvFile[j] = absPath(workingDir, f) - } - - if s.Extends != nil && s.Extends.File != "" { - s.Extends.File = absPath(workingDir, s.Extends.File) - } - - for i, vol := range s.Volumes { - if vol.Type != types.VolumeTypeBind { - continue - } - s.Volumes[i].Source = resolveMaybeUnixPath(workingDir, vol.Source) - } -} - -func absPath(workingDir string, filePath string) string { - if strings.HasPrefix(filePath, "~") { - home, _ := os.UserHomeDir() - return filepath.Join(home, filePath[1:]) - } - if filepath.IsAbs(filePath) { - return filePath - } - return filepath.Join(workingDir, filePath) -} - -func absComposeFiles(composeFiles []string) ([]string, error) { - for i, composeFile := range composeFiles { - absComposefile, err := filepath.Abs(composeFile) - if err != nil { - return nil, err - } - composeFiles[i] = absComposefile - } - return composeFiles, nil -} - -// isRemoteContext returns true if the value is a Git reference or HTTP(S) URL. -// -// Any other value is assumed to be a local filesystem path and returns false. -// -// See: https://github.com/moby/buildkit/blob/18fc875d9bfd6e065cd8211abc639434ba65aa56/frontend/dockerui/context.go#L76-L79 -func isRemoteContext(maybeURL string) bool { - for _, prefix := range []string{"https://", "http://", "git://", "ssh://", "github.com/", "git@"} { - if strings.HasPrefix(maybeURL, prefix) { - return true - } - } - return false -} - -func resolvePaths(basePath string, in types.StringList) types.StringList { - if in == nil { - return nil - } - ret := make(types.StringList, len(in)) - for i := range in { - ret[i] = absPath(basePath, in[i]) - } - return ret -} diff --git a/vendor/github.com/compose-spec/compose-go/loader/validate.go b/vendor/github.com/compose-spec/compose-go/loader/validate.go deleted file mode 100644 index b4c42c7f1..000000000 --- a/vendor/github.com/compose-spec/compose-go/loader/validate.go +++ /dev/null @@ -1,121 +0,0 @@ -/* - Copyright 2020 The Compose Specification 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 loader - -import ( - "fmt" - "strings" - - "github.com/compose-spec/compose-go/errdefs" - "github.com/compose-spec/compose-go/types" - "github.com/pkg/errors" -) - -// checkConsistency validate a compose model is consistent -func checkConsistency(project *types.Project) error { - for _, s := range project.Services { - if s.Build == nil && s.Image == "" { - return errors.Wrapf(errdefs.ErrInvalid, "service %q has neither an image nor a build context specified", s.Name) - } - - if s.Build != nil { - if s.Build.DockerfileInline != "" && s.Build.Dockerfile != "" { - return errors.Wrapf(errdefs.ErrInvalid, "service %q declares mutualy exclusive dockerfile and dockerfile_inline", s.Name) - } - - if len(s.Build.Platforms) > 0 && s.Platform != "" { - var found bool - for _, platform := range s.Build.Platforms { - if platform == s.Platform { - found = true - break - } - } - if !found { - return errors.Wrapf(errdefs.ErrInvalid, "service.build.platforms MUST include service.platform %q ", s.Platform) - } - } - } - - if s.NetworkMode != "" && len(s.Networks) > 0 { - return errors.Wrap(errdefs.ErrInvalid, fmt.Sprintf("service %s declares mutually exclusive `network_mode` and `networks`", s.Name)) - } - for network := range s.Networks { - if _, ok := project.Networks[network]; !ok { - return errors.Wrap(errdefs.ErrInvalid, fmt.Sprintf("service %q refers to undefined network %s", s.Name, network)) - } - } - - if s.HealthCheck != nil && len(s.HealthCheck.Test) > 0 { - switch s.HealthCheck.Test[0] { - case "CMD", "CMD-SHELL", "NONE": - default: - return errors.New(`healthcheck.test must start either by "CMD", "CMD-SHELL" or "NONE"`) - } - } - - for dependedService := range s.DependsOn { - if _, err := project.GetService(dependedService); err != nil { - return errors.Wrap(errdefs.ErrInvalid, fmt.Sprintf("service %q depends on undefined service %s", s.Name, dependedService)) - } - } - - if strings.HasPrefix(s.NetworkMode, types.ServicePrefix) { - serviceName := s.NetworkMode[len(types.ServicePrefix):] - if _, err := project.GetServices(serviceName); err != nil { - return fmt.Errorf("service %q not found for network_mode 'service:%s'", serviceName, serviceName) - } - } - - for _, volume := range s.Volumes { - if volume.Type == types.VolumeTypeVolume && volume.Source != "" { // non anonymous volumes - if _, ok := project.Volumes[volume.Source]; !ok { - return errors.Wrap(errdefs.ErrInvalid, fmt.Sprintf("service %q refers to undefined volume %s", s.Name, volume.Source)) - } - } - } - if s.Build != nil { - for _, secret := range s.Build.Secrets { - if _, ok := project.Secrets[secret.Source]; !ok { - return errors.Wrap(errdefs.ErrInvalid, fmt.Sprintf("service %q refers to undefined build secret %s", s.Name, secret.Source)) - } - } - } - for _, config := range s.Configs { - if _, ok := project.Configs[config.Source]; !ok { - return errors.Wrap(errdefs.ErrInvalid, fmt.Sprintf("service %q refers to undefined config %s", s.Name, config.Source)) - } - } - - for _, secret := range s.Secrets { - if _, ok := project.Secrets[secret.Source]; !ok { - return errors.Wrap(errdefs.ErrInvalid, fmt.Sprintf("service %q refers to undefined secret %s", s.Name, secret.Source)) - } - } - } - - for name, secret := range project.Secrets { - if secret.External.External { - continue - } - if secret.File == "" && secret.Environment == "" { - return errors.Wrap(errdefs.ErrInvalid, fmt.Sprintf("secret %q must declare either `file` or `environment`", name)) - } - } - - return nil -} diff --git a/vendor/github.com/compose-spec/compose-go/loader/volume.go b/vendor/github.com/compose-spec/compose-go/loader/volume.go deleted file mode 100644 index dd83414ac..000000000 --- a/vendor/github.com/compose-spec/compose-go/loader/volume.go +++ /dev/null @@ -1,183 +0,0 @@ -/* - Copyright 2020 The Compose Specification 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 loader - -import ( - "strings" - "unicode" - "unicode/utf8" - - "github.com/compose-spec/compose-go/types" - "github.com/pkg/errors" -) - -const endOfSpec = rune(0) - -// ParseVolume parses a volume spec without any knowledge of the target platform -func ParseVolume(spec string) (types.ServiceVolumeConfig, error) { - volume := types.ServiceVolumeConfig{} - - switch len(spec) { - case 0: - return volume, errors.New("invalid empty volume spec") - case 1, 2: - volume.Target = spec - volume.Type = types.VolumeTypeVolume - return volume, nil - } - - var buffer []rune - for _, char := range spec + string(endOfSpec) { - switch { - case isWindowsDrive(buffer, char): - buffer = append(buffer, char) - case char == ':' || char == endOfSpec: - if err := populateFieldFromBuffer(char, buffer, &volume); err != nil { - populateType(&volume) - return volume, errors.Wrapf(err, "invalid spec: %s", spec) - } - buffer = nil - default: - buffer = append(buffer, char) - } - } - - populateType(&volume) - return volume, nil -} - -func isWindowsDrive(buffer []rune, char rune) bool { - return char == ':' && len(buffer) == 1 && unicode.IsLetter(buffer[0]) -} - -func populateFieldFromBuffer(char rune, buffer []rune, volume *types.ServiceVolumeConfig) error { - strBuffer := string(buffer) - switch { - case len(buffer) == 0: - return errors.New("empty section between colons") - // Anonymous volume - case volume.Source == "" && char == endOfSpec: - volume.Target = strBuffer - return nil - case volume.Source == "": - volume.Source = strBuffer - return nil - case volume.Target == "": - volume.Target = strBuffer - return nil - case char == ':': - return errors.New("too many colons") - } - for _, option := range strings.Split(strBuffer, ",") { - switch option { - case "ro": - volume.ReadOnly = true - case "rw": - volume.ReadOnly = false - case "nocopy": - volume.Volume = &types.ServiceVolumeVolume{NoCopy: true} - default: - if isBindOption(option) { - setBindOption(volume, option) - } - // ignore unknown options - } - } - return nil -} - -var Propagations = []string{ - types.PropagationRPrivate, - types.PropagationPrivate, - types.PropagationRShared, - types.PropagationShared, - types.PropagationRSlave, - types.PropagationSlave, -} - -type setBindOptionFunc func(bind *types.ServiceVolumeBind, option string) - -var bindOptions = map[string]setBindOptionFunc{ - types.PropagationRPrivate: setBindPropagation, - types.PropagationPrivate: setBindPropagation, - types.PropagationRShared: setBindPropagation, - types.PropagationShared: setBindPropagation, - types.PropagationRSlave: setBindPropagation, - types.PropagationSlave: setBindPropagation, - types.SELinuxShared: setBindSELinux, - types.SELinuxPrivate: setBindSELinux, -} - -func setBindPropagation(bind *types.ServiceVolumeBind, option string) { - bind.Propagation = option -} - -func setBindSELinux(bind *types.ServiceVolumeBind, option string) { - bind.SELinux = option -} - -func isBindOption(option string) bool { - _, ok := bindOptions[option] - - return ok -} - -func setBindOption(volume *types.ServiceVolumeConfig, option string) { - if volume.Bind == nil { - volume.Bind = &types.ServiceVolumeBind{} - } - - bindOptions[option](volume.Bind, option) -} - -func populateType(volume *types.ServiceVolumeConfig) { - if isFilePath(volume.Source) { - volume.Type = types.VolumeTypeBind - if volume.Bind == nil { - volume.Bind = &types.ServiceVolumeBind{} - } - // For backward compatibility with docker-compose legacy, using short notation involves - // bind will create missing host path - volume.Bind.CreateHostPath = true - } else { - volume.Type = types.VolumeTypeVolume - if volume.Volume == nil { - volume.Volume = &types.ServiceVolumeVolume{} - } - } -} - -func isFilePath(source string) bool { - if source == "" { - return false - } - switch source[0] { - case '.', '/', '~': - return true - } - - // windows named pipes - if strings.HasPrefix(source, `\\`) { - return true - } - - first, nextIndex := utf8.DecodeRuneInString(source) - if len(source) <= nextIndex { - return false - } - return isWindowsDrive([]rune{first}, rune(source[nextIndex])) -} diff --git a/vendor/github.com/compose-spec/compose-go/loader/windows_path.go b/vendor/github.com/compose-spec/compose-go/loader/windows_path.go deleted file mode 100644 index 5094f5b57..000000000 --- a/vendor/github.com/compose-spec/compose-go/loader/windows_path.go +++ /dev/null @@ -1,82 +0,0 @@ -/* - Copyright 2020 The Compose Specification 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 loader - -// 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. -// https://github.com/golang/go/blob/master/LICENSE - -// This file contains utilities to check for Windows absolute paths on Linux. -// The code in this file was largely copied from the Golang filepath package -// https://github.com/golang/go/blob/1d0e94b1e13d5e8a323a63cd1cc1ef95290c9c36/src/path/filepath/path_windows.go#L12-L65 - -func isSlash(c uint8) bool { - return c == '\\' || c == '/' -} - -// isAbs reports whether the path is a Windows absolute path. -func isAbs(path string) (b bool) { - l := volumeNameLen(path) - if l == 0 { - return false - } - path = path[l:] - if path == "" { - return false - } - return isSlash(path[0]) -} - -// volumeNameLen returns length of the leading volume name on Windows. -// It returns 0 elsewhere. -// nolint: gocyclo -func volumeNameLen(path string) int { - if len(path) < 2 { - return 0 - } - // with drive letter - c := path[0] - if path[1] == ':' && ('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z') { - return 2 - } - // is it UNC? https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx - if l := len(path); l >= 5 && isSlash(path[0]) && isSlash(path[1]) && - !isSlash(path[2]) && path[2] != '.' { - // first, leading `\\` and next shouldn't be `\`. its server name. - for n := 3; n < l-1; n++ { - // second, next '\' shouldn't be repeated. - if isSlash(path[n]) { - n++ - // third, following something characters. its share name. - if !isSlash(path[n]) { - if path[n] == '.' { - break - } - for ; n < l; n++ { - if isSlash(path[n]) { - break - } - } - return n - } - break - } - } - } - return 0 -} diff --git a/vendor/github.com/compose-spec/compose-go/schema/compose-spec.json b/vendor/github.com/compose-spec/compose-go/schema/compose-spec.json deleted file mode 100644 index d39aa35ea..000000000 --- a/vendor/github.com/compose-spec/compose-go/schema/compose-spec.json +++ /dev/null @@ -1,852 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2019-09/schema#", - "id": "compose_spec.json", - "type": "object", - "title": "Compose Specification", - "description": "The Compose file is a YAML file defining a multi-containers based application.", - - "properties": { - "version": { - "type": "string", - "description": "declared for backward compatibility, ignored." - }, - - "name": { - "type": "string", - "pattern": "^[a-z0-9][a-z0-9_-]*$", - "description": "define the Compose project name, until user defines one explicitly." - }, - - "include": { - "type": "array", - "items": { - "type": "object", - "$ref": "#/definitions/include" - }, - "description": "compose sub-projects to be included." - }, - - "services": { - "id": "#/properties/services", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/service" - } - }, - "additionalProperties": false - }, - - "networks": { - "id": "#/properties/networks", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/network" - } - } - }, - - "volumes": { - "id": "#/properties/volumes", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/volume" - } - }, - "additionalProperties": false - }, - - "secrets": { - "id": "#/properties/secrets", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/secret" - } - }, - "additionalProperties": false - }, - - "configs": { - "id": "#/properties/configs", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/config" - } - }, - "additionalProperties": false - } - }, - - "patternProperties": {"^x-": {}}, - "additionalProperties": false, - - "definitions": { - - "service": { - "id": "#/definitions/service", - "type": "object", - - "properties": { - "deploy": {"$ref": "#/definitions/deployment"}, - "annotations": {"$ref": "#/definitions/list_or_dict"}, - "attach": {"type": "boolean"}, - "build": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "context": {"type": "string"}, - "dockerfile": {"type": "string"}, - "dockerfile_inline": {"type": "string"}, - "args": {"$ref": "#/definitions/list_or_dict"}, - "ssh": {"$ref": "#/definitions/list_or_dict"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "cache_from": {"type": "array", "items": {"type": "string"}}, - "cache_to": {"type": "array", "items": {"type": "string"}}, - "no_cache": {"type": "boolean"}, - "additional_contexts": {"$ref": "#/definitions/list_or_dict"}, - "network": {"type": "string"}, - "pull": {"type": "boolean"}, - "target": {"type": "string"}, - "shm_size": {"type": ["integer", "string"]}, - "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, - "isolation": {"type": "string"}, - "privileged": {"type": "boolean"}, - "secrets": {"$ref": "#/definitions/service_config_or_secret"}, - "tags": {"type": "array", "items": {"type": "string"}}, - "platforms": {"type": "array", "items": {"type": "string"}} - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - } - ] - }, - "blkio_config": { - "type": "object", - "properties": { - "device_read_bps": { - "type": "array", - "items": {"$ref": "#/definitions/blkio_limit"} - }, - "device_read_iops": { - "type": "array", - "items": {"$ref": "#/definitions/blkio_limit"} - }, - "device_write_bps": { - "type": "array", - "items": {"$ref": "#/definitions/blkio_limit"} - }, - "device_write_iops": { - "type": "array", - "items": {"$ref": "#/definitions/blkio_limit"} - }, - "weight": {"type": "integer"}, - "weight_device": { - "type": "array", - "items": {"$ref": "#/definitions/blkio_weight"} - } - }, - "additionalProperties": false - }, - "cap_add": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "cap_drop": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "cgroup": {"type": "string", "enum": ["host", "private"]}, - "cgroup_parent": {"type": "string"}, - "command": {"$ref": "#/definitions/command"}, - "configs": {"$ref": "#/definitions/service_config_or_secret"}, - "container_name": {"type": "string"}, - "cpu_count": {"type": "integer", "minimum": 0}, - "cpu_percent": {"type": "integer", "minimum": 0, "maximum": 100}, - "cpu_shares": {"type": ["number", "string"]}, - "cpu_quota": {"type": ["number", "string"]}, - "cpu_period": {"type": ["number", "string"]}, - "cpu_rt_period": {"type": ["number", "string"]}, - "cpu_rt_runtime": {"type": ["number", "string"]}, - "cpus": {"type": ["number", "string"]}, - "cpuset": {"type": "string"}, - "credential_spec": { - "type": "object", - "properties": { - "config": {"type": "string"}, - "file": {"type": "string"}, - "registry": {"type": "string"} - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - }, - "depends_on": { - "oneOf": [ - {"$ref": "#/definitions/list_of_strings"}, - { - "type": "object", - "additionalProperties": false, - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "type": "object", - "additionalProperties": false, - "properties": { - "restart": {"type": "boolean"}, - "required": { - "type": "boolean", - "default": true - }, - "condition": { - "type": "string", - "enum": ["service_started", "service_healthy", "service_completed_successfully"] - } - }, - "required": ["condition"] - } - } - } - ] - }, - "device_cgroup_rules": {"$ref": "#/definitions/list_of_strings"}, - "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "dns": {"$ref": "#/definitions/string_or_list"}, - "dns_opt": {"type": "array","items": {"type": "string"}, "uniqueItems": true}, - "dns_search": {"$ref": "#/definitions/string_or_list"}, - "domainname": {"type": "string"}, - "entrypoint": {"$ref": "#/definitions/command"}, - "env_file": {"$ref": "#/definitions/string_or_list"}, - "environment": {"$ref": "#/definitions/list_or_dict"}, - - "expose": { - "type": "array", - "items": { - "type": ["string", "number"], - "format": "expose" - }, - "uniqueItems": true - }, - "extends": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - - "properties": { - "service": {"type": "string"}, - "file": {"type": "string"} - }, - "required": ["service"], - "additionalProperties": false - } - ] - }, - "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, - "group_add": { - "type": "array", - "items": { - "type": ["string", "number"] - }, - "uniqueItems": true - }, - "healthcheck": {"$ref": "#/definitions/healthcheck"}, - "hostname": {"type": "string"}, - "image": {"type": "string"}, - "init": {"type": "boolean"}, - "ipc": {"type": "string"}, - "isolation": {"type": "string"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "logging": { - "type": "object", - - "properties": { - "driver": {"type": "string"}, - "options": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number", "null"]} - } - } - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - }, - "mac_address": {"type": "string"}, - "mem_limit": {"type": ["number", "string"]}, - "mem_reservation": {"type": ["string", "integer"]}, - "mem_swappiness": {"type": "integer"}, - "memswap_limit": {"type": ["number", "string"]}, - "network_mode": {"type": "string"}, - "networks": { - "oneOf": [ - {"$ref": "#/definitions/list_of_strings"}, - { - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "oneOf": [ - { - "type": "object", - "properties": { - "aliases": {"$ref": "#/definitions/list_of_strings"}, - "ipv4_address": {"type": "string"}, - "ipv6_address": {"type": "string"}, - "link_local_ips": {"$ref": "#/definitions/list_of_strings"}, - "priority": {"type": "number"} - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - }, - {"type": "null"} - ] - } - }, - "additionalProperties": false - } - ] - }, - "oom_kill_disable": {"type": "boolean"}, - "oom_score_adj": {"type": "integer", "minimum": -1000, "maximum": 1000}, - "pid": {"type": ["string", "null"]}, - "pids_limit": {"type": ["number", "string"]}, - "platform": {"type": "string"}, - "ports": { - "type": "array", - "items": { - "oneOf": [ - {"type": "number", "format": "ports"}, - {"type": "string", "format": "ports"}, - { - "type": "object", - "properties": { - "mode": {"type": "string"}, - "host_ip": {"type": "string"}, - "target": {"type": "integer"}, - "published": {"type": ["string", "integer"]}, - "protocol": {"type": "string"} - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - } - ] - }, - "uniqueItems": true - }, - "privileged": {"type": "boolean"}, - "profiles": {"$ref": "#/definitions/list_of_strings"}, - "pull_policy": {"type": "string", "enum": [ - "always", "never", "if_not_present", "build", "missing" - ]}, - "read_only": {"type": "boolean"}, - "restart": {"type": "string"}, - "runtime": { - "type": "string" - }, - "scale": { - "type": "integer" - }, - "security_opt": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "shm_size": {"type": ["number", "string"]}, - "secrets": {"$ref": "#/definitions/service_config_or_secret"}, - "sysctls": {"$ref": "#/definitions/list_or_dict"}, - "stdin_open": {"type": "boolean"}, - "stop_grace_period": {"type": "string", "format": "duration"}, - "stop_signal": {"type": "string"}, - "storage_opt": {"type": "object"}, - "tmpfs": {"$ref": "#/definitions/string_or_list"}, - "tty": {"type": "boolean"}, - "ulimits": { - "type": "object", - "patternProperties": { - "^[a-z]+$": { - "oneOf": [ - {"type": "integer"}, - { - "type": "object", - "properties": { - "hard": {"type": "integer"}, - "soft": {"type": "integer"} - }, - "required": ["soft", "hard"], - "additionalProperties": false, - "patternProperties": {"^x-": {}} - } - ] - } - } - }, - "user": {"type": "string"}, - "uts": {"type": "string"}, - "userns_mode": {"type": "string"}, - "volumes": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "required": ["type"], - "properties": { - "type": {"type": "string"}, - "source": {"type": "string"}, - "target": {"type": "string"}, - "read_only": {"type": "boolean"}, - "consistency": {"type": "string"}, - "bind": { - "type": "object", - "properties": { - "propagation": {"type": "string"}, - "create_host_path": {"type": "boolean"}, - "selinux": {"type": "string", "enum": ["z", "Z"]} - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - }, - "volume": { - "type": "object", - "properties": { - "nocopy": {"type": "boolean"} - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - }, - "tmpfs": { - "type": "object", - "properties": { - "size": { - "oneOf": [ - {"type": "integer", "minimum": 0}, - {"type": "string"} - ] - }, - "mode": {"type": "number"} - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - } - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - } - ] - }, - "uniqueItems": true - }, - "volumes_from": { - "type": "array", - "items": {"type": "string"}, - "uniqueItems": true - }, - "working_dir": {"type": "string"} - }, - "patternProperties": {"^x-": {}}, - "additionalProperties": false - }, - - "healthcheck": { - "id": "#/definitions/healthcheck", - "type": "object", - "properties": { - "disable": {"type": "boolean"}, - "interval": {"type": "string", "format": "duration"}, - "retries": {"type": "number"}, - "test": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "timeout": {"type": "string", "format": "duration"}, - "start_period": {"type": "string", "format": "duration"}, - "start_interval": {"type": "string", "format": "duration"} - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - }, - "deployment": { - "id": "#/definitions/deployment", - "type": ["object", "null"], - "properties": { - "mode": {"type": "string"}, - "endpoint_mode": {"type": "string"}, - "replicas": {"type": "integer"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "rollback_config": { - "type": "object", - "properties": { - "parallelism": {"type": "integer"}, - "delay": {"type": "string", "format": "duration"}, - "failure_action": {"type": "string"}, - "monitor": {"type": "string", "format": "duration"}, - "max_failure_ratio": {"type": "number"}, - "order": {"type": "string", "enum": [ - "start-first", "stop-first" - ]} - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - }, - "update_config": { - "type": "object", - "properties": { - "parallelism": {"type": "integer"}, - "delay": {"type": "string", "format": "duration"}, - "failure_action": {"type": "string"}, - "monitor": {"type": "string", "format": "duration"}, - "max_failure_ratio": {"type": "number"}, - "order": {"type": "string", "enum": [ - "start-first", "stop-first" - ]} - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - }, - "resources": { - "type": "object", - "properties": { - "limits": { - "type": "object", - "properties": { - "cpus": {"type": ["number", "string"]}, - "memory": {"type": "string"}, - "pids": {"type": "integer"} - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - }, - "reservations": { - "type": "object", - "properties": { - "cpus": {"type": ["number", "string"]}, - "memory": {"type": "string"}, - "generic_resources": {"$ref": "#/definitions/generic_resources"}, - "devices": {"$ref": "#/definitions/devices"} - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - } - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - }, - "restart_policy": { - "type": "object", - "properties": { - "condition": {"type": "string"}, - "delay": {"type": "string", "format": "duration"}, - "max_attempts": {"type": "integer"}, - "window": {"type": "string", "format": "duration"} - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - }, - "placement": { - "type": "object", - "properties": { - "constraints": {"type": "array", "items": {"type": "string"}}, - "preferences": { - "type": "array", - "items": { - "type": "object", - "properties": { - "spread": {"type": "string"} - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - } - }, - "max_replicas_per_node": {"type": "integer"} - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - } - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - }, - - "generic_resources": { - "id": "#/definitions/generic_resources", - "type": "array", - "items": { - "type": "object", - "properties": { - "discrete_resource_spec": { - "type": "object", - "properties": { - "kind": {"type": "string"}, - "value": {"type": "number"} - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - } - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - } - }, - - "devices": { - "id": "#/definitions/devices", - "type": "array", - "items": { - "type": "object", - "properties": { - "capabilities": {"$ref": "#/definitions/list_of_strings"}, - "count": {"type": ["string", "integer"]}, - "device_ids": {"$ref": "#/definitions/list_of_strings"}, - "driver":{"type": "string"}, - "options":{"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - } - }, - - "include": { - "id": "#/definitions/include", - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "path": {"$ref": "#/definitions/string_or_list"}, - "env_file": {"$ref": "#/definitions/string_or_list"}, - "project_directory": {"type": "string"} - }, - "additionalProperties": false - } - ] - }, - - "network": { - "id": "#/definitions/network", - "type": ["object", "null"], - "properties": { - "name": {"type": "string"}, - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "ipam": { - "type": "object", - "properties": { - "driver": {"type": "string"}, - "config": { - "type": "array", - "items": { - "type": "object", - "properties": { - "subnet": {"type": "string", "format": "subnet_ip_address"}, - "ip_range": {"type": "string"}, - "gateway": {"type": "string"}, - "aux_addresses": { - "type": "object", - "additionalProperties": false, - "patternProperties": {"^.+$": {"type": "string"}} - } - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - } - }, - "options": { - "type": "object", - "additionalProperties": false, - "patternProperties": {"^.+$": {"type": "string"}} - } - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - }, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": { - "deprecated": true, - "type": "string" - } - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - }, - "internal": {"type": "boolean"}, - "enable_ipv6": {"type": "boolean"}, - "attachable": {"type": "boolean"}, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - }, - - "volume": { - "id": "#/definitions/volume", - "type": ["object", "null"], - "properties": { - "name": {"type": "string"}, - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": { - "deprecated": true, - "type": "string" - } - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - }, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - }, - - "secret": { - "id": "#/definitions/secret", - "type": "object", - "properties": { - "name": {"type": "string"}, - "environment": {"type": "string"}, - "file": {"type": "string"}, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - } - }, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "template_driver": {"type": "string"} - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - }, - - "config": { - "id": "#/definitions/config", - "type": "object", - "properties": { - "name": {"type": "string"}, - "file": {"type": "string"}, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": { - "deprecated": true, - "type": "string" - } - } - }, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "template_driver": {"type": "string"} - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - }, - - "command": { - "oneOf": [ - {"type": "null"}, - {"type": "string"}, - {"type": "array","items": {"type": "string"}} - ] - }, - - "string_or_list": { - "oneOf": [ - {"type": "string"}, - {"$ref": "#/definitions/list_of_strings"} - ] - }, - - "list_of_strings": { - "type": "array", - "items": {"type": "string"}, - "uniqueItems": true - }, - - "list_or_dict": { - "oneOf": [ - { - "type": "object", - "patternProperties": { - ".+": { - "type": ["string", "number", "boolean", "null"] - } - }, - "additionalProperties": false - }, - {"type": "array", "items": {"type": "string"}, "uniqueItems": true} - ] - }, - - "blkio_limit": { - "type": "object", - "properties": { - "path": {"type": "string"}, - "rate": {"type": ["integer", "string"]} - }, - "additionalProperties": false - }, - "blkio_weight": { - "type": "object", - "properties": { - "path": {"type": "string"}, - "weight": {"type": "integer"} - }, - "additionalProperties": false - }, - - "service_config_or_secret": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "source": {"type": "string"}, - "target": {"type": "string"}, - "uid": {"type": "string"}, - "gid": {"type": "string"}, - "mode": {"type": "number"} - }, - "additionalProperties": false, - "patternProperties": {"^x-": {}} - } - ] - } - }, - - "constraints": { - "service": { - "id": "#/definitions/constraints/service", - "anyOf": [ - {"required": ["build"]}, - {"required": ["image"]} - ], - "properties": { - "build": { - "required": ["context"] - } - } - } - } - } -} diff --git a/vendor/github.com/compose-spec/compose-go/schema/schema.go b/vendor/github.com/compose-spec/compose-go/schema/schema.go deleted file mode 100644 index bfbaa9355..000000000 --- a/vendor/github.com/compose-spec/compose-go/schema/schema.go +++ /dev/null @@ -1,164 +0,0 @@ -/* - Copyright 2020 The Compose Specification 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 schema - -import ( - // Enable support for embedded static resources - _ "embed" - "fmt" - "strings" - "time" - - "github.com/xeipuuv/gojsonschema" -) - -type portsFormatChecker struct{} - -func (checker portsFormatChecker) IsFormat(_ interface{}) bool { - // TODO: implement this - return true -} - -type durationFormatChecker struct{} - -func (checker durationFormatChecker) IsFormat(input interface{}) bool { - value, ok := input.(string) - if !ok { - return false - } - _, err := time.ParseDuration(value) - return err == nil -} - -func init() { - gojsonschema.FormatCheckers.Add("expose", portsFormatChecker{}) - gojsonschema.FormatCheckers.Add("ports", portsFormatChecker{}) - gojsonschema.FormatCheckers.Add("duration", durationFormatChecker{}) -} - -// Schema is the compose-spec JSON schema -// -//go:embed compose-spec.json -var Schema string - -// Validate uses the jsonschema to validate the configuration -func Validate(config map[string]interface{}) error { - schemaLoader := gojsonschema.NewStringLoader(Schema) - dataLoader := gojsonschema.NewGoLoader(config) - - result, err := gojsonschema.Validate(schemaLoader, dataLoader) - if err != nil { - return err - } - - if !result.Valid() { - return toError(result) - } - - return nil -} - -func toError(result *gojsonschema.Result) error { - err := getMostSpecificError(result.Errors()) - return err -} - -const ( - jsonschemaOneOf = "number_one_of" - jsonschemaAnyOf = "number_any_of" -) - -func getDescription(err validationError) string { - switch err.parent.Type() { - case "invalid_type": - if expectedType, ok := err.parent.Details()["expected"].(string); ok { - return fmt.Sprintf("must be a %s", humanReadableType(expectedType)) - } - case jsonschemaOneOf, jsonschemaAnyOf: - if err.child == nil { - return err.parent.Description() - } - return err.child.Description() - } - return err.parent.Description() -} - -func humanReadableType(definition string) string { - if definition[0:1] == "[" { - allTypes := strings.Split(definition[1:len(definition)-1], ",") - for i, t := range allTypes { - allTypes[i] = humanReadableType(t) - } - return fmt.Sprintf( - "%s or %s", - strings.Join(allTypes[0:len(allTypes)-1], ", "), - allTypes[len(allTypes)-1], - ) - } - if definition == "object" { - return "mapping" - } - if definition == "array" { - return "list" - } - return definition -} - -type validationError struct { - parent gojsonschema.ResultError - child gojsonschema.ResultError -} - -func (err validationError) Error() string { - description := getDescription(err) - return fmt.Sprintf("%s %s", err.parent.Field(), description) -} - -func getMostSpecificError(errors []gojsonschema.ResultError) validationError { - mostSpecificError := 0 - for i, err := range errors { - if specificity(err) > specificity(errors[mostSpecificError]) { - mostSpecificError = i - continue - } - - if specificity(err) == specificity(errors[mostSpecificError]) { - // Invalid type errors win in a tie-breaker for most specific field name - if err.Type() == "invalid_type" && errors[mostSpecificError].Type() != "invalid_type" { - mostSpecificError = i - } - } - } - - if mostSpecificError+1 == len(errors) { - return validationError{parent: errors[mostSpecificError]} - } - - switch errors[mostSpecificError].Type() { - case "number_one_of", "number_any_of": - return validationError{ - parent: errors[mostSpecificError], - child: errors[mostSpecificError+1], - } - default: - return validationError{parent: errors[mostSpecificError]} - } -} - -func specificity(err gojsonschema.ResultError) int { - return len(strings.Split(err.Field(), ".")) -} diff --git a/vendor/github.com/compose-spec/compose-go/template/template.go b/vendor/github.com/compose-spec/compose-go/template/template.go deleted file mode 100644 index cce4c6251..000000000 --- a/vendor/github.com/compose-spec/compose-go/template/template.go +++ /dev/null @@ -1,465 +0,0 @@ -/* - Copyright 2020 The Compose Specification 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 template - -import ( - "errors" - "fmt" - "regexp" - "sort" - "strings" - - "github.com/sirupsen/logrus" -) - -var delimiter = "\\$" -var substitutionNamed = "[_a-z][_a-z0-9]*" - -var substitutionBraced = "[_a-z][_a-z0-9]*(?::?[-+?](.*))?" - -var patternString = fmt.Sprintf( - "%s(?i:(?P%s)|(?P%s)|{(?:(?P%s)}|(?P)))", - delimiter, delimiter, substitutionNamed, substitutionBraced, -) - -var defaultPattern = regexp.MustCompile(patternString) - -// InvalidTemplateError is returned when a variable template is not in a valid -// format -type InvalidTemplateError struct { - Template string -} - -func (e InvalidTemplateError) Error() string { - return fmt.Sprintf("Invalid template: %#v", e.Template) -} - -// MissingRequiredError is returned when a variable template is missing -type MissingRequiredError struct { - Variable string - Reason string -} - -func (e MissingRequiredError) Error() string { - if e.Reason != "" { - return fmt.Sprintf("required variable %s is missing a value: %s", e.Variable, e.Reason) - } - return fmt.Sprintf("required variable %s is missing a value", e.Variable) -} - -// Mapping is a user-supplied function which maps from variable names to values. -// Returns the value as a string and a bool indicating whether -// the value is present, to distinguish between an empty string -// and the absence of a value. -type Mapping func(string) (string, bool) - -// SubstituteFunc is a user-supplied function that apply substitution. -// Returns the value as a string, a bool indicating if the function could apply -// the substitution and an error. -type SubstituteFunc func(string, Mapping) (string, bool, error) - -// ReplacementFunc is a user-supplied function that is apply to the matching -// substring. Returns the value as a string and an error. -type ReplacementFunc func(string, Mapping, *Config) (string, error) - -type Config struct { - pattern *regexp.Regexp - substituteFunc SubstituteFunc - replacementFunc ReplacementFunc - logging bool -} - -type Option func(*Config) - -func WithPattern(pattern *regexp.Regexp) Option { - return func(cfg *Config) { - cfg.pattern = pattern - } -} - -func WithSubstitutionFunction(subsFunc SubstituteFunc) Option { - return func(cfg *Config) { - cfg.substituteFunc = subsFunc - } -} - -func WithReplacementFunction(replacementFunc ReplacementFunc) Option { - return func(cfg *Config) { - cfg.replacementFunc = replacementFunc - } -} - -func WithoutLogging(cfg *Config) { - cfg.logging = false -} - -// SubstituteWithOptions substitute variables in the string with their values. -// It accepts additional options such as a custom function or pattern. -func SubstituteWithOptions(template string, mapping Mapping, options ...Option) (string, error) { - var returnErr error - - cfg := &Config{ - pattern: defaultPattern, - replacementFunc: DefaultReplacementFunc, - logging: true, - } - for _, o := range options { - o(cfg) - } - - result := cfg.pattern.ReplaceAllStringFunc(template, func(substring string) string { - replacement, err := cfg.replacementFunc(substring, mapping, cfg) - if err != nil { - // Add the template for template errors - var tmplErr *InvalidTemplateError - if errors.As(err, &tmplErr) { - if tmplErr.Template == "" { - tmplErr.Template = template - } - } - // Save the first error to be returned - if returnErr == nil { - returnErr = err - } - - } - return replacement - }) - - return result, returnErr -} - -func DefaultReplacementFunc(substring string, mapping Mapping, cfg *Config) (string, error) { - value, _, err := DefaultReplacementAppliedFunc(substring, mapping, cfg) - return value, err -} - -func DefaultReplacementAppliedFunc(substring string, mapping Mapping, cfg *Config) (string, bool, error) { - pattern := cfg.pattern - subsFunc := cfg.substituteFunc - if subsFunc == nil { - _, subsFunc = getSubstitutionFunctionForTemplate(substring) - } - - closingBraceIndex := getFirstBraceClosingIndex(substring) - rest := "" - if closingBraceIndex > -1 { - rest = substring[closingBraceIndex+1:] - substring = substring[0 : closingBraceIndex+1] - } - - matches := pattern.FindStringSubmatch(substring) - groups := matchGroups(matches, pattern) - if escaped := groups["escaped"]; escaped != "" { - return escaped, true, nil - } - - braced := false - substitution := groups["named"] - if substitution == "" { - substitution = groups["braced"] - braced = true - } - - if substitution == "" { - return "", false, &InvalidTemplateError{} - } - - if braced { - value, applied, err := subsFunc(substitution, mapping) - if err != nil { - return "", false, err - } - if applied { - interpolatedNested, err := SubstituteWith(rest, mapping, pattern) - if err != nil { - return "", false, err - } - return value + interpolatedNested, true, nil - } - } - - value, ok := mapping(substitution) - if !ok && cfg.logging { - logrus.Warnf("The %q variable is not set. Defaulting to a blank string.", substitution) - } - - return value, ok, nil -} - -// SubstituteWith substitute variables in the string with their values. -// It accepts additional substitute function. -func SubstituteWith(template string, mapping Mapping, pattern *regexp.Regexp, subsFuncs ...SubstituteFunc) (string, error) { - options := []Option{ - WithPattern(pattern), - } - if len(subsFuncs) > 0 { - options = append(options, WithSubstitutionFunction(subsFuncs[0])) - } - - return SubstituteWithOptions(template, mapping, options...) -} - -func getSubstitutionFunctionForTemplate(template string) (string, SubstituteFunc) { - interpolationMapping := []struct { - string - SubstituteFunc - }{ - {":?", requiredErrorWhenEmptyOrUnset}, - {"?", requiredErrorWhenUnset}, - {":-", defaultWhenEmptyOrUnset}, - {"-", defaultWhenUnset}, - {":+", defaultWhenNotEmpty}, - {"+", defaultWhenSet}, - } - sort.Slice(interpolationMapping, func(i, j int) bool { - idxI := strings.Index(template, interpolationMapping[i].string) - idxJ := strings.Index(template, interpolationMapping[j].string) - if idxI < 0 { - return false - } - if idxJ < 0 { - return true - } - return idxI < idxJ - }) - - return interpolationMapping[0].string, interpolationMapping[0].SubstituteFunc -} - -func getFirstBraceClosingIndex(s string) int { - openVariableBraces := 0 - for i := 0; i < len(s); i++ { - if s[i] == '}' { - openVariableBraces-- - if openVariableBraces == 0 { - return i - } - } - if strings.HasPrefix(s[i:], "${") { - openVariableBraces++ - i++ - } - } - return -1 -} - -// Substitute variables in the string with their values -func Substitute(template string, mapping Mapping) (string, error) { - return SubstituteWith(template, mapping, defaultPattern) -} - -// ExtractVariables returns a map of all the variables defined in the specified -// composefile (dict representation) and their default value if any. -func ExtractVariables(configDict map[string]interface{}, pattern *regexp.Regexp) map[string]Variable { - if pattern == nil { - pattern = defaultPattern - } - return recurseExtract(configDict, pattern) -} - -func recurseExtract(value interface{}, pattern *regexp.Regexp) map[string]Variable { - m := map[string]Variable{} - - switch value := value.(type) { - case string: - if values, is := extractVariable(value, pattern); is { - for _, v := range values { - m[v.Name] = v - } - } - case map[string]interface{}: - for _, elem := range value { - submap := recurseExtract(elem, pattern) - for key, value := range submap { - m[key] = value - } - } - - case []interface{}: - for _, elem := range value { - if values, is := extractVariable(elem, pattern); is { - for _, v := range values { - m[v.Name] = v - } - } - } - } - - return m -} - -type Variable struct { - Name string - DefaultValue string - PresenceValue string - Required bool -} - -func extractVariable(value interface{}, pattern *regexp.Regexp) ([]Variable, bool) { - sValue, ok := value.(string) - if !ok { - return []Variable{}, false - } - matches := pattern.FindAllStringSubmatch(sValue, -1) - if len(matches) == 0 { - return []Variable{}, false - } - values := []Variable{} - for _, match := range matches { - groups := matchGroups(match, pattern) - if escaped := groups["escaped"]; escaped != "" { - continue - } - val := groups["named"] - if val == "" { - val = groups["braced"] - } - name := val - var defaultValue string - var presenceValue string - var required bool - switch { - case strings.Contains(val, ":?"): - name, _ = partition(val, ":?") - required = true - case strings.Contains(val, "?"): - name, _ = partition(val, "?") - required = true - case strings.Contains(val, ":-"): - name, defaultValue = partition(val, ":-") - case strings.Contains(val, "-"): - name, defaultValue = partition(val, "-") - case strings.Contains(val, ":+"): - name, presenceValue = partition(val, ":+") - case strings.Contains(val, "+"): - name, presenceValue = partition(val, "+") - } - values = append(values, Variable{ - Name: name, - DefaultValue: defaultValue, - PresenceValue: presenceValue, - Required: required, - }) - } - return values, len(values) > 0 -} - -// Soft default (fall back if unset or empty) -func defaultWhenEmptyOrUnset(substitution string, mapping Mapping) (string, bool, error) { - return withDefaultWhenAbsence(substitution, mapping, true) -} - -// Hard default (fall back if-and-only-if empty) -func defaultWhenUnset(substitution string, mapping Mapping) (string, bool, error) { - return withDefaultWhenAbsence(substitution, mapping, false) -} - -func defaultWhenNotEmpty(substitution string, mapping Mapping) (string, bool, error) { - return withDefaultWhenPresence(substitution, mapping, true) -} - -func defaultWhenSet(substitution string, mapping Mapping) (string, bool, error) { - return withDefaultWhenPresence(substitution, mapping, false) -} - -func requiredErrorWhenEmptyOrUnset(substitution string, mapping Mapping) (string, bool, error) { - return withRequired(substitution, mapping, ":?", func(v string) bool { return v != "" }) -} - -func requiredErrorWhenUnset(substitution string, mapping Mapping) (string, bool, error) { - return withRequired(substitution, mapping, "?", func(_ string) bool { return true }) -} - -func withDefaultWhenPresence(substitution string, mapping Mapping, notEmpty bool) (string, bool, error) { - sep := "+" - if notEmpty { - sep = ":+" - } - if !strings.Contains(substitution, sep) { - return "", false, nil - } - name, defaultValue := partition(substitution, sep) - defaultValue, err := Substitute(defaultValue, mapping) - if err != nil { - return "", false, err - } - value, ok := mapping(name) - if ok && (!notEmpty || (notEmpty && value != "")) { - return defaultValue, true, nil - } - return value, true, nil -} - -func withDefaultWhenAbsence(substitution string, mapping Mapping, emptyOrUnset bool) (string, bool, error) { - sep := "-" - if emptyOrUnset { - sep = ":-" - } - if !strings.Contains(substitution, sep) { - return "", false, nil - } - name, defaultValue := partition(substitution, sep) - defaultValue, err := Substitute(defaultValue, mapping) - if err != nil { - return "", false, err - } - value, ok := mapping(name) - if !ok || (emptyOrUnset && value == "") { - return defaultValue, true, nil - } - return value, true, nil -} - -func withRequired(substitution string, mapping Mapping, sep string, valid func(string) bool) (string, bool, error) { - if !strings.Contains(substitution, sep) { - return "", false, nil - } - name, errorMessage := partition(substitution, sep) - errorMessage, err := Substitute(errorMessage, mapping) - if err != nil { - return "", false, err - } - value, ok := mapping(name) - if !ok || !valid(value) { - return "", true, &MissingRequiredError{ - Reason: errorMessage, - Variable: name, - } - } - return value, true, nil -} - -func matchGroups(matches []string, pattern *regexp.Regexp) map[string]string { - groups := make(map[string]string) - for i, name := range pattern.SubexpNames()[1:] { - groups[name] = matches[i+1] - } - return groups -} - -// Split the string at the first occurrence of sep, and return the part before the separator, -// and the part after the separator. -// -// If the separator is not found, return the string itself, followed by an empty string. -func partition(s, sep string) (string, string) { - if strings.Contains(s, sep) { - parts := strings.SplitN(s, sep, 2) - return parts[0], parts[1] - } - return s, "" -} diff --git a/vendor/github.com/compose-spec/compose-go/tree/path.go b/vendor/github.com/compose-spec/compose-go/tree/path.go deleted file mode 100644 index 59c250307..000000000 --- a/vendor/github.com/compose-spec/compose-go/tree/path.go +++ /dev/null @@ -1,67 +0,0 @@ -/* - Copyright 2020 The Compose Specification 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 tree - -import "strings" - -const pathSeparator = "." - -// PathMatchAll is a token used as part of a Path to match any key at that level -// in the nested structure -const PathMatchAll = "*" - -// PathMatchList is a token used as part of a Path to match items in a list -const PathMatchList = "[]" - -// Path is a dotted path of keys to a value in a nested mapping structure. A * -// section in a path will match any key in the mapping structure. -type Path string - -// NewPath returns a new Path -func NewPath(items ...string) Path { - return Path(strings.Join(items, pathSeparator)) -} - -// Next returns a new path by append part to the current path -func (p Path) Next(part string) Path { - if p == "" { - return Path(part) - } - return Path(string(p) + pathSeparator + part) -} - -func (p Path) Parts() []string { - return strings.Split(string(p), pathSeparator) -} - -func (p Path) Matches(pattern Path) bool { - patternParts := pattern.Parts() - parts := p.Parts() - - if len(patternParts) != len(parts) { - return false - } - for index, part := range parts { - switch patternParts[index] { - case PathMatchAll, part: - continue - default: - return false - } - } - return true -} diff --git a/vendor/github.com/compose-spec/compose-go/types/config.go b/vendor/github.com/compose-spec/compose-go/types/config.go deleted file mode 100644 index 25e6f82ee..000000000 --- a/vendor/github.com/compose-spec/compose-go/types/config.go +++ /dev/null @@ -1,135 +0,0 @@ -/* - Copyright 2020 The Compose Specification 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 types - -import ( - "encoding/json" - "runtime" - "strings" - - "github.com/mitchellh/mapstructure" -) - -var ( - // isCaseInsensitiveEnvVars is true on platforms where environment variable names are treated case-insensitively. - isCaseInsensitiveEnvVars = (runtime.GOOS == "windows") -) - -// ConfigDetails are the details about a group of ConfigFiles -type ConfigDetails struct { - Version string - WorkingDir string - ConfigFiles []ConfigFile - Environment Mapping -} - -// LookupEnv provides a lookup function for environment variables -func (cd ConfigDetails) LookupEnv(key string) (string, bool) { - v, ok := cd.Environment[key] - if !isCaseInsensitiveEnvVars || ok { - return v, ok - } - // variable names must be treated case-insensitively on some platforms (that is, Windows). - // Resolves in this way: - // * Return the value if its name matches with the passed name case-sensitively. - // * Otherwise, return the value if its lower-cased name matches lower-cased passed name. - // * The value is indefinite if multiple variables match. - lowerKey := strings.ToLower(key) - for k, v := range cd.Environment { - if strings.ToLower(k) == lowerKey { - return v, true - } - } - return "", false -} - -// ConfigFile is a filename and the contents of the file as a Dict -type ConfigFile struct { - // Filename is the name of the yaml configuration file - Filename string - // Content is the raw yaml content. Will be loaded from Filename if not set - Content []byte - // Config if the yaml tree for this config file. Will be parsed from Content if not set - Config map[string]interface{} -} - -func ToConfigFiles(path []string) (f []ConfigFile) { - for _, p := range path { - f = append(f, ConfigFile{Filename: p}) - } - return -} - -// Config is a full compose file configuration and model -type Config struct { - Filename string `yaml:"-" json:"-"` - Name string `yaml:"name,omitempty" json:"name,omitempty"` - Services Services `yaml:"services" json:"services"` - Networks Networks `yaml:"networks,omitempty" json:"networks,omitempty"` - Volumes Volumes `yaml:"volumes,omitempty" json:"volumes,omitempty"` - Secrets Secrets `yaml:"secrets,omitempty" json:"secrets,omitempty"` - Configs Configs `yaml:"configs,omitempty" json:"configs,omitempty"` - Extensions Extensions `yaml:",inline" json:"-"` - Include []IncludeConfig `yaml:"include,omitempty" json:"include,omitempty"` -} - -// Volumes is a map of VolumeConfig -type Volumes map[string]VolumeConfig - -// Networks is a map of NetworkConfig -type Networks map[string]NetworkConfig - -// Secrets is a map of SecretConfig -type Secrets map[string]SecretConfig - -// Configs is a map of ConfigObjConfig -type Configs map[string]ConfigObjConfig - -// Extensions is a map of custom extension -type Extensions map[string]interface{} - -// MarshalJSON makes Config implement json.Marshaler -func (c Config) MarshalJSON() ([]byte, error) { - m := map[string]interface{}{ - "services": c.Services, - } - - if len(c.Networks) > 0 { - m["networks"] = c.Networks - } - if len(c.Volumes) > 0 { - m["volumes"] = c.Volumes - } - if len(c.Secrets) > 0 { - m["secrets"] = c.Secrets - } - if len(c.Configs) > 0 { - m["configs"] = c.Configs - } - for k, v := range c.Extensions { - m[k] = v - } - return json.Marshal(m) -} - -func (e Extensions) Get(name string, target interface{}) (bool, error) { - if v, ok := e[name]; ok { - err := mapstructure.Decode(v, target) - return true, err - } - return false, nil -} diff --git a/vendor/github.com/compose-spec/compose-go/types/project.go b/vendor/github.com/compose-spec/compose-go/types/project.go deleted file mode 100644 index 2a82ccfb6..000000000 --- a/vendor/github.com/compose-spec/compose-go/types/project.go +++ /dev/null @@ -1,560 +0,0 @@ -/* - Copyright 2020 The Compose Specification 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 types - -import ( - "bytes" - "encoding/json" - "fmt" - "os" - "path/filepath" - "sort" - - "github.com/compose-spec/compose-go/utils" - - "github.com/compose-spec/compose-go/dotenv" - "github.com/distribution/distribution/v3/reference" - godigest "github.com/opencontainers/go-digest" - "github.com/pkg/errors" - "golang.org/x/sync/errgroup" - "gopkg.in/yaml.v3" -) - -// Project is the result of loading a set of compose files -type Project struct { - Name string `yaml:"name,omitempty" json:"name,omitempty"` - WorkingDir string `yaml:"-" json:"-"` - Services Services `yaml:"services" json:"services"` - Networks Networks `yaml:"networks,omitempty" json:"networks,omitempty"` - Volumes Volumes `yaml:"volumes,omitempty" json:"volumes,omitempty"` - Secrets Secrets `yaml:"secrets,omitempty" json:"secrets,omitempty"` - Configs Configs `yaml:"configs,omitempty" json:"configs,omitempty"` - Extensions Extensions `yaml:"#extensions,inline" json:"-"` // https://github.com/golang/go/issues/6213 - - // IncludeReferences is keyed by Compose YAML filename and contains config for - // other Compose YAML files it directly triggered a load of via `include`. - // - // Note: this is - IncludeReferences map[string][]IncludeConfig `yaml:"-" json:"-"` - ComposeFiles []string `yaml:"-" json:"-"` - Environment Mapping `yaml:"-" json:"-"` - - // DisabledServices track services which have been disable as profile is not active - DisabledServices Services `yaml:"-" json:"-"` - Profiles []string `yaml:"-" json:"-"` -} - -// ServiceNames return names for all services in this Compose config -func (p *Project) ServiceNames() []string { - var names []string - for _, s := range p.Services { - names = append(names, s.Name) - } - sort.Strings(names) - return names -} - -// VolumeNames return names for all volumes in this Compose config -func (p *Project) VolumeNames() []string { - var names []string - for k := range p.Volumes { - names = append(names, k) - } - sort.Strings(names) - return names -} - -// NetworkNames return names for all volumes in this Compose config -func (p *Project) NetworkNames() []string { - var names []string - for k := range p.Networks { - names = append(names, k) - } - sort.Strings(names) - return names -} - -// SecretNames return names for all secrets in this Compose config -func (p *Project) SecretNames() []string { - var names []string - for k := range p.Secrets { - names = append(names, k) - } - sort.Strings(names) - return names -} - -// ConfigNames return names for all configs in this Compose config -func (p *Project) ConfigNames() []string { - var names []string - for k := range p.Configs { - names = append(names, k) - } - sort.Strings(names) - return names -} - -// GetServices retrieve services by names, or return all services if no name specified -func (p *Project) GetServices(names ...string) (Services, error) { - services, servicesNotFound := p.getServicesByNames(names...) - if len(servicesNotFound) > 0 { - return services, fmt.Errorf("no such service: %s", servicesNotFound[0]) - } - return services, nil -} - -func (p *Project) getServicesByNames(names ...string) (Services, []string) { - if len(names) == 0 { - return p.Services, nil - } - services := Services{} - var servicesNotFound []string - for _, name := range names { - var serviceConfig *ServiceConfig - for _, s := range p.Services { - if s.Name == name { - serviceConfig = &s - break - } - } - if serviceConfig == nil { - servicesNotFound = append(servicesNotFound, name) - continue - } - services = append(services, *serviceConfig) - } - return services, servicesNotFound -} - -// GetDisabledService retrieve disabled service by name -func (p Project) GetDisabledService(name string) (ServiceConfig, error) { - for _, config := range p.DisabledServices { - if config.Name == name { - return config, nil - } - } - return ServiceConfig{}, fmt.Errorf("no such service: %s", name) -} - -// GetService retrieve a specific service by name -func (p *Project) GetService(name string) (ServiceConfig, error) { - services, err := p.GetServices(name) - if err != nil { - return ServiceConfig{}, err - } - if len(services) == 0 { - return ServiceConfig{}, fmt.Errorf("no such service: %s", name) - } - return services[0], nil -} - -func (p *Project) AllServices() Services { - var all Services - all = append(all, p.Services...) - all = append(all, p.DisabledServices...) - return all -} - -type ServiceFunc func(service ServiceConfig) error - -// WithServices run ServiceFunc on each service and dependencies according to DependencyPolicy -func (p *Project) WithServices(names []string, fn ServiceFunc, options ...DependencyOption) error { - if len(options) == 0 { - // backward compatibility - options = []DependencyOption{IncludeDependencies} - } - return p.withServices(names, fn, map[string]bool{}, options, map[string]ServiceDependency{}) -} - -func (p *Project) withServices(names []string, fn ServiceFunc, seen map[string]bool, options []DependencyOption, dependencies map[string]ServiceDependency) error { - services, servicesNotFound := p.getServicesByNames(names...) - if len(servicesNotFound) > 0 { - for _, serviceNotFound := range servicesNotFound { - if dependency, ok := dependencies[serviceNotFound]; !ok || dependency.Required { - return fmt.Errorf("no such service: %s", serviceNotFound) - } - } - } - for _, service := range services { - if seen[service.Name] { - continue - } - seen[service.Name] = true - var dependencies map[string]ServiceDependency - for _, policy := range options { - switch policy { - case IncludeDependents: - dependencies = utils.MapsAppend(dependencies, p.dependentsForService(service)) - case IncludeDependencies: - dependencies = utils.MapsAppend(dependencies, service.DependsOn) - case IgnoreDependencies: - // Noop - default: - return fmt.Errorf("unsupported dependency policy %d", policy) - } - } - if len(dependencies) > 0 { - err := p.withServices(utils.MapKeys(dependencies), fn, seen, options, dependencies) - if err != nil { - return err - } - } - if err := fn(service); err != nil { - return err - } - } - return nil -} - -func (p *Project) GetDependentsForService(s ServiceConfig) []string { - return utils.MapKeys(p.dependentsForService(s)) -} - -func (p *Project) dependentsForService(s ServiceConfig) map[string]ServiceDependency { - dependent := make(map[string]ServiceDependency) - for _, service := range p.Services { - for name, dependency := range service.DependsOn { - if name == s.Name { - dependent[service.Name] = dependency - } - } - } - return dependent -} - -// RelativePath resolve a relative path based project's working directory -func (p *Project) RelativePath(path string) string { - if path[0] == '~' { - home, _ := os.UserHomeDir() - path = filepath.Join(home, path[1:]) - } - if filepath.IsAbs(path) { - return path - } - return filepath.Join(p.WorkingDir, path) -} - -// HasProfile return true if service has no profile declared or has at least one profile matching -func (s ServiceConfig) HasProfile(profiles []string) bool { - if len(s.Profiles) == 0 { - return true - } - for _, p := range profiles { - for _, sp := range s.Profiles { - if sp == p { - return true - } - } - } - return false -} - -// GetProfiles retrieve the profiles implicitly enabled by explicitly targeting selected services -func (s Services) GetProfiles() []string { - set := map[string]struct{}{} - for _, service := range s { - for _, p := range service.Profiles { - set[p] = struct{}{} - } - } - var profiles []string - for k := range set { - profiles = append(profiles, k) - } - return profiles -} - -// ApplyProfiles disables service which don't match selected profiles -func (p *Project) ApplyProfiles(profiles []string) { - for _, p := range profiles { - if p == "*" { - return - } - } - var enabled, disabled Services - for _, service := range p.AllServices() { - if service.HasProfile(profiles) { - enabled = append(enabled, service) - } else { - disabled = append(disabled, service) - } - } - p.Services = enabled - p.DisabledServices = disabled - p.Profiles = profiles -} - -// EnableServices ensure services are enabled and activate profiles accordingly -func (p *Project) EnableServices(names ...string) error { - if len(names) == 0 { - return nil - } - var enabled []string - for _, name := range names { - _, err := p.GetService(name) - if err == nil { - // already enabled - continue - } - def, err := p.GetDisabledService(name) - if err != nil { - return err - } - enabled = append(enabled, def.Profiles...) - } - - profiles := p.Profiles -PROFILES: - for _, profile := range enabled { - for _, p := range profiles { - if p == profile { - continue PROFILES - } - } - profiles = append(profiles, profile) - } - p.ApplyProfiles(profiles) - - return p.ResolveServicesEnvironment(true) -} - -// WithoutUnnecessaryResources drops networks/volumes/secrets/configs that are not referenced by active services -func (p *Project) WithoutUnnecessaryResources() { - requiredNetworks := map[string]struct{}{} - requiredVolumes := map[string]struct{}{} - requiredSecrets := map[string]struct{}{} - requiredConfigs := map[string]struct{}{} - for _, s := range p.Services { - for k := range s.Networks { - requiredNetworks[k] = struct{}{} - } - for _, v := range s.Volumes { - if v.Type != VolumeTypeVolume || v.Source == "" { - continue - } - requiredVolumes[v.Source] = struct{}{} - } - for _, v := range s.Secrets { - requiredSecrets[v.Source] = struct{}{} - } - if s.Build != nil { - for _, v := range s.Build.Secrets { - requiredSecrets[v.Source] = struct{}{} - } - } - for _, v := range s.Configs { - requiredConfigs[v.Source] = struct{}{} - } - } - - networks := Networks{} - for k := range requiredNetworks { - if value, ok := p.Networks[k]; ok { - networks[k] = value - } - } - p.Networks = networks - - volumes := Volumes{} - for k := range requiredVolumes { - if value, ok := p.Volumes[k]; ok { - volumes[k] = value - } - } - p.Volumes = volumes - - secrets := Secrets{} - for k := range requiredSecrets { - if value, ok := p.Secrets[k]; ok { - secrets[k] = value - } - } - p.Secrets = secrets - - configs := Configs{} - for k := range requiredConfigs { - if value, ok := p.Configs[k]; ok { - configs[k] = value - } - } - p.Configs = configs -} - -type DependencyOption int - -const ( - IncludeDependencies = iota - IncludeDependents - IgnoreDependencies -) - -// ForServices restrict the project model to selected services and dependencies -func (p *Project) ForServices(names []string, options ...DependencyOption) error { - if len(names) == 0 { - // All services - return nil - } - - set := map[string]struct{}{} - err := p.WithServices(names, func(service ServiceConfig) error { - set[service.Name] = struct{}{} - return nil - }, options...) - if err != nil { - return err - } - - // Disable all services which are not explicit target or dependencies - var enabled Services - for _, s := range p.Services { - if _, ok := set[s.Name]; ok { - for _, option := range options { - if option == IgnoreDependencies { - s.DependsOn = nil - } - } - enabled = append(enabled, s) - } else { - p.DisableService(s) - } - } - p.Services = enabled - return nil -} - -func (p *Project) DisableService(service ServiceConfig) { - // We should remove all dependencies which reference the disabled service - for i, s := range p.Services { - if _, ok := s.DependsOn[service.Name]; ok { - delete(s.DependsOn, service.Name) - p.Services[i] = s - } - } - p.DisabledServices = append(p.DisabledServices, service) -} - -// ResolveImages updates services images to include digest computed by a resolver function -func (p *Project) ResolveImages(resolver func(named reference.Named) (godigest.Digest, error)) error { - eg := errgroup.Group{} - for i, s := range p.Services { - idx := i - service := s - - if service.Image == "" { - continue - } - eg.Go(func() error { - named, err := reference.ParseDockerRef(service.Image) - if err != nil { - return err - } - - if _, ok := named.(reference.Canonical); !ok { - // image is named but not digested reference - digest, err := resolver(named) - if err != nil { - return err - } - named, err = reference.WithDigest(named, digest) - if err != nil { - return err - } - } - - service.Image = named.String() - p.Services[idx] = service - return nil - }) - } - return eg.Wait() -} - -// MarshalYAML marshal Project into a yaml tree -func (p *Project) MarshalYAML() ([]byte, error) { - buf := bytes.NewBuffer([]byte{}) - encoder := yaml.NewEncoder(buf) - encoder.SetIndent(2) - // encoder.CompactSeqIndent() FIXME https://github.com/go-yaml/yaml/pull/753 - err := encoder.Encode(p) - if err != nil { - return nil, err - } - return buf.Bytes(), nil -} - -// MarshalJSON makes Config implement json.Marshaler -func (p *Project) MarshalJSON() ([]byte, error) { - m := map[string]interface{}{ - "name": p.Name, - "services": p.Services, - } - - if len(p.Networks) > 0 { - m["networks"] = p.Networks - } - if len(p.Volumes) > 0 { - m["volumes"] = p.Volumes - } - if len(p.Secrets) > 0 { - m["secrets"] = p.Secrets - } - if len(p.Configs) > 0 { - m["configs"] = p.Configs - } - for k, v := range p.Extensions { - m[k] = v - } - return json.Marshal(m) -} - -// ResolveServicesEnvironment parse env_files set for services to resolve the actual environment map for services -func (p Project) ResolveServicesEnvironment(discardEnvFiles bool) error { - for i, service := range p.Services { - service.Environment = service.Environment.Resolve(p.Environment.Resolve) - - environment := MappingWithEquals{} - // resolve variables based on other files we already parsed, + project's environment - var resolve dotenv.LookupFn = func(s string) (string, bool) { - v, ok := environment[s] - if ok && v != nil { - return *v, ok - } - return p.Environment.Resolve(s) - } - - for _, envFile := range service.EnvFile { - b, err := os.ReadFile(envFile) - if err != nil { - return errors.Wrapf(err, "Failed to load %s", envFile) - } - - fileVars, err := dotenv.ParseWithLookup(bytes.NewBuffer(b), resolve) - if err != nil { - return errors.Wrapf(err, "failed to read %s", envFile) - } - environment.OverrideBy(Mapping(fileVars).ToMappingWithEquals()) - } - - service.Environment = environment.OverrideBy(service.Environment) - - if discardEnvFiles { - service.EnvFile = nil - } - p.Services[i] = service - } - return nil -} diff --git a/vendor/github.com/compose-spec/compose-go/types/types.go b/vendor/github.com/compose-spec/compose-go/types/types.go deleted file mode 100644 index 5864dc004..000000000 --- a/vendor/github.com/compose-spec/compose-go/types/types.go +++ /dev/null @@ -1,1076 +0,0 @@ -/* - Copyright 2020 The Compose Specification 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 types - -import ( - "encoding/json" - "fmt" - "sort" - "strings" - "time" - - "github.com/docker/go-connections/nat" -) - -// Duration is a thin wrapper around time.Duration with improved JSON marshalling -type Duration time.Duration - -func (d Duration) String() string { - return time.Duration(d).String() -} - -// ConvertDurationPtr converts a type defined Duration pointer to a time.Duration pointer with the same value. -func ConvertDurationPtr(d *Duration) *time.Duration { - if d == nil { - return nil - } - res := time.Duration(*d) - return &res -} - -// MarshalJSON makes Duration implement json.Marshaler -func (d Duration) MarshalJSON() ([]byte, error) { - return json.Marshal(d.String()) -} - -// MarshalYAML makes Duration implement yaml.Marshaler -func (d Duration) MarshalYAML() (interface{}, error) { - return d.String(), nil -} - -func (d *Duration) UnmarshalJSON(b []byte) error { - s := strings.Trim(string(b), "\"") - timeDuration, err := time.ParseDuration(s) - if err != nil { - return err - } - *d = Duration(timeDuration) - return nil -} - -// Services is a list of ServiceConfig -type Services []ServiceConfig - -// MarshalYAML makes Services implement yaml.Marshaller -func (s Services) MarshalYAML() (interface{}, error) { - services := map[string]ServiceConfig{} - for _, service := range s { - services[service.Name] = service - } - return services, nil -} - -// MarshalJSON makes Services implement json.Marshaler -func (s Services) MarshalJSON() ([]byte, error) { - data, err := s.MarshalYAML() - if err != nil { - return nil, err - } - return json.MarshalIndent(data, "", " ") -} - -// ServiceConfig is the configuration of one service -type ServiceConfig struct { - Name string `yaml:"-" json:"-"` - Profiles []string `yaml:"profiles,omitempty" json:"profiles,omitempty"` - - Annotations Mapping `yaml:"annotations,omitempty" json:"annotations,omitempty"` - Attach *bool `yaml:"attach,omitempty" json:"attach,omitempty"` - Build *BuildConfig `yaml:"build,omitempty" json:"build,omitempty"` - BlkioConfig *BlkioConfig `yaml:"blkio_config,omitempty" json:"blkio_config,omitempty"` - CapAdd []string `yaml:"cap_add,omitempty" json:"cap_add,omitempty"` - CapDrop []string `yaml:"cap_drop,omitempty" json:"cap_drop,omitempty"` - CgroupParent string `yaml:"cgroup_parent,omitempty" json:"cgroup_parent,omitempty"` - Cgroup string `yaml:"cgroup,omitempty" json:"cgroup,omitempty"` - CPUCount int64 `yaml:"cpu_count,omitempty" json:"cpu_count,omitempty"` - CPUPercent float32 `yaml:"cpu_percent,omitempty" json:"cpu_percent,omitempty"` - CPUPeriod int64 `yaml:"cpu_period,omitempty" json:"cpu_period,omitempty"` - CPUQuota int64 `yaml:"cpu_quota,omitempty" json:"cpu_quota,omitempty"` - CPURTPeriod int64 `yaml:"cpu_rt_period,omitempty" json:"cpu_rt_period,omitempty"` - CPURTRuntime int64 `yaml:"cpu_rt_runtime,omitempty" json:"cpu_rt_runtime,omitempty"` - CPUS float32 `yaml:"cpus,omitempty" json:"cpus,omitempty"` - CPUSet string `yaml:"cpuset,omitempty" json:"cpuset,omitempty"` - CPUShares int64 `yaml:"cpu_shares,omitempty" json:"cpu_shares,omitempty"` - - // Command for the service containers. - // If set, overrides COMMAND from the image. - // - // Set to `[]` or an empty string to clear the command from the image. - Command ShellCommand `yaml:"command,omitempty" json:"command"` // NOTE: we can NOT omitempty for JSON! see ShellCommand type for details. - - Configs []ServiceConfigObjConfig `yaml:"configs,omitempty" json:"configs,omitempty"` - ContainerName string `yaml:"container_name,omitempty" json:"container_name,omitempty"` - CredentialSpec *CredentialSpecConfig `yaml:"credential_spec,omitempty" json:"credential_spec,omitempty"` - DependsOn DependsOnConfig `yaml:"depends_on,omitempty" json:"depends_on,omitempty"` - Deploy *DeployConfig `yaml:"deploy,omitempty" json:"deploy,omitempty"` - DeviceCgroupRules []string `yaml:"device_cgroup_rules,omitempty" json:"device_cgroup_rules,omitempty"` - Devices []string `yaml:"devices,omitempty" json:"devices,omitempty"` - DNS StringList `yaml:"dns,omitempty" json:"dns,omitempty"` - DNSOpts []string `yaml:"dns_opt,omitempty" json:"dns_opt,omitempty"` - DNSSearch StringList `yaml:"dns_search,omitempty" json:"dns_search,omitempty"` - Dockerfile string `yaml:"dockerfile,omitempty" json:"dockerfile,omitempty"` - DomainName string `yaml:"domainname,omitempty" json:"domainname,omitempty"` - - // Entrypoint for the service containers. - // If set, overrides ENTRYPOINT from the image. - // - // Set to `[]` or an empty string to clear the entrypoint from the image. - Entrypoint ShellCommand `yaml:"entrypoint,omitempty" json:"entrypoint"` // NOTE: we can NOT omitempty for JSON! see ShellCommand type for details. - - Environment MappingWithEquals `yaml:"environment,omitempty" json:"environment,omitempty"` - EnvFile StringList `yaml:"env_file,omitempty" json:"env_file,omitempty"` - Expose StringOrNumberList `yaml:"expose,omitempty" json:"expose,omitempty"` - Extends *ExtendsConfig `yaml:"extends,omitempty" json:"extends,omitempty"` - ExternalLinks []string `yaml:"external_links,omitempty" json:"external_links,omitempty"` - ExtraHosts HostsList `yaml:"extra_hosts,omitempty" json:"extra_hosts,omitempty"` - GroupAdd []string `yaml:"group_add,omitempty" json:"group_add,omitempty"` - Hostname string `yaml:"hostname,omitempty" json:"hostname,omitempty"` - HealthCheck *HealthCheckConfig `yaml:"healthcheck,omitempty" json:"healthcheck,omitempty"` - Image string `yaml:"image,omitempty" json:"image,omitempty"` - Init *bool `yaml:"init,omitempty" json:"init,omitempty"` - Ipc string `yaml:"ipc,omitempty" json:"ipc,omitempty"` - Isolation string `yaml:"isolation,omitempty" json:"isolation,omitempty"` - Labels Labels `yaml:"labels,omitempty" json:"labels,omitempty"` - CustomLabels Labels `yaml:"-" json:"-"` - Links []string `yaml:"links,omitempty" json:"links,omitempty"` - Logging *LoggingConfig `yaml:"logging,omitempty" json:"logging,omitempty"` - LogDriver string `yaml:"log_driver,omitempty" json:"log_driver,omitempty"` - LogOpt map[string]string `yaml:"log_opt,omitempty" json:"log_opt,omitempty"` - MemLimit UnitBytes `yaml:"mem_limit,omitempty" json:"mem_limit,omitempty"` - MemReservation UnitBytes `yaml:"mem_reservation,omitempty" json:"mem_reservation,omitempty"` - MemSwapLimit UnitBytes `yaml:"memswap_limit,omitempty" json:"memswap_limit,omitempty"` - MemSwappiness UnitBytes `yaml:"mem_swappiness,omitempty" json:"mem_swappiness,omitempty"` - MacAddress string `yaml:"mac_address,omitempty" json:"mac_address,omitempty"` - Net string `yaml:"net,omitempty" json:"net,omitempty"` - NetworkMode string `yaml:"network_mode,omitempty" json:"network_mode,omitempty"` - Networks map[string]*ServiceNetworkConfig `yaml:"networks,omitempty" json:"networks,omitempty"` - OomKillDisable bool `yaml:"oom_kill_disable,omitempty" json:"oom_kill_disable,omitempty"` - OomScoreAdj int64 `yaml:"oom_score_adj,omitempty" json:"oom_score_adj,omitempty"` - Pid string `yaml:"pid,omitempty" json:"pid,omitempty"` - PidsLimit int64 `yaml:"pids_limit,omitempty" json:"pids_limit,omitempty"` - Platform string `yaml:"platform,omitempty" json:"platform,omitempty"` - Ports []ServicePortConfig `yaml:"ports,omitempty" json:"ports,omitempty"` - Privileged bool `yaml:"privileged,omitempty" json:"privileged,omitempty"` - PullPolicy string `yaml:"pull_policy,omitempty" json:"pull_policy,omitempty"` - ReadOnly bool `yaml:"read_only,omitempty" json:"read_only,omitempty"` - Restart string `yaml:"restart,omitempty" json:"restart,omitempty"` - Runtime string `yaml:"runtime,omitempty" json:"runtime,omitempty"` - Scale int `yaml:"scale,omitempty" json:"scale,omitempty"` - Secrets []ServiceSecretConfig `yaml:"secrets,omitempty" json:"secrets,omitempty"` - SecurityOpt []string `yaml:"security_opt,omitempty" json:"security_opt,omitempty"` - ShmSize UnitBytes `yaml:"shm_size,omitempty" json:"shm_size,omitempty"` - StdinOpen bool `yaml:"stdin_open,omitempty" json:"stdin_open,omitempty"` - StopGracePeriod *Duration `yaml:"stop_grace_period,omitempty" json:"stop_grace_period,omitempty"` - StopSignal string `yaml:"stop_signal,omitempty" json:"stop_signal,omitempty"` - Sysctls Mapping `yaml:"sysctls,omitempty" json:"sysctls,omitempty"` - Tmpfs StringList `yaml:"tmpfs,omitempty" json:"tmpfs,omitempty"` - Tty bool `yaml:"tty,omitempty" json:"tty,omitempty"` - Ulimits map[string]*UlimitsConfig `yaml:"ulimits,omitempty" json:"ulimits,omitempty"` - User string `yaml:"user,omitempty" json:"user,omitempty"` - UserNSMode string `yaml:"userns_mode,omitempty" json:"userns_mode,omitempty"` - Uts string `yaml:"uts,omitempty" json:"uts,omitempty"` - VolumeDriver string `yaml:"volume_driver,omitempty" json:"volume_driver,omitempty"` - Volumes []ServiceVolumeConfig `yaml:"volumes,omitempty" json:"volumes,omitempty"` - VolumesFrom []string `yaml:"volumes_from,omitempty" json:"volumes_from,omitempty"` - WorkingDir string `yaml:"working_dir,omitempty" json:"working_dir,omitempty"` - - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// MarshalYAML makes ServiceConfig implement yaml.Marshaller -func (s ServiceConfig) MarshalYAML() (interface{}, error) { - type t ServiceConfig - value := t(s) - value.Scale = 0 // deprecated, but default value "1" doesn't match omitempty - return value, nil -} - -// MarshalJSON makes SSHKey implement json.Marshaller -func (s ServiceConfig) MarshalJSON() ([]byte, error) { - type t ServiceConfig - value := t(s) - value.Scale = 0 // deprecated, but default value "1" doesn't match omitempty - return json.Marshal(value) -} - -// NetworksByPriority return the service networks IDs sorted according to Priority -func (s *ServiceConfig) NetworksByPriority() []string { - type key struct { - name string - priority int - } - var keys []key - for k, v := range s.Networks { - priority := 0 - if v != nil { - priority = v.Priority - } - keys = append(keys, key{ - name: k, - priority: priority, - }) - } - sort.Slice(keys, func(i, j int) bool { - return keys[i].priority > keys[j].priority - }) - var sorted []string - for _, k := range keys { - sorted = append(sorted, k.name) - } - return sorted -} - -const ( - // PullPolicyAlways always pull images - PullPolicyAlways = "always" - // PullPolicyNever never pull images - PullPolicyNever = "never" - // PullPolicyIfNotPresent pull missing images - PullPolicyIfNotPresent = "if_not_present" - // PullPolicyMissing pull missing images - PullPolicyMissing = "missing" - // PullPolicyBuild force building images - PullPolicyBuild = "build" -) - -const ( - // RestartPolicyAlways always restart the container if it stops - RestartPolicyAlways = "always" - // RestartPolicyOnFailure restart the container if it exits due to an error - RestartPolicyOnFailure = "on-failure" - // RestartPolicyNo do not automatically restart the container - RestartPolicyNo = "no" - // RestartPolicyUnlessStopped always restart the container unless the container is stopped (manually or otherwise) - RestartPolicyUnlessStopped = "unless-stopped" -) - -const ( - // ServicePrefix is the prefix for references pointing to a service - ServicePrefix = "service:" - // ContainerPrefix is the prefix for references pointing to a container - ContainerPrefix = "container:" - - // NetworkModeServicePrefix is the prefix for network_mode pointing to a service - // Deprecated prefer ServicePrefix - NetworkModeServicePrefix = ServicePrefix - // NetworkModeContainerPrefix is the prefix for network_mode pointing to a container - // Deprecated prefer ContainerPrefix - NetworkModeContainerPrefix = ContainerPrefix -) - -// GetDependencies retrieves all services this service depends on -func (s ServiceConfig) GetDependencies() []string { - var dependencies []string - for service := range s.DependsOn { - dependencies = append(dependencies, service) - } - return dependencies -} - -// GetDependents retrieves all services which depend on this service -func (s ServiceConfig) GetDependents(p *Project) []string { - var dependent []string - for _, service := range p.Services { - for name := range service.DependsOn { - if name == s.Name { - dependent = append(dependent, service.Name) - } - } - } - return dependent -} - -type set map[string]struct{} - -func (s set) append(strs ...string) { - for _, str := range strs { - s[str] = struct{}{} - } -} - -func (s set) toSlice() []string { - slice := make([]string, 0, len(s)) - for v := range s { - slice = append(slice, v) - } - return slice -} - -// BuildConfig is a type for build -type BuildConfig struct { - Context string `yaml:"context,omitempty" json:"context,omitempty"` - Dockerfile string `yaml:"dockerfile,omitempty" json:"dockerfile,omitempty"` - DockerfileInline string `yaml:"dockerfile_inline,omitempty" json:"dockerfile_inline,omitempty"` - Args MappingWithEquals `yaml:"args,omitempty" json:"args,omitempty"` - SSH SSHConfig `yaml:"ssh,omitempty" json:"ssh,omitempty"` - Labels Labels `yaml:"labels,omitempty" json:"labels,omitempty"` - CacheFrom StringList `yaml:"cache_from,omitempty" json:"cache_from,omitempty"` - CacheTo StringList `yaml:"cache_to,omitempty" json:"cache_to,omitempty"` - NoCache bool `yaml:"no_cache,omitempty" json:"no_cache,omitempty"` - AdditionalContexts Mapping `yaml:"additional_contexts,omitempty" json:"additional_contexts,omitempty"` - Pull bool `yaml:"pull,omitempty" json:"pull,omitempty"` - ExtraHosts HostsList `yaml:"extra_hosts,omitempty" json:"extra_hosts,omitempty"` - Isolation string `yaml:"isolation,omitempty" json:"isolation,omitempty"` - Network string `yaml:"network,omitempty" json:"network,omitempty"` - Target string `yaml:"target,omitempty" json:"target,omitempty"` - Secrets []ServiceSecretConfig `yaml:"secrets,omitempty" json:"secrets,omitempty"` - Tags StringList `yaml:"tags,omitempty" json:"tags,omitempty"` - Platforms StringList `yaml:"platforms,omitempty" json:"platforms,omitempty"` - Privileged bool `yaml:"privileged,omitempty" json:"privileged,omitempty"` - - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// BlkioConfig define blkio config -type BlkioConfig struct { - Weight uint16 `yaml:"weight,omitempty" json:"weight,omitempty"` - WeightDevice []WeightDevice `yaml:"weight_device,omitempty" json:"weight_device,omitempty"` - DeviceReadBps []ThrottleDevice `yaml:"device_read_bps,omitempty" json:"device_read_bps,omitempty"` - DeviceReadIOps []ThrottleDevice `yaml:"device_read_iops,omitempty" json:"device_read_iops,omitempty"` - DeviceWriteBps []ThrottleDevice `yaml:"device_write_bps,omitempty" json:"device_write_bps,omitempty"` - DeviceWriteIOps []ThrottleDevice `yaml:"device_write_iops,omitempty" json:"device_write_iops,omitempty"` - - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// WeightDevice is a structure that holds device:weight pair -type WeightDevice struct { - Path string - Weight uint16 - - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// ThrottleDevice is a structure that holds device:rate_per_second pair -type ThrottleDevice struct { - Path string - Rate UnitBytes - - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// ShellCommand is a string or list of string args. -// -// When marshaled to YAML, nil command fields will be omitted if `omitempty` -// is specified as a struct tag. Explicitly empty commands (i.e. `[]` or -// empty string will serialize to an empty array (`[]`). -// -// When marshaled to JSON, the `omitempty` struct must NOT be specified. -// If the command field is nil, it will be serialized as `null`. -// Explicitly empty commands (i.e. `[]` or empty string) will serialize to -// an empty array (`[]`). -// -// The distinction between nil and explicitly empty is important to distinguish -// between an unset value and a provided, but empty, value, which should be -// preserved so that it can override any base value (e.g. container entrypoint). -// -// The different semantics between YAML and JSON are due to limitations with -// JSON marshaling + `omitempty` in the Go stdlib, while gopkg.in/yaml.v3 gives -// us more flexibility via the yaml.IsZeroer interface. -// -// In the future, it might make sense to make fields of this type be -// `*ShellCommand` to avoid this situation, but that would constitute a -// breaking change. -type ShellCommand []string - -// IsZero returns true if the slice is nil. -// -// Empty (but non-nil) slices are NOT considered zero values. -func (s ShellCommand) IsZero() bool { - // we do NOT want len(s) == 0, ONLY explicitly nil - return s == nil -} - -// MarshalYAML returns nil (which will be serialized as `null`) for nil slices -// and delegates to the standard marshaller behavior otherwise. -// -// NOTE: Typically the nil case here is not hit because IsZero has already -// short-circuited marshalling, but this ensures that the type serializes -// accurately if the `omitempty` struct tag is omitted/forgotten. -// -// A similar MarshalJSON() implementation is not needed because the Go stdlib -// already serializes nil slices to `null`, whereas gopkg.in/yaml.v3 by default -// serializes nil slices to `[]`. -func (s ShellCommand) MarshalYAML() (interface{}, error) { - if s == nil { - return nil, nil - } - return []string(s), nil -} - -// StringList is a type for fields that can be a string or list of strings -type StringList []string - -// StringOrNumberList is a type for fields that can be a list of strings or -// numbers -type StringOrNumberList []string - -// MappingWithEquals is a mapping type that can be converted from a list of -// key[=value] strings. -// For the key with an empty value (`key=`), the mapped value is set to a pointer to `""`. -// For the key without value (`key`), the mapped value is set to nil. -type MappingWithEquals map[string]*string - -// NewMappingWithEquals build a new Mapping from a set of KEY=VALUE strings -func NewMappingWithEquals(values []string) MappingWithEquals { - mapping := MappingWithEquals{} - for _, env := range values { - tokens := strings.SplitN(env, "=", 2) - if len(tokens) > 1 { - mapping[tokens[0]] = &tokens[1] - } else { - mapping[env] = nil - } - } - return mapping -} - -// OverrideBy update MappingWithEquals with values from another MappingWithEquals -func (e MappingWithEquals) OverrideBy(other MappingWithEquals) MappingWithEquals { - for k, v := range other { - e[k] = v - } - return e -} - -// Resolve update a MappingWithEquals for keys without value (`key`, but not `key=`) -func (e MappingWithEquals) Resolve(lookupFn func(string) (string, bool)) MappingWithEquals { - for k, v := range e { - if v == nil { - if value, ok := lookupFn(k); ok { - e[k] = &value - } - } - } - return e -} - -// RemoveEmpty excludes keys that are not associated with a value -func (e MappingWithEquals) RemoveEmpty() MappingWithEquals { - for k, v := range e { - if v == nil { - delete(e, k) - } - } - return e -} - -// Mapping is a mapping type that can be converted from a list of -// key[=value] strings. -// For the key with an empty value (`key=`), or key without value (`key`), the -// mapped value is set to an empty string `""`. -type Mapping map[string]string - -// NewMapping build a new Mapping from a set of KEY=VALUE strings -func NewMapping(values []string) Mapping { - mapping := Mapping{} - for _, value := range values { - parts := strings.SplitN(value, "=", 2) - key := parts[0] - switch { - case len(parts) == 1: - mapping[key] = "" - default: - mapping[key] = parts[1] - } - } - return mapping -} - -// convert values into a set of KEY=VALUE strings -func (m Mapping) Values() []string { - values := make([]string, 0, len(m)) - for k, v := range m { - values = append(values, fmt.Sprintf("%s=%s", k, v)) - } - sort.Strings(values) - return values -} - -// ToMappingWithEquals converts Mapping into a MappingWithEquals with pointer references -func (m Mapping) ToMappingWithEquals() MappingWithEquals { - mapping := MappingWithEquals{} - for k, v := range m { - v := v - mapping[k] = &v - } - return mapping -} - -func (m Mapping) Resolve(s string) (string, bool) { - v, ok := m[s] - return v, ok -} - -func (m Mapping) Clone() Mapping { - clone := Mapping{} - for k, v := range m { - clone[k] = v - } - return clone -} - -// Merge adds all values from second mapping which are not already defined -func (m Mapping) Merge(o Mapping) Mapping { - for k, v := range o { - if _, set := m[k]; !set { - m[k] = v - } - } - return m -} - -// Labels is a mapping type for labels -type Labels map[string]string - -func (l Labels) Add(key, value string) Labels { - if l == nil { - l = Labels{} - } - l[key] = value - return l -} - -type SSHKey struct { - ID string - Path string -} - -// SSHConfig is a mapping type for SSH build config -type SSHConfig []SSHKey - -func (s SSHConfig) Get(id string) (string, error) { - for _, sshKey := range s { - if sshKey.ID == id { - return sshKey.Path, nil - } - } - return "", fmt.Errorf("ID %s not found in SSH keys", id) -} - -// MarshalYAML makes SSHKey implement yaml.Marshaller -func (s SSHKey) MarshalYAML() (interface{}, error) { - if s.Path == "" { - return s.ID, nil - } - return fmt.Sprintf("%s: %s", s.ID, s.Path), nil -} - -// MarshalJSON makes SSHKey implement json.Marshaller -func (s SSHKey) MarshalJSON() ([]byte, error) { - if s.Path == "" { - return []byte(fmt.Sprintf(`%q`, s.ID)), nil - } - return []byte(fmt.Sprintf(`%q: %s`, s.ID, s.Path)), nil -} - -// MappingWithColon is a mapping type that can be converted from a list of -// 'key: value' strings -type MappingWithColon map[string]string - -// HostsList is a list of colon-separated host-ip mappings -type HostsList map[string]string - -// AsList return host-ip mappings as a list of colon-separated strings -func (h HostsList) AsList() []string { - l := make([]string, 0, len(h)) - for k, v := range h { - l = append(l, fmt.Sprintf("%s:%s", k, v)) - } - return l -} - -func (h HostsList) MarshalYAML() (interface{}, error) { - list := h.AsList() - sort.Strings(list) - return list, nil -} - -func (h HostsList) MarshalJSON() ([]byte, error) { - list := h.AsList() - sort.Strings(list) - return json.Marshal(list) -} - -// LoggingConfig the logging configuration for a service -type LoggingConfig struct { - Driver string `yaml:"driver,omitempty" json:"driver,omitempty"` - Options map[string]string `yaml:"options,omitempty" json:"options,omitempty"` - - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// DeployConfig the deployment configuration for a service -type DeployConfig struct { - Mode string `yaml:"mode,omitempty" json:"mode,omitempty"` - Replicas *uint64 `yaml:"replicas,omitempty" json:"replicas,omitempty"` - Labels Labels `yaml:"labels,omitempty" json:"labels,omitempty"` - UpdateConfig *UpdateConfig `yaml:"update_config,omitempty" json:"update_config,omitempty"` - RollbackConfig *UpdateConfig `yaml:"rollback_config,omitempty" json:"rollback_config,omitempty"` - Resources Resources `yaml:"resources,omitempty" json:"resources,omitempty"` - RestartPolicy *RestartPolicy `yaml:"restart_policy,omitempty" json:"restart_policy,omitempty"` - Placement Placement `yaml:"placement,omitempty" json:"placement,omitempty"` - EndpointMode string `yaml:"endpoint_mode,omitempty" json:"endpoint_mode,omitempty"` - - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// HealthCheckConfig the healthcheck configuration for a service -type HealthCheckConfig struct { - Test HealthCheckTest `yaml:"test,omitempty" json:"test,omitempty"` - Timeout *Duration `yaml:"timeout,omitempty" json:"timeout,omitempty"` - Interval *Duration `yaml:"interval,omitempty" json:"interval,omitempty"` - Retries *uint64 `yaml:"retries,omitempty" json:"retries,omitempty"` - StartPeriod *Duration `yaml:"start_period,omitempty" json:"start_period,omitempty"` - StartInterval *Duration `yaml:"start_interval,omitempty" json:"start_interval,omitempty"` - Disable bool `yaml:"disable,omitempty" json:"disable,omitempty"` - - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// HealthCheckTest is the command run to test the health of a service -type HealthCheckTest []string - -// UpdateConfig the service update configuration -type UpdateConfig struct { - Parallelism *uint64 `yaml:"parallelism,omitempty" json:"parallelism,omitempty"` - Delay Duration `yaml:"delay,omitempty" json:"delay,omitempty"` - FailureAction string `yaml:"failure_action,omitempty" json:"failure_action,omitempty"` - Monitor Duration `yaml:"monitor,omitempty" json:"monitor,omitempty"` - MaxFailureRatio float32 `yaml:"max_failure_ratio,omitempty" json:"max_failure_ratio,omitempty"` - Order string `yaml:"order,omitempty" json:"order,omitempty"` - - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// Resources the resource limits and reservations -type Resources struct { - Limits *Resource `yaml:"limits,omitempty" json:"limits,omitempty"` - Reservations *Resource `yaml:"reservations,omitempty" json:"reservations,omitempty"` - - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// Resource is a resource to be limited or reserved -type Resource struct { - // TODO: types to convert from units and ratios - NanoCPUs string `yaml:"cpus,omitempty" json:"cpus,omitempty"` - MemoryBytes UnitBytes `yaml:"memory,omitempty" json:"memory,omitempty"` - Pids int64 `yaml:"pids,omitempty" json:"pids,omitempty"` - Devices []DeviceRequest `yaml:"devices,omitempty" json:"devices,omitempty"` - GenericResources []GenericResource `yaml:"generic_resources,omitempty" json:"generic_resources,omitempty"` - - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -type DeviceRequest struct { - Capabilities []string `yaml:"capabilities,omitempty" json:"capabilities,omitempty"` - Driver string `yaml:"driver,omitempty" json:"driver,omitempty"` - Count int64 `yaml:"count,omitempty" json:"count,omitempty"` - IDs []string `yaml:"device_ids,omitempty" json:"device_ids,omitempty"` -} - -// GenericResource represents a "user defined" resource which can -// only be an integer (e.g: SSD=3) for a service -type GenericResource struct { - DiscreteResourceSpec *DiscreteGenericResource `yaml:"discrete_resource_spec,omitempty" json:"discrete_resource_spec,omitempty"` - - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// DiscreteGenericResource represents a "user defined" resource which is defined -// as an integer -// "Kind" is used to describe the Kind of a resource (e.g: "GPU", "FPGA", "SSD", ...) -// Value is used to count the resource (SSD=5, HDD=3, ...) -type DiscreteGenericResource struct { - Kind string `json:"kind"` - Value int64 `json:"value"` - - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// UnitBytes is the bytes type -type UnitBytes int64 - -// MarshalYAML makes UnitBytes implement yaml.Marshaller -func (u UnitBytes) MarshalYAML() (interface{}, error) { - return fmt.Sprintf("%d", u), nil -} - -// MarshalJSON makes UnitBytes implement json.Marshaler -func (u UnitBytes) MarshalJSON() ([]byte, error) { - return []byte(fmt.Sprintf(`"%d"`, u)), nil -} - -// RestartPolicy the service restart policy -type RestartPolicy struct { - Condition string `yaml:"condition,omitempty" json:"condition,omitempty"` - Delay *Duration `yaml:"delay,omitempty" json:"delay,omitempty"` - MaxAttempts *uint64 `yaml:"max_attempts,omitempty" json:"max_attempts,omitempty"` - Window *Duration `yaml:"window,omitempty" json:"window,omitempty"` - - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// Placement constraints for the service -type Placement struct { - Constraints []string `yaml:"constraints,omitempty" json:"constraints,omitempty"` - Preferences []PlacementPreferences `yaml:"preferences,omitempty" json:"preferences,omitempty"` - MaxReplicas uint64 `yaml:"max_replicas_per_node,omitempty" json:"max_replicas_per_node,omitempty"` - - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// PlacementPreferences is the preferences for a service placement -type PlacementPreferences struct { - Spread string `yaml:"spread,omitempty" json:"spread,omitempty"` - - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// ServiceNetworkConfig is the network configuration for a service -type ServiceNetworkConfig struct { - Priority int `yaml:"priority,omitempty" json:"priority,omitempty"` - Aliases []string `yaml:"aliases,omitempty" json:"aliases,omitempty"` - Ipv4Address string `yaml:"ipv4_address,omitempty" json:"ipv4_address,omitempty"` - Ipv6Address string `yaml:"ipv6_address,omitempty" json:"ipv6_address,omitempty"` - LinkLocalIPs []string `yaml:"link_local_ips,omitempty" json:"link_local_ips,omitempty"` - - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// ServicePortConfig is the port configuration for a service -type ServicePortConfig struct { - Mode string `yaml:"mode,omitempty" json:"mode,omitempty"` - HostIP string `yaml:"host_ip,omitempty" json:"host_ip,omitempty"` - Target uint32 `yaml:"target,omitempty" json:"target,omitempty"` - Published string `yaml:"published,omitempty" json:"published,omitempty"` - Protocol string `yaml:"protocol,omitempty" json:"protocol,omitempty"` - - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// ParsePortConfig parse short syntax for service port configuration -func ParsePortConfig(value string) ([]ServicePortConfig, error) { - var portConfigs []ServicePortConfig - ports, portBindings, err := nat.ParsePortSpecs([]string{value}) - if err != nil { - return nil, err - } - // We need to sort the key of the ports to make sure it is consistent - keys := []string{} - for port := range ports { - keys = append(keys, string(port)) - } - sort.Strings(keys) - - for _, key := range keys { - port := nat.Port(key) - converted, err := convertPortToPortConfig(port, portBindings) - if err != nil { - return nil, err - } - portConfigs = append(portConfigs, converted...) - } - return portConfigs, nil -} - -func convertPortToPortConfig(port nat.Port, portBindings map[nat.Port][]nat.PortBinding) ([]ServicePortConfig, error) { - var portConfigs []ServicePortConfig - for _, binding := range portBindings[port] { - portConfigs = append(portConfigs, ServicePortConfig{ - HostIP: binding.HostIP, - Protocol: strings.ToLower(port.Proto()), - Target: uint32(port.Int()), - Published: binding.HostPort, - Mode: "ingress", - }) - } - return portConfigs, nil -} - -// ServiceVolumeConfig are references to a volume used by a service -type ServiceVolumeConfig struct { - Type string `yaml:"type,omitempty" json:"type,omitempty"` - Source string `yaml:"source,omitempty" json:"source,omitempty"` - Target string `yaml:"target,omitempty" json:"target,omitempty"` - ReadOnly bool `yaml:"read_only,omitempty" json:"read_only,omitempty"` - Consistency string `yaml:"consistency,omitempty" json:"consistency,omitempty"` - Bind *ServiceVolumeBind `yaml:"bind,omitempty" json:"bind,omitempty"` - Volume *ServiceVolumeVolume `yaml:"volume,omitempty" json:"volume,omitempty"` - Tmpfs *ServiceVolumeTmpfs `yaml:"tmpfs,omitempty" json:"tmpfs,omitempty"` - - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// String render ServiceVolumeConfig as a volume string, one can parse back using loader.ParseVolume -func (s ServiceVolumeConfig) String() string { - access := "rw" - if s.ReadOnly { - access = "ro" - } - options := []string{access} - if s.Bind != nil && s.Bind.SELinux != "" { - options = append(options, s.Bind.SELinux) - } - if s.Bind != nil && s.Bind.Propagation != "" { - options = append(options, s.Bind.Propagation) - } - if s.Volume != nil && s.Volume.NoCopy { - options = append(options, "nocopy") - } - return fmt.Sprintf("%s:%s:%s", s.Source, s.Target, strings.Join(options, ",")) -} - -const ( - // VolumeTypeBind is the type for mounting host dir - VolumeTypeBind = "bind" - // VolumeTypeVolume is the type for remote storage volumes - VolumeTypeVolume = "volume" - // VolumeTypeTmpfs is the type for mounting tmpfs - VolumeTypeTmpfs = "tmpfs" - // VolumeTypeNamedPipe is the type for mounting Windows named pipes - VolumeTypeNamedPipe = "npipe" - // VolumeTypeCluster is the type for mounting container storage interface (CSI) volumes - VolumeTypeCluster = "cluster" - - // SElinuxShared share the volume content - SElinuxShared = "z" - // SElinuxUnshared label content as private unshared - SElinuxUnshared = "Z" -) - -// ServiceVolumeBind are options for a service volume of type bind -type ServiceVolumeBind struct { - SELinux string `yaml:"selinux,omitempty" json:"selinux,omitempty"` - Propagation string `yaml:"propagation,omitempty" json:"propagation,omitempty"` - CreateHostPath bool `yaml:"create_host_path,omitempty" json:"create_host_path,omitempty"` - - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// SELinux represents the SELinux re-labeling options. -const ( - // SELinuxShared option indicates that the bind mount content is shared among multiple containers - SELinuxShared string = "z" - // SELinuxPrivate option indicates that the bind mount content is private and unshared - SELinuxPrivate string = "Z" -) - -// Propagation represents the propagation of a mount. -const ( - // PropagationRPrivate RPRIVATE - PropagationRPrivate string = "rprivate" - // PropagationPrivate PRIVATE - PropagationPrivate string = "private" - // PropagationRShared RSHARED - PropagationRShared string = "rshared" - // PropagationShared SHARED - PropagationShared string = "shared" - // PropagationRSlave RSLAVE - PropagationRSlave string = "rslave" - // PropagationSlave SLAVE - PropagationSlave string = "slave" -) - -// ServiceVolumeVolume are options for a service volume of type volume -type ServiceVolumeVolume struct { - NoCopy bool `yaml:"nocopy,omitempty" json:"nocopy,omitempty"` - - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// ServiceVolumeTmpfs are options for a service volume of type tmpfs -type ServiceVolumeTmpfs struct { - Size UnitBytes `yaml:"size,omitempty" json:"size,omitempty"` - - Mode uint32 `yaml:"mode,omitempty" json:"mode,omitempty"` - - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// FileReferenceConfig for a reference to a swarm file object -type FileReferenceConfig struct { - Source string `yaml:"source,omitempty" json:"source,omitempty"` - Target string `yaml:"target,omitempty" json:"target,omitempty"` - UID string `yaml:"uid,omitempty" json:"uid,omitempty"` - GID string `yaml:"gid,omitempty" json:"gid,omitempty"` - Mode *uint32 `yaml:"mode,omitempty" json:"mode,omitempty"` - - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// ServiceConfigObjConfig is the config obj configuration for a service -type ServiceConfigObjConfig FileReferenceConfig - -// ServiceSecretConfig is the secret configuration for a service -type ServiceSecretConfig FileReferenceConfig - -// UlimitsConfig the ulimit configuration -type UlimitsConfig struct { - Single int `yaml:"single,omitempty" json:"single,omitempty"` - Soft int `yaml:"soft,omitempty" json:"soft,omitempty"` - Hard int `yaml:"hard,omitempty" json:"hard,omitempty"` - - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// MarshalYAML makes UlimitsConfig implement yaml.Marshaller -func (u *UlimitsConfig) MarshalYAML() (interface{}, error) { - if u.Single != 0 { - return u.Single, nil - } - return struct { - Soft int - Hard int - }{ - Soft: u.Soft, - Hard: u.Hard, - }, nil -} - -// MarshalJSON makes UlimitsConfig implement json.Marshaller -func (u *UlimitsConfig) MarshalJSON() ([]byte, error) { - if u.Single != 0 { - return json.Marshal(u.Single) - } - // Pass as a value to avoid re-entering this method and use the default implementation - return json.Marshal(*u) -} - -// NetworkConfig for a network -type NetworkConfig struct { - Name string `yaml:"name,omitempty" json:"name,omitempty"` - Driver string `yaml:"driver,omitempty" json:"driver,omitempty"` - DriverOpts map[string]string `yaml:"driver_opts,omitempty" json:"driver_opts,omitempty"` - Ipam IPAMConfig `yaml:"ipam,omitempty" json:"ipam,omitempty"` - External External `yaml:"external,omitempty" json:"external,omitempty"` - Internal bool `yaml:"internal,omitempty" json:"internal,omitempty"` - Attachable bool `yaml:"attachable,omitempty" json:"attachable,omitempty"` - Labels Labels `yaml:"labels,omitempty" json:"labels,omitempty"` - EnableIPv6 bool `yaml:"enable_ipv6,omitempty" json:"enable_ipv6,omitempty"` - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// IPAMConfig for a network -type IPAMConfig struct { - Driver string `yaml:"driver,omitempty" json:"driver,omitempty"` - Config []*IPAMPool `yaml:"config,omitempty" json:"config,omitempty"` - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// IPAMPool for a network -type IPAMPool struct { - Subnet string `yaml:"subnet,omitempty" json:"subnet,omitempty"` - Gateway string `yaml:"gateway,omitempty" json:"gateway,omitempty"` - IPRange string `yaml:"ip_range,omitempty" json:"ip_range,omitempty"` - AuxiliaryAddresses map[string]string `yaml:"aux_addresses,omitempty" json:"aux_addresses,omitempty"` - Extensions map[string]interface{} `yaml:",inline" json:"-"` -} - -// VolumeConfig for a volume -type VolumeConfig struct { - Name string `yaml:"name,omitempty" json:"name,omitempty"` - Driver string `yaml:"driver,omitempty" json:"driver,omitempty"` - DriverOpts map[string]string `yaml:"driver_opts,omitempty" json:"driver_opts,omitempty"` - External External `yaml:"external,omitempty" json:"external,omitempty"` - Labels Labels `yaml:"labels,omitempty" json:"labels,omitempty"` - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// External identifies a Volume or Network as a reference to a resource that is -// not managed, and should already exist. -// External.name is deprecated and replaced by Volume.name -type External struct { - Name string `yaml:"name,omitempty" json:"name,omitempty"` - External bool `yaml:"external,omitempty" json:"external,omitempty"` - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// MarshalYAML makes External implement yaml.Marshaller -func (e External) MarshalYAML() (interface{}, error) { - if e.Name == "" { - return e.External, nil - } - return External{Name: e.Name}, nil -} - -// MarshalJSON makes External implement json.Marshaller -func (e External) MarshalJSON() ([]byte, error) { - if e.Name == "" { - return []byte(fmt.Sprintf("%v", e.External)), nil - } - return []byte(fmt.Sprintf(`{"name": %q}`, e.Name)), nil -} - -// CredentialSpecConfig for credential spec on Windows -type CredentialSpecConfig struct { - Config string `yaml:"config,omitempty" json:"config,omitempty"` // Config was added in API v1.40 - File string `yaml:"file,omitempty" json:"file,omitempty"` - Registry string `yaml:"registry,omitempty" json:"registry,omitempty"` - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -// FileObjectConfig is a config type for a file used by a service -type FileObjectConfig struct { - Name string `yaml:"name,omitempty" json:"name,omitempty"` - File string `yaml:"file,omitempty" json:"file,omitempty"` - Environment string `yaml:"environment,omitempty" json:"environment,omitempty"` - External External `yaml:"external,omitempty" json:"external,omitempty"` - Labels Labels `yaml:"labels,omitempty" json:"labels,omitempty"` - Driver string `yaml:"driver,omitempty" json:"driver,omitempty"` - DriverOpts map[string]string `yaml:"driver_opts,omitempty" json:"driver_opts,omitempty"` - TemplateDriver string `yaml:"template_driver,omitempty" json:"template_driver,omitempty"` - Extensions Extensions `yaml:"#extensions,inline" json:"-"` -} - -const ( - // ServiceConditionCompletedSuccessfully is the type for waiting until a service has completed successfully (exit code 0). - ServiceConditionCompletedSuccessfully = "service_completed_successfully" - - // ServiceConditionHealthy is the type for waiting until a service is healthy. - ServiceConditionHealthy = "service_healthy" - - // ServiceConditionStarted is the type for waiting until a service has started (default). - ServiceConditionStarted = "service_started" -) - -type DependsOnConfig map[string]ServiceDependency - -type ServiceDependency struct { - Condition string `yaml:"condition,omitempty" json:"condition,omitempty"` - Restart bool `yaml:"restart,omitempty" json:"restart,omitempty"` - Extensions Extensions `yaml:"#extensions,inline" json:"-"` - Required bool `yaml:"required" json:"required"` -} - -type ExtendsConfig struct { - File string `yaml:"file,omitempty" json:"file,omitempty"` - Service string `yaml:"service,omitempty" json:"service,omitempty"` -} - -// SecretConfig for a secret -type SecretConfig FileObjectConfig - -// ConfigObjConfig is the config for the swarm "Config" object -type ConfigObjConfig FileObjectConfig - -type IncludeConfig struct { - Path StringList `yaml:"path,omitempty" json:"path,omitempty"` - ProjectDirectory string `yaml:"project_directory,omitempty" json:"project_directory,omitempty"` - EnvFile StringList `yaml:"env_file,omitempty" json:"env_file,omitempty"` -} diff --git a/vendor/github.com/compose-spec/compose-go/utils/collectionutils.go b/vendor/github.com/compose-spec/compose-go/utils/collectionutils.go deleted file mode 100644 index 343692250..000000000 --- a/vendor/github.com/compose-spec/compose-go/utils/collectionutils.go +++ /dev/null @@ -1,51 +0,0 @@ -/* - Copyright 2020 The Compose Specification 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 utils - -import "golang.org/x/exp/slices" - -func MapKeys[T comparable, U any](theMap map[T]U) []T { - var result []T - for key := range theMap { - result = append(result, key) - } - return result -} - -func MapsAppend[T comparable, U any](target map[T]U, source map[T]U) map[T]U { - if target == nil { - return source - } - if source == nil { - return target - } - for key, value := range source { - if _, ok := target[key]; !ok { - target[key] = value - } - } - return target -} - -func ArrayContains[T comparable](source []T, toCheck []T) bool { - for _, value := range toCheck { - if !slices.Contains(source, value) { - return false - } - } - return true -} diff --git a/vendor/github.com/compose-spec/compose-go/utils/stringutils.go b/vendor/github.com/compose-spec/compose-go/utils/stringutils.go deleted file mode 100644 index 182ddf830..000000000 --- a/vendor/github.com/compose-spec/compose-go/utils/stringutils.go +++ /dev/null @@ -1,58 +0,0 @@ -/* - Copyright 2020 The Compose Specification 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 utils - -import ( - "fmt" - "strconv" - "strings" -) - -// StringContains check if an array contains a specific value -func StringContains(array []string, needle string) bool { - for _, val := range array { - if val == needle { - return true - } - } - return false -} - -// StringToBool converts a string to a boolean ignoring errors -func StringToBool(s string) bool { - b, _ := strconv.ParseBool(strings.ToLower(strings.TrimSpace(s))) - return b -} - -// GetAsEqualsMap split key=value formatted strings into a key : value map -func GetAsEqualsMap(em []string) map[string]string { - m := make(map[string]string) - for _, v := range em { - kv := strings.SplitN(v, "=", 2) - m[kv[0]] = kv[1] - } - return m -} - -// GetAsEqualsMap format a key : value map into key=value strings -func GetAsStringList(em map[string]string) []string { - m := make([]string, 0, len(em)) - for k, v := range em { - m = append(m, fmt.Sprintf("%s=%s", k, v)) - } - return m -} diff --git a/vendor/github.com/containerd/console/.golangci.yml b/vendor/github.com/containerd/console/.golangci.yml deleted file mode 100644 index abe3d84bb..000000000 --- a/vendor/github.com/containerd/console/.golangci.yml +++ /dev/null @@ -1,20 +0,0 @@ -linters: - enable: - - gofmt - - goimports - - ineffassign - - misspell - - revive - - staticcheck - - structcheck - - unconvert - - unused - - varcheck - - vet - disable: - - errcheck - -run: - timeout: 3m - skip-dirs: - - vendor diff --git a/vendor/github.com/containerd/console/LICENSE b/vendor/github.com/containerd/console/LICENSE deleted file mode 100644 index 584149b6e..000000000 --- a/vendor/github.com/containerd/console/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright The containerd 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 - - https://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/containerd/console/README.md b/vendor/github.com/containerd/console/README.md deleted file mode 100644 index a849a728f..000000000 --- a/vendor/github.com/containerd/console/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# console - -[![PkgGoDev](https://pkg.go.dev/badge/github.com/containerd/console)](https://pkg.go.dev/github.com/containerd/console) -[![Build Status](https://github.com/containerd/console/workflows/CI/badge.svg)](https://github.com/containerd/console/actions?query=workflow%3ACI) -[![Go Report Card](https://goreportcard.com/badge/github.com/containerd/console)](https://goreportcard.com/report/github.com/containerd/console) - -Golang package for dealing with consoles. Light on deps and a simple API. - -## Modifying the current process - -```go -current := console.Current() -defer current.Reset() - -if err := current.SetRaw(); err != nil { -} -ws, err := current.Size() -current.Resize(ws) -``` - -## Project details - -console is a containerd sub-project, licensed under the [Apache 2.0 license](./LICENSE). -As a containerd sub-project, you will find the: - * [Project governance](https://github.com/containerd/project/blob/main/GOVERNANCE.md), - * [Maintainers](https://github.com/containerd/project/blob/main/MAINTAINERS), - * and [Contributing guidelines](https://github.com/containerd/project/blob/main/CONTRIBUTING.md) - -information in our [`containerd/project`](https://github.com/containerd/project) repository. diff --git a/vendor/github.com/containerd/console/console.go b/vendor/github.com/containerd/console/console.go deleted file mode 100644 index dd587d88e..000000000 --- a/vendor/github.com/containerd/console/console.go +++ /dev/null @@ -1,90 +0,0 @@ -/* - Copyright The containerd 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 console - -import ( - "errors" - "io" - "os" -) - -var ( - ErrNotAConsole = errors.New("provided file is not a console") - ErrNotImplemented = errors.New("not implemented") -) - -type File interface { - io.ReadWriteCloser - - // Fd returns its file descriptor - Fd() uintptr - // Name returns its file name - Name() string -} - -type Console interface { - File - - // Resize resizes the console to the provided window size - Resize(WinSize) error - // ResizeFrom resizes the calling console to the size of the - // provided console - ResizeFrom(Console) error - // SetRaw sets the console in raw mode - SetRaw() error - // DisableEcho disables echo on the console - DisableEcho() error - // Reset restores the console to its original state - Reset() error - // Size returns the window size of the console - Size() (WinSize, error) -} - -// WinSize specifies the window size of the console -type WinSize struct { - // Height of the console - Height uint16 - // Width of the console - Width uint16 - x uint16 - y uint16 -} - -// Current returns the current process' console -func Current() (c Console) { - var err error - // Usually all three streams (stdin, stdout, and stderr) - // are open to the same console, but some might be redirected, - // so try all three. - for _, s := range []*os.File{os.Stderr, os.Stdout, os.Stdin} { - if c, err = ConsoleFromFile(s); err == nil { - return c - } - } - // One of the std streams should always be a console - // for the design of this function. - panic(err) -} - -// ConsoleFromFile returns a console using the provided file -// nolint:revive -func ConsoleFromFile(f File) (Console, error) { - if err := checkConsole(f); err != nil { - return nil, err - } - return newMaster(f) -} diff --git a/vendor/github.com/containerd/console/console_linux.go b/vendor/github.com/containerd/console/console_linux.go deleted file mode 100644 index 28b77b7a3..000000000 --- a/vendor/github.com/containerd/console/console_linux.go +++ /dev/null @@ -1,281 +0,0 @@ -//go:build linux -// +build linux - -/* - Copyright The containerd 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 console - -import ( - "io" - "os" - "sync" - - "golang.org/x/sys/unix" -) - -const ( - maxEvents = 128 -) - -// Epoller manages multiple epoll consoles using edge-triggered epoll api so we -// dont have to deal with repeated wake-up of EPOLLER or EPOLLHUP. -// For more details, see: -// - https://github.com/systemd/systemd/pull/4262 -// - https://github.com/moby/moby/issues/27202 -// -// Example usage of Epoller and EpollConsole can be as follow: -// -// epoller, _ := NewEpoller() -// epollConsole, _ := epoller.Add(console) -// go epoller.Wait() -// var ( -// b bytes.Buffer -// wg sync.WaitGroup -// ) -// wg.Add(1) -// go func() { -// io.Copy(&b, epollConsole) -// wg.Done() -// }() -// // perform I/O on the console -// epollConsole.Shutdown(epoller.CloseConsole) -// wg.Wait() -// epollConsole.Close() -type Epoller struct { - efd int - mu sync.Mutex - fdMapping map[int]*EpollConsole - closeOnce sync.Once -} - -// NewEpoller returns an instance of epoller with a valid epoll fd. -func NewEpoller() (*Epoller, error) { - efd, err := unix.EpollCreate1(unix.EPOLL_CLOEXEC) - if err != nil { - return nil, err - } - return &Epoller{ - efd: efd, - fdMapping: make(map[int]*EpollConsole), - }, nil -} - -// Add creates an epoll console based on the provided console. The console will -// be registered with EPOLLET (i.e. using edge-triggered notification) and its -// file descriptor will be set to non-blocking mode. After this, user should use -// the return console to perform I/O. -func (e *Epoller) Add(console Console) (*EpollConsole, error) { - sysfd := int(console.Fd()) - // Set sysfd to non-blocking mode - if err := unix.SetNonblock(sysfd, true); err != nil { - return nil, err - } - - ev := unix.EpollEvent{ - Events: unix.EPOLLIN | unix.EPOLLOUT | unix.EPOLLRDHUP | unix.EPOLLET, - Fd: int32(sysfd), - } - if err := unix.EpollCtl(e.efd, unix.EPOLL_CTL_ADD, sysfd, &ev); err != nil { - return nil, err - } - ef := &EpollConsole{ - Console: console, - sysfd: sysfd, - readc: sync.NewCond(&sync.Mutex{}), - writec: sync.NewCond(&sync.Mutex{}), - } - e.mu.Lock() - e.fdMapping[sysfd] = ef - e.mu.Unlock() - return ef, nil -} - -// Wait starts the loop to wait for its consoles' notifications and signal -// appropriate console that it can perform I/O. -func (e *Epoller) Wait() error { - events := make([]unix.EpollEvent, maxEvents) - for { - n, err := unix.EpollWait(e.efd, events, -1) - if err != nil { - // EINTR: The call was interrupted by a signal handler before either - // any of the requested events occurred or the timeout expired - if err == unix.EINTR { - continue - } - return err - } - for i := 0; i < n; i++ { - ev := &events[i] - // the console is ready to be read from - if ev.Events&(unix.EPOLLIN|unix.EPOLLHUP|unix.EPOLLERR) != 0 { - if epfile := e.getConsole(int(ev.Fd)); epfile != nil { - epfile.signalRead() - } - } - // the console is ready to be written to - if ev.Events&(unix.EPOLLOUT|unix.EPOLLHUP|unix.EPOLLERR) != 0 { - if epfile := e.getConsole(int(ev.Fd)); epfile != nil { - epfile.signalWrite() - } - } - } - } -} - -// CloseConsole unregisters the console's file descriptor from epoll interface -func (e *Epoller) CloseConsole(fd int) error { - e.mu.Lock() - defer e.mu.Unlock() - delete(e.fdMapping, fd) - return unix.EpollCtl(e.efd, unix.EPOLL_CTL_DEL, fd, &unix.EpollEvent{}) -} - -func (e *Epoller) getConsole(sysfd int) *EpollConsole { - e.mu.Lock() - f := e.fdMapping[sysfd] - e.mu.Unlock() - return f -} - -// Close closes the epoll fd -func (e *Epoller) Close() error { - closeErr := os.ErrClosed // default to "file already closed" - e.closeOnce.Do(func() { - closeErr = unix.Close(e.efd) - }) - return closeErr -} - -// EpollConsole acts like a console but registers its file descriptor with an -// epoll fd and uses epoll API to perform I/O. -type EpollConsole struct { - Console - readc *sync.Cond - writec *sync.Cond - sysfd int - closed bool -} - -// Read reads up to len(p) bytes into p. It returns the number of bytes read -// (0 <= n <= len(p)) and any error encountered. -// -// If the console's read returns EAGAIN or EIO, we assume that it's a -// temporary error because the other side went away and wait for the signal -// generated by epoll event to continue. -func (ec *EpollConsole) Read(p []byte) (n int, err error) { - var read int - ec.readc.L.Lock() - defer ec.readc.L.Unlock() - for { - read, err = ec.Console.Read(p[n:]) - n += read - if err != nil { - var hangup bool - if perr, ok := err.(*os.PathError); ok { - hangup = (perr.Err == unix.EAGAIN || perr.Err == unix.EIO) - } else { - hangup = (err == unix.EAGAIN || err == unix.EIO) - } - // if the other end disappear, assume this is temporary and wait for the - // signal to continue again. Unless we didnt read anything and the - // console is already marked as closed then we should exit - if hangup && !(n == 0 && len(p) > 0 && ec.closed) { - ec.readc.Wait() - continue - } - } - break - } - // if we didnt read anything then return io.EOF to end gracefully - if n == 0 && len(p) > 0 && err == nil { - err = io.EOF - } - // signal for others that we finished the read - ec.readc.Signal() - return n, err -} - -// Writes len(p) bytes from p to the console. It returns the number of bytes -// written from p (0 <= n <= len(p)) and any error encountered that caused -// the write to stop early. -// -// If writes to the console returns EAGAIN or EIO, we assume that it's a -// temporary error because the other side went away and wait for the signal -// generated by epoll event to continue. -func (ec *EpollConsole) Write(p []byte) (n int, err error) { - var written int - ec.writec.L.Lock() - defer ec.writec.L.Unlock() - for { - written, err = ec.Console.Write(p[n:]) - n += written - if err != nil { - var hangup bool - if perr, ok := err.(*os.PathError); ok { - hangup = (perr.Err == unix.EAGAIN || perr.Err == unix.EIO) - } else { - hangup = (err == unix.EAGAIN || err == unix.EIO) - } - // if the other end disappears, assume this is temporary and wait for the - // signal to continue again. - if hangup { - ec.writec.Wait() - continue - } - } - // unrecoverable error, break the loop and return the error - break - } - if n < len(p) && err == nil { - err = io.ErrShortWrite - } - // signal for others that we finished the write - ec.writec.Signal() - return n, err -} - -// Shutdown closes the file descriptor and signals call waiters for this fd. -// It accepts a callback which will be called with the console's fd. The -// callback typically will be used to do further cleanup such as unregister the -// console's fd from the epoll interface. -// User should call Shutdown and wait for all I/O operation to be finished -// before closing the console. -func (ec *EpollConsole) Shutdown(close func(int) error) error { - ec.readc.L.Lock() - defer ec.readc.L.Unlock() - ec.writec.L.Lock() - defer ec.writec.L.Unlock() - - ec.readc.Broadcast() - ec.writec.Broadcast() - ec.closed = true - return close(ec.sysfd) -} - -// signalRead signals that the console is readable. -func (ec *EpollConsole) signalRead() { - ec.readc.L.Lock() - ec.readc.Signal() - ec.readc.L.Unlock() -} - -// signalWrite signals that the console is writable. -func (ec *EpollConsole) signalWrite() { - ec.writec.L.Lock() - ec.writec.Signal() - ec.writec.L.Unlock() -} diff --git a/vendor/github.com/containerd/console/console_other.go b/vendor/github.com/containerd/console/console_other.go deleted file mode 100644 index 933dfaddd..000000000 --- a/vendor/github.com/containerd/console/console_other.go +++ /dev/null @@ -1,36 +0,0 @@ -//go:build !darwin && !freebsd && !linux && !netbsd && !openbsd && !solaris && !windows && !zos -// +build !darwin,!freebsd,!linux,!netbsd,!openbsd,!solaris,!windows,!zos - -/* - Copyright The containerd 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 console - -// NewPty creates a new pty pair -// The master is returned as the first console and a string -// with the path to the pty slave is returned as the second -func NewPty() (Console, string, error) { - return nil, "", ErrNotImplemented -} - -// checkConsole checks if the provided file is a console -func checkConsole(f File) error { - return ErrNotAConsole -} - -func newMaster(f File) (Console, error) { - return nil, ErrNotImplemented -} diff --git a/vendor/github.com/containerd/console/console_unix.go b/vendor/github.com/containerd/console/console_unix.go deleted file mode 100644 index 161f5d126..000000000 --- a/vendor/github.com/containerd/console/console_unix.go +++ /dev/null @@ -1,157 +0,0 @@ -//go:build darwin || freebsd || linux || netbsd || openbsd || zos -// +build darwin freebsd linux netbsd openbsd zos - -/* - Copyright The containerd 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 console - -import ( - "golang.org/x/sys/unix" -) - -// NewPty creates a new pty pair -// The master is returned as the first console and a string -// with the path to the pty slave is returned as the second -func NewPty() (Console, string, error) { - f, err := openpt() - if err != nil { - return nil, "", err - } - slave, err := ptsname(f) - if err != nil { - return nil, "", err - } - if err := unlockpt(f); err != nil { - return nil, "", err - } - m, err := newMaster(f) - if err != nil { - return nil, "", err - } - return m, slave, nil -} - -type master struct { - f File - original *unix.Termios -} - -func (m *master) Read(b []byte) (int, error) { - return m.f.Read(b) -} - -func (m *master) Write(b []byte) (int, error) { - return m.f.Write(b) -} - -func (m *master) Close() error { - return m.f.Close() -} - -func (m *master) Resize(ws WinSize) error { - return tcswinsz(m.f.Fd(), ws) -} - -func (m *master) ResizeFrom(c Console) error { - ws, err := c.Size() - if err != nil { - return err - } - return m.Resize(ws) -} - -func (m *master) Reset() error { - if m.original == nil { - return nil - } - return tcset(m.f.Fd(), m.original) -} - -func (m *master) getCurrent() (unix.Termios, error) { - var termios unix.Termios - if err := tcget(m.f.Fd(), &termios); err != nil { - return unix.Termios{}, err - } - return termios, nil -} - -func (m *master) SetRaw() error { - rawState, err := m.getCurrent() - if err != nil { - return err - } - rawState = cfmakeraw(rawState) - rawState.Oflag = rawState.Oflag | unix.OPOST - return tcset(m.f.Fd(), &rawState) -} - -func (m *master) DisableEcho() error { - rawState, err := m.getCurrent() - if err != nil { - return err - } - rawState.Lflag = rawState.Lflag &^ unix.ECHO - return tcset(m.f.Fd(), &rawState) -} - -func (m *master) Size() (WinSize, error) { - return tcgwinsz(m.f.Fd()) -} - -func (m *master) Fd() uintptr { - return m.f.Fd() -} - -func (m *master) Name() string { - return m.f.Name() -} - -// checkConsole checks if the provided file is a console -func checkConsole(f File) error { - var termios unix.Termios - if tcget(f.Fd(), &termios) != nil { - return ErrNotAConsole - } - return nil -} - -func newMaster(f File) (Console, error) { - m := &master{ - f: f, - } - t, err := m.getCurrent() - if err != nil { - return nil, err - } - m.original = &t - return m, nil -} - -// ClearONLCR sets the necessary tty_ioctl(4)s to ensure that a pty pair -// created by us acts normally. In particular, a not-very-well-known default of -// Linux unix98 ptys is that they have +onlcr by default. While this isn't a -// problem for terminal emulators, because we relay data from the terminal we -// also relay that funky line discipline. -func ClearONLCR(fd uintptr) error { - return setONLCR(fd, false) -} - -// SetONLCR sets the necessary tty_ioctl(4)s to ensure that a pty pair -// created by us acts as intended for a terminal emulator. -func SetONLCR(fd uintptr) error { - return setONLCR(fd, true) -} diff --git a/vendor/github.com/containerd/console/console_windows.go b/vendor/github.com/containerd/console/console_windows.go deleted file mode 100644 index 6896db182..000000000 --- a/vendor/github.com/containerd/console/console_windows.go +++ /dev/null @@ -1,219 +0,0 @@ -/* - Copyright The containerd 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 console - -import ( - "errors" - "fmt" - "os" - - "golang.org/x/sys/windows" -) - -var vtInputSupported bool - -func (m *master) initStdios() { - // Note: We discard console mode warnings, because in/out can be redirected. - // - // TODO: Investigate opening CONOUT$/CONIN$ to handle this correctly - - m.in = windows.Handle(os.Stdin.Fd()) - if err := windows.GetConsoleMode(m.in, &m.inMode); err == nil { - // Validate that windows.ENABLE_VIRTUAL_TERMINAL_INPUT is supported, but do not set it. - if err = windows.SetConsoleMode(m.in, m.inMode|windows.ENABLE_VIRTUAL_TERMINAL_INPUT); err == nil { - vtInputSupported = true - } - // Unconditionally set the console mode back even on failure because SetConsoleMode - // remembers invalid bits on input handles. - windows.SetConsoleMode(m.in, m.inMode) - } - - m.out = windows.Handle(os.Stdout.Fd()) - if err := windows.GetConsoleMode(m.out, &m.outMode); err == nil { - if err := windows.SetConsoleMode(m.out, m.outMode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING); err == nil { - m.outMode |= windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING - } else { - windows.SetConsoleMode(m.out, m.outMode) - } - } - - m.err = windows.Handle(os.Stderr.Fd()) - if err := windows.GetConsoleMode(m.err, &m.errMode); err == nil { - if err := windows.SetConsoleMode(m.err, m.errMode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING); err == nil { - m.errMode |= windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING - } else { - windows.SetConsoleMode(m.err, m.errMode) - } - } -} - -type master struct { - in windows.Handle - inMode uint32 - - out windows.Handle - outMode uint32 - - err windows.Handle - errMode uint32 -} - -func (m *master) SetRaw() error { - if err := makeInputRaw(m.in, m.inMode); err != nil { - return err - } - - // Set StdOut and StdErr to raw mode, we ignore failures since - // windows.DISABLE_NEWLINE_AUTO_RETURN might not be supported on this version of - // Windows. - - windows.SetConsoleMode(m.out, m.outMode|windows.DISABLE_NEWLINE_AUTO_RETURN) - - windows.SetConsoleMode(m.err, m.errMode|windows.DISABLE_NEWLINE_AUTO_RETURN) - - return nil -} - -func (m *master) Reset() error { - var errs []error - - for _, s := range []struct { - fd windows.Handle - mode uint32 - }{ - {m.in, m.inMode}, - {m.out, m.outMode}, - {m.err, m.errMode}, - } { - if err := windows.SetConsoleMode(s.fd, s.mode); err != nil { - // we can't just abort on the first error, otherwise we might leave - // the console in an unexpected state. - errs = append(errs, fmt.Errorf("unable to restore console mode: %w", err)) - } - } - - if len(errs) > 0 { - return errs[0] - } - - return nil -} - -func (m *master) Size() (WinSize, error) { - var info windows.ConsoleScreenBufferInfo - err := windows.GetConsoleScreenBufferInfo(m.out, &info) - if err != nil { - return WinSize{}, fmt.Errorf("unable to get console info: %w", err) - } - - winsize := WinSize{ - Width: uint16(info.Window.Right - info.Window.Left + 1), - Height: uint16(info.Window.Bottom - info.Window.Top + 1), - } - - return winsize, nil -} - -func (m *master) Resize(ws WinSize) error { - return ErrNotImplemented -} - -func (m *master) ResizeFrom(c Console) error { - return ErrNotImplemented -} - -func (m *master) DisableEcho() error { - mode := m.inMode &^ windows.ENABLE_ECHO_INPUT - mode |= windows.ENABLE_PROCESSED_INPUT - mode |= windows.ENABLE_LINE_INPUT - - if err := windows.SetConsoleMode(m.in, mode); err != nil { - return fmt.Errorf("unable to set console to disable echo: %w", err) - } - - return nil -} - -func (m *master) Close() error { - return nil -} - -func (m *master) Read(b []byte) (int, error) { - return os.Stdin.Read(b) -} - -func (m *master) Write(b []byte) (int, error) { - return os.Stdout.Write(b) -} - -func (m *master) Fd() uintptr { - return uintptr(m.in) -} - -// on windows, console can only be made from os.Std{in,out,err}, hence there -// isnt a single name here we can use. Return a dummy "console" value in this -// case should be sufficient. -func (m *master) Name() string { - return "console" -} - -// makeInputRaw puts the terminal (Windows Console) connected to the given -// file descriptor into raw mode -func makeInputRaw(fd windows.Handle, mode uint32) error { - // See - // -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx - // -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms683462(v=vs.85).aspx - - // Disable these modes - mode &^= windows.ENABLE_ECHO_INPUT - mode &^= windows.ENABLE_LINE_INPUT - mode &^= windows.ENABLE_MOUSE_INPUT - mode &^= windows.ENABLE_WINDOW_INPUT - mode &^= windows.ENABLE_PROCESSED_INPUT - - // Enable these modes - mode |= windows.ENABLE_EXTENDED_FLAGS - mode |= windows.ENABLE_INSERT_MODE - mode |= windows.ENABLE_QUICK_EDIT_MODE - - if vtInputSupported { - mode |= windows.ENABLE_VIRTUAL_TERMINAL_INPUT - } - - if err := windows.SetConsoleMode(fd, mode); err != nil { - return fmt.Errorf("unable to set console to raw mode: %w", err) - } - - return nil -} - -func checkConsole(f File) error { - var mode uint32 - if err := windows.GetConsoleMode(windows.Handle(f.Fd()), &mode); err != nil { - return err - } - return nil -} - -func newMaster(f File) (Console, error) { - if f != os.Stdin && f != os.Stdout && f != os.Stderr { - return nil, errors.New("creating a console from a file is not supported on windows") - } - m := &master{} - m.initStdios() - return m, nil -} diff --git a/vendor/github.com/containerd/console/pty_freebsd_cgo.go b/vendor/github.com/containerd/console/pty_freebsd_cgo.go deleted file mode 100644 index 22368623a..000000000 --- a/vendor/github.com/containerd/console/pty_freebsd_cgo.go +++ /dev/null @@ -1,46 +0,0 @@ -//go:build freebsd && cgo -// +build freebsd,cgo - -/* - Copyright The containerd 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 console - -import ( - "fmt" - "os" -) - -/* -#include -#include -#include -*/ -import "C" - -// openpt allocates a new pseudo-terminal and establishes a connection with its -// control device. -func openpt() (*os.File, error) { - fd, err := C.posix_openpt(C.O_RDWR) - if err != nil { - return nil, fmt.Errorf("posix_openpt: %w", err) - } - if _, err := C.grantpt(fd); err != nil { - C.close(fd) - return nil, fmt.Errorf("grantpt: %w", err) - } - return os.NewFile(uintptr(fd), ""), nil -} diff --git a/vendor/github.com/containerd/console/pty_freebsd_nocgo.go b/vendor/github.com/containerd/console/pty_freebsd_nocgo.go deleted file mode 100644 index ceb90a47b..000000000 --- a/vendor/github.com/containerd/console/pty_freebsd_nocgo.go +++ /dev/null @@ -1,37 +0,0 @@ -//go:build freebsd && !cgo -// +build freebsd,!cgo - -/* - Copyright The containerd 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 console - -import ( - "os" -) - -// -// Implementing the functions below requires cgo support. Non-cgo stubs -// versions are defined below to enable cross-compilation of source code -// that depends on these functions, but the resultant cross-compiled -// binaries cannot actually be used. If the stub function(s) below are -// actually invoked they will display an error message and cause the -// calling process to exit. -// - -func openpt() (*os.File, error) { - panic("openpt() support requires cgo.") -} diff --git a/vendor/github.com/containerd/console/pty_unix.go b/vendor/github.com/containerd/console/pty_unix.go deleted file mode 100644 index f5a5b8058..000000000 --- a/vendor/github.com/containerd/console/pty_unix.go +++ /dev/null @@ -1,31 +0,0 @@ -//go:build darwin || linux || netbsd || openbsd -// +build darwin linux netbsd openbsd - -/* - Copyright The containerd 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 console - -import ( - "os" - - "golang.org/x/sys/unix" -) - -// openpt allocates a new pseudo-terminal by opening the /dev/ptmx device -func openpt() (*os.File, error) { - return os.OpenFile("/dev/ptmx", unix.O_RDWR|unix.O_NOCTTY|unix.O_CLOEXEC, 0) -} diff --git a/vendor/github.com/containerd/console/pty_zos.go b/vendor/github.com/containerd/console/pty_zos.go deleted file mode 100644 index 58f59aba5..000000000 --- a/vendor/github.com/containerd/console/pty_zos.go +++ /dev/null @@ -1,43 +0,0 @@ -//go:build zos -// +build zos - -/* - Copyright The containerd 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 console - -import ( - "fmt" - "os" -) - -// openpt allocates a new pseudo-terminal by opening the first available /dev/ptypXX device -func openpt() (*os.File, error) { - var f *os.File - var err error - for i := 0; ; i++ { - ptyp := fmt.Sprintf("/dev/ptyp%04d", i) - f, err = os.OpenFile(ptyp, os.O_RDWR, 0600) - if err == nil { - break - } - if os.IsNotExist(err) { - return nil, err - } - // else probably Resource Busy - } - return f, nil -} diff --git a/vendor/github.com/containerd/console/tc_darwin.go b/vendor/github.com/containerd/console/tc_darwin.go deleted file mode 100644 index 787154580..000000000 --- a/vendor/github.com/containerd/console/tc_darwin.go +++ /dev/null @@ -1,44 +0,0 @@ -/* - Copyright The containerd 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 console - -import ( - "fmt" - "os" - - "golang.org/x/sys/unix" -) - -const ( - cmdTcGet = unix.TIOCGETA - cmdTcSet = unix.TIOCSETA -) - -// unlockpt unlocks the slave pseudoterminal device corresponding to the master pseudoterminal referred to by f. -// unlockpt should be called before opening the slave side of a pty. -func unlockpt(f *os.File) error { - return unix.IoctlSetPointerInt(int(f.Fd()), unix.TIOCPTYUNLK, 0) -} - -// ptsname retrieves the name of the first available pts for the given master. -func ptsname(f *os.File) (string, error) { - n, err := unix.IoctlGetInt(int(f.Fd()), unix.TIOCPTYGNAME) - if err != nil { - return "", err - } - return fmt.Sprintf("/dev/pts/%d", n), nil -} diff --git a/vendor/github.com/containerd/console/tc_freebsd_cgo.go b/vendor/github.com/containerd/console/tc_freebsd_cgo.go deleted file mode 100644 index 332825794..000000000 --- a/vendor/github.com/containerd/console/tc_freebsd_cgo.go +++ /dev/null @@ -1,58 +0,0 @@ -//go:build freebsd && cgo -// +build freebsd,cgo - -/* - Copyright The containerd 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 console - -import ( - "fmt" - "os" - - "golang.org/x/sys/unix" -) - -/* -#include -#include -*/ -import "C" - -const ( - cmdTcGet = unix.TIOCGETA - cmdTcSet = unix.TIOCSETA -) - -// unlockpt unlocks the slave pseudoterminal device corresponding to the master pseudoterminal referred to by f. -// unlockpt should be called before opening the slave side of a pty. -func unlockpt(f *os.File) error { - fd := C.int(f.Fd()) - if _, err := C.unlockpt(fd); err != nil { - C.close(fd) - return fmt.Errorf("unlockpt: %w", err) - } - return nil -} - -// ptsname retrieves the name of the first available pts for the given master. -func ptsname(f *os.File) (string, error) { - n, err := unix.IoctlGetInt(int(f.Fd()), unix.TIOCGPTN) - if err != nil { - return "", err - } - return fmt.Sprintf("/dev/pts/%d", n), nil -} diff --git a/vendor/github.com/containerd/console/tc_freebsd_nocgo.go b/vendor/github.com/containerd/console/tc_freebsd_nocgo.go deleted file mode 100644 index 18a9b9cbe..000000000 --- a/vendor/github.com/containerd/console/tc_freebsd_nocgo.go +++ /dev/null @@ -1,56 +0,0 @@ -//go:build freebsd && !cgo -// +build freebsd,!cgo - -/* - Copyright The containerd 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 console - -import ( - "fmt" - "os" - - "golang.org/x/sys/unix" -) - -const ( - cmdTcGet = unix.TIOCGETA - cmdTcSet = unix.TIOCSETA -) - -// -// Implementing the functions below requires cgo support. Non-cgo stubs -// versions are defined below to enable cross-compilation of source code -// that depends on these functions, but the resultant cross-compiled -// binaries cannot actually be used. If the stub function(s) below are -// actually invoked they will display an error message and cause the -// calling process to exit. -// - -// unlockpt unlocks the slave pseudoterminal device corresponding to the master pseudoterminal referred to by f. -// unlockpt should be called before opening the slave side of a pty. -func unlockpt(f *os.File) error { - panic("unlockpt() support requires cgo.") -} - -// ptsname retrieves the name of the first available pts for the given master. -func ptsname(f *os.File) (string, error) { - n, err := unix.IoctlGetInt(int(f.Fd()), unix.TIOCGPTN) - if err != nil { - return "", err - } - return fmt.Sprintf("/dev/pts/%d", n), nil -} diff --git a/vendor/github.com/containerd/console/tc_linux.go b/vendor/github.com/containerd/console/tc_linux.go deleted file mode 100644 index 7d552ea4b..000000000 --- a/vendor/github.com/containerd/console/tc_linux.go +++ /dev/null @@ -1,51 +0,0 @@ -/* - Copyright The containerd 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 console - -import ( - "fmt" - "os" - "unsafe" - - "golang.org/x/sys/unix" -) - -const ( - cmdTcGet = unix.TCGETS - cmdTcSet = unix.TCSETS -) - -// unlockpt unlocks the slave pseudoterminal device corresponding to the master pseudoterminal referred to by f. -// unlockpt should be called before opening the slave side of a pty. -func unlockpt(f *os.File) error { - var u int32 - // XXX do not use unix.IoctlSetPointerInt here, see commit dbd69c59b81. - if _, _, err := unix.Syscall(unix.SYS_IOCTL, f.Fd(), unix.TIOCSPTLCK, uintptr(unsafe.Pointer(&u))); err != 0 { - return err - } - return nil -} - -// ptsname retrieves the name of the first available pts for the given master. -func ptsname(f *os.File) (string, error) { - var u uint32 - // XXX do not use unix.IoctlGetInt here, see commit dbd69c59b81. - if _, _, err := unix.Syscall(unix.SYS_IOCTL, f.Fd(), unix.TIOCGPTN, uintptr(unsafe.Pointer(&u))); err != 0 { - return "", err - } - return fmt.Sprintf("/dev/pts/%d", u), nil -} diff --git a/vendor/github.com/containerd/console/tc_netbsd.go b/vendor/github.com/containerd/console/tc_netbsd.go deleted file mode 100644 index 71227aefd..000000000 --- a/vendor/github.com/containerd/console/tc_netbsd.go +++ /dev/null @@ -1,45 +0,0 @@ -/* - Copyright The containerd 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 console - -import ( - "bytes" - "os" - - "golang.org/x/sys/unix" -) - -const ( - cmdTcGet = unix.TIOCGETA - cmdTcSet = unix.TIOCSETA -) - -// unlockpt unlocks the slave pseudoterminal device corresponding to the master pseudoterminal referred to by f. -// unlockpt should be called before opening the slave side of a pty. -// This does not exist on NetBSD, it does not allocate controlling terminals on open -func unlockpt(f *os.File) error { - return nil -} - -// ptsname retrieves the name of the first available pts for the given master. -func ptsname(f *os.File) (string, error) { - ptm, err := unix.IoctlGetPtmget(int(f.Fd()), unix.TIOCPTSNAME) - if err != nil { - return "", err - } - return string(ptm.Sn[:bytes.IndexByte(ptm.Sn[:], 0)]), nil -} diff --git a/vendor/github.com/containerd/console/tc_openbsd_cgo.go b/vendor/github.com/containerd/console/tc_openbsd_cgo.go deleted file mode 100644 index 0e76f6cc3..000000000 --- a/vendor/github.com/containerd/console/tc_openbsd_cgo.go +++ /dev/null @@ -1,52 +0,0 @@ -//go:build openbsd && cgo -// +build openbsd,cgo - -/* - Copyright The containerd 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 console - -import ( - "os" - - "golang.org/x/sys/unix" -) - -//#include -import "C" - -const ( - cmdTcGet = unix.TIOCGETA - cmdTcSet = unix.TIOCSETA -) - -// ptsname retrieves the name of the first available pts for the given master. -func ptsname(f *os.File) (string, error) { - ptspath, err := C.ptsname(C.int(f.Fd())) - if err != nil { - return "", err - } - return C.GoString(ptspath), nil -} - -// unlockpt unlocks the slave pseudoterminal device corresponding to the master pseudoterminal referred to by f. -// unlockpt should be called before opening the slave side of a pty. -func unlockpt(f *os.File) error { - if _, err := C.grantpt(C.int(f.Fd())); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/containerd/console/tc_openbsd_nocgo.go b/vendor/github.com/containerd/console/tc_openbsd_nocgo.go deleted file mode 100644 index dca92418b..000000000 --- a/vendor/github.com/containerd/console/tc_openbsd_nocgo.go +++ /dev/null @@ -1,48 +0,0 @@ -//go:build openbsd && !cgo -// +build openbsd,!cgo - -/* - Copyright The containerd 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. -*/ - -// -// Implementing the functions below requires cgo support. Non-cgo stubs -// versions are defined below to enable cross-compilation of source code -// that depends on these functions, but the resultant cross-compiled -// binaries cannot actually be used. If the stub function(s) below are -// actually invoked they will display an error message and cause the -// calling process to exit. -// - -package console - -import ( - "os" - - "golang.org/x/sys/unix" -) - -const ( - cmdTcGet = unix.TIOCGETA - cmdTcSet = unix.TIOCSETA -) - -func ptsname(f *os.File) (string, error) { - panic("ptsname() support requires cgo.") -} - -func unlockpt(f *os.File) error { - panic("unlockpt() support requires cgo.") -} diff --git a/vendor/github.com/containerd/console/tc_unix.go b/vendor/github.com/containerd/console/tc_unix.go deleted file mode 100644 index 2ecf188fc..000000000 --- a/vendor/github.com/containerd/console/tc_unix.go +++ /dev/null @@ -1,92 +0,0 @@ -//go:build darwin || freebsd || linux || netbsd || openbsd || zos -// +build darwin freebsd linux netbsd openbsd zos - -/* - Copyright The containerd 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 console - -import ( - "golang.org/x/sys/unix" -) - -func tcget(fd uintptr, p *unix.Termios) error { - termios, err := unix.IoctlGetTermios(int(fd), cmdTcGet) - if err != nil { - return err - } - *p = *termios - return nil -} - -func tcset(fd uintptr, p *unix.Termios) error { - return unix.IoctlSetTermios(int(fd), cmdTcSet, p) -} - -func tcgwinsz(fd uintptr) (WinSize, error) { - var ws WinSize - - uws, err := unix.IoctlGetWinsize(int(fd), unix.TIOCGWINSZ) - if err != nil { - return ws, err - } - - // Translate from unix.Winsize to console.WinSize - ws.Height = uws.Row - ws.Width = uws.Col - ws.x = uws.Xpixel - ws.y = uws.Ypixel - return ws, nil -} - -func tcswinsz(fd uintptr, ws WinSize) error { - // Translate from console.WinSize to unix.Winsize - - var uws unix.Winsize - uws.Row = ws.Height - uws.Col = ws.Width - uws.Xpixel = ws.x - uws.Ypixel = ws.y - - return unix.IoctlSetWinsize(int(fd), unix.TIOCSWINSZ, &uws) -} - -func setONLCR(fd uintptr, enable bool) error { - var termios unix.Termios - if err := tcget(fd, &termios); err != nil { - return err - } - if enable { - // Set +onlcr so we can act like a real terminal - termios.Oflag |= unix.ONLCR - } else { - // Set -onlcr so we don't have to deal with \r. - termios.Oflag &^= unix.ONLCR - } - return tcset(fd, &termios) -} - -func cfmakeraw(t unix.Termios) unix.Termios { - t.Iflag &^= (unix.IGNBRK | unix.BRKINT | unix.PARMRK | unix.ISTRIP | unix.INLCR | unix.IGNCR | unix.ICRNL | unix.IXON) - t.Oflag &^= unix.OPOST - t.Lflag &^= (unix.ECHO | unix.ECHONL | unix.ICANON | unix.ISIG | unix.IEXTEN) - t.Cflag &^= (unix.CSIZE | unix.PARENB) - t.Cflag |= unix.CS8 - t.Cc[unix.VMIN] = 1 - t.Cc[unix.VTIME] = 0 - - return t -} diff --git a/vendor/github.com/containerd/console/tc_zos.go b/vendor/github.com/containerd/console/tc_zos.go deleted file mode 100644 index fc90ba5fb..000000000 --- a/vendor/github.com/containerd/console/tc_zos.go +++ /dev/null @@ -1,39 +0,0 @@ -/* - Copyright The containerd 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 console - -import ( - "os" - "strings" - - "golang.org/x/sys/unix" -) - -const ( - cmdTcGet = unix.TCGETS - cmdTcSet = unix.TCSETS -) - -// unlockpt is a no-op on zos. -func unlockpt(_ *os.File) error { - return nil -} - -// ptsname retrieves the name of the first available pts for the given master. -func ptsname(f *os.File) (string, error) { - return "/dev/ttyp" + strings.TrimPrefix(f.Name(), "/dev/ptyp"), nil -} diff --git a/vendor/github.com/containerd/containerd/LICENSE b/vendor/github.com/containerd/containerd/LICENSE deleted file mode 100644 index 584149b6e..000000000 --- a/vendor/github.com/containerd/containerd/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright The containerd 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 - - https://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/containerd/containerd/NOTICE b/vendor/github.com/containerd/containerd/NOTICE deleted file mode 100644 index 8915f0277..000000000 --- a/vendor/github.com/containerd/containerd/NOTICE +++ /dev/null @@ -1,16 +0,0 @@ -Docker -Copyright 2012-2015 Docker, Inc. - -This product includes software developed at Docker, Inc. (https://www.docker.com). - -The following is courtesy of our legal counsel: - - -Use and transfer of Docker may be subject to certain restrictions by the -United States and other governments. -It is your responsibility to ensure that your use and/or transfer does not -violate applicable laws. - -For more information, please see https://www.bis.doc.gov - -See also https://www.apache.org/dev/crypto.html and/or seek legal counsel. diff --git a/vendor/github.com/containerd/containerd/api/services/content/v1/content.pb.go b/vendor/github.com/containerd/containerd/api/services/content/v1/content.pb.go deleted file mode 100644 index 283664662..000000000 --- a/vendor/github.com/containerd/containerd/api/services/content/v1/content.pb.go +++ /dev/null @@ -1,1788 +0,0 @@ -// -//Copyright The containerd 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. - -// Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.28.1 -// protoc v3.20.1 -// source: github.com/containerd/containerd/api/services/content/v1/content.proto - -package content - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - emptypb "google.golang.org/protobuf/types/known/emptypb" - fieldmaskpb "google.golang.org/protobuf/types/known/fieldmaskpb" - timestamppb "google.golang.org/protobuf/types/known/timestamppb" - reflect "reflect" - sync "sync" -) - -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) -) - -// WriteAction defines the behavior of a WriteRequest. -type WriteAction int32 - -const ( - // WriteActionStat instructs the writer to return the current status while - // holding the lock on the write. - WriteAction_STAT WriteAction = 0 - // WriteActionWrite sets the action for the write request to write data. - // - // Any data included will be written at the provided offset. The - // transaction will be left open for further writes. - // - // This is the default. - WriteAction_WRITE WriteAction = 1 - // WriteActionCommit will write any outstanding data in the message and - // commit the write, storing it under the digest. - // - // This can be used in a single message to send the data, verify it and - // commit it. - // - // This action will always terminate the write. - WriteAction_COMMIT WriteAction = 2 -) - -// Enum value maps for WriteAction. -var ( - WriteAction_name = map[int32]string{ - 0: "STAT", - 1: "WRITE", - 2: "COMMIT", - } - WriteAction_value = map[string]int32{ - "STAT": 0, - "WRITE": 1, - "COMMIT": 2, - } -) - -func (x WriteAction) Enum() *WriteAction { - p := new(WriteAction) - *p = x - return p -} - -func (x WriteAction) String() string { - return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) -} - -func (WriteAction) Descriptor() protoreflect.EnumDescriptor { - return file_github_com_containerd_containerd_api_services_content_v1_content_proto_enumTypes[0].Descriptor() -} - -func (WriteAction) Type() protoreflect.EnumType { - return &file_github_com_containerd_containerd_api_services_content_v1_content_proto_enumTypes[0] -} - -func (x WriteAction) Number() protoreflect.EnumNumber { - return protoreflect.EnumNumber(x) -} - -// Deprecated: Use WriteAction.Descriptor instead. -func (WriteAction) EnumDescriptor() ([]byte, []int) { - return file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDescGZIP(), []int{0} -} - -type Info struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // Digest is the hash identity of the blob. - Digest string `protobuf:"bytes,1,opt,name=digest,proto3" json:"digest,omitempty"` - // Size is the total number of bytes in the blob. - Size int64 `protobuf:"varint,2,opt,name=size,proto3" json:"size,omitempty"` - // CreatedAt provides the time at which the blob was committed. - CreatedAt *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=created_at,json=createdAt,proto3" json:"created_at,omitempty"` - // UpdatedAt provides the time the info was last updated. - UpdatedAt *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=updated_at,json=updatedAt,proto3" json:"updated_at,omitempty"` - // Labels are arbitrary data on snapshots. - // - // The combined size of a key/value pair cannot exceed 4096 bytes. - Labels map[string]string `protobuf:"bytes,5,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` -} - -func (x *Info) Reset() { - *x = Info{} - if protoimpl.UnsafeEnabled { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *Info) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*Info) ProtoMessage() {} - -func (x *Info) ProtoReflect() protoreflect.Message { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_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 Info.ProtoReflect.Descriptor instead. -func (*Info) Descriptor() ([]byte, []int) { - return file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDescGZIP(), []int{0} -} - -func (x *Info) GetDigest() string { - if x != nil { - return x.Digest - } - return "" -} - -func (x *Info) GetSize() int64 { - if x != nil { - return x.Size - } - return 0 -} - -func (x *Info) GetCreatedAt() *timestamppb.Timestamp { - if x != nil { - return x.CreatedAt - } - return nil -} - -func (x *Info) GetUpdatedAt() *timestamppb.Timestamp { - if x != nil { - return x.UpdatedAt - } - return nil -} - -func (x *Info) GetLabels() map[string]string { - if x != nil { - return x.Labels - } - return nil -} - -type InfoRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Digest string `protobuf:"bytes,1,opt,name=digest,proto3" json:"digest,omitempty"` -} - -func (x *InfoRequest) Reset() { - *x = InfoRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *InfoRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*InfoRequest) ProtoMessage() {} - -func (x *InfoRequest) ProtoReflect() protoreflect.Message { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_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 InfoRequest.ProtoReflect.Descriptor instead. -func (*InfoRequest) Descriptor() ([]byte, []int) { - return file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDescGZIP(), []int{1} -} - -func (x *InfoRequest) GetDigest() string { - if x != nil { - return x.Digest - } - return "" -} - -type InfoResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Info *Info `protobuf:"bytes,1,opt,name=info,proto3" json:"info,omitempty"` -} - -func (x *InfoResponse) Reset() { - *x = InfoResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *InfoResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*InfoResponse) ProtoMessage() {} - -func (x *InfoResponse) ProtoReflect() protoreflect.Message { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_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 InfoResponse.ProtoReflect.Descriptor instead. -func (*InfoResponse) Descriptor() ([]byte, []int) { - return file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDescGZIP(), []int{2} -} - -func (x *InfoResponse) GetInfo() *Info { - if x != nil { - return x.Info - } - return nil -} - -type UpdateRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Info *Info `protobuf:"bytes,1,opt,name=info,proto3" json:"info,omitempty"` - // UpdateMask specifies which fields to perform the update on. If empty, - // the operation applies to all fields. - // - // In info, Digest, Size, and CreatedAt are immutable, - // other field may be updated using this mask. - // If no mask is provided, all mutable field are updated. - UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` -} - -func (x *UpdateRequest) Reset() { - *x = UpdateRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[3] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *UpdateRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*UpdateRequest) ProtoMessage() {} - -func (x *UpdateRequest) ProtoReflect() protoreflect.Message { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_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 UpdateRequest.ProtoReflect.Descriptor instead. -func (*UpdateRequest) Descriptor() ([]byte, []int) { - return file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDescGZIP(), []int{3} -} - -func (x *UpdateRequest) GetInfo() *Info { - if x != nil { - return x.Info - } - return nil -} - -func (x *UpdateRequest) GetUpdateMask() *fieldmaskpb.FieldMask { - if x != nil { - return x.UpdateMask - } - return nil -} - -type UpdateResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Info *Info `protobuf:"bytes,1,opt,name=info,proto3" json:"info,omitempty"` -} - -func (x *UpdateResponse) Reset() { - *x = UpdateResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[4] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *UpdateResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*UpdateResponse) ProtoMessage() {} - -func (x *UpdateResponse) ProtoReflect() protoreflect.Message { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_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 UpdateResponse.ProtoReflect.Descriptor instead. -func (*UpdateResponse) Descriptor() ([]byte, []int) { - return file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDescGZIP(), []int{4} -} - -func (x *UpdateResponse) GetInfo() *Info { - if x != nil { - return x.Info - } - return nil -} - -type ListContentRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // Filters contains one or more filters using the syntax defined in the - // containerd filter package. - // - // The returned result will be those that match any of the provided - // filters. Expanded, containers that match the following will be - // returned: - // - // filters[0] or filters[1] or ... or filters[n-1] or filters[n] - // - // If filters is zero-length or nil, all items will be returned. - Filters []string `protobuf:"bytes,1,rep,name=filters,proto3" json:"filters,omitempty"` -} - -func (x *ListContentRequest) Reset() { - *x = ListContentRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[5] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *ListContentRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ListContentRequest) ProtoMessage() {} - -func (x *ListContentRequest) ProtoReflect() protoreflect.Message { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_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 ListContentRequest.ProtoReflect.Descriptor instead. -func (*ListContentRequest) Descriptor() ([]byte, []int) { - return file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDescGZIP(), []int{5} -} - -func (x *ListContentRequest) GetFilters() []string { - if x != nil { - return x.Filters - } - return nil -} - -type ListContentResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Info []*Info `protobuf:"bytes,1,rep,name=info,proto3" json:"info,omitempty"` -} - -func (x *ListContentResponse) Reset() { - *x = ListContentResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[6] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *ListContentResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ListContentResponse) ProtoMessage() {} - -func (x *ListContentResponse) ProtoReflect() protoreflect.Message { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_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 ListContentResponse.ProtoReflect.Descriptor instead. -func (*ListContentResponse) Descriptor() ([]byte, []int) { - return file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDescGZIP(), []int{6} -} - -func (x *ListContentResponse) GetInfo() []*Info { - if x != nil { - return x.Info - } - return nil -} - -type DeleteContentRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // Digest specifies which content to delete. - Digest string `protobuf:"bytes,1,opt,name=digest,proto3" json:"digest,omitempty"` -} - -func (x *DeleteContentRequest) Reset() { - *x = DeleteContentRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[7] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *DeleteContentRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*DeleteContentRequest) ProtoMessage() {} - -func (x *DeleteContentRequest) ProtoReflect() protoreflect.Message { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_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 DeleteContentRequest.ProtoReflect.Descriptor instead. -func (*DeleteContentRequest) Descriptor() ([]byte, []int) { - return file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDescGZIP(), []int{7} -} - -func (x *DeleteContentRequest) GetDigest() string { - if x != nil { - return x.Digest - } - return "" -} - -// ReadContentRequest defines the fields that make up a request to read a portion of -// data from a stored object. -type ReadContentRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // Digest is the hash identity to read. - Digest string `protobuf:"bytes,1,opt,name=digest,proto3" json:"digest,omitempty"` - // Offset specifies the number of bytes from the start at which to begin - // the read. If zero or less, the read will be from the start. This uses - // standard zero-indexed semantics. - Offset int64 `protobuf:"varint,2,opt,name=offset,proto3" json:"offset,omitempty"` - // size is the total size of the read. If zero, the entire blob will be - // returned by the service. - Size int64 `protobuf:"varint,3,opt,name=size,proto3" json:"size,omitempty"` -} - -func (x *ReadContentRequest) Reset() { - *x = ReadContentRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[8] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *ReadContentRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ReadContentRequest) ProtoMessage() {} - -func (x *ReadContentRequest) ProtoReflect() protoreflect.Message { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_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 ReadContentRequest.ProtoReflect.Descriptor instead. -func (*ReadContentRequest) Descriptor() ([]byte, []int) { - return file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDescGZIP(), []int{8} -} - -func (x *ReadContentRequest) GetDigest() string { - if x != nil { - return x.Digest - } - return "" -} - -func (x *ReadContentRequest) GetOffset() int64 { - if x != nil { - return x.Offset - } - return 0 -} - -func (x *ReadContentRequest) GetSize() int64 { - if x != nil { - return x.Size - } - return 0 -} - -// ReadContentResponse carries byte data for a read request. -type ReadContentResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Offset int64 `protobuf:"varint,1,opt,name=offset,proto3" json:"offset,omitempty"` // offset of the returned data - Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` // actual data -} - -func (x *ReadContentResponse) Reset() { - *x = ReadContentResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[9] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *ReadContentResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ReadContentResponse) ProtoMessage() {} - -func (x *ReadContentResponse) ProtoReflect() protoreflect.Message { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_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 ReadContentResponse.ProtoReflect.Descriptor instead. -func (*ReadContentResponse) Descriptor() ([]byte, []int) { - return file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDescGZIP(), []int{9} -} - -func (x *ReadContentResponse) GetOffset() int64 { - if x != nil { - return x.Offset - } - return 0 -} - -func (x *ReadContentResponse) GetData() []byte { - if x != nil { - return x.Data - } - return nil -} - -type Status struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - StartedAt *timestamppb.Timestamp `protobuf:"bytes,1,opt,name=started_at,json=startedAt,proto3" json:"started_at,omitempty"` - UpdatedAt *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=updated_at,json=updatedAt,proto3" json:"updated_at,omitempty"` - Ref string `protobuf:"bytes,3,opt,name=ref,proto3" json:"ref,omitempty"` - Offset int64 `protobuf:"varint,4,opt,name=offset,proto3" json:"offset,omitempty"` - Total int64 `protobuf:"varint,5,opt,name=total,proto3" json:"total,omitempty"` - Expected string `protobuf:"bytes,6,opt,name=expected,proto3" json:"expected,omitempty"` -} - -func (x *Status) Reset() { - *x = Status{} - if protoimpl.UnsafeEnabled { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[10] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *Status) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*Status) ProtoMessage() {} - -func (x *Status) ProtoReflect() protoreflect.Message { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_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 Status.ProtoReflect.Descriptor instead. -func (*Status) Descriptor() ([]byte, []int) { - return file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDescGZIP(), []int{10} -} - -func (x *Status) GetStartedAt() *timestamppb.Timestamp { - if x != nil { - return x.StartedAt - } - return nil -} - -func (x *Status) GetUpdatedAt() *timestamppb.Timestamp { - if x != nil { - return x.UpdatedAt - } - return nil -} - -func (x *Status) GetRef() string { - if x != nil { - return x.Ref - } - return "" -} - -func (x *Status) GetOffset() int64 { - if x != nil { - return x.Offset - } - return 0 -} - -func (x *Status) GetTotal() int64 { - if x != nil { - return x.Total - } - return 0 -} - -func (x *Status) GetExpected() string { - if x != nil { - return x.Expected - } - return "" -} - -type StatusRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Ref string `protobuf:"bytes,1,opt,name=ref,proto3" json:"ref,omitempty"` -} - -func (x *StatusRequest) Reset() { - *x = StatusRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[11] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *StatusRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*StatusRequest) ProtoMessage() {} - -func (x *StatusRequest) ProtoReflect() protoreflect.Message { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_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 StatusRequest.ProtoReflect.Descriptor instead. -func (*StatusRequest) Descriptor() ([]byte, []int) { - return file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDescGZIP(), []int{11} -} - -func (x *StatusRequest) GetRef() string { - if x != nil { - return x.Ref - } - return "" -} - -type StatusResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Status *Status `protobuf:"bytes,1,opt,name=status,proto3" json:"status,omitempty"` -} - -func (x *StatusResponse) Reset() { - *x = StatusResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[12] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *StatusResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*StatusResponse) ProtoMessage() {} - -func (x *StatusResponse) ProtoReflect() protoreflect.Message { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_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 StatusResponse.ProtoReflect.Descriptor instead. -func (*StatusResponse) Descriptor() ([]byte, []int) { - return file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDescGZIP(), []int{12} -} - -func (x *StatusResponse) GetStatus() *Status { - if x != nil { - return x.Status - } - return nil -} - -type ListStatusesRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Filters []string `protobuf:"bytes,1,rep,name=filters,proto3" json:"filters,omitempty"` -} - -func (x *ListStatusesRequest) Reset() { - *x = ListStatusesRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[13] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *ListStatusesRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ListStatusesRequest) ProtoMessage() {} - -func (x *ListStatusesRequest) ProtoReflect() protoreflect.Message { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_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 ListStatusesRequest.ProtoReflect.Descriptor instead. -func (*ListStatusesRequest) Descriptor() ([]byte, []int) { - return file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDescGZIP(), []int{13} -} - -func (x *ListStatusesRequest) GetFilters() []string { - if x != nil { - return x.Filters - } - return nil -} - -type ListStatusesResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Statuses []*Status `protobuf:"bytes,1,rep,name=statuses,proto3" json:"statuses,omitempty"` -} - -func (x *ListStatusesResponse) Reset() { - *x = ListStatusesResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[14] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *ListStatusesResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ListStatusesResponse) ProtoMessage() {} - -func (x *ListStatusesResponse) ProtoReflect() protoreflect.Message { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_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 ListStatusesResponse.ProtoReflect.Descriptor instead. -func (*ListStatusesResponse) Descriptor() ([]byte, []int) { - return file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDescGZIP(), []int{14} -} - -func (x *ListStatusesResponse) GetStatuses() []*Status { - if x != nil { - return x.Statuses - } - return nil -} - -// WriteContentRequest writes data to the request ref at offset. -type WriteContentRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // Action sets the behavior of the write. - // - // When this is a write and the ref is not yet allocated, the ref will be - // allocated and the data will be written at offset. - // - // If the action is write and the ref is allocated, it will accept data to - // an offset that has not yet been written. - // - // If the action is write and there is no data, the current write status - // will be returned. This works differently from status because the stream - // holds a lock. - Action WriteAction `protobuf:"varint,1,opt,name=action,proto3,enum=containerd.services.content.v1.WriteAction" json:"action,omitempty"` - // Ref identifies the pre-commit object to write to. - Ref string `protobuf:"bytes,2,opt,name=ref,proto3" json:"ref,omitempty"` - // Total can be set to have the service validate the total size of the - // committed content. - // - // The latest value before or with the commit action message will be use to - // validate the content. If the offset overflows total, the service may - // report an error. It is only required on one message for the write. - // - // If the value is zero or less, no validation of the final content will be - // performed. - Total int64 `protobuf:"varint,3,opt,name=total,proto3" json:"total,omitempty"` - // Expected can be set to have the service validate the final content against - // the provided digest. - // - // If the digest is already present in the object store, an AlreadyExists - // error will be returned. - // - // Only the latest version will be used to check the content against the - // digest. It is only required to include it on a single message, before or - // with the commit action message. - Expected string `protobuf:"bytes,4,opt,name=expected,proto3" json:"expected,omitempty"` - // Offset specifies the number of bytes from the start at which to begin - // the write. For most implementations, this means from the start of the - // file. This uses standard, zero-indexed semantics. - // - // If the action is write, the remote may remove all previously written - // data after the offset. Implementations may support arbitrary offsets but - // MUST support reseting this value to zero with a write. If an - // implementation does not support a write at a particular offset, an - // OutOfRange error must be returned. - Offset int64 `protobuf:"varint,5,opt,name=offset,proto3" json:"offset,omitempty"` - // Data is the actual bytes to be written. - // - // If this is empty and the message is not a commit, a response will be - // returned with the current write state. - Data []byte `protobuf:"bytes,6,opt,name=data,proto3" json:"data,omitempty"` - // Labels are arbitrary data on snapshots. - // - // The combined size of a key/value pair cannot exceed 4096 bytes. - Labels map[string]string `protobuf:"bytes,7,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` -} - -func (x *WriteContentRequest) Reset() { - *x = WriteContentRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[15] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *WriteContentRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*WriteContentRequest) ProtoMessage() {} - -func (x *WriteContentRequest) ProtoReflect() protoreflect.Message { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_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 WriteContentRequest.ProtoReflect.Descriptor instead. -func (*WriteContentRequest) Descriptor() ([]byte, []int) { - return file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDescGZIP(), []int{15} -} - -func (x *WriteContentRequest) GetAction() WriteAction { - if x != nil { - return x.Action - } - return WriteAction_STAT -} - -func (x *WriteContentRequest) GetRef() string { - if x != nil { - return x.Ref - } - return "" -} - -func (x *WriteContentRequest) GetTotal() int64 { - if x != nil { - return x.Total - } - return 0 -} - -func (x *WriteContentRequest) GetExpected() string { - if x != nil { - return x.Expected - } - return "" -} - -func (x *WriteContentRequest) GetOffset() int64 { - if x != nil { - return x.Offset - } - return 0 -} - -func (x *WriteContentRequest) GetData() []byte { - if x != nil { - return x.Data - } - return nil -} - -func (x *WriteContentRequest) GetLabels() map[string]string { - if x != nil { - return x.Labels - } - return nil -} - -// WriteContentResponse is returned on the culmination of a write call. -type WriteContentResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // Action contains the action for the final message of the stream. A writer - // should confirm that they match the intended result. - Action WriteAction `protobuf:"varint,1,opt,name=action,proto3,enum=containerd.services.content.v1.WriteAction" json:"action,omitempty"` - // StartedAt provides the time at which the write began. - // - // This must be set for stat and commit write actions. All other write - // actions may omit this. - StartedAt *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=started_at,json=startedAt,proto3" json:"started_at,omitempty"` - // UpdatedAt provides the last time of a successful write. - // - // This must be set for stat and commit write actions. All other write - // actions may omit this. - UpdatedAt *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=updated_at,json=updatedAt,proto3" json:"updated_at,omitempty"` - // Offset is the current committed size for the write. - Offset int64 `protobuf:"varint,4,opt,name=offset,proto3" json:"offset,omitempty"` - // Total provides the current, expected total size of the write. - // - // We include this to provide consistency with the Status structure on the - // client writer. - // - // This is only valid on the Stat and Commit response. - Total int64 `protobuf:"varint,5,opt,name=total,proto3" json:"total,omitempty"` - // Digest, if present, includes the digest up to the currently committed - // bytes. If action is commit, this field will be set. It is implementation - // defined if this is set for other actions. - Digest string `protobuf:"bytes,6,opt,name=digest,proto3" json:"digest,omitempty"` -} - -func (x *WriteContentResponse) Reset() { - *x = WriteContentResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[16] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *WriteContentResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*WriteContentResponse) ProtoMessage() {} - -func (x *WriteContentResponse) ProtoReflect() protoreflect.Message { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_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 WriteContentResponse.ProtoReflect.Descriptor instead. -func (*WriteContentResponse) Descriptor() ([]byte, []int) { - return file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDescGZIP(), []int{16} -} - -func (x *WriteContentResponse) GetAction() WriteAction { - if x != nil { - return x.Action - } - return WriteAction_STAT -} - -func (x *WriteContentResponse) GetStartedAt() *timestamppb.Timestamp { - if x != nil { - return x.StartedAt - } - return nil -} - -func (x *WriteContentResponse) GetUpdatedAt() *timestamppb.Timestamp { - if x != nil { - return x.UpdatedAt - } - return nil -} - -func (x *WriteContentResponse) GetOffset() int64 { - if x != nil { - return x.Offset - } - return 0 -} - -func (x *WriteContentResponse) GetTotal() int64 { - if x != nil { - return x.Total - } - return 0 -} - -func (x *WriteContentResponse) GetDigest() string { - if x != nil { - return x.Digest - } - return "" -} - -type AbortRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Ref string `protobuf:"bytes,1,opt,name=ref,proto3" json:"ref,omitempty"` -} - -func (x *AbortRequest) Reset() { - *x = AbortRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[17] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *AbortRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*AbortRequest) ProtoMessage() {} - -func (x *AbortRequest) ProtoReflect() protoreflect.Message { - mi := &file_github_com_containerd_containerd_api_services_content_v1_content_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 AbortRequest.ProtoReflect.Descriptor instead. -func (*AbortRequest) Descriptor() ([]byte, []int) { - return file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDescGZIP(), []int{17} -} - -func (x *AbortRequest) GetRef() string { - if x != nil { - return x.Ref - } - return "" -} - -var File_github_com_containerd_containerd_api_services_content_v1_content_proto protoreflect.FileDescriptor - -var file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDesc = []byte{ - 0x0a, 0x46, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x6e, - 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x64, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, - 0x72, 0x64, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2f, - 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2f, 0x76, 0x31, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x65, - 0x6e, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1e, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, - 0x6e, 0x65, 0x72, 0x64, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x63, 0x6f, - 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x31, 0x1a, 0x20, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, - 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x5f, - 0x6d, 0x61, 0x73, 0x6b, 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, 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, 0x22, 0xad, 0x02, 0x0a, 0x04, 0x49, 0x6e, 0x66, - 0x6f, 0x12, 0x16, 0x0a, 0x06, 0x64, 0x69, 0x67, 0x65, 0x73, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, - 0x09, 0x52, 0x06, 0x64, 0x69, 0x67, 0x65, 0x73, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x73, 0x69, 0x7a, - 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x04, 0x73, 0x69, 0x7a, 0x65, 0x12, 0x39, 0x0a, - 0x0a, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x5f, 0x61, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x63, - 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x41, 0x74, 0x12, 0x39, 0x0a, 0x0a, 0x75, 0x70, 0x64, 0x61, - 0x74, 0x65, 0x64, 0x5f, 0x61, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, - 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, - 0x64, 0x41, 0x74, 0x12, 0x48, 0x0a, 0x06, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x73, 0x18, 0x05, 0x20, - 0x03, 0x28, 0x0b, 0x32, 0x30, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x64, - 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, - 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x4c, 0x61, 0x62, 0x65, 0x6c, 0x73, - 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x06, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x73, 0x1a, 0x39, 0x0a, - 0x0b, 0x4c, 0x61, 0x62, 0x65, 0x6c, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, - 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, - 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, - 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0x25, 0x0a, 0x0b, 0x49, 0x6e, 0x66, 0x6f, - 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x64, 0x69, 0x67, 0x65, 0x73, - 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x64, 0x69, 0x67, 0x65, 0x73, 0x74, 0x22, - 0x48, 0x0a, 0x0c, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, - 0x38, 0x0a, 0x04, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x24, 0x2e, - 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x64, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, - 0x63, 0x65, 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x49, - 0x6e, 0x66, 0x6f, 0x52, 0x04, 0x69, 0x6e, 0x66, 0x6f, 0x22, 0x86, 0x01, 0x0a, 0x0d, 0x55, 0x70, - 0x64, 0x61, 0x74, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x38, 0x0a, 0x04, 0x69, - 0x6e, 0x66, 0x6f, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x63, 0x6f, 0x6e, 0x74, - 0x61, 0x69, 0x6e, 0x65, 0x72, 0x64, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, - 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x49, 0x6e, 0x66, 0x6f, 0x52, - 0x04, 0x69, 0x6e, 0x66, 0x6f, 0x12, 0x3b, 0x0a, 0x0b, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x5f, - 0x6d, 0x61, 0x73, 0x6b, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x46, 0x69, 0x65, - 0x6c, 0x64, 0x4d, 0x61, 0x73, 0x6b, 0x52, 0x0a, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x4d, 0x61, - 0x73, 0x6b, 0x22, 0x4a, 0x0a, 0x0e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x52, 0x65, 0x73, 0x70, - 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x38, 0x0a, 0x04, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x01, 0x20, 0x01, - 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x64, 0x2e, - 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, - 0x2e, 0x76, 0x31, 0x2e, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x04, 0x69, 0x6e, 0x66, 0x6f, 0x22, 0x2e, - 0x0a, 0x12, 0x4c, 0x69, 0x73, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x71, - 0x75, 0x65, 0x73, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x73, 0x18, - 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x07, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x73, 0x22, 0x4f, - 0x0a, 0x13, 0x4c, 0x69, 0x73, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x73, - 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x38, 0x0a, 0x04, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x01, 0x20, - 0x03, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x64, - 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, - 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x04, 0x69, 0x6e, 0x66, 0x6f, 0x22, - 0x2e, 0x0a, 0x14, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, - 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x64, 0x69, 0x67, 0x65, 0x73, - 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x64, 0x69, 0x67, 0x65, 0x73, 0x74, 0x22, - 0x58, 0x0a, 0x12, 0x52, 0x65, 0x61, 0x64, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x52, 0x65, - 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x64, 0x69, 0x67, 0x65, 0x73, 0x74, 0x18, - 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x64, 0x69, 0x67, 0x65, 0x73, 0x74, 0x12, 0x16, 0x0a, - 0x06, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x06, 0x6f, - 0x66, 0x66, 0x73, 0x65, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x03, 0x20, - 0x01, 0x28, 0x03, 0x52, 0x04, 0x73, 0x69, 0x7a, 0x65, 0x22, 0x41, 0x0a, 0x13, 0x52, 0x65, 0x61, - 0x64, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, - 0x12, 0x16, 0x0a, 0x06, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, - 0x52, 0x06, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, - 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x22, 0xda, 0x01, 0x0a, - 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x39, 0x0a, 0x0a, 0x73, 0x74, 0x61, 0x72, 0x74, - 0x65, 0x64, 0x5f, 0x61, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, - 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, - 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x73, 0x74, 0x61, 0x72, 0x74, 0x65, 0x64, - 0x41, 0x74, 0x12, 0x39, 0x0a, 0x0a, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x5f, 0x61, 0x74, - 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, - 0x6d, 0x70, 0x52, 0x09, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x41, 0x74, 0x12, 0x10, 0x0a, - 0x03, 0x72, 0x65, 0x66, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x72, 0x65, 0x66, 0x12, - 0x16, 0x0a, 0x06, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, - 0x06, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x6f, 0x74, 0x61, 0x6c, - 0x18, 0x05, 0x20, 0x01, 0x28, 0x03, 0x52, 0x05, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x12, 0x1a, 0x0a, - 0x08, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x08, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x22, 0x21, 0x0a, 0x0d, 0x53, 0x74, 0x61, - 0x74, 0x75, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x10, 0x0a, 0x03, 0x72, 0x65, - 0x66, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x72, 0x65, 0x66, 0x22, 0x50, 0x0a, 0x0e, - 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3e, - 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x26, - 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x64, 0x2e, 0x73, 0x65, 0x72, 0x76, - 0x69, 0x63, 0x65, 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x31, 0x2e, - 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0x2f, - 0x0a, 0x13, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x65, 0x73, 0x52, 0x65, - 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x73, - 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x07, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x73, 0x22, - 0x5a, 0x0a, 0x14, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x65, 0x73, 0x52, - 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x42, 0x0a, 0x08, 0x73, 0x74, 0x61, 0x74, 0x75, - 0x73, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x63, 0x6f, 0x6e, 0x74, - 0x61, 0x69, 0x6e, 0x65, 0x72, 0x64, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, - 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, - 0x73, 0x52, 0x08, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x65, 0x73, 0x22, 0xde, 0x02, 0x0a, 0x13, - 0x57, 0x72, 0x69, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x71, 0x75, - 0x65, 0x73, 0x74, 0x12, 0x43, 0x0a, 0x06, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, - 0x01, 0x28, 0x0e, 0x32, 0x2b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x64, - 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, - 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x57, 0x72, 0x69, 0x74, 0x65, 0x41, 0x63, 0x74, 0x69, 0x6f, 0x6e, - 0x52, 0x06, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x10, 0x0a, 0x03, 0x72, 0x65, 0x66, 0x18, - 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x72, 0x65, 0x66, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x6f, - 0x74, 0x61, 0x6c, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x05, 0x74, 0x6f, 0x74, 0x61, 0x6c, - 0x12, 0x1a, 0x0a, 0x08, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x18, 0x04, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x08, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x12, 0x16, 0x0a, 0x06, - 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x03, 0x52, 0x06, 0x6f, 0x66, - 0x66, 0x73, 0x65, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x06, 0x20, 0x01, - 0x28, 0x0c, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x12, 0x57, 0x0a, 0x06, 0x6c, 0x61, 0x62, 0x65, - 0x6c, 0x73, 0x18, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x3f, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x61, - 0x69, 0x6e, 0x65, 0x72, 0x64, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x63, - 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x57, 0x72, 0x69, 0x74, 0x65, 0x43, - 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x4c, 0x61, - 0x62, 0x65, 0x6c, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x06, 0x6c, 0x61, 0x62, 0x65, 0x6c, - 0x73, 0x1a, 0x39, 0x0a, 0x0b, 0x4c, 0x61, 0x62, 0x65, 0x6c, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, - 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, - 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, - 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0x97, 0x02, 0x0a, - 0x14, 0x57, 0x72, 0x69, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x73, - 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x43, 0x0a, 0x06, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x18, - 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2b, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, - 0x72, 0x64, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, - 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x57, 0x72, 0x69, 0x74, 0x65, 0x41, 0x63, 0x74, 0x69, - 0x6f, 0x6e, 0x52, 0x06, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x39, 0x0a, 0x0a, 0x73, 0x74, - 0x61, 0x72, 0x74, 0x65, 0x64, 0x5f, 0x61, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, - 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, - 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x73, 0x74, 0x61, 0x72, - 0x74, 0x65, 0x64, 0x41, 0x74, 0x12, 0x39, 0x0a, 0x0a, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, - 0x5f, 0x61, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, - 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, - 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x41, 0x74, - 0x12, 0x16, 0x0a, 0x06, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, - 0x52, 0x06, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x6f, 0x74, 0x61, - 0x6c, 0x18, 0x05, 0x20, 0x01, 0x28, 0x03, 0x52, 0x05, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x12, 0x16, - 0x0a, 0x06, 0x64, 0x69, 0x67, 0x65, 0x73, 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, - 0x64, 0x69, 0x67, 0x65, 0x73, 0x74, 0x22, 0x20, 0x0a, 0x0c, 0x41, 0x62, 0x6f, 0x72, 0x74, 0x52, - 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x10, 0x0a, 0x03, 0x72, 0x65, 0x66, 0x18, 0x01, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x03, 0x72, 0x65, 0x66, 0x2a, 0x2e, 0x0a, 0x0b, 0x57, 0x72, 0x69, 0x74, - 0x65, 0x41, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x08, 0x0a, 0x04, 0x53, 0x54, 0x41, 0x54, 0x10, - 0x00, 0x12, 0x09, 0x0a, 0x05, 0x57, 0x52, 0x49, 0x54, 0x45, 0x10, 0x01, 0x12, 0x0a, 0x0a, 0x06, - 0x43, 0x4f, 0x4d, 0x4d, 0x49, 0x54, 0x10, 0x02, 0x32, 0xbe, 0x07, 0x0a, 0x07, 0x43, 0x6f, 0x6e, - 0x74, 0x65, 0x6e, 0x74, 0x12, 0x61, 0x0a, 0x04, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x2b, 0x2e, 0x63, - 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x64, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, - 0x65, 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x49, 0x6e, - 0x66, 0x6f, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2c, 0x2e, 0x63, 0x6f, 0x6e, 0x74, - 0x61, 0x69, 0x6e, 0x65, 0x72, 0x64, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, - 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x49, 0x6e, 0x66, 0x6f, 0x52, - 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x67, 0x0a, 0x06, 0x55, 0x70, 0x64, 0x61, 0x74, - 0x65, 0x12, 0x2d, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x64, 0x2e, 0x73, - 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2e, - 0x76, 0x31, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x1a, 0x2e, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x64, 0x2e, 0x73, 0x65, - 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2e, 0x76, - 0x31, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, - 0x12, 0x71, 0x0a, 0x04, 0x4c, 0x69, 0x73, 0x74, 0x12, 0x32, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x61, - 0x69, 0x6e, 0x65, 0x72, 0x64, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x63, - 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x43, 0x6f, - 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x33, 0x2e, 0x63, - 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x64, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, - 0x65, 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x4c, 0x69, - 0x73, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, - 0x65, 0x30, 0x01, 0x12, 0x56, 0x0a, 0x06, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x12, 0x34, 0x2e, - 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x64, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, - 0x63, 0x65, 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x44, - 0x65, 0x6c, 0x65, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x71, 0x75, - 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x71, 0x0a, 0x04, 0x52, - 0x65, 0x61, 0x64, 0x12, 0x32, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x64, - 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, - 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x61, 0x64, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, - 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x33, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, - 0x6e, 0x65, 0x72, 0x64, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x63, 0x6f, - 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x61, 0x64, 0x43, 0x6f, 0x6e, - 0x74, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x30, 0x01, 0x12, 0x67, - 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x2d, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x61, - 0x69, 0x6e, 0x65, 0x72, 0x64, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x63, - 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, - 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2e, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, - 0x6e, 0x65, 0x72, 0x64, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x63, 0x6f, - 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, - 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x79, 0x0a, 0x0c, 0x4c, 0x69, 0x73, 0x74, 0x53, - 0x74, 0x61, 0x74, 0x75, 0x73, 0x65, 0x73, 0x12, 0x33, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, - 0x6e, 0x65, 0x72, 0x64, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x63, 0x6f, - 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x74, 0x61, - 0x74, 0x75, 0x73, 0x65, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x34, 0x2e, 0x63, - 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x64, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, - 0x65, 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x4c, 0x69, - 0x73, 0x74, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x65, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, - 0x73, 0x65, 0x12, 0x76, 0x0a, 0x05, 0x57, 0x72, 0x69, 0x74, 0x65, 0x12, 0x33, 0x2e, 0x63, 0x6f, - 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x64, 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, - 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x57, 0x72, 0x69, - 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x1a, 0x34, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x64, 0x2e, 0x73, 0x65, - 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2e, 0x76, - 0x31, 0x2e, 0x57, 0x72, 0x69, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x52, 0x65, - 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x28, 0x01, 0x30, 0x01, 0x12, 0x4d, 0x0a, 0x05, 0x41, 0x62, - 0x6f, 0x72, 0x74, 0x12, 0x2c, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x64, - 0x2e, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, - 0x74, 0x2e, 0x76, 0x31, 0x2e, 0x41, 0x62, 0x6f, 0x72, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, - 0x74, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x42, 0x42, 0x5a, 0x40, 0x67, 0x69, 0x74, - 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, - 0x72, 0x64, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x64, 0x2f, 0x61, 0x70, - 0x69, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x65, - 0x6e, 0x74, 0x2f, 0x76, 0x31, 0x3b, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x62, 0x06, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x33, -} - -var ( - file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDescOnce sync.Once - file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDescData = file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDesc -) - -func file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDescGZIP() []byte { - file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDescOnce.Do(func() { - file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDescData = protoimpl.X.CompressGZIP(file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDescData) - }) - return file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDescData -} - -var file_github_com_containerd_containerd_api_services_content_v1_content_proto_enumTypes = make([]protoimpl.EnumInfo, 1) -var file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes = make([]protoimpl.MessageInfo, 20) -var file_github_com_containerd_containerd_api_services_content_v1_content_proto_goTypes = []interface{}{ - (WriteAction)(0), // 0: containerd.services.content.v1.WriteAction - (*Info)(nil), // 1: containerd.services.content.v1.Info - (*InfoRequest)(nil), // 2: containerd.services.content.v1.InfoRequest - (*InfoResponse)(nil), // 3: containerd.services.content.v1.InfoResponse - (*UpdateRequest)(nil), // 4: containerd.services.content.v1.UpdateRequest - (*UpdateResponse)(nil), // 5: containerd.services.content.v1.UpdateResponse - (*ListContentRequest)(nil), // 6: containerd.services.content.v1.ListContentRequest - (*ListContentResponse)(nil), // 7: containerd.services.content.v1.ListContentResponse - (*DeleteContentRequest)(nil), // 8: containerd.services.content.v1.DeleteContentRequest - (*ReadContentRequest)(nil), // 9: containerd.services.content.v1.ReadContentRequest - (*ReadContentResponse)(nil), // 10: containerd.services.content.v1.ReadContentResponse - (*Status)(nil), // 11: containerd.services.content.v1.Status - (*StatusRequest)(nil), // 12: containerd.services.content.v1.StatusRequest - (*StatusResponse)(nil), // 13: containerd.services.content.v1.StatusResponse - (*ListStatusesRequest)(nil), // 14: containerd.services.content.v1.ListStatusesRequest - (*ListStatusesResponse)(nil), // 15: containerd.services.content.v1.ListStatusesResponse - (*WriteContentRequest)(nil), // 16: containerd.services.content.v1.WriteContentRequest - (*WriteContentResponse)(nil), // 17: containerd.services.content.v1.WriteContentResponse - (*AbortRequest)(nil), // 18: containerd.services.content.v1.AbortRequest - nil, // 19: containerd.services.content.v1.Info.LabelsEntry - nil, // 20: containerd.services.content.v1.WriteContentRequest.LabelsEntry - (*timestamppb.Timestamp)(nil), // 21: google.protobuf.Timestamp - (*fieldmaskpb.FieldMask)(nil), // 22: google.protobuf.FieldMask - (*emptypb.Empty)(nil), // 23: google.protobuf.Empty -} -var file_github_com_containerd_containerd_api_services_content_v1_content_proto_depIdxs = []int32{ - 21, // 0: containerd.services.content.v1.Info.created_at:type_name -> google.protobuf.Timestamp - 21, // 1: containerd.services.content.v1.Info.updated_at:type_name -> google.protobuf.Timestamp - 19, // 2: containerd.services.content.v1.Info.labels:type_name -> containerd.services.content.v1.Info.LabelsEntry - 1, // 3: containerd.services.content.v1.InfoResponse.info:type_name -> containerd.services.content.v1.Info - 1, // 4: containerd.services.content.v1.UpdateRequest.info:type_name -> containerd.services.content.v1.Info - 22, // 5: containerd.services.content.v1.UpdateRequest.update_mask:type_name -> google.protobuf.FieldMask - 1, // 6: containerd.services.content.v1.UpdateResponse.info:type_name -> containerd.services.content.v1.Info - 1, // 7: containerd.services.content.v1.ListContentResponse.info:type_name -> containerd.services.content.v1.Info - 21, // 8: containerd.services.content.v1.Status.started_at:type_name -> google.protobuf.Timestamp - 21, // 9: containerd.services.content.v1.Status.updated_at:type_name -> google.protobuf.Timestamp - 11, // 10: containerd.services.content.v1.StatusResponse.status:type_name -> containerd.services.content.v1.Status - 11, // 11: containerd.services.content.v1.ListStatusesResponse.statuses:type_name -> containerd.services.content.v1.Status - 0, // 12: containerd.services.content.v1.WriteContentRequest.action:type_name -> containerd.services.content.v1.WriteAction - 20, // 13: containerd.services.content.v1.WriteContentRequest.labels:type_name -> containerd.services.content.v1.WriteContentRequest.LabelsEntry - 0, // 14: containerd.services.content.v1.WriteContentResponse.action:type_name -> containerd.services.content.v1.WriteAction - 21, // 15: containerd.services.content.v1.WriteContentResponse.started_at:type_name -> google.protobuf.Timestamp - 21, // 16: containerd.services.content.v1.WriteContentResponse.updated_at:type_name -> google.protobuf.Timestamp - 2, // 17: containerd.services.content.v1.Content.Info:input_type -> containerd.services.content.v1.InfoRequest - 4, // 18: containerd.services.content.v1.Content.Update:input_type -> containerd.services.content.v1.UpdateRequest - 6, // 19: containerd.services.content.v1.Content.List:input_type -> containerd.services.content.v1.ListContentRequest - 8, // 20: containerd.services.content.v1.Content.Delete:input_type -> containerd.services.content.v1.DeleteContentRequest - 9, // 21: containerd.services.content.v1.Content.Read:input_type -> containerd.services.content.v1.ReadContentRequest - 12, // 22: containerd.services.content.v1.Content.Status:input_type -> containerd.services.content.v1.StatusRequest - 14, // 23: containerd.services.content.v1.Content.ListStatuses:input_type -> containerd.services.content.v1.ListStatusesRequest - 16, // 24: containerd.services.content.v1.Content.Write:input_type -> containerd.services.content.v1.WriteContentRequest - 18, // 25: containerd.services.content.v1.Content.Abort:input_type -> containerd.services.content.v1.AbortRequest - 3, // 26: containerd.services.content.v1.Content.Info:output_type -> containerd.services.content.v1.InfoResponse - 5, // 27: containerd.services.content.v1.Content.Update:output_type -> containerd.services.content.v1.UpdateResponse - 7, // 28: containerd.services.content.v1.Content.List:output_type -> containerd.services.content.v1.ListContentResponse - 23, // 29: containerd.services.content.v1.Content.Delete:output_type -> google.protobuf.Empty - 10, // 30: containerd.services.content.v1.Content.Read:output_type -> containerd.services.content.v1.ReadContentResponse - 13, // 31: containerd.services.content.v1.Content.Status:output_type -> containerd.services.content.v1.StatusResponse - 15, // 32: containerd.services.content.v1.Content.ListStatuses:output_type -> containerd.services.content.v1.ListStatusesResponse - 17, // 33: containerd.services.content.v1.Content.Write:output_type -> containerd.services.content.v1.WriteContentResponse - 23, // 34: containerd.services.content.v1.Content.Abort:output_type -> google.protobuf.Empty - 26, // [26:35] is the sub-list for method output_type - 17, // [17:26] is the sub-list for method input_type - 17, // [17:17] is the sub-list for extension type_name - 17, // [17:17] is the sub-list for extension extendee - 0, // [0:17] is the sub-list for field type_name -} - -func init() { file_github_com_containerd_containerd_api_services_content_v1_content_proto_init() } -func file_github_com_containerd_containerd_api_services_content_v1_content_proto_init() { - if File_github_com_containerd_containerd_api_services_content_v1_content_proto != nil { - return - } - if !protoimpl.UnsafeEnabled { - file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Info); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*InfoRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*InfoResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*UpdateRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*UpdateResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListContentRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListContentResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*DeleteContentRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ReadContentRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ReadContentResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[10].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 - } - } - file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[11].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*StatusRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[12].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*StatusResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[13].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListStatusesRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[14].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListStatusesResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[15].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*WriteContentRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[16].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*WriteContentResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes[17].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*AbortRequest); 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_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDesc, - NumEnums: 1, - NumMessages: 20, - NumExtensions: 0, - NumServices: 1, - }, - GoTypes: file_github_com_containerd_containerd_api_services_content_v1_content_proto_goTypes, - DependencyIndexes: file_github_com_containerd_containerd_api_services_content_v1_content_proto_depIdxs, - EnumInfos: file_github_com_containerd_containerd_api_services_content_v1_content_proto_enumTypes, - MessageInfos: file_github_com_containerd_containerd_api_services_content_v1_content_proto_msgTypes, - }.Build() - File_github_com_containerd_containerd_api_services_content_v1_content_proto = out.File - file_github_com_containerd_containerd_api_services_content_v1_content_proto_rawDesc = nil - file_github_com_containerd_containerd_api_services_content_v1_content_proto_goTypes = nil - file_github_com_containerd_containerd_api_services_content_v1_content_proto_depIdxs = nil -} diff --git a/vendor/github.com/containerd/containerd/api/services/content/v1/content.proto b/vendor/github.com/containerd/containerd/api/services/content/v1/content.proto deleted file mode 100644 index 8aea0636b..000000000 --- a/vendor/github.com/containerd/containerd/api/services/content/v1/content.proto +++ /dev/null @@ -1,330 +0,0 @@ -/* - Copyright The containerd 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. -*/ - -syntax = "proto3"; - -package containerd.services.content.v1; - -import "google/protobuf/field_mask.proto"; -import "google/protobuf/timestamp.proto"; -import "google/protobuf/empty.proto"; - -option go_package = "github.com/containerd/containerd/api/services/content/v1;content"; - -// Content provides access to a content addressable storage system. -service Content { - // Info returns information about a committed object. - // - // This call can be used for getting the size of content and checking for - // existence. - rpc Info(InfoRequest) returns (InfoResponse); - - // Update updates content metadata. - // - // This call can be used to manage the mutable content labels. The - // immutable metadata such as digest, size, and committed at cannot - // be updated. - rpc Update(UpdateRequest) returns (UpdateResponse); - - // List streams the entire set of content as Info objects and closes the - // stream. - // - // Typically, this will yield a large response, chunked into messages. - // Clients should make provisions to ensure they can handle the entire data - // set. - rpc List(ListContentRequest) returns (stream ListContentResponse); - - // Delete will delete the referenced object. - rpc Delete(DeleteContentRequest) returns (google.protobuf.Empty); - - // Read allows one to read an object based on the offset into the content. - // - // The requested data may be returned in one or more messages. - rpc Read(ReadContentRequest) returns (stream ReadContentResponse); - - // Status returns the status for a single reference. - rpc Status(StatusRequest) returns (StatusResponse); - - // ListStatuses returns the status of ongoing object ingestions, started via - // Write. - // - // Only those matching the regular expression will be provided in the - // response. If the provided regular expression is empty, all ingestions - // will be provided. - rpc ListStatuses(ListStatusesRequest) returns (ListStatusesResponse); - - // Write begins or resumes writes to a resource identified by a unique ref. - // Only one active stream may exist at a time for each ref. - // - // Once a write stream has started, it may only write to a single ref, thus - // once a stream is started, the ref may be omitted on subsequent writes. - // - // For any write transaction represented by a ref, only a single write may - // be made to a given offset. If overlapping writes occur, it is an error. - // Writes should be sequential and implementations may throw an error if - // this is required. - // - // If expected_digest is set and already part of the content store, the - // write will fail. - // - // When completed, the commit flag should be set to true. If expected size - // or digest is set, the content will be validated against those values. - rpc Write(stream WriteContentRequest) returns (stream WriteContentResponse); - - // Abort cancels the ongoing write named in the request. Any resources - // associated with the write will be collected. - rpc Abort(AbortRequest) returns (google.protobuf.Empty); -} - -message Info { - // Digest is the hash identity of the blob. - string digest = 1; - - // Size is the total number of bytes in the blob. - int64 size = 2; - - // CreatedAt provides the time at which the blob was committed. - google.protobuf.Timestamp created_at = 3; - - // UpdatedAt provides the time the info was last updated. - google.protobuf.Timestamp updated_at = 4; - - // Labels are arbitrary data on snapshots. - // - // The combined size of a key/value pair cannot exceed 4096 bytes. - map labels = 5; -} - -message InfoRequest { - string digest = 1; -} - -message InfoResponse { - Info info = 1; -} - -message UpdateRequest { - Info info = 1; - - // UpdateMask specifies which fields to perform the update on. If empty, - // the operation applies to all fields. - // - // In info, Digest, Size, and CreatedAt are immutable, - // other field may be updated using this mask. - // If no mask is provided, all mutable field are updated. - google.protobuf.FieldMask update_mask = 2; -} - -message UpdateResponse { - Info info = 1; -} - -message ListContentRequest { - // Filters contains one or more filters using the syntax defined in the - // containerd filter package. - // - // The returned result will be those that match any of the provided - // filters. Expanded, containers that match the following will be - // returned: - // - // filters[0] or filters[1] or ... or filters[n-1] or filters[n] - // - // If filters is zero-length or nil, all items will be returned. - repeated string filters = 1; -} - -message ListContentResponse { - repeated Info info = 1; -} - -message DeleteContentRequest { - // Digest specifies which content to delete. - string digest = 1; -} - -// ReadContentRequest defines the fields that make up a request to read a portion of -// data from a stored object. -message ReadContentRequest { - // Digest is the hash identity to read. - string digest = 1; - - // Offset specifies the number of bytes from the start at which to begin - // the read. If zero or less, the read will be from the start. This uses - // standard zero-indexed semantics. - int64 offset = 2; - - // size is the total size of the read. If zero, the entire blob will be - // returned by the service. - int64 size = 3; -} - -// ReadContentResponse carries byte data for a read request. -message ReadContentResponse { - int64 offset = 1; // offset of the returned data - bytes data = 2; // actual data -} - -message Status { - google.protobuf.Timestamp started_at = 1; - google.protobuf.Timestamp updated_at = 2; - string ref = 3; - int64 offset = 4; - int64 total = 5; - string expected = 6; -} - - -message StatusRequest { - string ref = 1; -} - -message StatusResponse { - Status status = 1; -} - -message ListStatusesRequest { - repeated string filters = 1; -} - -message ListStatusesResponse { - repeated Status statuses = 1; -} - -// WriteAction defines the behavior of a WriteRequest. -enum WriteAction { - // WriteActionStat instructs the writer to return the current status while - // holding the lock on the write. - STAT = 0; - - // WriteActionWrite sets the action for the write request to write data. - // - // Any data included will be written at the provided offset. The - // transaction will be left open for further writes. - // - // This is the default. - WRITE = 1; - - // WriteActionCommit will write any outstanding data in the message and - // commit the write, storing it under the digest. - // - // This can be used in a single message to send the data, verify it and - // commit it. - // - // This action will always terminate the write. - COMMIT = 2; -} - -// WriteContentRequest writes data to the request ref at offset. -message WriteContentRequest { - // Action sets the behavior of the write. - // - // When this is a write and the ref is not yet allocated, the ref will be - // allocated and the data will be written at offset. - // - // If the action is write and the ref is allocated, it will accept data to - // an offset that has not yet been written. - // - // If the action is write and there is no data, the current write status - // will be returned. This works differently from status because the stream - // holds a lock. - WriteAction action = 1; - - // Ref identifies the pre-commit object to write to. - string ref = 2; - - // Total can be set to have the service validate the total size of the - // committed content. - // - // The latest value before or with the commit action message will be use to - // validate the content. If the offset overflows total, the service may - // report an error. It is only required on one message for the write. - // - // If the value is zero or less, no validation of the final content will be - // performed. - int64 total = 3; - - // Expected can be set to have the service validate the final content against - // the provided digest. - // - // If the digest is already present in the object store, an AlreadyExists - // error will be returned. - // - // Only the latest version will be used to check the content against the - // digest. It is only required to include it on a single message, before or - // with the commit action message. - string expected = 4; - - // Offset specifies the number of bytes from the start at which to begin - // the write. For most implementations, this means from the start of the - // file. This uses standard, zero-indexed semantics. - // - // If the action is write, the remote may remove all previously written - // data after the offset. Implementations may support arbitrary offsets but - // MUST support reseting this value to zero with a write. If an - // implementation does not support a write at a particular offset, an - // OutOfRange error must be returned. - int64 offset = 5; - - // Data is the actual bytes to be written. - // - // If this is empty and the message is not a commit, a response will be - // returned with the current write state. - bytes data = 6; - - // Labels are arbitrary data on snapshots. - // - // The combined size of a key/value pair cannot exceed 4096 bytes. - map labels = 7; -} - -// WriteContentResponse is returned on the culmination of a write call. -message WriteContentResponse { - // Action contains the action for the final message of the stream. A writer - // should confirm that they match the intended result. - WriteAction action = 1; - - // StartedAt provides the time at which the write began. - // - // This must be set for stat and commit write actions. All other write - // actions may omit this. - google.protobuf.Timestamp started_at = 2; - - // UpdatedAt provides the last time of a successful write. - // - // This must be set for stat and commit write actions. All other write - // actions may omit this. - google.protobuf.Timestamp updated_at = 3; - - // Offset is the current committed size for the write. - int64 offset = 4; - - // Total provides the current, expected total size of the write. - // - // We include this to provide consistency with the Status structure on the - // client writer. - // - // This is only valid on the Stat and Commit response. - int64 total = 5; - - // Digest, if present, includes the digest up to the currently committed - // bytes. If action is commit, this field will be set. It is implementation - // defined if this is set for other actions. - string digest = 6; -} - -message AbortRequest { - string ref = 1; -} diff --git a/vendor/github.com/containerd/containerd/api/services/content/v1/content_grpc.pb.go b/vendor/github.com/containerd/containerd/api/services/content/v1/content_grpc.pb.go deleted file mode 100644 index e230c45a6..000000000 --- a/vendor/github.com/containerd/containerd/api/services/content/v1/content_grpc.pb.go +++ /dev/null @@ -1,569 +0,0 @@ -// Code generated by protoc-gen-go-grpc. DO NOT EDIT. -// versions: -// - protoc-gen-go-grpc v1.2.0 -// - protoc v3.20.1 -// source: github.com/containerd/containerd/api/services/content/v1/content.proto - -package content - -import ( - context "context" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - emptypb "google.golang.org/protobuf/types/known/emptypb" -) - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -// Requires gRPC-Go v1.32.0 or later. -const _ = grpc.SupportPackageIsVersion7 - -// ContentClient is the client API for Content 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 ContentClient interface { - // Info returns information about a committed object. - // - // This call can be used for getting the size of content and checking for - // existence. - Info(ctx context.Context, in *InfoRequest, opts ...grpc.CallOption) (*InfoResponse, error) - // Update updates content metadata. - // - // This call can be used to manage the mutable content labels. The - // immutable metadata such as digest, size, and committed at cannot - // be updated. - Update(ctx context.Context, in *UpdateRequest, opts ...grpc.CallOption) (*UpdateResponse, error) - // List streams the entire set of content as Info objects and closes the - // stream. - // - // Typically, this will yield a large response, chunked into messages. - // Clients should make provisions to ensure they can handle the entire data - // set. - List(ctx context.Context, in *ListContentRequest, opts ...grpc.CallOption) (Content_ListClient, error) - // Delete will delete the referenced object. - Delete(ctx context.Context, in *DeleteContentRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) - // Read allows one to read an object based on the offset into the content. - // - // The requested data may be returned in one or more messages. - Read(ctx context.Context, in *ReadContentRequest, opts ...grpc.CallOption) (Content_ReadClient, error) - // Status returns the status for a single reference. - Status(ctx context.Context, in *StatusRequest, opts ...grpc.CallOption) (*StatusResponse, error) - // ListStatuses returns the status of ongoing object ingestions, started via - // Write. - // - // Only those matching the regular expression will be provided in the - // response. If the provided regular expression is empty, all ingestions - // will be provided. - ListStatuses(ctx context.Context, in *ListStatusesRequest, opts ...grpc.CallOption) (*ListStatusesResponse, error) - // Write begins or resumes writes to a resource identified by a unique ref. - // Only one active stream may exist at a time for each ref. - // - // Once a write stream has started, it may only write to a single ref, thus - // once a stream is started, the ref may be omitted on subsequent writes. - // - // For any write transaction represented by a ref, only a single write may - // be made to a given offset. If overlapping writes occur, it is an error. - // Writes should be sequential and implementations may throw an error if - // this is required. - // - // If expected_digest is set and already part of the content store, the - // write will fail. - // - // When completed, the commit flag should be set to true. If expected size - // or digest is set, the content will be validated against those values. - Write(ctx context.Context, opts ...grpc.CallOption) (Content_WriteClient, error) - // Abort cancels the ongoing write named in the request. Any resources - // associated with the write will be collected. - Abort(ctx context.Context, in *AbortRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) -} - -type contentClient struct { - cc grpc.ClientConnInterface -} - -func NewContentClient(cc grpc.ClientConnInterface) ContentClient { - return &contentClient{cc} -} - -func (c *contentClient) Info(ctx context.Context, in *InfoRequest, opts ...grpc.CallOption) (*InfoResponse, error) { - out := new(InfoResponse) - err := c.cc.Invoke(ctx, "/containerd.services.content.v1.Content/Info", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *contentClient) Update(ctx context.Context, in *UpdateRequest, opts ...grpc.CallOption) (*UpdateResponse, error) { - out := new(UpdateResponse) - err := c.cc.Invoke(ctx, "/containerd.services.content.v1.Content/Update", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *contentClient) List(ctx context.Context, in *ListContentRequest, opts ...grpc.CallOption) (Content_ListClient, error) { - stream, err := c.cc.NewStream(ctx, &Content_ServiceDesc.Streams[0], "/containerd.services.content.v1.Content/List", opts...) - if err != nil { - return nil, err - } - x := &contentListClient{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 Content_ListClient interface { - Recv() (*ListContentResponse, error) - grpc.ClientStream -} - -type contentListClient struct { - grpc.ClientStream -} - -func (x *contentListClient) Recv() (*ListContentResponse, error) { - m := new(ListContentResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *contentClient) Delete(ctx context.Context, in *DeleteContentRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) { - out := new(emptypb.Empty) - err := c.cc.Invoke(ctx, "/containerd.services.content.v1.Content/Delete", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *contentClient) Read(ctx context.Context, in *ReadContentRequest, opts ...grpc.CallOption) (Content_ReadClient, error) { - stream, err := c.cc.NewStream(ctx, &Content_ServiceDesc.Streams[1], "/containerd.services.content.v1.Content/Read", opts...) - if err != nil { - return nil, err - } - x := &contentReadClient{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 Content_ReadClient interface { - Recv() (*ReadContentResponse, error) - grpc.ClientStream -} - -type contentReadClient struct { - grpc.ClientStream -} - -func (x *contentReadClient) Recv() (*ReadContentResponse, error) { - m := new(ReadContentResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *contentClient) Status(ctx context.Context, in *StatusRequest, opts ...grpc.CallOption) (*StatusResponse, error) { - out := new(StatusResponse) - err := c.cc.Invoke(ctx, "/containerd.services.content.v1.Content/Status", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *contentClient) ListStatuses(ctx context.Context, in *ListStatusesRequest, opts ...grpc.CallOption) (*ListStatusesResponse, error) { - out := new(ListStatusesResponse) - err := c.cc.Invoke(ctx, "/containerd.services.content.v1.Content/ListStatuses", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *contentClient) Write(ctx context.Context, opts ...grpc.CallOption) (Content_WriteClient, error) { - stream, err := c.cc.NewStream(ctx, &Content_ServiceDesc.Streams[2], "/containerd.services.content.v1.Content/Write", opts...) - if err != nil { - return nil, err - } - x := &contentWriteClient{stream} - return x, nil -} - -type Content_WriteClient interface { - Send(*WriteContentRequest) error - Recv() (*WriteContentResponse, error) - grpc.ClientStream -} - -type contentWriteClient struct { - grpc.ClientStream -} - -func (x *contentWriteClient) Send(m *WriteContentRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *contentWriteClient) Recv() (*WriteContentResponse, error) { - m := new(WriteContentResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *contentClient) Abort(ctx context.Context, in *AbortRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) { - out := new(emptypb.Empty) - err := c.cc.Invoke(ctx, "/containerd.services.content.v1.Content/Abort", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// ContentServer is the server API for Content service. -// All implementations must embed UnimplementedContentServer -// for forward compatibility -type ContentServer interface { - // Info returns information about a committed object. - // - // This call can be used for getting the size of content and checking for - // existence. - Info(context.Context, *InfoRequest) (*InfoResponse, error) - // Update updates content metadata. - // - // This call can be used to manage the mutable content labels. The - // immutable metadata such as digest, size, and committed at cannot - // be updated. - Update(context.Context, *UpdateRequest) (*UpdateResponse, error) - // List streams the entire set of content as Info objects and closes the - // stream. - // - // Typically, this will yield a large response, chunked into messages. - // Clients should make provisions to ensure they can handle the entire data - // set. - List(*ListContentRequest, Content_ListServer) error - // Delete will delete the referenced object. - Delete(context.Context, *DeleteContentRequest) (*emptypb.Empty, error) - // Read allows one to read an object based on the offset into the content. - // - // The requested data may be returned in one or more messages. - Read(*ReadContentRequest, Content_ReadServer) error - // Status returns the status for a single reference. - Status(context.Context, *StatusRequest) (*StatusResponse, error) - // ListStatuses returns the status of ongoing object ingestions, started via - // Write. - // - // Only those matching the regular expression will be provided in the - // response. If the provided regular expression is empty, all ingestions - // will be provided. - ListStatuses(context.Context, *ListStatusesRequest) (*ListStatusesResponse, error) - // Write begins or resumes writes to a resource identified by a unique ref. - // Only one active stream may exist at a time for each ref. - // - // Once a write stream has started, it may only write to a single ref, thus - // once a stream is started, the ref may be omitted on subsequent writes. - // - // For any write transaction represented by a ref, only a single write may - // be made to a given offset. If overlapping writes occur, it is an error. - // Writes should be sequential and implementations may throw an error if - // this is required. - // - // If expected_digest is set and already part of the content store, the - // write will fail. - // - // When completed, the commit flag should be set to true. If expected size - // or digest is set, the content will be validated against those values. - Write(Content_WriteServer) error - // Abort cancels the ongoing write named in the request. Any resources - // associated with the write will be collected. - Abort(context.Context, *AbortRequest) (*emptypb.Empty, error) - mustEmbedUnimplementedContentServer() -} - -// UnimplementedContentServer must be embedded to have forward compatible implementations. -type UnimplementedContentServer struct { -} - -func (UnimplementedContentServer) Info(context.Context, *InfoRequest) (*InfoResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Info not implemented") -} -func (UnimplementedContentServer) Update(context.Context, *UpdateRequest) (*UpdateResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Update not implemented") -} -func (UnimplementedContentServer) List(*ListContentRequest, Content_ListServer) error { - return status.Errorf(codes.Unimplemented, "method List not implemented") -} -func (UnimplementedContentServer) Delete(context.Context, *DeleteContentRequest) (*emptypb.Empty, error) { - return nil, status.Errorf(codes.Unimplemented, "method Delete not implemented") -} -func (UnimplementedContentServer) Read(*ReadContentRequest, Content_ReadServer) error { - return status.Errorf(codes.Unimplemented, "method Read not implemented") -} -func (UnimplementedContentServer) Status(context.Context, *StatusRequest) (*StatusResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Status not implemented") -} -func (UnimplementedContentServer) ListStatuses(context.Context, *ListStatusesRequest) (*ListStatusesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ListStatuses not implemented") -} -func (UnimplementedContentServer) Write(Content_WriteServer) error { - return status.Errorf(codes.Unimplemented, "method Write not implemented") -} -func (UnimplementedContentServer) Abort(context.Context, *AbortRequest) (*emptypb.Empty, error) { - return nil, status.Errorf(codes.Unimplemented, "method Abort not implemented") -} -func (UnimplementedContentServer) mustEmbedUnimplementedContentServer() {} - -// UnsafeContentServer may be embedded to opt out of forward compatibility for this service. -// Use of this interface is not recommended, as added methods to ContentServer will -// result in compilation errors. -type UnsafeContentServer interface { - mustEmbedUnimplementedContentServer() -} - -func RegisterContentServer(s grpc.ServiceRegistrar, srv ContentServer) { - s.RegisterService(&Content_ServiceDesc, srv) -} - -func _Content_Info_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(InfoRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ContentServer).Info(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/containerd.services.content.v1.Content/Info", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ContentServer).Info(ctx, req.(*InfoRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Content_Update_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(UpdateRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ContentServer).Update(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/containerd.services.content.v1.Content/Update", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ContentServer).Update(ctx, req.(*UpdateRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Content_List_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(ListContentRequest) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(ContentServer).List(m, &contentListServer{stream}) -} - -type Content_ListServer interface { - Send(*ListContentResponse) error - grpc.ServerStream -} - -type contentListServer struct { - grpc.ServerStream -} - -func (x *contentListServer) Send(m *ListContentResponse) error { - return x.ServerStream.SendMsg(m) -} - -func _Content_Delete_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(DeleteContentRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ContentServer).Delete(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/containerd.services.content.v1.Content/Delete", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ContentServer).Delete(ctx, req.(*DeleteContentRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Content_Read_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(ReadContentRequest) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(ContentServer).Read(m, &contentReadServer{stream}) -} - -type Content_ReadServer interface { - Send(*ReadContentResponse) error - grpc.ServerStream -} - -type contentReadServer struct { - grpc.ServerStream -} - -func (x *contentReadServer) Send(m *ReadContentResponse) error { - return x.ServerStream.SendMsg(m) -} - -func _Content_Status_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(StatusRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ContentServer).Status(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/containerd.services.content.v1.Content/Status", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ContentServer).Status(ctx, req.(*StatusRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Content_ListStatuses_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ListStatusesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ContentServer).ListStatuses(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/containerd.services.content.v1.Content/ListStatuses", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ContentServer).ListStatuses(ctx, req.(*ListStatusesRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Content_Write_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(ContentServer).Write(&contentWriteServer{stream}) -} - -type Content_WriteServer interface { - Send(*WriteContentResponse) error - Recv() (*WriteContentRequest, error) - grpc.ServerStream -} - -type contentWriteServer struct { - grpc.ServerStream -} - -func (x *contentWriteServer) Send(m *WriteContentResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *contentWriteServer) Recv() (*WriteContentRequest, error) { - m := new(WriteContentRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func _Content_Abort_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(AbortRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ContentServer).Abort(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/containerd.services.content.v1.Content/Abort", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ContentServer).Abort(ctx, req.(*AbortRequest)) - } - return interceptor(ctx, in, info, handler) -} - -// Content_ServiceDesc is the grpc.ServiceDesc for Content service. -// It's only intended for direct use with grpc.RegisterService, -// and not to be introspected or modified (even as a copy) -var Content_ServiceDesc = grpc.ServiceDesc{ - ServiceName: "containerd.services.content.v1.Content", - HandlerType: (*ContentServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Info", - Handler: _Content_Info_Handler, - }, - { - MethodName: "Update", - Handler: _Content_Update_Handler, - }, - { - MethodName: "Delete", - Handler: _Content_Delete_Handler, - }, - { - MethodName: "Status", - Handler: _Content_Status_Handler, - }, - { - MethodName: "ListStatuses", - Handler: _Content_ListStatuses_Handler, - }, - { - MethodName: "Abort", - Handler: _Content_Abort_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "List", - Handler: _Content_List_Handler, - ServerStreams: true, - }, - { - StreamName: "Read", - Handler: _Content_Read_Handler, - ServerStreams: true, - }, - { - StreamName: "Write", - Handler: _Content_Write_Handler, - ServerStreams: true, - ClientStreams: true, - }, - }, - Metadata: "github.com/containerd/containerd/api/services/content/v1/content.proto", -} diff --git a/vendor/github.com/containerd/containerd/api/services/content/v1/doc.go b/vendor/github.com/containerd/containerd/api/services/content/v1/doc.go deleted file mode 100644 index 3bf106c89..000000000 --- a/vendor/github.com/containerd/containerd/api/services/content/v1/doc.go +++ /dev/null @@ -1,17 +0,0 @@ -/* - Copyright The containerd 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 content diff --git a/vendor/github.com/containerd/containerd/archive/compression/compression.go b/vendor/github.com/containerd/containerd/archive/compression/compression.go deleted file mode 100644 index ceceb21f5..000000000 --- a/vendor/github.com/containerd/containerd/archive/compression/compression.go +++ /dev/null @@ -1,323 +0,0 @@ -/* - Copyright The containerd 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 compression - -import ( - "bufio" - "bytes" - "compress/gzip" - "context" - "encoding/binary" - "fmt" - "io" - "os" - "strconv" - "sync" - - "github.com/containerd/containerd/log" - "github.com/klauspost/compress/zstd" - exec "golang.org/x/sys/execabs" -) - -type ( - // Compression is the state represents if compressed or not. - Compression int -) - -const ( - // Uncompressed represents the uncompressed. - Uncompressed Compression = iota - // Gzip is gzip compression algorithm. - Gzip - // Zstd is zstd compression algorithm. - Zstd -) - -const disablePigzEnv = "CONTAINERD_DISABLE_PIGZ" - -var ( - initPigz sync.Once - unpigzPath string -) - -var ( - bufioReader32KPool = &sync.Pool{ - New: func() interface{} { return bufio.NewReaderSize(nil, 32*1024) }, - } -) - -// DecompressReadCloser include the stream after decompress and the compress method detected. -type DecompressReadCloser interface { - io.ReadCloser - // GetCompression returns the compress method which is used before decompressing - GetCompression() Compression -} - -type readCloserWrapper struct { - io.Reader - compression Compression - closer func() error -} - -func (r *readCloserWrapper) Close() error { - if r.closer != nil { - return r.closer() - } - return nil -} - -func (r *readCloserWrapper) GetCompression() Compression { - return r.compression -} - -type writeCloserWrapper struct { - io.Writer - closer func() error -} - -func (w *writeCloserWrapper) Close() error { - if w.closer != nil { - w.closer() - } - return nil -} - -type bufferedReader struct { - buf *bufio.Reader -} - -func newBufferedReader(r io.Reader) *bufferedReader { - buf := bufioReader32KPool.Get().(*bufio.Reader) - buf.Reset(r) - return &bufferedReader{buf} -} - -func (r *bufferedReader) Read(p []byte) (n int, err error) { - if r.buf == nil { - return 0, io.EOF - } - n, err = r.buf.Read(p) - if err == io.EOF { - r.buf.Reset(nil) - bufioReader32KPool.Put(r.buf) - r.buf = nil - } - return -} - -func (r *bufferedReader) Peek(n int) ([]byte, error) { - if r.buf == nil { - return nil, io.EOF - } - return r.buf.Peek(n) -} - -const ( - zstdMagicSkippableStart = 0x184D2A50 - zstdMagicSkippableMask = 0xFFFFFFF0 -) - -var ( - gzipMagic = []byte{0x1F, 0x8B, 0x08} - zstdMagic = []byte{0x28, 0xb5, 0x2f, 0xfd} -) - -type matcher = func([]byte) bool - -func magicNumberMatcher(m []byte) matcher { - return func(source []byte) bool { - return bytes.HasPrefix(source, m) - } -} - -// zstdMatcher detects zstd compression algorithm. -// There are two frame formats defined by Zstandard: Zstandard frames and Skippable frames. -// See https://tools.ietf.org/id/draft-kucherawy-dispatch-zstd-00.html#rfc.section.2 for more details. -func zstdMatcher() matcher { - return func(source []byte) bool { - if bytes.HasPrefix(source, zstdMagic) { - // Zstandard frame - return true - } - // skippable frame - if len(source) < 8 { - return false - } - // magic number from 0x184D2A50 to 0x184D2A5F. - if binary.LittleEndian.Uint32(source[:4])&zstdMagicSkippableMask == zstdMagicSkippableStart { - return true - } - return false - } -} - -// DetectCompression detects the compression algorithm of the source. -func DetectCompression(source []byte) Compression { - for compression, fn := range map[Compression]matcher{ - Gzip: magicNumberMatcher(gzipMagic), - Zstd: zstdMatcher(), - } { - if fn(source) { - return compression - } - } - return Uncompressed -} - -// DecompressStream decompresses the archive and returns a ReaderCloser with the decompressed archive. -func DecompressStream(archive io.Reader) (DecompressReadCloser, error) { - buf := newBufferedReader(archive) - bs, err := buf.Peek(10) - if err != nil && err != io.EOF { - // Note: we'll ignore any io.EOF error because there are some odd - // cases where the layer.tar file will be empty (zero bytes) and - // that results in an io.EOF from the Peek() call. So, in those - // cases we'll just treat it as a non-compressed stream and - // that means just create an empty layer. - // See Issue docker/docker#18170 - return nil, err - } - - switch compression := DetectCompression(bs); compression { - case Uncompressed: - return &readCloserWrapper{ - Reader: buf, - compression: compression, - }, nil - case Gzip: - ctx, cancel := context.WithCancel(context.Background()) - gzReader, err := gzipDecompress(ctx, buf) - if err != nil { - cancel() - return nil, err - } - - return &readCloserWrapper{ - Reader: gzReader, - compression: compression, - closer: func() error { - cancel() - return gzReader.Close() - }, - }, nil - case Zstd: - zstdReader, err := zstd.NewReader(buf) - if err != nil { - return nil, err - } - return &readCloserWrapper{ - Reader: zstdReader, - compression: compression, - closer: func() error { - zstdReader.Close() - return nil - }, - }, nil - - default: - return nil, fmt.Errorf("unsupported compression format %s", (&compression).Extension()) - } -} - -// CompressStream compresses the dest with specified compression algorithm. -func CompressStream(dest io.Writer, compression Compression) (io.WriteCloser, error) { - switch compression { - case Uncompressed: - return &writeCloserWrapper{dest, nil}, nil - case Gzip: - return gzip.NewWriter(dest), nil - case Zstd: - return zstd.NewWriter(dest) - default: - return nil, fmt.Errorf("unsupported compression format %s", (&compression).Extension()) - } -} - -// Extension returns the extension of a file that uses the specified compression algorithm. -func (compression *Compression) Extension() string { - switch *compression { - case Gzip: - return "gz" - case Zstd: - return "zst" - } - return "" -} - -func gzipDecompress(ctx context.Context, buf io.Reader) (io.ReadCloser, error) { - initPigz.Do(func() { - if unpigzPath = detectPigz(); unpigzPath != "" { - log.L.Debug("using pigz for decompression") - } - }) - - if unpigzPath == "" { - return gzip.NewReader(buf) - } - - return cmdStream(exec.CommandContext(ctx, unpigzPath, "-d", "-c"), buf) -} - -func cmdStream(cmd *exec.Cmd, in io.Reader) (io.ReadCloser, error) { - reader, writer := io.Pipe() - - cmd.Stdin = in - cmd.Stdout = writer - - var errBuf bytes.Buffer - cmd.Stderr = &errBuf - - if err := cmd.Start(); err != nil { - return nil, err - } - - go func() { - if err := cmd.Wait(); err != nil { - writer.CloseWithError(fmt.Errorf("%s: %s", err, errBuf.String())) - } else { - writer.Close() - } - }() - - return reader, nil -} - -func detectPigz() string { - path, err := exec.LookPath("unpigz") - if err != nil { - log.L.WithError(err).Debug("unpigz not found, falling back to go gzip") - return "" - } - - // Check if pigz disabled via CONTAINERD_DISABLE_PIGZ env variable - value := os.Getenv(disablePigzEnv) - if value == "" { - return path - } - - disable, err := strconv.ParseBool(value) - if err != nil { - log.L.WithError(err).Warnf("could not parse %s: %s", disablePigzEnv, value) - return path - } - - if disable { - return "" - } - - return path -} diff --git a/vendor/github.com/containerd/containerd/archive/compression/compression_fuzzer.go b/vendor/github.com/containerd/containerd/archive/compression/compression_fuzzer.go deleted file mode 100644 index 3516494ac..000000000 --- a/vendor/github.com/containerd/containerd/archive/compression/compression_fuzzer.go +++ /dev/null @@ -1,28 +0,0 @@ -//go:build gofuzz - -/* - Copyright The containerd 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 compression - -import ( - "bytes" -) - -func FuzzDecompressStream(data []byte) int { - _, _ = DecompressStream(bytes.NewReader(data)) - return 1 -} diff --git a/vendor/github.com/containerd/containerd/content/adaptor.go b/vendor/github.com/containerd/containerd/content/adaptor.go deleted file mode 100644 index 88bad2610..000000000 --- a/vendor/github.com/containerd/containerd/content/adaptor.go +++ /dev/null @@ -1,52 +0,0 @@ -/* - Copyright The containerd 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 content - -import ( - "strings" - - "github.com/containerd/containerd/filters" -) - -// AdaptInfo returns `filters.Adaptor` that handles `content.Info`. -func AdaptInfo(info Info) filters.Adaptor { - return filters.AdapterFunc(func(fieldpath []string) (string, bool) { - if len(fieldpath) == 0 { - return "", false - } - - switch fieldpath[0] { - case "digest": - return info.Digest.String(), true - case "size": - // TODO: support size based filtering - case "labels": - return checkMap(fieldpath[1:], info.Labels) - } - - return "", false - }) -} - -func checkMap(fieldpath []string, m map[string]string) (string, bool) { - if len(m) == 0 { - return "", false - } - - value, ok := m[strings.Join(fieldpath, ".")] - return value, ok -} diff --git a/vendor/github.com/containerd/containerd/content/content.go b/vendor/github.com/containerd/containerd/content/content.go deleted file mode 100644 index 8eb1a1692..000000000 --- a/vendor/github.com/containerd/containerd/content/content.go +++ /dev/null @@ -1,201 +0,0 @@ -/* - Copyright The containerd 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 content - -import ( - "context" - "io" - "time" - - "github.com/opencontainers/go-digest" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" -) - -// Store combines the methods of content-oriented interfaces into a set that -// are commonly provided by complete implementations. -// -// Overall content lifecycle: -// - Ingester is used to initiate a write operation (aka ingestion) -// - IngestManager is used to manage (e.g. list, abort) active ingestions -// - Once an ingestion is complete (see Writer.Commit), Provider is used to -// query a single piece of content by its digest -// - Manager is used to manage (e.g. list, delete) previously committed content -// -// Note that until ingestion is complete, its content is not visible through -// Provider or Manager. Once ingestion is complete, it is no longer exposed -// through IngestManager. -type Store interface { - Manager - Provider - IngestManager - Ingester -} - -// ReaderAt extends the standard io.ReaderAt interface with reporting of Size and io.Closer -type ReaderAt interface { - io.ReaderAt - io.Closer - Size() int64 -} - -// Provider provides a reader interface for specific content -type Provider interface { - // ReaderAt only requires desc.Digest to be set. - // Other fields in the descriptor may be used internally for resolving - // the location of the actual data. - ReaderAt(ctx context.Context, desc ocispec.Descriptor) (ReaderAt, error) -} - -// Ingester writes content -type Ingester interface { - // Writer initiates a writing operation (aka ingestion). A single ingestion - // is uniquely identified by its ref, provided using a WithRef option. - // Writer can be called multiple times with the same ref to access the same - // ingestion. - // Once all the data is written, use Writer.Commit to complete the ingestion. - Writer(ctx context.Context, opts ...WriterOpt) (Writer, error) -} - -// IngestManager provides methods for managing ingestions. An ingestion is a -// not-yet-complete writing operation initiated using Ingester and identified -// by a ref string. -type IngestManager interface { - // Status returns the status of the provided ref. - Status(ctx context.Context, ref string) (Status, error) - - // ListStatuses returns the status of any active ingestions whose ref match - // the provided regular expression. If empty, all active ingestions will be - // returned. - ListStatuses(ctx context.Context, filters ...string) ([]Status, error) - - // Abort completely cancels the ingest operation targeted by ref. - Abort(ctx context.Context, ref string) error -} - -// Info holds content specific information -type Info struct { - Digest digest.Digest - Size int64 - CreatedAt time.Time - UpdatedAt time.Time - Labels map[string]string -} - -// Status of a content operation (i.e. an ingestion) -type Status struct { - Ref string - Offset int64 - Total int64 - Expected digest.Digest - StartedAt time.Time - UpdatedAt time.Time -} - -// WalkFunc defines the callback for a blob walk. -type WalkFunc func(Info) error - -// InfoProvider provides info for content inspection. -type InfoProvider interface { - // Info will return metadata about content available in the content store. - // - // If the content is not present, ErrNotFound will be returned. - Info(ctx context.Context, dgst digest.Digest) (Info, error) -} - -// Manager provides methods for inspecting, listing and removing content. -type Manager interface { - InfoProvider - - // Update updates mutable information related to content. - // If one or more fieldpaths are provided, only those - // fields will be updated. - // Mutable fields: - // labels.* - Update(ctx context.Context, info Info, fieldpaths ...string) (Info, error) - - // Walk will call fn for each item in the content store which - // match the provided filters. If no filters are given all - // items will be walked. - Walk(ctx context.Context, fn WalkFunc, filters ...string) error - - // Delete removes the content from the store. - Delete(ctx context.Context, dgst digest.Digest) error -} - -// Writer handles writing of content into a content store -type Writer interface { - // Close closes the writer, if the writer has not been - // committed this allows resuming or aborting. - // Calling Close on a closed writer will not error. - io.WriteCloser - - // Digest may return empty digest or panics until committed. - Digest() digest.Digest - - // Commit commits the blob (but no roll-back is guaranteed on an error). - // size and expected can be zero-value when unknown. - // Commit always closes the writer, even on error. - // ErrAlreadyExists aborts the writer. - Commit(ctx context.Context, size int64, expected digest.Digest, opts ...Opt) error - - // Status returns the current state of write - Status() (Status, error) - - // Truncate updates the size of the target blob - Truncate(size int64) error -} - -// Opt is used to alter the mutable properties of content -type Opt func(*Info) error - -// WithLabels allows labels to be set on content -func WithLabels(labels map[string]string) Opt { - return func(info *Info) error { - info.Labels = labels - return nil - } -} - -// WriterOpts is internally used by WriterOpt. -type WriterOpts struct { - Ref string - Desc ocispec.Descriptor -} - -// WriterOpt is used for passing options to Ingester.Writer. -type WriterOpt func(*WriterOpts) error - -// WithDescriptor specifies an OCI descriptor. -// Writer may optionally use the descriptor internally for resolving -// the location of the actual data. -// Write does not require any field of desc to be set. -// If the data size is unknown, desc.Size should be set to 0. -// Some implementations may also accept negative values as "unknown". -func WithDescriptor(desc ocispec.Descriptor) WriterOpt { - return func(opts *WriterOpts) error { - opts.Desc = desc - return nil - } -} - -// WithRef specifies a ref string. -func WithRef(ref string) WriterOpt { - return func(opts *WriterOpts) error { - opts.Ref = ref - return nil - } -} diff --git a/vendor/github.com/containerd/containerd/content/helpers.go b/vendor/github.com/containerd/containerd/content/helpers.go deleted file mode 100644 index 5404109a6..000000000 --- a/vendor/github.com/containerd/containerd/content/helpers.go +++ /dev/null @@ -1,334 +0,0 @@ -/* - Copyright The containerd 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 content - -import ( - "context" - "errors" - "fmt" - "io" - "sync" - "time" - - "github.com/containerd/containerd/errdefs" - "github.com/containerd/containerd/log" - "github.com/containerd/containerd/pkg/randutil" - "github.com/opencontainers/go-digest" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" -) - -// maxResets is the no.of times the Copy() method can tolerate a reset of the body -const maxResets = 5 - -var ErrReset = errors.New("writer has been reset") - -var bufPool = sync.Pool{ - New: func() interface{} { - buffer := make([]byte, 1<<20) - return &buffer - }, -} - -type reader interface { - Reader() io.Reader -} - -// NewReader returns a io.Reader from a ReaderAt -func NewReader(ra ReaderAt) io.Reader { - if rd, ok := ra.(reader); ok { - return rd.Reader() - } - return io.NewSectionReader(ra, 0, ra.Size()) -} - -// ReadBlob retrieves the entire contents of the blob from the provider. -// -// Avoid using this for large blobs, such as layers. -func ReadBlob(ctx context.Context, provider Provider, desc ocispec.Descriptor) ([]byte, error) { - if int64(len(desc.Data)) == desc.Size && digest.FromBytes(desc.Data) == desc.Digest { - return desc.Data, nil - } - - ra, err := provider.ReaderAt(ctx, desc) - if err != nil { - return nil, err - } - defer ra.Close() - - p := make([]byte, ra.Size()) - - n, err := ra.ReadAt(p, 0) - if err == io.EOF { - if int64(n) != ra.Size() { - err = io.ErrUnexpectedEOF - } else { - err = nil - } - } - return p, err -} - -// WriteBlob writes data with the expected digest into the content store. If -// expected already exists, the method returns immediately and the reader will -// not be consumed. -// -// This is useful when the digest and size are known beforehand. -// -// Copy is buffered, so no need to wrap reader in buffered io. -func WriteBlob(ctx context.Context, cs Ingester, ref string, r io.Reader, desc ocispec.Descriptor, opts ...Opt) error { - cw, err := OpenWriter(ctx, cs, WithRef(ref), WithDescriptor(desc)) - if err != nil { - if !errdefs.IsAlreadyExists(err) { - return fmt.Errorf("failed to open writer: %w", err) - } - - return nil // already present - } - defer cw.Close() - - return Copy(ctx, cw, r, desc.Size, desc.Digest, opts...) -} - -// OpenWriter opens a new writer for the given reference, retrying if the writer -// is locked until the reference is available or returns an error. -func OpenWriter(ctx context.Context, cs Ingester, opts ...WriterOpt) (Writer, error) { - var ( - cw Writer - err error - retry = 16 - ) - for { - cw, err = cs.Writer(ctx, opts...) - if err != nil { - if !errdefs.IsUnavailable(err) { - return nil, err - } - - // TODO: Check status to determine if the writer is active, - // continue waiting while active, otherwise return lock - // error or abort. Requires asserting for an ingest manager - - select { - case <-time.After(time.Millisecond * time.Duration(randutil.Intn(retry))): - if retry < 2048 { - retry = retry << 1 - } - continue - case <-ctx.Done(): - // Propagate lock error - return nil, err - } - - } - break - } - - return cw, err -} - -// Copy copies data with the expected digest from the reader into the -// provided content store writer. This copy commits the writer. -// -// This is useful when the digest and size are known beforehand. When -// the size or digest is unknown, these values may be empty. -// -// Copy is buffered, so no need to wrap reader in buffered io. -func Copy(ctx context.Context, cw Writer, or io.Reader, size int64, expected digest.Digest, opts ...Opt) error { - ws, err := cw.Status() - if err != nil { - return fmt.Errorf("failed to get status: %w", err) - } - r := or - if ws.Offset > 0 { - r, err = seekReader(or, ws.Offset, size) - if err != nil { - return fmt.Errorf("unable to resume write to %v: %w", ws.Ref, err) - } - } - - for i := 0; i < maxResets; i++ { - if i >= 1 { - log.G(ctx).WithField("digest", expected).Debugf("retrying copy due to reset") - } - copied, err := copyWithBuffer(cw, r) - if errors.Is(err, ErrReset) { - ws, err := cw.Status() - if err != nil { - return fmt.Errorf("failed to get status: %w", err) - } - r, err = seekReader(or, ws.Offset, size) - if err != nil { - return fmt.Errorf("unable to resume write to %v: %w", ws.Ref, err) - } - continue - } - if err != nil { - return fmt.Errorf("failed to copy: %w", err) - } - if size != 0 && copied < size-ws.Offset { - // Short writes would return its own error, this indicates a read failure - return fmt.Errorf("failed to read expected number of bytes: %w", io.ErrUnexpectedEOF) - } - if err := cw.Commit(ctx, size, expected, opts...); err != nil { - if errors.Is(err, ErrReset) { - ws, err := cw.Status() - if err != nil { - return fmt.Errorf("failed to get status: %w", err) - } - r, err = seekReader(or, ws.Offset, size) - if err != nil { - return fmt.Errorf("unable to resume write to %v: %w", ws.Ref, err) - } - continue - } - if !errdefs.IsAlreadyExists(err) { - return fmt.Errorf("failed commit on ref %q: %w", ws.Ref, err) - } - } - return nil - } - - log.G(ctx).WithField("digest", expected).Errorf("failed to copy after %d retries", maxResets) - return fmt.Errorf("failed to copy after %d retries", maxResets) -} - -// CopyReaderAt copies to a writer from a given reader at for the given -// number of bytes. This copy does not commit the writer. -func CopyReaderAt(cw Writer, ra ReaderAt, n int64) error { - ws, err := cw.Status() - if err != nil { - return err - } - - copied, err := copyWithBuffer(cw, io.NewSectionReader(ra, ws.Offset, n)) - if err != nil { - return fmt.Errorf("failed to copy: %w", err) - } - if copied < n { - // Short writes would return its own error, this indicates a read failure - return fmt.Errorf("failed to read expected number of bytes: %w", io.ErrUnexpectedEOF) - } - return nil -} - -// CopyReader copies to a writer from a given reader, returning -// the number of bytes copied. -// Note: if the writer has a non-zero offset, the total number -// of bytes read may be greater than those copied if the reader -// is not an io.Seeker. -// This copy does not commit the writer. -func CopyReader(cw Writer, r io.Reader) (int64, error) { - ws, err := cw.Status() - if err != nil { - return 0, fmt.Errorf("failed to get status: %w", err) - } - - if ws.Offset > 0 { - r, err = seekReader(r, ws.Offset, 0) - if err != nil { - return 0, fmt.Errorf("unable to resume write to %v: %w", ws.Ref, err) - } - } - - return copyWithBuffer(cw, r) -} - -// seekReader attempts to seek the reader to the given offset, either by -// resolving `io.Seeker`, by detecting `io.ReaderAt`, or discarding -// up to the given offset. -func seekReader(r io.Reader, offset, size int64) (io.Reader, error) { - // attempt to resolve r as a seeker and setup the offset. - seeker, ok := r.(io.Seeker) - if ok { - nn, err := seeker.Seek(offset, io.SeekStart) - if nn != offset { - if err == nil { - err = fmt.Errorf("unexpected seek location without seek error") - } - return nil, fmt.Errorf("failed to seek to offset %v: %w", offset, err) - } - - if err != nil { - return nil, err - } - - return r, nil - } - - // ok, let's try io.ReaderAt! - readerAt, ok := r.(io.ReaderAt) - if ok && size > offset { - sr := io.NewSectionReader(readerAt, offset, size) - return sr, nil - } - - // well then, let's just discard up to the offset - n, err := copyWithBuffer(io.Discard, io.LimitReader(r, offset)) - if err != nil { - return nil, fmt.Errorf("failed to discard to offset: %w", err) - } - if n != offset { - return nil, errors.New("unable to discard to offset") - } - - return r, nil -} - -// copyWithBuffer is very similar to io.CopyBuffer https://golang.org/pkg/io/#CopyBuffer -// but instead of using Read to read from the src, we use ReadAtLeast to make sure we have -// a full buffer before we do a write operation to dst to reduce overheads associated -// with the write operations of small buffers. -func copyWithBuffer(dst io.Writer, src io.Reader) (written int64, err error) { - // If the reader has a WriteTo method, use it to do the copy. - // Avoids an allocation and a copy. - if wt, ok := src.(io.WriterTo); ok { - return wt.WriteTo(dst) - } - // Similarly, if the writer has a ReadFrom method, use it to do the copy. - if rt, ok := dst.(io.ReaderFrom); ok { - return rt.ReadFrom(src) - } - bufRef := bufPool.Get().(*[]byte) - defer bufPool.Put(bufRef) - buf := *bufRef - for { - nr, er := io.ReadAtLeast(src, buf, len(buf)) - if nr > 0 { - nw, ew := dst.Write(buf[0:nr]) - if nw > 0 { - written += int64(nw) - } - if ew != nil { - err = ew - break - } - if nr != nw { - err = io.ErrShortWrite - break - } - } - if er != nil { - // If an EOF happens after reading fewer than the requested bytes, - // ReadAtLeast returns ErrUnexpectedEOF. - if er != io.EOF && er != io.ErrUnexpectedEOF { - err = er - } - break - } - } - return -} diff --git a/vendor/github.com/containerd/containerd/content/local/content_local_fuzzer.go b/vendor/github.com/containerd/containerd/content/local/content_local_fuzzer.go deleted file mode 100644 index a523f28d9..000000000 --- a/vendor/github.com/containerd/containerd/content/local/content_local_fuzzer.go +++ /dev/null @@ -1,76 +0,0 @@ -//go:build gofuzz - -/* - Copyright The containerd 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 local - -import ( - "bufio" - "bytes" - "context" - _ "crypto/sha256" - "io" - "testing" - - "github.com/opencontainers/go-digest" - - "github.com/containerd/containerd/content" -) - -func FuzzContentStoreWriter(data []byte) int { - t := &testing.T{} - ctx := context.Background() - ctx, _, cs, cleanup := contentStoreEnv(t) - defer cleanup() - - cw, err := cs.Writer(ctx, content.WithRef("myref")) - if err != nil { - return 0 - } - if err := cw.Close(); err != nil { - return 0 - } - - // reopen, so we can test things - cw, err = cs.Writer(ctx, content.WithRef("myref")) - if err != nil { - return 0 - } - - err = checkCopyFuzz(int64(len(data)), cw, bufio.NewReader(io.NopCloser(bytes.NewReader(data)))) - if err != nil { - return 0 - } - expected := digest.FromBytes(data) - - if err = cw.Commit(ctx, int64(len(data)), expected); err != nil { - return 0 - } - return 1 -} - -func checkCopyFuzz(size int64, dst io.Writer, src io.Reader) error { - nn, err := io.Copy(dst, src) - if err != nil { - return err - } - - if nn != size { - return err - } - return nil -} diff --git a/vendor/github.com/containerd/containerd/content/local/locks.go b/vendor/github.com/containerd/containerd/content/local/locks.go deleted file mode 100644 index 1e59f39b3..000000000 --- a/vendor/github.com/containerd/containerd/content/local/locks.go +++ /dev/null @@ -1,62 +0,0 @@ -/* - Copyright The containerd 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 local - -import ( - "fmt" - "sync" - "time" - - "github.com/containerd/containerd/errdefs" -) - -// Handles locking references - -type lock struct { - since time.Time -} - -var ( - // locks lets us lock in process - locks = make(map[string]*lock) - locksMu sync.Mutex -) - -func tryLock(ref string) error { - locksMu.Lock() - defer locksMu.Unlock() - - if v, ok := locks[ref]; ok { - // Returning the duration may help developers distinguish dead locks (long duration) from - // lock contentions (short duration). - now := time.Now() - return fmt.Errorf( - "ref %s locked for %s (since %s): %w", ref, now.Sub(v.since), v.since, - errdefs.ErrUnavailable, - ) - } - - locks[ref] = &lock{time.Now()} - return nil -} - -func unlock(ref string) { - locksMu.Lock() - defer locksMu.Unlock() - - delete(locks, ref) -} diff --git a/vendor/github.com/containerd/containerd/content/local/readerat.go b/vendor/github.com/containerd/containerd/content/local/readerat.go deleted file mode 100644 index 899e85c0b..000000000 --- a/vendor/github.com/containerd/containerd/content/local/readerat.go +++ /dev/null @@ -1,72 +0,0 @@ -/* - Copyright The containerd 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 local - -import ( - "fmt" - "io" - "os" - - "github.com/containerd/containerd/content" - "github.com/containerd/containerd/errdefs" -) - -// readerat implements io.ReaderAt in a completely stateless manner by opening -// the referenced file for each call to ReadAt. -type sizeReaderAt struct { - size int64 - fp *os.File -} - -// OpenReader creates ReaderAt from a file -func OpenReader(p string) (content.ReaderAt, error) { - fi, err := os.Stat(p) - if err != nil { - if !os.IsNotExist(err) { - return nil, err - } - - return nil, fmt.Errorf("blob not found: %w", errdefs.ErrNotFound) - } - - fp, err := os.Open(p) - if err != nil { - if !os.IsNotExist(err) { - return nil, err - } - - return nil, fmt.Errorf("blob not found: %w", errdefs.ErrNotFound) - } - - return sizeReaderAt{size: fi.Size(), fp: fp}, nil -} - -func (ra sizeReaderAt) ReadAt(p []byte, offset int64) (int, error) { - return ra.fp.ReadAt(p, offset) -} - -func (ra sizeReaderAt) Size() int64 { - return ra.size -} - -func (ra sizeReaderAt) Close() error { - return ra.fp.Close() -} - -func (ra sizeReaderAt) Reader() io.Reader { - return io.LimitReader(ra.fp, ra.size) -} diff --git a/vendor/github.com/containerd/containerd/content/local/store.go b/vendor/github.com/containerd/containerd/content/local/store.go deleted file mode 100644 index baae3565b..000000000 --- a/vendor/github.com/containerd/containerd/content/local/store.go +++ /dev/null @@ -1,704 +0,0 @@ -/* - Copyright The containerd 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 local - -import ( - "context" - "fmt" - "io" - "os" - "path/filepath" - "strconv" - "strings" - "sync" - "time" - - "github.com/containerd/containerd/content" - "github.com/containerd/containerd/errdefs" - "github.com/containerd/containerd/filters" - "github.com/containerd/containerd/log" - "github.com/containerd/containerd/pkg/randutil" - "github.com/sirupsen/logrus" - - "github.com/opencontainers/go-digest" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" -) - -var bufPool = sync.Pool{ - New: func() interface{} { - buffer := make([]byte, 1<<20) - return &buffer - }, -} - -// LabelStore is used to store mutable labels for digests -type LabelStore interface { - // Get returns all the labels for the given digest - Get(digest.Digest) (map[string]string, error) - - // Set sets all the labels for a given digest - Set(digest.Digest, map[string]string) error - - // Update replaces the given labels for a digest, - // a key with an empty value removes a label. - Update(digest.Digest, map[string]string) (map[string]string, error) -} - -// Store is digest-keyed store for content. All data written into the store is -// stored under a verifiable digest. -// -// Store can generally support multi-reader, single-writer ingest of data, -// including resumable ingest. -type store struct { - root string - ls LabelStore -} - -// NewStore returns a local content store -func NewStore(root string) (content.Store, error) { - return NewLabeledStore(root, nil) -} - -// NewLabeledStore returns a new content store using the provided label store -// -// Note: content stores which are used underneath a metadata store may not -// require labels and should use `NewStore`. `NewLabeledStore` is primarily -// useful for tests or standalone implementations. -func NewLabeledStore(root string, ls LabelStore) (content.Store, error) { - if err := os.MkdirAll(filepath.Join(root, "ingest"), 0777); err != nil { - return nil, err - } - - return &store{ - root: root, - ls: ls, - }, nil -} - -func (s *store) Info(ctx context.Context, dgst digest.Digest) (content.Info, error) { - p, err := s.blobPath(dgst) - if err != nil { - return content.Info{}, fmt.Errorf("calculating blob info path: %w", err) - } - - fi, err := os.Stat(p) - if err != nil { - if os.IsNotExist(err) { - err = fmt.Errorf("content %v: %w", dgst, errdefs.ErrNotFound) - } - - return content.Info{}, err - } - var labels map[string]string - if s.ls != nil { - labels, err = s.ls.Get(dgst) - if err != nil { - return content.Info{}, err - } - } - return s.info(dgst, fi, labels), nil -} - -func (s *store) info(dgst digest.Digest, fi os.FileInfo, labels map[string]string) content.Info { - return content.Info{ - Digest: dgst, - Size: fi.Size(), - CreatedAt: fi.ModTime(), - UpdatedAt: getATime(fi), - Labels: labels, - } -} - -// ReaderAt returns an io.ReaderAt for the blob. -func (s *store) ReaderAt(ctx context.Context, desc ocispec.Descriptor) (content.ReaderAt, error) { - p, err := s.blobPath(desc.Digest) - if err != nil { - return nil, fmt.Errorf("calculating blob path for ReaderAt: %w", err) - } - - reader, err := OpenReader(p) - if err != nil { - return nil, fmt.Errorf("blob %s expected at %s: %w", desc.Digest, p, err) - } - - return reader, nil -} - -// Delete removes a blob by its digest. -// -// While this is safe to do concurrently, safe exist-removal logic must hold -// some global lock on the store. -func (s *store) Delete(ctx context.Context, dgst digest.Digest) error { - bp, err := s.blobPath(dgst) - if err != nil { - return fmt.Errorf("calculating blob path for delete: %w", err) - } - - if err := os.RemoveAll(bp); err != nil { - if !os.IsNotExist(err) { - return err - } - - return fmt.Errorf("content %v: %w", dgst, errdefs.ErrNotFound) - } - - return nil -} - -func (s *store) Update(ctx context.Context, info content.Info, fieldpaths ...string) (content.Info, error) { - if s.ls == nil { - return content.Info{}, fmt.Errorf("update not supported on immutable content store: %w", errdefs.ErrFailedPrecondition) - } - - p, err := s.blobPath(info.Digest) - if err != nil { - return content.Info{}, fmt.Errorf("calculating blob path for update: %w", err) - } - - fi, err := os.Stat(p) - if err != nil { - if os.IsNotExist(err) { - err = fmt.Errorf("content %v: %w", info.Digest, errdefs.ErrNotFound) - } - - return content.Info{}, err - } - - var ( - all bool - labels map[string]string - ) - if len(fieldpaths) > 0 { - for _, path := range fieldpaths { - if strings.HasPrefix(path, "labels.") { - if labels == nil { - labels = map[string]string{} - } - - key := strings.TrimPrefix(path, "labels.") - labels[key] = info.Labels[key] - continue - } - - switch path { - case "labels": - all = true - labels = info.Labels - default: - return content.Info{}, fmt.Errorf("cannot update %q field on content info %q: %w", path, info.Digest, errdefs.ErrInvalidArgument) - } - } - } else { - all = true - labels = info.Labels - } - - if all { - err = s.ls.Set(info.Digest, labels) - } else { - labels, err = s.ls.Update(info.Digest, labels) - } - if err != nil { - return content.Info{}, err - } - - info = s.info(info.Digest, fi, labels) - info.UpdatedAt = time.Now() - - if err := os.Chtimes(p, info.UpdatedAt, info.CreatedAt); err != nil { - log.G(ctx).WithError(err).Warnf("could not change access time for %s", info.Digest) - } - - return info, nil -} - -func (s *store) Walk(ctx context.Context, fn content.WalkFunc, fs ...string) error { - root := filepath.Join(s.root, "blobs") - - filter, err := filters.ParseAll(fs...) - if err != nil { - return err - } - - var alg digest.Algorithm - return filepath.Walk(root, func(path string, fi os.FileInfo, err error) error { - if err != nil { - return err - } - if !fi.IsDir() && !alg.Available() { - return nil - } - - // TODO(stevvooe): There are few more cases with subdirs that should be - // handled in case the layout gets corrupted. This isn't strict enough - // and may spew bad data. - - if path == root { - return nil - } - if filepath.Dir(path) == root { - alg = digest.Algorithm(filepath.Base(path)) - - if !alg.Available() { - alg = "" - return filepath.SkipDir - } - - // descending into a hash directory - return nil - } - - dgst := digest.NewDigestFromEncoded(alg, filepath.Base(path)) - if err := dgst.Validate(); err != nil { - // log error but don't report - log.L.WithError(err).WithField("path", path).Error("invalid digest for blob path") - // if we see this, it could mean some sort of corruption of the - // store or extra paths not expected previously. - } - - var labels map[string]string - if s.ls != nil { - labels, err = s.ls.Get(dgst) - if err != nil { - return err - } - } - - info := s.info(dgst, fi, labels) - if !filter.Match(content.AdaptInfo(info)) { - return nil - } - return fn(info) - }) -} - -func (s *store) Status(ctx context.Context, ref string) (content.Status, error) { - return s.status(s.ingestRoot(ref)) -} - -func (s *store) ListStatuses(ctx context.Context, fs ...string) ([]content.Status, error) { - fp, err := os.Open(filepath.Join(s.root, "ingest")) - if err != nil { - return nil, err - } - - defer fp.Close() - - fis, err := fp.Readdir(-1) - if err != nil { - return nil, err - } - - filter, err := filters.ParseAll(fs...) - if err != nil { - return nil, err - } - - var active []content.Status - for _, fi := range fis { - p := filepath.Join(s.root, "ingest", fi.Name()) - stat, err := s.status(p) - if err != nil { - if !os.IsNotExist(err) { - return nil, err - } - - // TODO(stevvooe): This is a common error if uploads are being - // completed while making this listing. Need to consider taking a - // lock on the whole store to coordinate this aspect. - // - // Another option is to cleanup downloads asynchronously and - // coordinate this method with the cleanup process. - // - // For now, we just skip them, as they really don't exist. - continue - } - - if filter.Match(adaptStatus(stat)) { - active = append(active, stat) - } - } - - return active, nil -} - -// WalkStatusRefs is used to walk all status references -// Failed status reads will be logged and ignored, if -// this function is called while references are being altered, -// these error messages may be produced. -func (s *store) WalkStatusRefs(ctx context.Context, fn func(string) error) error { - fp, err := os.Open(filepath.Join(s.root, "ingest")) - if err != nil { - return err - } - - defer fp.Close() - - fis, err := fp.Readdir(-1) - if err != nil { - return err - } - - for _, fi := range fis { - rf := filepath.Join(s.root, "ingest", fi.Name(), "ref") - - ref, err := readFileString(rf) - if err != nil { - log.G(ctx).WithError(err).WithField("path", rf).Error("failed to read ingest ref") - continue - } - - if err := fn(ref); err != nil { - return err - } - } - - return nil -} - -// status works like stat above except uses the path to the ingest. -func (s *store) status(ingestPath string) (content.Status, error) { - dp := filepath.Join(ingestPath, "data") - fi, err := os.Stat(dp) - if err != nil { - if os.IsNotExist(err) { - err = fmt.Errorf("%s: %w", err.Error(), errdefs.ErrNotFound) - } - return content.Status{}, err - } - - ref, err := readFileString(filepath.Join(ingestPath, "ref")) - if err != nil { - if os.IsNotExist(err) { - err = fmt.Errorf("%s: %w", err.Error(), errdefs.ErrNotFound) - } - return content.Status{}, err - } - - startedAt, err := readFileTimestamp(filepath.Join(ingestPath, "startedat")) - if err != nil { - return content.Status{}, fmt.Errorf("could not read startedat: %w", err) - } - - updatedAt, err := readFileTimestamp(filepath.Join(ingestPath, "updatedat")) - if err != nil { - return content.Status{}, fmt.Errorf("could not read updatedat: %w", err) - } - - // because we don't write updatedat on every write, the mod time may - // actually be more up to date. - if fi.ModTime().After(updatedAt) { - updatedAt = fi.ModTime() - } - - return content.Status{ - Ref: ref, - Offset: fi.Size(), - Total: s.total(ingestPath), - UpdatedAt: updatedAt, - StartedAt: startedAt, - }, nil -} - -func adaptStatus(status content.Status) filters.Adaptor { - return filters.AdapterFunc(func(fieldpath []string) (string, bool) { - if len(fieldpath) == 0 { - return "", false - } - switch fieldpath[0] { - case "ref": - return status.Ref, true - } - - return "", false - }) -} - -// total attempts to resolve the total expected size for the write. -func (s *store) total(ingestPath string) int64 { - totalS, err := readFileString(filepath.Join(ingestPath, "total")) - if err != nil { - return 0 - } - - total, err := strconv.ParseInt(totalS, 10, 64) - if err != nil { - // represents a corrupted file, should probably remove. - return 0 - } - - return total -} - -// Writer begins or resumes the active writer identified by ref. If the writer -// is already in use, an error is returned. Only one writer may be in use per -// ref at a time. -// -// The argument `ref` is used to uniquely identify a long-lived writer transaction. -func (s *store) Writer(ctx context.Context, opts ...content.WriterOpt) (content.Writer, error) { - var wOpts content.WriterOpts - for _, opt := range opts { - if err := opt(&wOpts); err != nil { - return nil, err - } - } - // TODO(AkihiroSuda): we could create a random string or one calculated based on the context - // https://github.com/containerd/containerd/issues/2129#issuecomment-380255019 - if wOpts.Ref == "" { - return nil, fmt.Errorf("ref must not be empty: %w", errdefs.ErrInvalidArgument) - } - var lockErr error - for count := uint64(0); count < 10; count++ { - if err := tryLock(wOpts.Ref); err != nil { - if !errdefs.IsUnavailable(err) { - return nil, err - } - - lockErr = err - } else { - lockErr = nil - break - } - time.Sleep(time.Millisecond * time.Duration(randutil.Intn(1< 0 && status.Total > 0 && total != status.Total { - return status, fmt.Errorf("provided total differs from status: %v != %v", total, status.Total) - } - - //nolint:dupword - // TODO(stevvooe): slow slow slow!!, send to goroutine or use resumable hashes - fp, err := os.Open(data) - if err != nil { - return status, err - } - - p := bufPool.Get().(*[]byte) - status.Offset, err = io.CopyBuffer(digester.Hash(), fp, *p) - bufPool.Put(p) - fp.Close() - return status, err -} - -// writer provides the main implementation of the Writer method. The caller -// must hold the lock correctly and release on error if there is a problem. -func (s *store) writer(ctx context.Context, ref string, total int64, expected digest.Digest) (content.Writer, error) { - // TODO(stevvooe): Need to actually store expected here. We have - // code in the service that shouldn't be dealing with this. - if expected != "" { - p, err := s.blobPath(expected) - if err != nil { - return nil, fmt.Errorf("calculating expected blob path for writer: %w", err) - } - if _, err := os.Stat(p); err == nil { - return nil, fmt.Errorf("content %v: %w", expected, errdefs.ErrAlreadyExists) - } - } - - path, refp, data := s.ingestPaths(ref) - - var ( - digester = digest.Canonical.Digester() - offset int64 - startedAt time.Time - updatedAt time.Time - ) - - foundValidIngest := false - // ensure that the ingest path has been created. - if err := os.Mkdir(path, 0755); err != nil { - if !os.IsExist(err) { - return nil, err - } - status, err := s.resumeStatus(ref, total, digester) - if err == nil { - foundValidIngest = true - updatedAt = status.UpdatedAt - startedAt = status.StartedAt - total = status.Total - offset = status.Offset - } else { - logrus.Infof("failed to resume the status from path %s: %s. will recreate them", path, err.Error()) - } - } - - if !foundValidIngest { - startedAt = time.Now() - updatedAt = startedAt - - // the ingest is new, we need to setup the target location. - // write the ref to a file for later use - if err := os.WriteFile(refp, []byte(ref), 0666); err != nil { - return nil, err - } - - if err := writeTimestampFile(filepath.Join(path, "startedat"), startedAt); err != nil { - return nil, err - } - - if err := writeTimestampFile(filepath.Join(path, "updatedat"), startedAt); err != nil { - return nil, err - } - - if total > 0 { - if err := os.WriteFile(filepath.Join(path, "total"), []byte(fmt.Sprint(total)), 0666); err != nil { - return nil, err - } - } - } - - fp, err := os.OpenFile(data, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - return nil, fmt.Errorf("failed to open data file: %w", err) - } - - if _, err := fp.Seek(offset, io.SeekStart); err != nil { - fp.Close() - return nil, fmt.Errorf("could not seek to current write offset: %w", err) - } - - return &writer{ - s: s, - fp: fp, - ref: ref, - path: path, - offset: offset, - total: total, - digester: digester, - startedAt: startedAt, - updatedAt: updatedAt, - }, nil -} - -// Abort an active transaction keyed by ref. If the ingest is active, it will -// be cancelled. Any resources associated with the ingest will be cleaned. -func (s *store) Abort(ctx context.Context, ref string) error { - root := s.ingestRoot(ref) - if err := os.RemoveAll(root); err != nil { - if os.IsNotExist(err) { - return fmt.Errorf("ingest ref %q: %w", ref, errdefs.ErrNotFound) - } - - return err - } - - return nil -} - -func (s *store) blobPath(dgst digest.Digest) (string, error) { - if err := dgst.Validate(); err != nil { - return "", fmt.Errorf("cannot calculate blob path from invalid digest: %v: %w", err, errdefs.ErrInvalidArgument) - } - - return filepath.Join(s.root, "blobs", dgst.Algorithm().String(), dgst.Encoded()), nil -} - -func (s *store) ingestRoot(ref string) string { - // we take a digest of the ref to keep the ingest paths constant length. - // Note that this is not the current or potential digest of incoming content. - dgst := digest.FromString(ref) - return filepath.Join(s.root, "ingest", dgst.Encoded()) -} - -// ingestPaths are returned. The paths are the following: -// -// - root: entire ingest directory -// - ref: name of the starting ref, must be unique -// - data: file where data is written -func (s *store) ingestPaths(ref string) (string, string, string) { - var ( - fp = s.ingestRoot(ref) - rp = filepath.Join(fp, "ref") - dp = filepath.Join(fp, "data") - ) - - return fp, rp, dp -} - -func readFileString(path string) (string, error) { - p, err := os.ReadFile(path) - return string(p), err -} - -// readFileTimestamp reads a file with just a timestamp present. -func readFileTimestamp(p string) (time.Time, error) { - b, err := os.ReadFile(p) - if err != nil { - if os.IsNotExist(err) { - err = fmt.Errorf("%s: %w", err.Error(), errdefs.ErrNotFound) - } - return time.Time{}, err - } - - var t time.Time - if err := t.UnmarshalText(b); err != nil { - return time.Time{}, fmt.Errorf("could not parse timestamp file %v: %w", p, err) - } - - return t, nil -} - -func writeTimestampFile(p string, t time.Time) error { - b, err := t.MarshalText() - if err != nil { - return err - } - return writeToCompletion(p, b, 0666) -} - -func writeToCompletion(path string, data []byte, mode os.FileMode) error { - tmp := fmt.Sprintf("%s.tmp", path) - f, err := os.OpenFile(tmp, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_SYNC, mode) - if err != nil { - return fmt.Errorf("create tmp file: %w", err) - } - _, err = f.Write(data) - f.Close() - if err != nil { - return fmt.Errorf("write tmp file: %w", err) - } - err = os.Rename(tmp, path) - if err != nil { - return fmt.Errorf("rename tmp file: %w", err) - } - return nil -} diff --git a/vendor/github.com/containerd/containerd/content/local/store_bsd.go b/vendor/github.com/containerd/containerd/content/local/store_bsd.go deleted file mode 100644 index 7dcc19232..000000000 --- a/vendor/github.com/containerd/containerd/content/local/store_bsd.go +++ /dev/null @@ -1,33 +0,0 @@ -//go:build darwin || freebsd || netbsd - -/* - Copyright The containerd 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 local - -import ( - "os" - "syscall" - "time" -) - -func getATime(fi os.FileInfo) time.Time { - if st, ok := fi.Sys().(*syscall.Stat_t); ok { - return time.Unix(st.Atimespec.Unix()) - } - - return fi.ModTime() -} diff --git a/vendor/github.com/containerd/containerd/content/local/store_openbsd.go b/vendor/github.com/containerd/containerd/content/local/store_openbsd.go deleted file mode 100644 index 45dfa9997..000000000 --- a/vendor/github.com/containerd/containerd/content/local/store_openbsd.go +++ /dev/null @@ -1,33 +0,0 @@ -//go:build openbsd - -/* - Copyright The containerd 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 local - -import ( - "os" - "syscall" - "time" -) - -func getATime(fi os.FileInfo) time.Time { - if st, ok := fi.Sys().(*syscall.Stat_t); ok { - return time.Unix(st.Atim.Unix()) - } - - return fi.ModTime() -} diff --git a/vendor/github.com/containerd/containerd/content/local/store_unix.go b/vendor/github.com/containerd/containerd/content/local/store_unix.go deleted file mode 100644 index cb01c91c7..000000000 --- a/vendor/github.com/containerd/containerd/content/local/store_unix.go +++ /dev/null @@ -1,33 +0,0 @@ -//go:build linux || solaris - -/* - Copyright The containerd 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 local - -import ( - "os" - "syscall" - "time" -) - -func getATime(fi os.FileInfo) time.Time { - if st, ok := fi.Sys().(*syscall.Stat_t); ok { - return time.Unix(st.Atim.Unix()) - } - - return fi.ModTime() -} diff --git a/vendor/github.com/containerd/containerd/content/local/store_windows.go b/vendor/github.com/containerd/containerd/content/local/store_windows.go deleted file mode 100644 index bce849979..000000000 --- a/vendor/github.com/containerd/containerd/content/local/store_windows.go +++ /dev/null @@ -1,26 +0,0 @@ -/* - Copyright The containerd 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 local - -import ( - "os" - "time" -) - -func getATime(fi os.FileInfo) time.Time { - return fi.ModTime() -} diff --git a/vendor/github.com/containerd/containerd/content/local/test_helper.go b/vendor/github.com/containerd/containerd/content/local/test_helper.go deleted file mode 100644 index 42de01cae..000000000 --- a/vendor/github.com/containerd/containerd/content/local/test_helper.go +++ /dev/null @@ -1,38 +0,0 @@ -/* - Copyright The containerd 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 local - -import ( - "context" - "testing" - - "github.com/containerd/containerd/content" -) - -func contentStoreEnv(t testing.TB) (context.Context, string, content.Store, func()) { - tmpdir := t.TempDir() - - cs, err := NewStore(tmpdir) - if err != nil { - t.Fatal(err) - } - - ctx, cancel := context.WithCancel(context.Background()) - return ctx, tmpdir, cs, func() { - cancel() - } -} diff --git a/vendor/github.com/containerd/containerd/content/local/writer.go b/vendor/github.com/containerd/containerd/content/local/writer.go deleted file mode 100644 index b187e524c..000000000 --- a/vendor/github.com/containerd/containerd/content/local/writer.go +++ /dev/null @@ -1,208 +0,0 @@ -/* - Copyright The containerd 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 local - -import ( - "context" - "errors" - "fmt" - "io" - "os" - "path/filepath" - "runtime" - "time" - - "github.com/containerd/containerd/content" - "github.com/containerd/containerd/errdefs" - "github.com/containerd/containerd/log" - "github.com/opencontainers/go-digest" -) - -// writer represents a write transaction against the blob store. -type writer struct { - s *store - fp *os.File // opened data file - path string // path to writer dir - ref string // ref key - offset int64 - total int64 - digester digest.Digester - startedAt time.Time - updatedAt time.Time -} - -func (w *writer) Status() (content.Status, error) { - return content.Status{ - Ref: w.ref, - Offset: w.offset, - Total: w.total, - StartedAt: w.startedAt, - UpdatedAt: w.updatedAt, - }, nil -} - -// Digest returns the current digest of the content, up to the current write. -// -// Cannot be called concurrently with `Write`. -func (w *writer) Digest() digest.Digest { - return w.digester.Digest() -} - -// Write p to the transaction. -// -// Note that writes are unbuffered to the backing file. When writing, it is -// recommended to wrap in a bufio.Writer or, preferably, use io.CopyBuffer. -func (w *writer) Write(p []byte) (n int, err error) { - n, err = w.fp.Write(p) - w.digester.Hash().Write(p[:n]) - w.offset += int64(len(p)) - w.updatedAt = time.Now() - return n, err -} - -func (w *writer) Commit(ctx context.Context, size int64, expected digest.Digest, opts ...content.Opt) error { - // Ensure even on error the writer is fully closed - defer unlock(w.ref) - - var base content.Info - for _, opt := range opts { - if err := opt(&base); err != nil { - return err - } - } - - fp := w.fp - w.fp = nil - - if fp == nil { - return fmt.Errorf("cannot commit on closed writer: %w", errdefs.ErrFailedPrecondition) - } - - if err := fp.Sync(); err != nil { - fp.Close() - return fmt.Errorf("sync failed: %w", err) - } - - fi, err := fp.Stat() - closeErr := fp.Close() - if err != nil { - return fmt.Errorf("stat on ingest file failed: %w", err) - } - if closeErr != nil { - return fmt.Errorf("failed to close ingest file: %w", closeErr) - } - - if size > 0 && size != fi.Size() { - return fmt.Errorf("unexpected commit size %d, expected %d: %w", fi.Size(), size, errdefs.ErrFailedPrecondition) - } - - dgst := w.digester.Digest() - if expected != "" && expected != dgst { - return fmt.Errorf("unexpected commit digest %s, expected %s: %w", dgst, expected, errdefs.ErrFailedPrecondition) - } - - var ( - ingest = filepath.Join(w.path, "data") - target, _ = w.s.blobPath(dgst) // ignore error because we calculated this dgst - ) - - // make sure parent directories of blob exist - if err := os.MkdirAll(filepath.Dir(target), 0755); err != nil { - return err - } - - if _, err := os.Stat(target); err == nil { - // collision with the target file! - if err := os.RemoveAll(w.path); err != nil { - log.G(ctx).WithField("ref", w.ref).WithField("path", w.path).Error("failed to remove ingest directory") - } - return fmt.Errorf("content %v: %w", dgst, errdefs.ErrAlreadyExists) - } - - if err := os.Rename(ingest, target); err != nil { - return err - } - - // Ingest has now been made available in the content store, attempt to complete - // setting metadata but errors should only be logged and not returned since - // the content store cannot be cleanly rolled back. - - commitTime := time.Now() - if err := os.Chtimes(target, commitTime, commitTime); err != nil { - log.G(ctx).WithField("digest", dgst).Error("failed to change file time to commit time") - } - - // clean up!! - if err := os.RemoveAll(w.path); err != nil { - log.G(ctx).WithField("ref", w.ref).WithField("path", w.path).Error("failed to remove ingest directory") - } - - if w.s.ls != nil && base.Labels != nil { - if err := w.s.ls.Set(dgst, base.Labels); err != nil { - log.G(ctx).WithField("digest", dgst).Error("failed to set labels") - } - } - - // change to readonly, more important for read, but provides _some_ - // protection from this point on. We use the existing perms with a mask - // only allowing reads honoring the umask on creation. - // - // This removes write and exec, only allowing read per the creation umask. - // - // NOTE: Windows does not support this operation - if runtime.GOOS != "windows" { - if err := os.Chmod(target, (fi.Mode()&os.ModePerm)&^0333); err != nil { - log.G(ctx).WithField("ref", w.ref).Error("failed to make readonly") - } - } - - return nil -} - -// Close the writer, flushing any unwritten data and leaving the progress in -// tact. -// -// If one needs to resume the transaction, a new writer can be obtained from -// `Ingester.Writer` using the same key. The write can then be continued -// from it was left off. -// -// To abandon a transaction completely, first call close then `IngestManager.Abort` to -// clean up the associated resources. -func (w *writer) Close() (err error) { - if w.fp != nil { - w.fp.Sync() - err = w.fp.Close() - writeTimestampFile(filepath.Join(w.path, "updatedat"), w.updatedAt) - w.fp = nil - unlock(w.ref) - return - } - - return nil -} - -func (w *writer) Truncate(size int64) error { - if size != 0 { - return errors.New("Truncate: unsupported size") - } - w.offset = 0 - w.digester.Hash().Reset() - if _, err := w.fp.Seek(0, io.SeekStart); err != nil { - return err - } - return w.fp.Truncate(0) -} diff --git a/vendor/github.com/containerd/containerd/content/proxy/content_reader.go b/vendor/github.com/containerd/containerd/content/proxy/content_reader.go deleted file mode 100644 index 893e3b0f2..000000000 --- a/vendor/github.com/containerd/containerd/content/proxy/content_reader.go +++ /dev/null @@ -1,71 +0,0 @@ -/* - Copyright The containerd 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 proxy - -import ( - "context" - - contentapi "github.com/containerd/containerd/api/services/content/v1" - digest "github.com/opencontainers/go-digest" -) - -type remoteReaderAt struct { - ctx context.Context - digest digest.Digest - size int64 - client contentapi.ContentClient -} - -func (ra *remoteReaderAt) Size() int64 { - return ra.size -} - -func (ra *remoteReaderAt) ReadAt(p []byte, off int64) (n int, err error) { - rr := &contentapi.ReadContentRequest{ - Digest: ra.digest.String(), - Offset: off, - Size: int64(len(p)), - } - // we need a child context with cancel, or the eventually called - // grpc.NewStream will leak the goroutine until the whole thing is cleared. - // See comment at https://godoc.org/google.golang.org/grpc#ClientConn.NewStream - childCtx, cancel := context.WithCancel(ra.ctx) - // we MUST cancel the child context; see comment above - defer cancel() - rc, err := ra.client.Read(childCtx, rr) - if err != nil { - return 0, err - } - - for len(p) > 0 { - var resp *contentapi.ReadContentResponse - // fill our buffer up until we can fill p. - resp, err = rc.Recv() - if err != nil { - return n, err - } - - copied := copy(p, resp.Data) - n += copied - p = p[copied:] - } - return n, nil -} - -func (ra *remoteReaderAt) Close() error { - return nil -} diff --git a/vendor/github.com/containerd/containerd/content/proxy/content_store.go b/vendor/github.com/containerd/containerd/content/proxy/content_store.go deleted file mode 100644 index 8e7fb42cf..000000000 --- a/vendor/github.com/containerd/containerd/content/proxy/content_store.go +++ /dev/null @@ -1,235 +0,0 @@ -/* - Copyright The containerd 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 proxy - -import ( - "context" - "io" - - contentapi "github.com/containerd/containerd/api/services/content/v1" - "github.com/containerd/containerd/content" - "github.com/containerd/containerd/errdefs" - "github.com/containerd/containerd/protobuf" - protobuftypes "github.com/containerd/containerd/protobuf/types" - digest "github.com/opencontainers/go-digest" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" -) - -type proxyContentStore struct { - client contentapi.ContentClient -} - -// NewContentStore returns a new content store which communicates over a GRPC -// connection using the containerd content GRPC API. -func NewContentStore(client contentapi.ContentClient) content.Store { - return &proxyContentStore{ - client: client, - } -} - -func (pcs *proxyContentStore) Info(ctx context.Context, dgst digest.Digest) (content.Info, error) { - resp, err := pcs.client.Info(ctx, &contentapi.InfoRequest{ - Digest: dgst.String(), - }) - if err != nil { - return content.Info{}, errdefs.FromGRPC(err) - } - - return infoFromGRPC(resp.Info), nil -} - -func (pcs *proxyContentStore) Walk(ctx context.Context, fn content.WalkFunc, filters ...string) error { - session, err := pcs.client.List(ctx, &contentapi.ListContentRequest{ - Filters: filters, - }) - if err != nil { - return errdefs.FromGRPC(err) - } - - for { - msg, err := session.Recv() - if err != nil { - if err != io.EOF { - return errdefs.FromGRPC(err) - } - - break - } - - for _, info := range msg.Info { - if err := fn(infoFromGRPC(info)); err != nil { - return err - } - } - } - - return nil -} - -func (pcs *proxyContentStore) Delete(ctx context.Context, dgst digest.Digest) error { - if _, err := pcs.client.Delete(ctx, &contentapi.DeleteContentRequest{ - Digest: dgst.String(), - }); err != nil { - return errdefs.FromGRPC(err) - } - - return nil -} - -// ReaderAt ignores MediaType. -func (pcs *proxyContentStore) ReaderAt(ctx context.Context, desc ocispec.Descriptor) (content.ReaderAt, error) { - i, err := pcs.Info(ctx, desc.Digest) - if err != nil { - return nil, err - } - - return &remoteReaderAt{ - ctx: ctx, - digest: desc.Digest, - size: i.Size, - client: pcs.client, - }, nil -} - -func (pcs *proxyContentStore) Status(ctx context.Context, ref string) (content.Status, error) { - resp, err := pcs.client.Status(ctx, &contentapi.StatusRequest{ - Ref: ref, - }) - if err != nil { - return content.Status{}, errdefs.FromGRPC(err) - } - - status := resp.Status - return content.Status{ - Ref: status.Ref, - StartedAt: protobuf.FromTimestamp(status.StartedAt), - UpdatedAt: protobuf.FromTimestamp(status.UpdatedAt), - Offset: status.Offset, - Total: status.Total, - Expected: digest.Digest(status.Expected), - }, nil -} - -func (pcs *proxyContentStore) Update(ctx context.Context, info content.Info, fieldpaths ...string) (content.Info, error) { - resp, err := pcs.client.Update(ctx, &contentapi.UpdateRequest{ - Info: infoToGRPC(&info), - UpdateMask: &protobuftypes.FieldMask{ - Paths: fieldpaths, - }, - }) - if err != nil { - return content.Info{}, errdefs.FromGRPC(err) - } - return infoFromGRPC(resp.Info), nil -} - -func (pcs *proxyContentStore) ListStatuses(ctx context.Context, filters ...string) ([]content.Status, error) { - resp, err := pcs.client.ListStatuses(ctx, &contentapi.ListStatusesRequest{ - Filters: filters, - }) - if err != nil { - return nil, errdefs.FromGRPC(err) - } - - var statuses []content.Status - for _, status := range resp.Statuses { - statuses = append(statuses, content.Status{ - Ref: status.Ref, - StartedAt: protobuf.FromTimestamp(status.StartedAt), - UpdatedAt: protobuf.FromTimestamp(status.UpdatedAt), - Offset: status.Offset, - Total: status.Total, - Expected: digest.Digest(status.Expected), - }) - } - - return statuses, nil -} - -// Writer ignores MediaType. -func (pcs *proxyContentStore) Writer(ctx context.Context, opts ...content.WriterOpt) (content.Writer, error) { - var wOpts content.WriterOpts - for _, opt := range opts { - if err := opt(&wOpts); err != nil { - return nil, err - } - } - wrclient, offset, err := pcs.negotiate(ctx, wOpts.Ref, wOpts.Desc.Size, wOpts.Desc.Digest) - if err != nil { - return nil, errdefs.FromGRPC(err) - } - - return &remoteWriter{ - ref: wOpts.Ref, - client: wrclient, - offset: offset, - }, nil -} - -// Abort implements asynchronous abort. It starts a new write session on the ref l -func (pcs *proxyContentStore) Abort(ctx context.Context, ref string) error { - if _, err := pcs.client.Abort(ctx, &contentapi.AbortRequest{ - Ref: ref, - }); err != nil { - return errdefs.FromGRPC(err) - } - - return nil -} - -func (pcs *proxyContentStore) negotiate(ctx context.Context, ref string, size int64, expected digest.Digest) (contentapi.Content_WriteClient, int64, error) { - wrclient, err := pcs.client.Write(ctx) - if err != nil { - return nil, 0, err - } - - if err := wrclient.Send(&contentapi.WriteContentRequest{ - Action: contentapi.WriteAction_STAT, - Ref: ref, - Total: size, - Expected: expected.String(), - }); err != nil { - return nil, 0, err - } - - resp, err := wrclient.Recv() - if err != nil { - return nil, 0, err - } - - return wrclient, resp.Offset, nil -} - -func infoToGRPC(info *content.Info) *contentapi.Info { - return &contentapi.Info{ - Digest: info.Digest.String(), - Size: info.Size, - CreatedAt: protobuf.ToTimestamp(info.CreatedAt), - UpdatedAt: protobuf.ToTimestamp(info.UpdatedAt), - Labels: info.Labels, - } -} - -func infoFromGRPC(info *contentapi.Info) content.Info { - return content.Info{ - Digest: digest.Digest(info.Digest), - Size: info.Size, - CreatedAt: protobuf.FromTimestamp(info.CreatedAt), - UpdatedAt: protobuf.FromTimestamp(info.UpdatedAt), - Labels: info.Labels, - } -} diff --git a/vendor/github.com/containerd/containerd/content/proxy/content_writer.go b/vendor/github.com/containerd/containerd/content/proxy/content_writer.go deleted file mode 100644 index 185115b0a..000000000 --- a/vendor/github.com/containerd/containerd/content/proxy/content_writer.go +++ /dev/null @@ -1,148 +0,0 @@ -/* - Copyright The containerd 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 proxy - -import ( - "context" - "fmt" - "io" - - contentapi "github.com/containerd/containerd/api/services/content/v1" - "github.com/containerd/containerd/content" - "github.com/containerd/containerd/errdefs" - "github.com/containerd/containerd/protobuf" - digest "github.com/opencontainers/go-digest" -) - -type remoteWriter struct { - ref string - client contentapi.Content_WriteClient - offset int64 - digest digest.Digest -} - -// send performs a synchronous req-resp cycle on the client. -func (rw *remoteWriter) send(req *contentapi.WriteContentRequest) (*contentapi.WriteContentResponse, error) { - if err := rw.client.Send(req); err != nil { - return nil, err - } - - resp, err := rw.client.Recv() - - if err == nil { - // try to keep these in sync - if resp.Digest != "" { - rw.digest = digest.Digest(resp.Digest) - } - } - - return resp, err -} - -func (rw *remoteWriter) Status() (content.Status, error) { - resp, err := rw.send(&contentapi.WriteContentRequest{ - Action: contentapi.WriteAction_STAT, - }) - if err != nil { - return content.Status{}, fmt.Errorf("error getting writer status: %w", errdefs.FromGRPC(err)) - } - - return content.Status{ - Ref: rw.ref, - Offset: resp.Offset, - Total: resp.Total, - StartedAt: protobuf.FromTimestamp(resp.StartedAt), - UpdatedAt: protobuf.FromTimestamp(resp.UpdatedAt), - }, nil -} - -func (rw *remoteWriter) Digest() digest.Digest { - return rw.digest -} - -func (rw *remoteWriter) Write(p []byte) (n int, err error) { - offset := rw.offset - - resp, err := rw.send(&contentapi.WriteContentRequest{ - Action: contentapi.WriteAction_WRITE, - Offset: offset, - Data: p, - }) - if err != nil { - return 0, fmt.Errorf("failed to send write: %w", errdefs.FromGRPC(err)) - } - - n = int(resp.Offset - offset) - if n < len(p) { - err = io.ErrShortWrite - } - - rw.offset += int64(n) - if resp.Digest != "" { - rw.digest = digest.Digest(resp.Digest) - } - return -} - -func (rw *remoteWriter) Commit(ctx context.Context, size int64, expected digest.Digest, opts ...content.Opt) (err error) { - defer func() { - err1 := rw.Close() - if err == nil { - err = err1 - } - }() - - var base content.Info - for _, opt := range opts { - if err := opt(&base); err != nil { - return err - } - } - resp, err := rw.send(&contentapi.WriteContentRequest{ - Action: contentapi.WriteAction_COMMIT, - Total: size, - Offset: rw.offset, - Expected: expected.String(), - Labels: base.Labels, - }) - if err != nil { - return fmt.Errorf("commit failed: %w", errdefs.FromGRPC(err)) - } - - if size != 0 && resp.Offset != size { - return fmt.Errorf("unexpected size: %v != %v", resp.Offset, size) - } - - actual := digest.Digest(resp.Digest) - if expected != "" && actual != expected { - return fmt.Errorf("unexpected digest: %v != %v", resp.Digest, expected) - } - - rw.digest = actual - rw.offset = resp.Offset - return nil -} - -func (rw *remoteWriter) Truncate(size int64) error { - // This truncation won't actually be validated until a write is issued. - rw.offset = size - return nil -} - -func (rw *remoteWriter) Close() error { - return rw.client.CloseSend() -} diff --git a/vendor/github.com/containerd/containerd/defaults/defaults.go b/vendor/github.com/containerd/containerd/defaults/defaults.go deleted file mode 100644 index 6f5b122ec..000000000 --- a/vendor/github.com/containerd/containerd/defaults/defaults.go +++ /dev/null @@ -1,32 +0,0 @@ -/* - Copyright The containerd 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 defaults - -const ( - // DefaultMaxRecvMsgSize defines the default maximum message size for - // receiving protobufs passed over the GRPC API. - DefaultMaxRecvMsgSize = 16 << 20 - // DefaultMaxSendMsgSize defines the default maximum message size for - // sending protobufs passed over the GRPC API. - DefaultMaxSendMsgSize = 16 << 20 - // DefaultRuntimeNSLabel defines the namespace label to check for the - // default runtime - DefaultRuntimeNSLabel = "containerd.io/defaults/runtime" - // DefaultSnapshotterNSLabel defines the namespace label to check for the - // default snapshotter - DefaultSnapshotterNSLabel = "containerd.io/defaults/snapshotter" -) diff --git a/vendor/github.com/containerd/containerd/defaults/defaults_darwin.go b/vendor/github.com/containerd/containerd/defaults/defaults_darwin.go deleted file mode 100644 index 1391884cd..000000000 --- a/vendor/github.com/containerd/containerd/defaults/defaults_darwin.go +++ /dev/null @@ -1,37 +0,0 @@ -/* - Copyright The containerd 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 defaults - -const ( - // DefaultRootDir is the default location used by containerd to store - // persistent data - DefaultRootDir = "/var/lib/containerd" - // DefaultStateDir is the default location used by containerd to store - // transient data - DefaultStateDir = "/var/run/containerd" - // DefaultAddress is the default unix socket address - DefaultAddress = "/var/run/containerd/containerd.sock" - // DefaultDebugAddress is the default unix socket address for pprof data - DefaultDebugAddress = "/var/run/containerd/debug.sock" - // DefaultFIFODir is the default location used by client-side cio library - // to store FIFOs. - DefaultFIFODir = "/var/run/containerd/fifo" - // DefaultRuntime would be a multiple of choices, thus empty - DefaultRuntime = "" - // DefaultConfigDir is the default location for config files. - DefaultConfigDir = "/etc/containerd" -) diff --git a/vendor/github.com/containerd/containerd/defaults/defaults_unix.go b/vendor/github.com/containerd/containerd/defaults/defaults_unix.go deleted file mode 100644 index c79f9ba7d..000000000 --- a/vendor/github.com/containerd/containerd/defaults/defaults_unix.go +++ /dev/null @@ -1,39 +0,0 @@ -//go:build !windows && !darwin - -/* - Copyright The containerd 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 defaults - -const ( - // DefaultRootDir is the default location used by containerd to store - // persistent data - DefaultRootDir = "/var/lib/containerd" - // DefaultStateDir is the default location used by containerd to store - // transient data - DefaultStateDir = "/run/containerd" - // DefaultAddress is the default unix socket address - DefaultAddress = "/run/containerd/containerd.sock" - // DefaultDebugAddress is the default unix socket address for pprof data - DefaultDebugAddress = "/run/containerd/debug.sock" - // DefaultFIFODir is the default location used by client-side cio library - // to store FIFOs. - DefaultFIFODir = "/run/containerd/fifo" - // DefaultRuntime is the default linux runtime - DefaultRuntime = "io.containerd.runc.v2" - // DefaultConfigDir is the default location for config files. - DefaultConfigDir = "/etc/containerd" -) diff --git a/vendor/github.com/containerd/containerd/defaults/defaults_windows.go b/vendor/github.com/containerd/containerd/defaults/defaults_windows.go deleted file mode 100644 index 9f4bed8b0..000000000 --- a/vendor/github.com/containerd/containerd/defaults/defaults_windows.go +++ /dev/null @@ -1,46 +0,0 @@ -/* - Copyright The containerd 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 defaults - -import ( - "os" - "path/filepath" -) - -var ( - // DefaultRootDir is the default location used by containerd to store - // persistent data - DefaultRootDir = filepath.Join(os.Getenv("ProgramData"), "containerd", "root") - // DefaultStateDir is the default location used by containerd to store - // transient data - DefaultStateDir = filepath.Join(os.Getenv("ProgramData"), "containerd", "state") - - // DefaultConfigDir is the default location for config files. - DefaultConfigDir = filepath.Join(os.Getenv("programfiles"), "containerd") -) - -const ( - // DefaultAddress is the default winpipe address - DefaultAddress = `\\.\pipe\containerd-containerd` - // DefaultDebugAddress is the default winpipe address for pprof data - DefaultDebugAddress = `\\.\pipe\containerd-debug` - // DefaultFIFODir is the default location used by client-side cio library - // to store FIFOs. Unused on Windows. - DefaultFIFODir = "" - // DefaultRuntime is the default windows runtime - DefaultRuntime = "io.containerd.runhcs.v1" -) diff --git a/vendor/github.com/containerd/containerd/defaults/doc.go b/vendor/github.com/containerd/containerd/defaults/doc.go deleted file mode 100644 index 6da863ce2..000000000 --- a/vendor/github.com/containerd/containerd/defaults/doc.go +++ /dev/null @@ -1,19 +0,0 @@ -/* - Copyright The containerd 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 defaults provides several common defaults for interacting with -// containerd. These can be used on the client-side or server-side. -package defaults diff --git a/vendor/github.com/containerd/containerd/errdefs/errors.go b/vendor/github.com/containerd/containerd/errdefs/errors.go deleted file mode 100644 index 876225597..000000000 --- a/vendor/github.com/containerd/containerd/errdefs/errors.go +++ /dev/null @@ -1,92 +0,0 @@ -/* - Copyright The containerd 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 errdefs defines the common errors used throughout containerd -// packages. -// -// Use with fmt.Errorf to add context to an error. -// -// To detect an error class, use the IsXXX functions to tell whether an error -// is of a certain type. -// -// The functions ToGRPC and FromGRPC can be used to map server-side and -// client-side errors to the correct types. -package errdefs - -import ( - "context" - "errors" -) - -// Definitions of common error types used throughout containerd. All containerd -// errors returned by most packages will map into one of these errors classes. -// Packages should return errors of these types when they want to instruct a -// client to take a particular action. -// -// For the most part, we just try to provide local grpc errors. Most conditions -// map very well to those defined by grpc. -var ( - ErrUnknown = errors.New("unknown") // used internally to represent a missed mapping. - ErrInvalidArgument = errors.New("invalid argument") - ErrNotFound = errors.New("not found") - ErrAlreadyExists = errors.New("already exists") - ErrFailedPrecondition = errors.New("failed precondition") - ErrUnavailable = errors.New("unavailable") - ErrNotImplemented = errors.New("not implemented") // represents not supported and unimplemented -) - -// IsInvalidArgument returns true if the error is due to an invalid argument -func IsInvalidArgument(err error) bool { - return errors.Is(err, ErrInvalidArgument) -} - -// IsNotFound returns true if the error is due to a missing object -func IsNotFound(err error) bool { - return errors.Is(err, ErrNotFound) -} - -// IsAlreadyExists returns true if the error is due to an already existing -// metadata item -func IsAlreadyExists(err error) bool { - return errors.Is(err, ErrAlreadyExists) -} - -// IsFailedPrecondition returns true if an operation could not proceed to the -// lack of a particular condition -func IsFailedPrecondition(err error) bool { - return errors.Is(err, ErrFailedPrecondition) -} - -// IsUnavailable returns true if the error is due to a resource being unavailable -func IsUnavailable(err error) bool { - return errors.Is(err, ErrUnavailable) -} - -// IsNotImplemented returns true if the error is due to not being implemented -func IsNotImplemented(err error) bool { - return errors.Is(err, ErrNotImplemented) -} - -// IsCanceled returns true if the error is due to `context.Canceled`. -func IsCanceled(err error) bool { - return errors.Is(err, context.Canceled) -} - -// IsDeadlineExceeded returns true if the error is due to -// `context.DeadlineExceeded`. -func IsDeadlineExceeded(err error) bool { - return errors.Is(err, context.DeadlineExceeded) -} diff --git a/vendor/github.com/containerd/containerd/errdefs/grpc.go b/vendor/github.com/containerd/containerd/errdefs/grpc.go deleted file mode 100644 index 7a9b33e05..000000000 --- a/vendor/github.com/containerd/containerd/errdefs/grpc.go +++ /dev/null @@ -1,147 +0,0 @@ -/* - Copyright The containerd 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 errdefs - -import ( - "context" - "fmt" - "strings" - - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" -) - -// ToGRPC will attempt to map the backend containerd error into a grpc error, -// using the original error message as a description. -// -// Further information may be extracted from certain errors depending on their -// type. -// -// If the error is unmapped, the original error will be returned to be handled -// by the regular grpc error handling stack. -func ToGRPC(err error) error { - if err == nil { - return nil - } - - if isGRPCError(err) { - // error has already been mapped to grpc - return err - } - - switch { - case IsInvalidArgument(err): - return status.Errorf(codes.InvalidArgument, err.Error()) - case IsNotFound(err): - return status.Errorf(codes.NotFound, err.Error()) - case IsAlreadyExists(err): - return status.Errorf(codes.AlreadyExists, err.Error()) - case IsFailedPrecondition(err): - return status.Errorf(codes.FailedPrecondition, err.Error()) - case IsUnavailable(err): - return status.Errorf(codes.Unavailable, err.Error()) - case IsNotImplemented(err): - return status.Errorf(codes.Unimplemented, err.Error()) - case IsCanceled(err): - return status.Errorf(codes.Canceled, err.Error()) - case IsDeadlineExceeded(err): - return status.Errorf(codes.DeadlineExceeded, err.Error()) - } - - return err -} - -// ToGRPCf maps the error to grpc error codes, assembling the formatting string -// and combining it with the target error string. -// -// This is equivalent to errdefs.ToGRPC(fmt.Errorf("%s: %w", fmt.Sprintf(format, args...), err)) -func ToGRPCf(err error, format string, args ...interface{}) error { - return ToGRPC(fmt.Errorf("%s: %w", fmt.Sprintf(format, args...), err)) -} - -// FromGRPC returns the underlying error from a grpc service based on the grpc error code -func FromGRPC(err error) error { - if err == nil { - return nil - } - - var cls error // divide these into error classes, becomes the cause - - switch code(err) { - case codes.InvalidArgument: - cls = ErrInvalidArgument - case codes.AlreadyExists: - cls = ErrAlreadyExists - case codes.NotFound: - cls = ErrNotFound - case codes.Unavailable: - cls = ErrUnavailable - case codes.FailedPrecondition: - cls = ErrFailedPrecondition - case codes.Unimplemented: - cls = ErrNotImplemented - case codes.Canceled: - cls = context.Canceled - case codes.DeadlineExceeded: - cls = context.DeadlineExceeded - default: - cls = ErrUnknown - } - - msg := rebaseMessage(cls, err) - if msg != "" { - err = fmt.Errorf("%s: %w", msg, cls) - } else { - err = cls - } - - return err -} - -// rebaseMessage removes the repeats for an error at the end of an error -// string. This will happen when taking an error over grpc then remapping it. -// -// Effectively, we just remove the string of cls from the end of err if it -// appears there. -func rebaseMessage(cls error, err error) string { - desc := errDesc(err) - clss := cls.Error() - if desc == clss { - return "" - } - - return strings.TrimSuffix(desc, ": "+clss) -} - -func isGRPCError(err error) bool { - _, ok := status.FromError(err) - return ok -} - -func code(err error) codes.Code { - if s, ok := status.FromError(err); ok { - return s.Code() - } - return codes.Unknown -} - -func errDesc(err error) string { - if s, ok := status.FromError(err); ok { - return s.Message() - } - return err.Error() -} diff --git a/vendor/github.com/containerd/containerd/filters/adaptor.go b/vendor/github.com/containerd/containerd/filters/adaptor.go deleted file mode 100644 index 5a9c559c1..000000000 --- a/vendor/github.com/containerd/containerd/filters/adaptor.go +++ /dev/null @@ -1,33 +0,0 @@ -/* - Copyright The containerd 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 filters - -// Adaptor specifies the mapping of fieldpaths to a type. For the given field -// path, the value and whether it is present should be returned. The mapping of -// the fieldpath to a field is deferred to the adaptor implementation, but -// should generally follow protobuf field path/mask semantics. -type Adaptor interface { - Field(fieldpath []string) (value string, present bool) -} - -// AdapterFunc allows implementation specific matching of fieldpaths -type AdapterFunc func(fieldpath []string) (string, bool) - -// Field returns the field name and true if it exists -func (fn AdapterFunc) Field(fieldpath []string) (string, bool) { - return fn(fieldpath) -} diff --git a/vendor/github.com/containerd/containerd/filters/filter.go b/vendor/github.com/containerd/containerd/filters/filter.go deleted file mode 100644 index e13f2625c..000000000 --- a/vendor/github.com/containerd/containerd/filters/filter.go +++ /dev/null @@ -1,178 +0,0 @@ -/* - Copyright The containerd 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 filters defines a syntax and parser that can be used for the -// filtration of items across the containerd API. The core is built on the -// concept of protobuf field paths, with quoting. Several operators allow the -// user to flexibly select items based on field presence, equality, inequality -// and regular expressions. Flexible adaptors support working with any type. -// -// The syntax is fairly familiar, if you've used container ecosystem -// projects. At the core, we base it on the concept of protobuf field -// paths, augmenting with the ability to quote portions of the field path -// to match arbitrary labels. These "selectors" come in the following -// syntax: -// -// ``` -// [] -// ``` -// -// A basic example is as follows: -// -// ``` -// name==foo -// ``` -// -// This would match all objects that have a field `name` with the value -// `foo`. If we only want to test if the field is present, we can omit the -// operator. This is most useful for matching labels in containerd. The -// following will match objects that have the field "labels" and have the -// label "foo" defined: -// -// ``` -// labels.foo -// ``` -// -// We also allow for quoting of parts of the field path to allow matching -// of arbitrary items: -// -// ``` -// labels."very complex label"==something -// ``` -// -// We also define `!=` and `~=` as operators. The `!=` will match all -// objects that don't match the value for a field and `~=` will compile the -// target value as a regular expression and match the field value against that. -// -// Selectors can be combined using a comma, such that the resulting -// selector will require all selectors are matched for the object to match. -// The following example will match objects that are named `foo` and have -// the label `bar`: -// -// ``` -// name==foo,labels.bar -// ``` -package filters - -import ( - "regexp" - - "github.com/containerd/containerd/log" -) - -// Filter matches specific resources based the provided filter -type Filter interface { - Match(adaptor Adaptor) bool -} - -// FilterFunc is a function that handles matching with an adaptor -type FilterFunc func(Adaptor) bool - -// Match matches the FilterFunc returning true if the object matches the filter -func (fn FilterFunc) Match(adaptor Adaptor) bool { - return fn(adaptor) -} - -// Always is a filter that always returns true for any type of object -var Always FilterFunc = func(adaptor Adaptor) bool { - return true -} - -// Any allows multiple filters to be matched against the object -type Any []Filter - -// Match returns true if any of the provided filters are true -func (m Any) Match(adaptor Adaptor) bool { - for _, m := range m { - if m.Match(adaptor) { - return true - } - } - - return false -} - -// All allows multiple filters to be matched against the object -type All []Filter - -// Match only returns true if all filters match the object -func (m All) Match(adaptor Adaptor) bool { - for _, m := range m { - if !m.Match(adaptor) { - return false - } - } - - return true -} - -type operator int - -const ( - operatorPresent = iota - operatorEqual - operatorNotEqual - operatorMatches -) - -func (op operator) String() string { - switch op { - case operatorPresent: - return "?" - case operatorEqual: - return "==" - case operatorNotEqual: - return "!=" - case operatorMatches: - return "~=" - } - - return "unknown" -} - -type selector struct { - fieldpath []string - operator operator - value string - re *regexp.Regexp -} - -func (m selector) Match(adaptor Adaptor) bool { - value, present := adaptor.Field(m.fieldpath) - - switch m.operator { - case operatorPresent: - return present - case operatorEqual: - return present && value == m.value - case operatorNotEqual: - return value != m.value - case operatorMatches: - if m.re == nil { - r, err := regexp.Compile(m.value) - if err != nil { - log.L.Errorf("error compiling regexp %q", m.value) - return false - } - - m.re = r - } - - return m.re.MatchString(value) - default: - return false - } -} diff --git a/vendor/github.com/containerd/containerd/filters/parser.go b/vendor/github.com/containerd/containerd/filters/parser.go deleted file mode 100644 index 32767909b..000000000 --- a/vendor/github.com/containerd/containerd/filters/parser.go +++ /dev/null @@ -1,290 +0,0 @@ -/* - Copyright The containerd 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 filters - -import ( - "fmt" - "io" - - "github.com/containerd/containerd/errdefs" -) - -/* -Parse the strings into a filter that may be used with an adaptor. - -The filter is made up of zero or more selectors. - -The format is a comma separated list of expressions, in the form of -``, known as selectors. All selectors must match the -target object for the filter to be true. - -We define the operators "==" for equality, "!=" for not equal and "~=" for a -regular expression. If the operator and value are not present, the matcher will -test for the presence of a value, as defined by the target object. - -The formal grammar is as follows: - -selectors := selector ("," selector)* -selector := fieldpath (operator value) -fieldpath := field ('.' field)* -field := quoted | [A-Za-z] [A-Za-z0-9_]+ -operator := "==" | "!=" | "~=" -value := quoted | [^\s,]+ -quoted := -*/ -func Parse(s string) (Filter, error) { - // special case empty to match all - if s == "" { - return Always, nil - } - - p := parser{input: s} - return p.parse() -} - -// ParseAll parses each filter in ss and returns a filter that will return true -// if any filter matches the expression. -// -// If no filters are provided, the filter will match anything. -func ParseAll(ss ...string) (Filter, error) { - if len(ss) == 0 { - return Always, nil - } - - var fs []Filter - for _, s := range ss { - f, err := Parse(s) - if err != nil { - return nil, fmt.Errorf("%s: %w", err.Error(), errdefs.ErrInvalidArgument) - } - - fs = append(fs, f) - } - - return Any(fs), nil -} - -type parser struct { - input string - scanner scanner -} - -func (p *parser) parse() (Filter, error) { - p.scanner.init(p.input) - - ss, err := p.selectors() - if err != nil { - return nil, fmt.Errorf("filters: %w", err) - } - - return ss, nil -} - -func (p *parser) selectors() (Filter, error) { - s, err := p.selector() - if err != nil { - return nil, err - } - - ss := All{s} - -loop: - for { - tok := p.scanner.peek() - switch tok { - case ',': - pos, tok, _ := p.scanner.scan() - if tok != tokenSeparator { - return nil, p.mkerr(pos, "expected a separator") - } - - s, err := p.selector() - if err != nil { - return nil, err - } - - ss = append(ss, s) - case tokenEOF: - break loop - default: - return nil, p.mkerr(p.scanner.ppos, "unexpected input: %v", string(tok)) - } - } - - return ss, nil -} - -func (p *parser) selector() (selector, error) { - fieldpath, err := p.fieldpath() - if err != nil { - return selector{}, err - } - - switch p.scanner.peek() { - case ',', tokenSeparator, tokenEOF: - return selector{ - fieldpath: fieldpath, - operator: operatorPresent, - }, nil - } - - op, err := p.operator() - if err != nil { - return selector{}, err - } - - var allowAltQuotes bool - if op == operatorMatches { - allowAltQuotes = true - } - - value, err := p.value(allowAltQuotes) - if err != nil { - if err == io.EOF { - return selector{}, io.ErrUnexpectedEOF - } - return selector{}, err - } - - return selector{ - fieldpath: fieldpath, - value: value, - operator: op, - }, nil -} - -func (p *parser) fieldpath() ([]string, error) { - f, err := p.field() - if err != nil { - return nil, err - } - - fs := []string{f} -loop: - for { - tok := p.scanner.peek() // lookahead to consume field separator - - switch tok { - case '.': - pos, tok, _ := p.scanner.scan() // consume separator - if tok != tokenSeparator { - return nil, p.mkerr(pos, "expected a field separator (`.`)") - } - - f, err := p.field() - if err != nil { - return nil, err - } - - fs = append(fs, f) - default: - // let the layer above handle the other bad cases. - break loop - } - } - - return fs, nil -} - -func (p *parser) field() (string, error) { - pos, tok, s := p.scanner.scan() - switch tok { - case tokenField: - return s, nil - case tokenQuoted: - return p.unquote(pos, s, false) - case tokenIllegal: - return "", p.mkerr(pos, p.scanner.err) - } - - return "", p.mkerr(pos, "expected field or quoted") -} - -func (p *parser) operator() (operator, error) { - pos, tok, s := p.scanner.scan() - switch tok { - case tokenOperator: - switch s { - case "==": - return operatorEqual, nil - case "!=": - return operatorNotEqual, nil - case "~=": - return operatorMatches, nil - default: - return 0, p.mkerr(pos, "unsupported operator %q", s) - } - case tokenIllegal: - return 0, p.mkerr(pos, p.scanner.err) - } - - return 0, p.mkerr(pos, `expected an operator ("=="|"!="|"~=")`) -} - -func (p *parser) value(allowAltQuotes bool) (string, error) { - pos, tok, s := p.scanner.scan() - - switch tok { - case tokenValue, tokenField: - return s, nil - case tokenQuoted: - return p.unquote(pos, s, allowAltQuotes) - case tokenIllegal: - return "", p.mkerr(pos, p.scanner.err) - } - - return "", p.mkerr(pos, "expected value or quoted") -} - -func (p *parser) unquote(pos int, s string, allowAlts bool) (string, error) { - if !allowAlts && s[0] != '\'' && s[0] != '"' { - return "", p.mkerr(pos, "invalid quote encountered") - } - - uq, err := unquote(s) - if err != nil { - return "", p.mkerr(pos, "unquoting failed: %v", err) - } - - return uq, nil -} - -type parseError struct { - input string - pos int - msg string -} - -func (pe parseError) Error() string { - if pe.pos < len(pe.input) { - before := pe.input[:pe.pos] - location := pe.input[pe.pos : pe.pos+1] // need to handle end - after := pe.input[pe.pos+1:] - - return fmt.Sprintf("[%s >|%s|< %s]: %v", before, location, after, pe.msg) - } - - return fmt.Sprintf("[%s]: %v", pe.input, pe.msg) -} - -func (p *parser) mkerr(pos int, format string, args ...interface{}) error { - return fmt.Errorf("parse error: %w", parseError{ - input: p.input, - pos: pos, - msg: fmt.Sprintf(format, args...), - }) -} diff --git a/vendor/github.com/containerd/containerd/filters/quote.go b/vendor/github.com/containerd/containerd/filters/quote.go deleted file mode 100644 index 5c800ef84..000000000 --- a/vendor/github.com/containerd/containerd/filters/quote.go +++ /dev/null @@ -1,252 +0,0 @@ -/* - Copyright The containerd 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 filters - -import ( - "errors" - "unicode/utf8" -) - -// NOTE(stevvooe): Most of this code in this file is copied from the stdlib -// strconv package and modified to be able to handle quoting with `/` and `|` -// as delimiters. The copyright is held by the Go authors. - -var errQuoteSyntax = errors.New("quote syntax error") - -// UnquoteChar decodes the first character or byte in the escaped string -// or character literal represented by the string s. -// It returns four values: -// -// 1. value, the decoded Unicode code point or byte value; -// 2. multibyte, a boolean indicating whether the decoded character requires a multibyte UTF-8 representation; -// 3. tail, the remainder of the string after the character; and -// 4. an error that will be nil if the character is syntactically valid. -// -// The second argument, quote, specifies the type of literal being parsed -// and therefore which escaped quote character is permitted. -// If set to a single quote, it permits the sequence \' and disallows unescaped '. -// If set to a double quote, it permits \" and disallows unescaped ". -// If set to zero, it does not permit either escape and allows both quote characters to appear unescaped. -// -// This is from Go strconv package, modified to support `|` and `/` as double -// quotes for use with regular expressions. -func unquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, err error) { - // easy cases - switch c := s[0]; { - case c == quote && (quote == '\'' || quote == '"' || quote == '/' || quote == '|'): - err = errQuoteSyntax - return - case c >= utf8.RuneSelf: - r, size := utf8.DecodeRuneInString(s) - return r, true, s[size:], nil - case c != '\\': - return rune(s[0]), false, s[1:], nil - } - - // hard case: c is backslash - if len(s) <= 1 { - err = errQuoteSyntax - return - } - c := s[1] - s = s[2:] - - switch c { - case 'a': - value = '\a' - case 'b': - value = '\b' - case 'f': - value = '\f' - case 'n': - value = '\n' - case 'r': - value = '\r' - case 't': - value = '\t' - case 'v': - value = '\v' - case 'x', 'u', 'U': - n := 0 - switch c { - case 'x': - n = 2 - case 'u': - n = 4 - case 'U': - n = 8 - } - var v rune - if len(s) < n { - err = errQuoteSyntax - return - } - for j := 0; j < n; j++ { - x, ok := unhex(s[j]) - if !ok { - err = errQuoteSyntax - return - } - v = v<<4 | x - } - s = s[n:] - if c == 'x' { - // single-byte string, possibly not UTF-8 - value = v - break - } - if v > utf8.MaxRune { - err = errQuoteSyntax - return - } - value = v - multibyte = true - case '0', '1', '2', '3', '4', '5', '6', '7': - v := rune(c) - '0' - if len(s) < 2 { - err = errQuoteSyntax - return - } - for j := 0; j < 2; j++ { // one digit already; two more - x := rune(s[j]) - '0' - if x < 0 || x > 7 { - err = errQuoteSyntax - return - } - v = (v << 3) | x - } - s = s[2:] - if v > 255 { - err = errQuoteSyntax - return - } - value = v - case '\\': - value = '\\' - case '\'', '"', '|', '/': - if c != quote { - err = errQuoteSyntax - return - } - value = rune(c) - default: - err = errQuoteSyntax - return - } - tail = s - return -} - -// unquote interprets s as a single-quoted, double-quoted, -// or backquoted Go string literal, returning the string value -// that s quotes. (If s is single-quoted, it would be a Go -// character literal; Unquote returns the corresponding -// one-character string.) -// -// This is modified from the standard library to support `|` and `/` as quote -// characters for use with regular expressions. -func unquote(s string) (string, error) { - n := len(s) - if n < 2 { - return "", errQuoteSyntax - } - quote := s[0] - if quote != s[n-1] { - return "", errQuoteSyntax - } - s = s[1 : n-1] - - if quote == '`' { - if contains(s, '`') { - return "", errQuoteSyntax - } - if contains(s, '\r') { - // -1 because we know there is at least one \r to remove. - buf := make([]byte, 0, len(s)-1) - for i := 0; i < len(s); i++ { - if s[i] != '\r' { - buf = append(buf, s[i]) - } - } - return string(buf), nil - } - return s, nil - } - if quote != '"' && quote != '\'' && quote != '|' && quote != '/' { - return "", errQuoteSyntax - } - if contains(s, '\n') { - return "", errQuoteSyntax - } - - // Is it trivial? Avoid allocation. - if !contains(s, '\\') && !contains(s, quote) { - switch quote { - case '"', '/', '|': // pipe and slash are treated like double quote - return s, nil - case '\'': - r, size := utf8.DecodeRuneInString(s) - if size == len(s) && (r != utf8.RuneError || size != 1) { - return s, nil - } - } - } - - var runeTmp [utf8.UTFMax]byte - buf := make([]byte, 0, 3*len(s)/2) // Try to avoid more allocations. - for len(s) > 0 { - c, multibyte, ss, err := unquoteChar(s, quote) - if err != nil { - return "", err - } - s = ss - if c < utf8.RuneSelf || !multibyte { - buf = append(buf, byte(c)) - } else { - n := utf8.EncodeRune(runeTmp[:], c) - buf = append(buf, runeTmp[:n]...) - } - if quote == '\'' && len(s) != 0 { - // single-quoted must be single character - return "", errQuoteSyntax - } - } - return string(buf), nil -} - -// contains reports whether the string contains the byte c. -func contains(s string, c byte) bool { - for i := 0; i < len(s); i++ { - if s[i] == c { - return true - } - } - return false -} - -func unhex(b byte) (v rune, ok bool) { - c := rune(b) - switch { - case '0' <= c && c <= '9': - return c - '0', true - case 'a' <= c && c <= 'f': - return c - 'a' + 10, true - case 'A' <= c && c <= 'F': - return c - 'A' + 10, true - } - return -} diff --git a/vendor/github.com/containerd/containerd/filters/scanner.go b/vendor/github.com/containerd/containerd/filters/scanner.go deleted file mode 100644 index 6a485467b..000000000 --- a/vendor/github.com/containerd/containerd/filters/scanner.go +++ /dev/null @@ -1,297 +0,0 @@ -/* - Copyright The containerd 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 filters - -import ( - "unicode" - "unicode/utf8" -) - -const ( - tokenEOF = -(iota + 1) - tokenQuoted - tokenValue - tokenField - tokenSeparator - tokenOperator - tokenIllegal -) - -type token rune - -func (t token) String() string { - switch t { - case tokenEOF: - return "EOF" - case tokenQuoted: - return "Quoted" - case tokenValue: - return "Value" - case tokenField: - return "Field" - case tokenSeparator: - return "Separator" - case tokenOperator: - return "Operator" - case tokenIllegal: - return "Illegal" - } - - return string(t) -} - -func (t token) GoString() string { - return "token" + t.String() -} - -type scanner struct { - input string - pos int - ppos int // bounds the current rune in the string - value bool - err string -} - -func (s *scanner) init(input string) { - s.input = input - s.pos = 0 - s.ppos = 0 -} - -func (s *scanner) next() rune { - if s.pos >= len(s.input) { - return tokenEOF - } - s.pos = s.ppos - - r, w := utf8.DecodeRuneInString(s.input[s.ppos:]) - s.ppos += w - if r == utf8.RuneError { - if w > 0 { - s.error("rune error") - return tokenIllegal - } - return tokenEOF - } - - if r == 0 { - s.error("unexpected null") - return tokenIllegal - } - - return r -} - -func (s *scanner) peek() rune { - pos := s.pos - ppos := s.ppos - ch := s.next() - s.pos = pos - s.ppos = ppos - return ch -} - -func (s *scanner) scan() (nextp int, tk token, text string) { - var ( - ch = s.next() - pos = s.pos - ) - -chomp: - switch { - case ch == tokenEOF: - case ch == tokenIllegal: - case isQuoteRune(ch): - if !s.scanQuoted(ch) { - return pos, tokenIllegal, s.input[pos:s.ppos] - } - return pos, tokenQuoted, s.input[pos:s.ppos] - case isSeparatorRune(ch): - s.value = false - return pos, tokenSeparator, s.input[pos:s.ppos] - case isOperatorRune(ch): - s.scanOperator() - s.value = true - return pos, tokenOperator, s.input[pos:s.ppos] - case unicode.IsSpace(ch): - // chomp - ch = s.next() - pos = s.pos - goto chomp - case s.value: - s.scanValue() - s.value = false - return pos, tokenValue, s.input[pos:s.ppos] - case isFieldRune(ch): - s.scanField() - return pos, tokenField, s.input[pos:s.ppos] - } - - return s.pos, token(ch), "" -} - -func (s *scanner) scanField() { - for { - ch := s.peek() - if !isFieldRune(ch) { - break - } - s.next() - } -} - -func (s *scanner) scanOperator() { - for { - ch := s.peek() - switch ch { - case '=', '!', '~': - s.next() - default: - return - } - } -} - -func (s *scanner) scanValue() { - for { - ch := s.peek() - if !isValueRune(ch) { - break - } - s.next() - } -} - -func (s *scanner) scanQuoted(quote rune) bool { - var illegal bool - ch := s.next() // read character after quote - for ch != quote { - if ch == '\n' || ch < 0 { - s.error("quoted literal not terminated") - return false - } - if ch == '\\' { - var legal bool - ch, legal = s.scanEscape(quote) - if !legal { - illegal = true - } - } else { - ch = s.next() - } - } - return !illegal -} - -func (s *scanner) scanEscape(quote rune) (ch rune, legal bool) { - ch = s.next() // read character after '/' - switch ch { - case 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', quote: - // nothing to do - ch = s.next() - legal = true - case '0', '1', '2', '3', '4', '5', '6', '7': - ch, legal = s.scanDigits(ch, 8, 3) - case 'x': - ch, legal = s.scanDigits(s.next(), 16, 2) - case 'u': - ch, legal = s.scanDigits(s.next(), 16, 4) - case 'U': - ch, legal = s.scanDigits(s.next(), 16, 8) - default: - s.error("illegal escape sequence") - } - return -} - -func (s *scanner) scanDigits(ch rune, base, n int) (rune, bool) { - for n > 0 && digitVal(ch) < base { - ch = s.next() - n-- - } - if n > 0 { - s.error("illegal numeric escape sequence") - return ch, false - } - return ch, true -} - -func (s *scanner) error(msg string) { - if s.err == "" { - s.err = msg - } -} - -func digitVal(ch rune) int { - switch { - case '0' <= ch && ch <= '9': - return int(ch - '0') - case 'a' <= ch && ch <= 'f': - return int(ch - 'a' + 10) - case 'A' <= ch && ch <= 'F': - return int(ch - 'A' + 10) - } - return 16 // larger than any legal digit val -} - -func isFieldRune(r rune) bool { - return (r == '_' || isAlphaRune(r) || isDigitRune(r)) -} - -func isAlphaRune(r rune) bool { - return r >= 'A' && r <= 'Z' || r >= 'a' && r <= 'z' -} - -func isDigitRune(r rune) bool { - return r >= '0' && r <= '9' -} - -func isOperatorRune(r rune) bool { - switch r { - case '=', '!', '~': - return true - } - - return false -} - -func isQuoteRune(r rune) bool { - switch r { - case '/', '|', '"': // maybe add single quoting? - return true - } - - return false -} - -func isSeparatorRune(r rune) bool { - switch r { - case ',', '.': - return true - } - - return false -} - -func isValueRune(r rune) bool { - return r != ',' && !unicode.IsSpace(r) && - (unicode.IsLetter(r) || - unicode.IsDigit(r) || - unicode.IsNumber(r) || - unicode.IsGraphic(r) || - unicode.IsPunct(r)) -} diff --git a/vendor/github.com/containerd/containerd/images/annotations.go b/vendor/github.com/containerd/containerd/images/annotations.go deleted file mode 100644 index 47d92104c..000000000 --- a/vendor/github.com/containerd/containerd/images/annotations.go +++ /dev/null @@ -1,23 +0,0 @@ -/* - Copyright The containerd 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 images - -const ( - // AnnotationImageName is an annotation on a Descriptor in an index.json - // containing the `Name` value as used by an `Image` struct - AnnotationImageName = "io.containerd.image.name" -) diff --git a/vendor/github.com/containerd/containerd/images/diffid.go b/vendor/github.com/containerd/containerd/images/diffid.go deleted file mode 100644 index 56193cc28..000000000 --- a/vendor/github.com/containerd/containerd/images/diffid.go +++ /dev/null @@ -1,81 +0,0 @@ -/* - Copyright The containerd 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 images - -import ( - "context" - "io" - - "github.com/containerd/containerd/archive/compression" - "github.com/containerd/containerd/content" - "github.com/containerd/containerd/labels" - "github.com/opencontainers/go-digest" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" - "github.com/sirupsen/logrus" -) - -// GetDiffID gets the diff ID of the layer blob descriptor. -func GetDiffID(ctx context.Context, cs content.Store, desc ocispec.Descriptor) (digest.Digest, error) { - switch desc.MediaType { - case - // If the layer is already uncompressed, we can just return its digest - MediaTypeDockerSchema2Layer, - ocispec.MediaTypeImageLayer, - MediaTypeDockerSchema2LayerForeign, - ocispec.MediaTypeImageLayerNonDistributable: - return desc.Digest, nil - } - info, err := cs.Info(ctx, desc.Digest) - if err != nil { - return "", err - } - v, ok := info.Labels[labels.LabelUncompressed] - if ok { - // Fast path: if the image is already unpacked, we can use the label value - return digest.Parse(v) - } - // if the image is not unpacked, we may not have the label - ra, err := cs.ReaderAt(ctx, desc) - if err != nil { - return "", err - } - defer ra.Close() - r := content.NewReader(ra) - uR, err := compression.DecompressStream(r) - if err != nil { - return "", err - } - defer uR.Close() - digester := digest.Canonical.Digester() - hashW := digester.Hash() - if _, err := io.Copy(hashW, uR); err != nil { - return "", err - } - if err := ra.Close(); err != nil { - return "", err - } - digest := digester.Digest() - // memorize the computed value - if info.Labels == nil { - info.Labels = make(map[string]string) - } - info.Labels[labels.LabelUncompressed] = digest.String() - if _, err := cs.Update(ctx, info, "labels"); err != nil { - logrus.WithError(err).Warnf("failed to set %s label for %s", labels.LabelUncompressed, desc.Digest) - } - return digest, nil -} diff --git a/vendor/github.com/containerd/containerd/images/handlers.go b/vendor/github.com/containerd/containerd/images/handlers.go deleted file mode 100644 index 077d88e78..000000000 --- a/vendor/github.com/containerd/containerd/images/handlers.go +++ /dev/null @@ -1,322 +0,0 @@ -/* - Copyright The containerd 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 images - -import ( - "context" - "errors" - "fmt" - "sort" - - "github.com/containerd/containerd/content" - "github.com/containerd/containerd/errdefs" - "github.com/containerd/containerd/platforms" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" - "golang.org/x/sync/errgroup" - "golang.org/x/sync/semaphore" -) - -var ( - // ErrSkipDesc is used to skip processing of a descriptor and - // its descendants. - ErrSkipDesc = errors.New("skip descriptor") - - // ErrStopHandler is used to signify that the descriptor - // has been handled and should not be handled further. - // This applies only to a single descriptor in a handler - // chain and does not apply to descendant descriptors. - ErrStopHandler = errors.New("stop handler") - - // ErrEmptyWalk is used when the WalkNotEmpty handlers return no - // children (e.g.: they were filtered out). - ErrEmptyWalk = errors.New("image might be filtered out") -) - -// Handler handles image manifests -type Handler interface { - Handle(ctx context.Context, desc ocispec.Descriptor) (subdescs []ocispec.Descriptor, err error) -} - -// HandlerFunc function implementing the Handler interface -type HandlerFunc func(ctx context.Context, desc ocispec.Descriptor) (subdescs []ocispec.Descriptor, err error) - -// Handle image manifests -func (fn HandlerFunc) Handle(ctx context.Context, desc ocispec.Descriptor) (subdescs []ocispec.Descriptor, err error) { - return fn(ctx, desc) -} - -// Handlers returns a handler that will run the handlers in sequence. -// -// A handler may return `ErrStopHandler` to stop calling additional handlers -func Handlers(handlers ...Handler) HandlerFunc { - return func(ctx context.Context, desc ocispec.Descriptor) (subdescs []ocispec.Descriptor, err error) { - var children []ocispec.Descriptor - for _, handler := range handlers { - ch, err := handler.Handle(ctx, desc) - if err != nil { - if errors.Is(err, ErrStopHandler) { - break - } - return nil, err - } - - children = append(children, ch...) - } - - return children, nil - } -} - -// Walk the resources of an image and call the handler for each. If the handler -// decodes the sub-resources for each image, -// -// This differs from dispatch in that each sibling resource is considered -// synchronously. -func Walk(ctx context.Context, handler Handler, descs ...ocispec.Descriptor) error { - for _, desc := range descs { - - children, err := handler.Handle(ctx, desc) - if err != nil { - if errors.Is(err, ErrSkipDesc) { - continue // don't traverse the children. - } - return err - } - - if len(children) > 0 { - if err := Walk(ctx, handler, children...); err != nil { - return err - } - } - } - return nil -} - -// WalkNotEmpty works the same way Walk does, with the exception that it ensures that -// some children are still found by Walking the descriptors (for example, not all of -// them have been filtered out by one of the handlers). If there are no children, -// then an ErrEmptyWalk error is returned. -func WalkNotEmpty(ctx context.Context, handler Handler, descs ...ocispec.Descriptor) error { - isEmpty := true - var notEmptyHandler HandlerFunc = func(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) { - children, err := handler.Handle(ctx, desc) - if err != nil { - return children, err - } - - if len(children) > 0 { - isEmpty = false - } - - return children, nil - } - - err := Walk(ctx, notEmptyHandler, descs...) - if err != nil { - return err - } - - if isEmpty { - return ErrEmptyWalk - } - - return nil -} - -// Dispatch runs the provided handler for content specified by the descriptors. -// If the handler decode subresources, they will be visited, as well. -// -// Handlers for siblings are run in parallel on the provided descriptors. A -// handler may return `ErrSkipDesc` to signal to the dispatcher to not traverse -// any children. -// -// A concurrency limiter can be passed in to limit the number of concurrent -// handlers running. When limiter is nil, there is no limit. -// -// Typically, this function will be used with `FetchHandler`, often composed -// with other handlers. -// -// If any handler returns an error, the dispatch session will be canceled. -func Dispatch(ctx context.Context, handler Handler, limiter *semaphore.Weighted, descs ...ocispec.Descriptor) error { - eg, ctx2 := errgroup.WithContext(ctx) - for _, desc := range descs { - desc := desc - - if limiter != nil { - if err := limiter.Acquire(ctx, 1); err != nil { - return err - } - } - - eg.Go(func() error { - desc := desc - - children, err := handler.Handle(ctx2, desc) - if limiter != nil { - limiter.Release(1) - } - if err != nil { - if errors.Is(err, ErrSkipDesc) { - return nil // don't traverse the children. - } - return err - } - - if len(children) > 0 { - return Dispatch(ctx2, handler, limiter, children...) - } - - return nil - }) - } - - return eg.Wait() -} - -// ChildrenHandler decodes well-known manifest types and returns their children. -// -// This is useful for supporting recursive fetch and other use cases where you -// want to do a full walk of resources. -// -// One can also replace this with another implementation to allow descending of -// arbitrary types. -func ChildrenHandler(provider content.Provider) HandlerFunc { - return func(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) { - return Children(ctx, provider, desc) - } -} - -// SetChildrenLabels is a handler wrapper which sets labels for the content on -// the children returned by the handler and passes through the children. -// Must follow a handler that returns the children to be labeled. -func SetChildrenLabels(manager content.Manager, f HandlerFunc) HandlerFunc { - return SetChildrenMappedLabels(manager, f, nil) -} - -// SetChildrenMappedLabels is a handler wrapper which sets labels for the content on -// the children returned by the handler and passes through the children. -// Must follow a handler that returns the children to be labeled. -// The label map allows the caller to control the labels per child descriptor. -// For returned labels, the index of the child will be appended to the end -// except for the first index when the returned label does not end with '.'. -func SetChildrenMappedLabels(manager content.Manager, f HandlerFunc, labelMap func(ocispec.Descriptor) []string) HandlerFunc { - if labelMap == nil { - labelMap = ChildGCLabels - } - return func(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) { - children, err := f(ctx, desc) - if err != nil { - return children, err - } - - if len(children) > 0 { - var ( - info = content.Info{ - Digest: desc.Digest, - Labels: map[string]string{}, - } - fields = []string{} - keys = map[string]uint{} - ) - for _, ch := range children { - labelKeys := labelMap(ch) - for _, key := range labelKeys { - idx := keys[key] - keys[key] = idx + 1 - if idx > 0 || key[len(key)-1] == '.' { - key = fmt.Sprintf("%s%d", key, idx) - } - - info.Labels[key] = ch.Digest.String() - fields = append(fields, "labels."+key) - } - } - - _, err := manager.Update(ctx, info, fields...) - if err != nil { - return nil, err - } - } - - return children, err - } -} - -// FilterPlatforms is a handler wrapper which limits the descriptors returned -// based on matching the specified platform matcher. -func FilterPlatforms(f HandlerFunc, m platforms.Matcher) HandlerFunc { - return func(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) { - children, err := f(ctx, desc) - if err != nil { - return children, err - } - - var descs []ocispec.Descriptor - - if m == nil { - descs = children - } else { - for _, d := range children { - if d.Platform == nil || m.Match(*d.Platform) { - descs = append(descs, d) - } - } - } - - return descs, nil - } -} - -// LimitManifests is a handler wrapper which filters the manifest descriptors -// returned using the provided platform. -// The results will be ordered according to the comparison operator and -// use the ordering in the manifests for equal matches. -// A limit of 0 or less is considered no limit. -// A not found error is returned if no manifest is matched. -func LimitManifests(f HandlerFunc, m platforms.MatchComparer, n int) HandlerFunc { - return func(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) { - children, err := f(ctx, desc) - if err != nil { - return children, err - } - - switch desc.MediaType { - case ocispec.MediaTypeImageIndex, MediaTypeDockerSchema2ManifestList: - sort.SliceStable(children, func(i, j int) bool { - if children[i].Platform == nil { - return false - } - if children[j].Platform == nil { - return true - } - return m.Less(*children[i].Platform, *children[j].Platform) - }) - - if n > 0 { - if len(children) == 0 { - return children, fmt.Errorf("no match for platform in manifest: %w", errdefs.ErrNotFound) - } - if len(children) > n { - children = children[:n] - } - } - default: - // only limit manifests from an index - } - return children, nil - } -} diff --git a/vendor/github.com/containerd/containerd/images/image.go b/vendor/github.com/containerd/containerd/images/image.go deleted file mode 100644 index 2d2e36a9a..000000000 --- a/vendor/github.com/containerd/containerd/images/image.go +++ /dev/null @@ -1,440 +0,0 @@ -/* - Copyright The containerd 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 images - -import ( - "context" - "encoding/json" - "fmt" - "sort" - "time" - - "github.com/containerd/containerd/content" - "github.com/containerd/containerd/errdefs" - "github.com/containerd/containerd/log" - "github.com/containerd/containerd/platforms" - digest "github.com/opencontainers/go-digest" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" -) - -// Image provides the model for how containerd views container images. -type Image struct { - // Name of the image. - // - // To be pulled, it must be a reference compatible with resolvers. - // - // This field is required. - Name string - - // Labels provide runtime decoration for the image record. - // - // There is no default behavior for how these labels are propagated. They - // only decorate the static metadata object. - // - // This field is optional. - Labels map[string]string - - // Target describes the root content for this image. Typically, this is - // a manifest, index or manifest list. - Target ocispec.Descriptor - - CreatedAt, UpdatedAt time.Time -} - -// DeleteOptions provide options on image delete -type DeleteOptions struct { - Synchronous bool -} - -// DeleteOpt allows configuring a delete operation -type DeleteOpt func(context.Context, *DeleteOptions) error - -// SynchronousDelete is used to indicate that an image deletion and removal of -// the image resources should occur synchronously before returning a result. -func SynchronousDelete() DeleteOpt { - return func(ctx context.Context, o *DeleteOptions) error { - o.Synchronous = true - return nil - } -} - -// Store and interact with images -type Store interface { - Get(ctx context.Context, name string) (Image, error) - List(ctx context.Context, filters ...string) ([]Image, error) - Create(ctx context.Context, image Image) (Image, error) - - // Update will replace the data in the store with the provided image. If - // one or more fieldpaths are provided, only those fields will be updated. - Update(ctx context.Context, image Image, fieldpaths ...string) (Image, error) - - Delete(ctx context.Context, name string, opts ...DeleteOpt) error -} - -// TODO(stevvooe): Many of these functions make strong platform assumptions, -// which are untrue in a lot of cases. More refactoring must be done here to -// make this work in all cases. - -// Config resolves the image configuration descriptor. -// -// The caller can then use the descriptor to resolve and process the -// configuration of the image. -func (image *Image) Config(ctx context.Context, provider content.Provider, platform platforms.MatchComparer) (ocispec.Descriptor, error) { - return Config(ctx, provider, image.Target, platform) -} - -// RootFS returns the unpacked diffids that make up and images rootfs. -// -// These are used to verify that a set of layers unpacked to the expected -// values. -func (image *Image) RootFS(ctx context.Context, provider content.Provider, platform platforms.MatchComparer) ([]digest.Digest, error) { - desc, err := image.Config(ctx, provider, platform) - if err != nil { - return nil, err - } - return RootFS(ctx, provider, desc) -} - -// Size returns the total size of an image's packed resources. -func (image *Image) Size(ctx context.Context, provider content.Provider, platform platforms.MatchComparer) (int64, error) { - var size int64 - return size, Walk(ctx, Handlers(HandlerFunc(func(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) { - if desc.Size < 0 { - return nil, fmt.Errorf("invalid size %v in %v (%v)", desc.Size, desc.Digest, desc.MediaType) - } - size += desc.Size - return nil, nil - }), LimitManifests(FilterPlatforms(ChildrenHandler(provider), platform), platform, 1)), image.Target) -} - -type platformManifest struct { - p *ocispec.Platform - m *ocispec.Manifest -} - -// Manifest resolves a manifest from the image for the given platform. -// -// When a manifest descriptor inside of a manifest index does not have -// a platform defined, the platform from the image config is considered. -// -// If the descriptor points to a non-index manifest, then the manifest is -// unmarshalled and returned without considering the platform inside of the -// config. -// -// TODO(stevvooe): This violates the current platform agnostic approach to this -// package by returning a specific manifest type. We'll need to refactor this -// to return a manifest descriptor or decide that we want to bring the API in -// this direction because this abstraction is not needed. -func Manifest(ctx context.Context, provider content.Provider, image ocispec.Descriptor, platform platforms.MatchComparer) (ocispec.Manifest, error) { - var ( - limit = 1 - m []platformManifest - wasIndex bool - ) - - if err := Walk(ctx, HandlerFunc(func(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) { - switch desc.MediaType { - case MediaTypeDockerSchema2Manifest, ocispec.MediaTypeImageManifest: - p, err := content.ReadBlob(ctx, provider, desc) - if err != nil { - return nil, err - } - - if err := validateMediaType(p, desc.MediaType); err != nil { - return nil, fmt.Errorf("manifest: invalid desc %s: %w", desc.Digest, err) - } - - var manifest ocispec.Manifest - if err := json.Unmarshal(p, &manifest); err != nil { - return nil, err - } - - if desc.Digest != image.Digest && platform != nil { - if desc.Platform != nil && !platform.Match(*desc.Platform) { - return nil, nil - } - - if desc.Platform == nil { - p, err := content.ReadBlob(ctx, provider, manifest.Config) - if err != nil { - return nil, err - } - - var image ocispec.Image - if err := json.Unmarshal(p, &image); err != nil { - return nil, err - } - - if !platform.Match(platforms.Normalize(ocispec.Platform{OS: image.OS, Architecture: image.Architecture})) { - return nil, nil - } - - } - } - - m = append(m, platformManifest{ - p: desc.Platform, - m: &manifest, - }) - - return nil, nil - case MediaTypeDockerSchema2ManifestList, ocispec.MediaTypeImageIndex: - p, err := content.ReadBlob(ctx, provider, desc) - if err != nil { - return nil, err - } - - if err := validateMediaType(p, desc.MediaType); err != nil { - return nil, fmt.Errorf("manifest: invalid desc %s: %w", desc.Digest, err) - } - - var idx ocispec.Index - if err := json.Unmarshal(p, &idx); err != nil { - return nil, err - } - - if platform == nil { - return idx.Manifests, nil - } - - var descs []ocispec.Descriptor - for _, d := range idx.Manifests { - if d.Platform == nil || platform.Match(*d.Platform) { - descs = append(descs, d) - } - } - - sort.SliceStable(descs, func(i, j int) bool { - if descs[i].Platform == nil { - return false - } - if descs[j].Platform == nil { - return true - } - return platform.Less(*descs[i].Platform, *descs[j].Platform) - }) - - wasIndex = true - - if len(descs) > limit { - return descs[:limit], nil - } - return descs, nil - } - return nil, fmt.Errorf("unexpected media type %v for %v: %w", desc.MediaType, desc.Digest, errdefs.ErrNotFound) - }), image); err != nil { - return ocispec.Manifest{}, err - } - - if len(m) == 0 { - err := fmt.Errorf("manifest %v: %w", image.Digest, errdefs.ErrNotFound) - if wasIndex { - err = fmt.Errorf("no match for platform in manifest %v: %w", image.Digest, errdefs.ErrNotFound) - } - return ocispec.Manifest{}, err - } - return *m[0].m, nil -} - -// Config resolves the image configuration descriptor using a content provided -// to resolve child resources on the image. -// -// The caller can then use the descriptor to resolve and process the -// configuration of the image. -func Config(ctx context.Context, provider content.Provider, image ocispec.Descriptor, platform platforms.MatchComparer) (ocispec.Descriptor, error) { - manifest, err := Manifest(ctx, provider, image, platform) - if err != nil { - return ocispec.Descriptor{}, err - } - return manifest.Config, err -} - -// Platforms returns one or more platforms supported by the image. -func Platforms(ctx context.Context, provider content.Provider, image ocispec.Descriptor) ([]ocispec.Platform, error) { - var platformSpecs []ocispec.Platform - return platformSpecs, Walk(ctx, Handlers(HandlerFunc(func(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) { - if desc.Platform != nil { - platformSpecs = append(platformSpecs, *desc.Platform) - return nil, ErrSkipDesc - } - - switch desc.MediaType { - case MediaTypeDockerSchema2Config, ocispec.MediaTypeImageConfig: - p, err := content.ReadBlob(ctx, provider, desc) - if err != nil { - return nil, err - } - - var image ocispec.Image - if err := json.Unmarshal(p, &image); err != nil { - return nil, err - } - - platformSpecs = append(platformSpecs, - platforms.Normalize(ocispec.Platform{OS: image.OS, Architecture: image.Architecture})) - } - return nil, nil - }), ChildrenHandler(provider)), image) -} - -// Check returns nil if the all components of an image are available in the -// provider for the specified platform. -// -// If available is true, the caller can assume that required represents the -// complete set of content required for the image. -// -// missing will have the components that are part of required but not available -// in the provider. -// -// If there is a problem resolving content, an error will be returned. -func Check(ctx context.Context, provider content.Provider, image ocispec.Descriptor, platform platforms.MatchComparer) (available bool, required, present, missing []ocispec.Descriptor, err error) { - mfst, err := Manifest(ctx, provider, image, platform) - if err != nil { - if errdefs.IsNotFound(err) { - return false, []ocispec.Descriptor{image}, nil, []ocispec.Descriptor{image}, nil - } - - return false, nil, nil, nil, fmt.Errorf("failed to check image %v: %w", image.Digest, err) - } - - // TODO(stevvooe): It is possible that referenced components could have - // children, but this is rare. For now, we ignore this and only verify - // that manifest components are present. - required = append([]ocispec.Descriptor{mfst.Config}, mfst.Layers...) - - for _, desc := range required { - ra, err := provider.ReaderAt(ctx, desc) - if err != nil { - if errdefs.IsNotFound(err) { - missing = append(missing, desc) - continue - } else { - return false, nil, nil, nil, fmt.Errorf("failed to check image %v: %w", desc.Digest, err) - } - } - ra.Close() - present = append(present, desc) - - } - - return true, required, present, missing, nil -} - -// Children returns the immediate children of content described by the descriptor. -func Children(ctx context.Context, provider content.Provider, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) { - var descs []ocispec.Descriptor - switch desc.MediaType { - case MediaTypeDockerSchema2Manifest, ocispec.MediaTypeImageManifest: - p, err := content.ReadBlob(ctx, provider, desc) - if err != nil { - return nil, err - } - - if err := validateMediaType(p, desc.MediaType); err != nil { - return nil, fmt.Errorf("children: invalid desc %s: %w", desc.Digest, err) - } - - // TODO(stevvooe): We just assume oci manifest, for now. There may be - // subtle differences from the docker version. - var manifest ocispec.Manifest - if err := json.Unmarshal(p, &manifest); err != nil { - return nil, err - } - - descs = append(descs, manifest.Config) - descs = append(descs, manifest.Layers...) - case MediaTypeDockerSchema2ManifestList, ocispec.MediaTypeImageIndex: - p, err := content.ReadBlob(ctx, provider, desc) - if err != nil { - return nil, err - } - - if err := validateMediaType(p, desc.MediaType); err != nil { - return nil, fmt.Errorf("children: invalid desc %s: %w", desc.Digest, err) - } - - var index ocispec.Index - if err := json.Unmarshal(p, &index); err != nil { - return nil, err - } - - descs = append(descs, index.Manifests...) - default: - if IsLayerType(desc.MediaType) || IsKnownConfig(desc.MediaType) { - // childless data types. - return nil, nil - } - log.G(ctx).Debugf("encountered unknown type %v; children may not be fetched", desc.MediaType) - } - - return descs, nil -} - -// unknownDocument represents a manifest, manifest list, or index that has not -// yet been validated. -type unknownDocument struct { - MediaType string `json:"mediaType,omitempty"` - Config json.RawMessage `json:"config,omitempty"` - Layers json.RawMessage `json:"layers,omitempty"` - Manifests json.RawMessage `json:"manifests,omitempty"` - FSLayers json.RawMessage `json:"fsLayers,omitempty"` // schema 1 -} - -// validateMediaType returns an error if the byte slice is invalid JSON or if -// the media type identifies the blob as one format but it contains elements of -// another format. -func validateMediaType(b []byte, mt string) error { - var doc unknownDocument - if err := json.Unmarshal(b, &doc); err != nil { - return err - } - if len(doc.FSLayers) != 0 { - return fmt.Errorf("media-type: schema 1 not supported") - } - switch mt { - case MediaTypeDockerSchema2Manifest, ocispec.MediaTypeImageManifest: - if len(doc.Manifests) != 0 || - doc.MediaType == MediaTypeDockerSchema2ManifestList || - doc.MediaType == ocispec.MediaTypeImageIndex { - return fmt.Errorf("media-type: expected manifest but found index (%s)", mt) - } - case MediaTypeDockerSchema2ManifestList, ocispec.MediaTypeImageIndex: - if len(doc.Config) != 0 || len(doc.Layers) != 0 || - doc.MediaType == MediaTypeDockerSchema2Manifest || - doc.MediaType == ocispec.MediaTypeImageManifest { - return fmt.Errorf("media-type: expected index but found manifest (%s)", mt) - } - } - return nil -} - -// RootFS returns the unpacked diffids that make up and images rootfs. -// -// These are used to verify that a set of layers unpacked to the expected -// values. -func RootFS(ctx context.Context, provider content.Provider, configDesc ocispec.Descriptor) ([]digest.Digest, error) { - p, err := content.ReadBlob(ctx, provider, configDesc) - if err != nil { - return nil, err - } - - var config ocispec.Image - if err := json.Unmarshal(p, &config); err != nil { - return nil, err - } - return config.RootFS.DiffIDs, nil -} diff --git a/vendor/github.com/containerd/containerd/images/importexport.go b/vendor/github.com/containerd/containerd/images/importexport.go deleted file mode 100644 index 843adcadc..000000000 --- a/vendor/github.com/containerd/containerd/images/importexport.go +++ /dev/null @@ -1,37 +0,0 @@ -/* - Copyright The containerd 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 images - -import ( - "context" - "io" - - "github.com/containerd/containerd/content" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" -) - -// Importer is the interface for image importer. -type Importer interface { - // Import imports an image from a tar stream. - Import(ctx context.Context, store content.Store, reader io.Reader) (ocispec.Descriptor, error) -} - -// Exporter is the interface for image exporter. -type Exporter interface { - // Export exports an image to a tar stream. - Export(ctx context.Context, store content.Provider, desc ocispec.Descriptor, writer io.Writer) error -} diff --git a/vendor/github.com/containerd/containerd/images/labels.go b/vendor/github.com/containerd/containerd/images/labels.go deleted file mode 100644 index 06dfed572..000000000 --- a/vendor/github.com/containerd/containerd/images/labels.go +++ /dev/null @@ -1,21 +0,0 @@ -/* - Copyright The containerd 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 images - -const ( - ConvertedDockerSchema1LabelKey = "io.containerd.image/converted-docker-schema1" -) diff --git a/vendor/github.com/containerd/containerd/images/mediatypes.go b/vendor/github.com/containerd/containerd/images/mediatypes.go deleted file mode 100644 index 067963bab..000000000 --- a/vendor/github.com/containerd/containerd/images/mediatypes.go +++ /dev/null @@ -1,215 +0,0 @@ -/* - Copyright The containerd 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 images - -import ( - "context" - "fmt" - "sort" - "strings" - - "github.com/containerd/containerd/errdefs" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" -) - -// mediatype definitions for image components handled in containerd. -// -// oci components are generally referenced directly, although we may centralize -// here for clarity. -const ( - MediaTypeDockerSchema2Layer = "application/vnd.docker.image.rootfs.diff.tar" - MediaTypeDockerSchema2LayerForeign = "application/vnd.docker.image.rootfs.foreign.diff.tar" - MediaTypeDockerSchema2LayerGzip = "application/vnd.docker.image.rootfs.diff.tar.gzip" - MediaTypeDockerSchema2LayerForeignGzip = "application/vnd.docker.image.rootfs.foreign.diff.tar.gzip" - MediaTypeDockerSchema2Config = "application/vnd.docker.container.image.v1+json" - MediaTypeDockerSchema2Manifest = "application/vnd.docker.distribution.manifest.v2+json" - MediaTypeDockerSchema2ManifestList = "application/vnd.docker.distribution.manifest.list.v2+json" - - // Checkpoint/Restore Media Types - - MediaTypeContainerd1Checkpoint = "application/vnd.containerd.container.criu.checkpoint.criu.tar" - MediaTypeContainerd1CheckpointPreDump = "application/vnd.containerd.container.criu.checkpoint.predump.tar" - MediaTypeContainerd1Resource = "application/vnd.containerd.container.resource.tar" - MediaTypeContainerd1RW = "application/vnd.containerd.container.rw.tar" - MediaTypeContainerd1CheckpointConfig = "application/vnd.containerd.container.checkpoint.config.v1+proto" - MediaTypeContainerd1CheckpointOptions = "application/vnd.containerd.container.checkpoint.options.v1+proto" - MediaTypeContainerd1CheckpointRuntimeName = "application/vnd.containerd.container.checkpoint.runtime.name" - MediaTypeContainerd1CheckpointRuntimeOptions = "application/vnd.containerd.container.checkpoint.runtime.options+proto" - - // MediaTypeDockerSchema1Manifest is the legacy Docker schema1 manifest - MediaTypeDockerSchema1Manifest = "application/vnd.docker.distribution.manifest.v1+prettyjws" - - // Encrypted media types - - MediaTypeImageLayerEncrypted = ocispec.MediaTypeImageLayer + "+encrypted" - MediaTypeImageLayerGzipEncrypted = ocispec.MediaTypeImageLayerGzip + "+encrypted" -) - -// DiffCompression returns the compression as defined by the layer diff media -// type. For Docker media types without compression, "unknown" is returned to -// indicate that the media type may be compressed. If the media type is not -// recognized as a layer diff, then it returns errdefs.ErrNotImplemented -func DiffCompression(ctx context.Context, mediaType string) (string, error) { - base, ext := parseMediaTypes(mediaType) - switch base { - case MediaTypeDockerSchema2Layer, MediaTypeDockerSchema2LayerForeign: - if len(ext) > 0 { - // Type is wrapped - return "", nil - } - // These media types may have been compressed but failed to - // use the correct media type. The decompression function - // should detect and handle this case. - return "unknown", nil - case MediaTypeDockerSchema2LayerGzip, MediaTypeDockerSchema2LayerForeignGzip: - if len(ext) > 0 { - // Type is wrapped - return "", nil - } - return "gzip", nil - case ocispec.MediaTypeImageLayer, ocispec.MediaTypeImageLayerNonDistributable: - if len(ext) > 0 { - switch ext[len(ext)-1] { - case "gzip": - return "gzip", nil - case "zstd": - return "zstd", nil - } - } - return "", nil - default: - return "", fmt.Errorf("unrecognised mediatype %s: %w", mediaType, errdefs.ErrNotImplemented) - } -} - -// parseMediaTypes splits the media type into the base type and -// an array of sorted extensions -func parseMediaTypes(mt string) (mediaType string, suffixes []string) { - if mt == "" { - return "", []string{} - } - mediaType, ext, ok := strings.Cut(mt, "+") - if !ok { - return mediaType, []string{} - } - - // Splitting the extensions following the mediatype "(+)gzip+encrypted". - // We expect this to be a limited list, so add an arbitrary limit (50). - // - // Note that DiffCompression is only using the last element, so perhaps we - // should split on the last "+" only. - suffixes = strings.SplitN(ext, "+", 50) - sort.Strings(suffixes) - return mediaType, suffixes -} - -// IsNonDistributable returns true if the media type is non-distributable. -func IsNonDistributable(mt string) bool { - return strings.HasPrefix(mt, "application/vnd.oci.image.layer.nondistributable.") || - strings.HasPrefix(mt, "application/vnd.docker.image.rootfs.foreign.") -} - -// IsLayerType returns true if the media type is a layer -func IsLayerType(mt string) bool { - if strings.HasPrefix(mt, "application/vnd.oci.image.layer.") { - return true - } - - // Parse Docker media types, strip off any + suffixes first - switch base, _ := parseMediaTypes(mt); base { - case MediaTypeDockerSchema2Layer, MediaTypeDockerSchema2LayerGzip, - MediaTypeDockerSchema2LayerForeign, MediaTypeDockerSchema2LayerForeignGzip: - return true - } - return false -} - -// IsDockerType returns true if the media type has "application/vnd.docker." prefix -func IsDockerType(mt string) bool { - return strings.HasPrefix(mt, "application/vnd.docker.") -} - -// IsManifestType returns true if the media type is an OCI-compatible manifest. -// No support for schema1 manifest. -func IsManifestType(mt string) bool { - switch mt { - case MediaTypeDockerSchema2Manifest, ocispec.MediaTypeImageManifest: - return true - default: - return false - } -} - -// IsIndexType returns true if the media type is an OCI-compatible index. -func IsIndexType(mt string) bool { - switch mt { - case ocispec.MediaTypeImageIndex, MediaTypeDockerSchema2ManifestList: - return true - default: - return false - } -} - -// IsConfigType returns true if the media type is an OCI-compatible image config. -// No support for containerd checkpoint configs. -func IsConfigType(mt string) bool { - switch mt { - case MediaTypeDockerSchema2Config, ocispec.MediaTypeImageConfig: - return true - default: - return false - } -} - -// IsKnownConfig returns true if the media type is a known config type, -// including containerd checkpoint configs -func IsKnownConfig(mt string) bool { - switch mt { - case MediaTypeDockerSchema2Config, ocispec.MediaTypeImageConfig, - MediaTypeContainerd1Checkpoint, MediaTypeContainerd1CheckpointConfig: - return true - } - return false -} - -// ChildGCLabels returns the label for a given descriptor to reference it -func ChildGCLabels(desc ocispec.Descriptor) []string { - mt := desc.MediaType - if IsKnownConfig(mt) { - return []string{"containerd.io/gc.ref.content.config"} - } - - switch mt { - case MediaTypeDockerSchema2Manifest, ocispec.MediaTypeImageManifest: - return []string{"containerd.io/gc.ref.content.m."} - } - - if IsLayerType(mt) { - return []string{"containerd.io/gc.ref.content.l."} - } - - return []string{"containerd.io/gc.ref.content."} -} - -// ChildGCLabelsFilterLayers returns the labels for a given descriptor to -// reference it, skipping layer media types -func ChildGCLabelsFilterLayers(desc ocispec.Descriptor) []string { - if IsLayerType(desc.MediaType) { - return nil - } - return ChildGCLabels(desc) -} diff --git a/vendor/github.com/containerd/containerd/labels/labels.go b/vendor/github.com/containerd/containerd/labels/labels.go deleted file mode 100644 index 0f9bab5c5..000000000 --- a/vendor/github.com/containerd/containerd/labels/labels.go +++ /dev/null @@ -1,29 +0,0 @@ -/* - Copyright The containerd 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 labels - -// LabelUncompressed is added to compressed layer contents. -// The value is digest of the uncompressed content. -const LabelUncompressed = "containerd.io/uncompressed" - -// LabelSharedNamespace is added to a namespace to allow that namespaces -// contents to be shared. -const LabelSharedNamespace = "containerd.io/namespace.shareable" - -// LabelDistributionSource is added to content to indicate its origin. -// e.g., "containerd.io/distribution.source.docker.io=library/redis" -const LabelDistributionSource = "containerd.io/distribution.source" diff --git a/vendor/github.com/containerd/containerd/labels/validate.go b/vendor/github.com/containerd/containerd/labels/validate.go deleted file mode 100644 index f83b5dde2..000000000 --- a/vendor/github.com/containerd/containerd/labels/validate.go +++ /dev/null @@ -1,41 +0,0 @@ -/* - Copyright The containerd 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 labels - -import ( - "fmt" - - "github.com/containerd/containerd/errdefs" -) - -const ( - maxSize = 4096 - // maximum length of key portion of error message if len of key + len of value > maxSize - keyMaxLen = 64 -) - -// Validate a label's key and value are under 4096 bytes -func Validate(k, v string) error { - total := len(k) + len(v) - if total > maxSize { - if len(k) > keyMaxLen { - k = k[:keyMaxLen] - } - return fmt.Errorf("label key and value length (%d bytes) greater than maximum size (%d bytes), key: %s: %w", total, maxSize, k, errdefs.ErrInvalidArgument) - } - return nil -} diff --git a/vendor/github.com/containerd/containerd/log/context_deprecated.go b/vendor/github.com/containerd/containerd/log/context_deprecated.go deleted file mode 100644 index 9e9e8b491..000000000 --- a/vendor/github.com/containerd/containerd/log/context_deprecated.go +++ /dev/null @@ -1,149 +0,0 @@ -/* - Copyright The containerd 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 log - -import ( - "context" - - "github.com/containerd/log" -) - -// G is a shorthand for [GetLogger]. -// -// Deprecated: use [log.G]. -var G = log.G - -// L is an alias for the standard logger. -// -// Deprecated: use [log.L]. -var L = log.L - -// Fields type to pass to "WithFields". -// -// Deprecated: use [log.Fields]. -type Fields = log.Fields - -// Entry is a logging entry. -// -// Deprecated: use [log.Entry]. -type Entry = log.Entry - -// RFC3339NanoFixed is [time.RFC3339Nano] with nanoseconds padded using -// zeros to ensure the formatted time is always the same number of -// characters. -// -// Deprecated: use [log.RFC3339NanoFixed]. -const RFC3339NanoFixed = log.RFC3339NanoFixed - -// Level is a logging level. -// -// Deprecated: use [log.Level]. -type Level = log.Level - -// Supported log levels. -const ( - // TraceLevel level. - // - // Deprecated: use [log.TraceLevel]. - TraceLevel Level = log.TraceLevel - - // DebugLevel level. - // - // Deprecated: use [log.DebugLevel]. - DebugLevel Level = log.DebugLevel - - // InfoLevel level. - // - // Deprecated: use [log.InfoLevel]. - InfoLevel Level = log.InfoLevel - - // WarnLevel level. - // - // Deprecated: use [log.WarnLevel]. - WarnLevel Level = log.WarnLevel - - // ErrorLevel level - // - // Deprecated: use [log.ErrorLevel]. - ErrorLevel Level = log.ErrorLevel - - // FatalLevel level. - // - // Deprecated: use [log.FatalLevel]. - FatalLevel Level = log.FatalLevel - - // PanicLevel level. - // - // Deprecated: use [log.PanicLevel]. - PanicLevel Level = log.PanicLevel -) - -// SetLevel sets log level globally. It returns an error if the given -// level is not supported. -// -// Deprecated: use [log.SetLevel]. -func SetLevel(level string) error { - return log.SetLevel(level) -} - -// GetLevel returns the current log level. -// -// Deprecated: use [log.GetLevel]. -func GetLevel() log.Level { - return log.GetLevel() -} - -// OutputFormat specifies a log output format. -// -// Deprecated: use [log.OutputFormat]. -type OutputFormat = log.OutputFormat - -// Supported log output formats. -const ( - // TextFormat represents the text logging format. - // - // Deprecated: use [log.TextFormat]. - TextFormat log.OutputFormat = "text" - - // JSONFormat represents the JSON logging format. - // - // Deprecated: use [log.JSONFormat]. - JSONFormat log.OutputFormat = "json" -) - -// SetFormat sets the log output format. -// -// Deprecated: use [log.SetFormat]. -func SetFormat(format OutputFormat) error { - return log.SetFormat(format) -} - -// WithLogger returns a new context with the provided logger. Use in -// combination with logger.WithField(s) for great effect. -// -// Deprecated: use [log.WithLogger]. -func WithLogger(ctx context.Context, logger *log.Entry) context.Context { - return log.WithLogger(ctx, logger) -} - -// GetLogger retrieves the current logger from the context. If no logger is -// available, the default logger is returned. -// -// Deprecated: use [log.GetLogger]. -func GetLogger(ctx context.Context) *log.Entry { - return log.GetLogger(ctx) -} diff --git a/vendor/github.com/containerd/containerd/pkg/randutil/randutil.go b/vendor/github.com/containerd/containerd/pkg/randutil/randutil.go deleted file mode 100644 index f4b657d7d..000000000 --- a/vendor/github.com/containerd/containerd/pkg/randutil/randutil.go +++ /dev/null @@ -1,48 +0,0 @@ -/* - Copyright The containerd 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 randutil provides utilities for [cyrpto/rand]. -package randutil - -import ( - "crypto/rand" - "math" - "math/big" -) - -// Int63n is similar to [math/rand.Int63n] but uses [crypto/rand.Reader] under the hood. -func Int63n(n int64) int64 { - b, err := rand.Int(rand.Reader, big.NewInt(n)) - if err != nil { - panic(err) - } - return b.Int64() -} - -// Int63 is similar to [math/rand.Int63] but uses [crypto/rand.Reader] under the hood. -func Int63() int64 { - return Int63n(math.MaxInt64) -} - -// Intn is similar to [math/rand.Intn] but uses [crypto/rand.Reader] under the hood. -func Intn(n int) int { - return int(Int63n(int64(n))) -} - -// Int is similar to [math/rand.Int] but uses [crypto/rand.Reader] under the hood. -func Int() int { - return int(Int63()) -} diff --git a/vendor/github.com/containerd/containerd/pkg/userns/userns_linux.go b/vendor/github.com/containerd/containerd/pkg/userns/userns_linux.go deleted file mode 100644 index 6656465ef..000000000 --- a/vendor/github.com/containerd/containerd/pkg/userns/userns_linux.go +++ /dev/null @@ -1,62 +0,0 @@ -/* - Copyright The containerd 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 userns - -import ( - "bufio" - "fmt" - "os" - "sync" -) - -var ( - inUserNS bool - nsOnce sync.Once -) - -// RunningInUserNS detects whether we are currently running in a user namespace. -// Originally copied from github.com/lxc/lxd/shared/util.go -func RunningInUserNS() bool { - nsOnce.Do(func() { - file, err := os.Open("/proc/self/uid_map") - if err != nil { - // This kernel-provided file only exists if user namespaces are supported - return - } - defer file.Close() - - buf := bufio.NewReader(file) - l, _, err := buf.ReadLine() - if err != nil { - return - } - - line := string(l) - var a, b, c int64 - fmt.Sscanf(line, "%d %d %d", &a, &b, &c) - - /* - * We assume we are in the initial user namespace if we have a full - * range - 4294967295 uids starting at uid 0. - */ - if a == 0 && b == 0 && c == 4294967295 { - return - } - inUserNS = true - }) - return inUserNS -} diff --git a/vendor/github.com/containerd/containerd/pkg/userns/userns_unsupported.go b/vendor/github.com/containerd/containerd/pkg/userns/userns_unsupported.go deleted file mode 100644 index c67f773d0..000000000 --- a/vendor/github.com/containerd/containerd/pkg/userns/userns_unsupported.go +++ /dev/null @@ -1,25 +0,0 @@ -//go:build !linux - -/* - Copyright The containerd 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 userns - -// RunningInUserNS is a stub for non-Linux systems -// Always returns false -func RunningInUserNS() bool { - return false -} diff --git a/vendor/github.com/containerd/containerd/platforms/compare.go b/vendor/github.com/containerd/containerd/platforms/compare.go deleted file mode 100644 index 3913ef663..000000000 --- a/vendor/github.com/containerd/containerd/platforms/compare.go +++ /dev/null @@ -1,203 +0,0 @@ -/* - Copyright The containerd 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 platforms - -import ( - "strconv" - "strings" - - specs "github.com/opencontainers/image-spec/specs-go/v1" -) - -// MatchComparer is able to match and compare platforms to -// filter and sort platforms. -type MatchComparer interface { - Matcher - - Less(specs.Platform, specs.Platform) bool -} - -// platformVector returns an (ordered) vector of appropriate specs.Platform -// objects to try matching for the given platform object (see platforms.Only). -func platformVector(platform specs.Platform) []specs.Platform { - vector := []specs.Platform{platform} - - switch platform.Architecture { - case "amd64": - if amd64Version, err := strconv.Atoi(strings.TrimPrefix(platform.Variant, "v")); err == nil && amd64Version > 1 { - for amd64Version--; amd64Version >= 1; amd64Version-- { - vector = append(vector, specs.Platform{ - Architecture: platform.Architecture, - OS: platform.OS, - OSVersion: platform.OSVersion, - OSFeatures: platform.OSFeatures, - Variant: "v" + strconv.Itoa(amd64Version), - }) - } - } - vector = append(vector, specs.Platform{ - Architecture: "386", - OS: platform.OS, - OSVersion: platform.OSVersion, - OSFeatures: platform.OSFeatures, - }) - case "arm": - if armVersion, err := strconv.Atoi(strings.TrimPrefix(platform.Variant, "v")); err == nil && armVersion > 5 { - for armVersion--; armVersion >= 5; armVersion-- { - vector = append(vector, specs.Platform{ - Architecture: platform.Architecture, - OS: platform.OS, - OSVersion: platform.OSVersion, - OSFeatures: platform.OSFeatures, - Variant: "v" + strconv.Itoa(armVersion), - }) - } - } - case "arm64": - variant := platform.Variant - if variant == "" { - variant = "v8" - } - vector = append(vector, platformVector(specs.Platform{ - Architecture: "arm", - OS: platform.OS, - OSVersion: platform.OSVersion, - OSFeatures: platform.OSFeatures, - Variant: variant, - })...) - } - - return vector -} - -// Only returns a match comparer for a single platform -// using default resolution logic for the platform. -// -// For arm/v8, will also match arm/v7, arm/v6 and arm/v5 -// For arm/v7, will also match arm/v6 and arm/v5 -// For arm/v6, will also match arm/v5 -// For amd64, will also match 386 -func Only(platform specs.Platform) MatchComparer { - return Ordered(platformVector(Normalize(platform))...) -} - -// OnlyStrict returns a match comparer for a single platform. -// -// Unlike Only, OnlyStrict does not match sub platforms. -// So, "arm/vN" will not match "arm/vM" where M < N, -// and "amd64" will not also match "386". -// -// OnlyStrict matches non-canonical forms. -// So, "arm64" matches "arm/64/v8". -func OnlyStrict(platform specs.Platform) MatchComparer { - return Ordered(Normalize(platform)) -} - -// Ordered returns a platform MatchComparer which matches any of the platforms -// but orders them in order they are provided. -func Ordered(platforms ...specs.Platform) MatchComparer { - matchers := make([]Matcher, len(platforms)) - for i := range platforms { - matchers[i] = NewMatcher(platforms[i]) - } - return orderedPlatformComparer{ - matchers: matchers, - } -} - -// Any returns a platform MatchComparer which matches any of the platforms -// with no preference for ordering. -func Any(platforms ...specs.Platform) MatchComparer { - matchers := make([]Matcher, len(platforms)) - for i := range platforms { - matchers[i] = NewMatcher(platforms[i]) - } - return anyPlatformComparer{ - matchers: matchers, - } -} - -// All is a platform MatchComparer which matches all platforms -// with preference for ordering. -var All MatchComparer = allPlatformComparer{} - -type orderedPlatformComparer struct { - matchers []Matcher -} - -func (c orderedPlatformComparer) Match(platform specs.Platform) bool { - for _, m := range c.matchers { - if m.Match(platform) { - return true - } - } - return false -} - -func (c orderedPlatformComparer) Less(p1 specs.Platform, p2 specs.Platform) bool { - for _, m := range c.matchers { - p1m := m.Match(p1) - p2m := m.Match(p2) - if p1m && !p2m { - return true - } - if p1m || p2m { - return false - } - } - return false -} - -type anyPlatformComparer struct { - matchers []Matcher -} - -func (c anyPlatformComparer) Match(platform specs.Platform) bool { - for _, m := range c.matchers { - if m.Match(platform) { - return true - } - } - return false -} - -func (c anyPlatformComparer) Less(p1, p2 specs.Platform) bool { - var p1m, p2m bool - for _, m := range c.matchers { - if !p1m && m.Match(p1) { - p1m = true - } - if !p2m && m.Match(p2) { - p2m = true - } - if p1m && p2m { - return false - } - } - // If one matches, and the other does, sort match first - return p1m && !p2m -} - -type allPlatformComparer struct{} - -func (allPlatformComparer) Match(specs.Platform) bool { - return true -} - -func (allPlatformComparer) Less(specs.Platform, specs.Platform) bool { - return false -} diff --git a/vendor/github.com/containerd/containerd/platforms/cpuinfo.go b/vendor/github.com/containerd/containerd/platforms/cpuinfo.go deleted file mode 100644 index 8c600fc96..000000000 --- a/vendor/github.com/containerd/containerd/platforms/cpuinfo.go +++ /dev/null @@ -1,43 +0,0 @@ -/* - Copyright The containerd 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 platforms - -import ( - "runtime" - "sync" - - "github.com/containerd/containerd/log" -) - -// Present the ARM instruction set architecture, eg: v7, v8 -// Don't use this value directly; call cpuVariant() instead. -var cpuVariantValue string - -var cpuVariantOnce sync.Once - -func cpuVariant() string { - cpuVariantOnce.Do(func() { - if isArmArch(runtime.GOARCH) { - var err error - cpuVariantValue, err = getCPUVariant() - if err != nil { - log.L.Errorf("Error getCPUVariant for OS %s: %v", runtime.GOOS, err) - } - } - }) - return cpuVariantValue -} diff --git a/vendor/github.com/containerd/containerd/platforms/cpuinfo_linux.go b/vendor/github.com/containerd/containerd/platforms/cpuinfo_linux.go deleted file mode 100644 index 722d86c35..000000000 --- a/vendor/github.com/containerd/containerd/platforms/cpuinfo_linux.go +++ /dev/null @@ -1,161 +0,0 @@ -/* - Copyright The containerd 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 platforms - -import ( - "bufio" - "bytes" - "fmt" - "os" - "runtime" - "strings" - - "github.com/containerd/containerd/errdefs" - "golang.org/x/sys/unix" -) - -// getMachineArch retrieves the machine architecture through system call -func getMachineArch() (string, error) { - var uname unix.Utsname - err := unix.Uname(&uname) - if err != nil { - return "", err - } - - arch := string(uname.Machine[:bytes.IndexByte(uname.Machine[:], 0)]) - - return arch, nil -} - -// For Linux, the kernel has already detected the ABI, ISA and Features. -// So we don't need to access the ARM registers to detect platform information -// by ourselves. We can just parse these information from /proc/cpuinfo -func getCPUInfo(pattern string) (info string, err error) { - - cpuinfo, err := os.Open("/proc/cpuinfo") - if err != nil { - return "", err - } - defer cpuinfo.Close() - - // Start to Parse the Cpuinfo line by line. For SMP SoC, we parse - // the first core is enough. - scanner := bufio.NewScanner(cpuinfo) - for scanner.Scan() { - newline := scanner.Text() - list := strings.Split(newline, ":") - - if len(list) > 1 && strings.EqualFold(strings.TrimSpace(list[0]), pattern) { - return strings.TrimSpace(list[1]), nil - } - } - - // Check whether the scanner encountered errors - err = scanner.Err() - if err != nil { - return "", err - } - - return "", fmt.Errorf("getCPUInfo for pattern %s: %w", pattern, errdefs.ErrNotFound) -} - -// getCPUVariantFromArch get CPU variant from arch through a system call -func getCPUVariantFromArch(arch string) (string, error) { - - var variant string - - arch = strings.ToLower(arch) - - if arch == "aarch64" { - variant = "8" - } else if arch[0:4] == "armv" && len(arch) >= 5 { - //Valid arch format is in form of armvXx - switch arch[3:5] { - case "v8": - variant = "8" - case "v7": - variant = "7" - case "v6": - variant = "6" - case "v5": - variant = "5" - case "v4": - variant = "4" - case "v3": - variant = "3" - default: - variant = "unknown" - } - } else { - return "", fmt.Errorf("getCPUVariantFromArch invalid arch: %s, %w", arch, errdefs.ErrInvalidArgument) - } - return variant, nil -} - -// getCPUVariant returns cpu variant for ARM -// We first try reading "Cpu architecture" field from /proc/cpuinfo -// If we can't find it, then fall back using a system call -// This is to cover running ARM in emulated environment on x86 host as this field in /proc/cpuinfo -// was not present. -func getCPUVariant() (string, error) { - - variant, err := getCPUInfo("Cpu architecture") - if err != nil { - if errdefs.IsNotFound(err) { - //Let's try getting CPU variant from machine architecture - arch, err := getMachineArch() - if err != nil { - return "", fmt.Errorf("failure getting machine architecture: %v", err) - } - - variant, err = getCPUVariantFromArch(arch) - if err != nil { - return "", fmt.Errorf("failure getting CPU variant from machine architecture: %v", err) - } - } else { - return "", fmt.Errorf("failure getting CPU variant: %v", err) - } - } - - // handle edge case for Raspberry Pi ARMv6 devices (which due to a kernel quirk, report "CPU architecture: 7") - // https://www.raspberrypi.org/forums/viewtopic.php?t=12614 - if runtime.GOARCH == "arm" && variant == "7" { - model, err := getCPUInfo("model name") - if err == nil && strings.HasPrefix(strings.ToLower(model), "armv6-compatible") { - variant = "6" - } - } - - switch strings.ToLower(variant) { - case "8", "aarch64": - variant = "v8" - case "7", "7m", "?(12)", "?(13)", "?(14)", "?(15)", "?(16)", "?(17)": - variant = "v7" - case "6", "6tej": - variant = "v6" - case "5", "5t", "5te", "5tej": - variant = "v5" - case "4", "4t": - variant = "v4" - case "3": - variant = "v3" - default: - variant = "unknown" - } - - return variant, nil -} diff --git a/vendor/github.com/containerd/containerd/platforms/cpuinfo_other.go b/vendor/github.com/containerd/containerd/platforms/cpuinfo_other.go deleted file mode 100644 index fa5f19c42..000000000 --- a/vendor/github.com/containerd/containerd/platforms/cpuinfo_other.go +++ /dev/null @@ -1,59 +0,0 @@ -//go:build !linux - -/* - Copyright The containerd 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 platforms - -import ( - "fmt" - "runtime" - - "github.com/containerd/containerd/errdefs" -) - -func getCPUVariant() (string, error) { - - var variant string - - if runtime.GOOS == "windows" || runtime.GOOS == "darwin" { - // Windows/Darwin only supports v7 for ARM32 and v8 for ARM64 and so we can use - // runtime.GOARCH to determine the variants - switch runtime.GOARCH { - case "arm64": - variant = "v8" - case "arm": - variant = "v7" - default: - variant = "unknown" - } - } else if runtime.GOOS == "freebsd" { - // FreeBSD supports ARMv6 and ARMv7 as well as ARMv4 and ARMv5 (though deprecated) - // detecting those variants is currently unimplemented - switch runtime.GOARCH { - case "arm64": - variant = "v8" - default: - variant = "unknown" - } - - } else { - return "", fmt.Errorf("getCPUVariant for OS %s: %v", runtime.GOOS, errdefs.ErrNotImplemented) - - } - - return variant, nil -} diff --git a/vendor/github.com/containerd/containerd/platforms/database.go b/vendor/github.com/containerd/containerd/platforms/database.go deleted file mode 100644 index 2e26fd3b4..000000000 --- a/vendor/github.com/containerd/containerd/platforms/database.go +++ /dev/null @@ -1,109 +0,0 @@ -/* - Copyright The containerd 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 platforms - -import ( - "runtime" - "strings" -) - -// These function are generated from https://golang.org/src/go/build/syslist.go. -// -// We use switch statements because they are slightly faster than map lookups -// and use a little less memory. - -// isKnownOS returns true if we know about the operating system. -// -// The OS value should be normalized before calling this function. -func isKnownOS(os string) bool { - switch os { - case "aix", "android", "darwin", "dragonfly", "freebsd", "hurd", "illumos", "ios", "js", "linux", "nacl", "netbsd", "openbsd", "plan9", "solaris", "windows", "zos": - return true - } - return false -} - -// isArmArch returns true if the architecture is ARM. -// -// The arch value should be normalized before being passed to this function. -func isArmArch(arch string) bool { - switch arch { - case "arm", "arm64": - return true - } - return false -} - -// isKnownArch returns true if we know about the architecture. -// -// The arch value should be normalized before being passed to this function. -func isKnownArch(arch string) bool { - switch arch { - case "386", "amd64", "amd64p32", "arm", "armbe", "arm64", "arm64be", "ppc64", "ppc64le", "loong64", "mips", "mipsle", "mips64", "mips64le", "mips64p32", "mips64p32le", "ppc", "riscv", "riscv64", "s390", "s390x", "sparc", "sparc64", "wasm": - return true - } - return false -} - -func normalizeOS(os string) string { - if os == "" { - return runtime.GOOS - } - os = strings.ToLower(os) - - switch os { - case "macos": - os = "darwin" - } - return os -} - -// normalizeArch normalizes the architecture. -func normalizeArch(arch, variant string) (string, string) { - arch, variant = strings.ToLower(arch), strings.ToLower(variant) - switch arch { - case "i386": - arch = "386" - variant = "" - case "x86_64", "x86-64", "amd64": - arch = "amd64" - if variant == "v1" { - variant = "" - } - case "aarch64", "arm64": - arch = "arm64" - switch variant { - case "8", "v8": - variant = "" - } - case "armhf": - arch = "arm" - variant = "v7" - case "armel": - arch = "arm" - variant = "v6" - case "arm": - switch variant { - case "", "7": - variant = "v7" - case "5", "6", "8": - variant = "v" + variant - } - } - - return arch, variant -} diff --git a/vendor/github.com/containerd/containerd/platforms/defaults.go b/vendor/github.com/containerd/containerd/platforms/defaults.go deleted file mode 100644 index cfa3ff34a..000000000 --- a/vendor/github.com/containerd/containerd/platforms/defaults.go +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright The containerd 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 platforms - -// DefaultString returns the default string specifier for the platform. -func DefaultString() string { - return Format(DefaultSpec()) -} - -// DefaultStrict returns strict form of Default. -func DefaultStrict() MatchComparer { - return OnlyStrict(DefaultSpec()) -} diff --git a/vendor/github.com/containerd/containerd/platforms/defaults_darwin.go b/vendor/github.com/containerd/containerd/platforms/defaults_darwin.go deleted file mode 100644 index 72355ca85..000000000 --- a/vendor/github.com/containerd/containerd/platforms/defaults_darwin.go +++ /dev/null @@ -1,44 +0,0 @@ -//go:build darwin - -/* - Copyright The containerd 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 platforms - -import ( - "runtime" - - specs "github.com/opencontainers/image-spec/specs-go/v1" -) - -// DefaultSpec returns the current platform's default platform specification. -func DefaultSpec() specs.Platform { - return specs.Platform{ - OS: runtime.GOOS, - Architecture: runtime.GOARCH, - // The Variant field will be empty if arch != ARM. - Variant: cpuVariant(), - } -} - -// Default returns the default matcher for the platform. -func Default() MatchComparer { - return Ordered(DefaultSpec(), specs.Platform{ - // darwin runtime also supports Linux binary via runu/LKL - OS: "linux", - Architecture: runtime.GOARCH, - }) -} diff --git a/vendor/github.com/containerd/containerd/platforms/defaults_freebsd.go b/vendor/github.com/containerd/containerd/platforms/defaults_freebsd.go deleted file mode 100644 index d3fe89e07..000000000 --- a/vendor/github.com/containerd/containerd/platforms/defaults_freebsd.go +++ /dev/null @@ -1,43 +0,0 @@ -/* - Copyright The containerd 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 platforms - -import ( - "runtime" - - specs "github.com/opencontainers/image-spec/specs-go/v1" -) - -// DefaultSpec returns the current platform's default platform specification. -func DefaultSpec() specs.Platform { - return specs.Platform{ - OS: runtime.GOOS, - Architecture: runtime.GOARCH, - // The Variant field will be empty if arch != ARM. - Variant: cpuVariant(), - } -} - -// Default returns the default matcher for the platform. -func Default() MatchComparer { - return Ordered(DefaultSpec(), specs.Platform{ - OS: "linux", - Architecture: runtime.GOARCH, - // The Variant field will be empty if arch != ARM. - Variant: cpuVariant(), - }) -} diff --git a/vendor/github.com/containerd/containerd/platforms/defaults_unix.go b/vendor/github.com/containerd/containerd/platforms/defaults_unix.go deleted file mode 100644 index 44acc47eb..000000000 --- a/vendor/github.com/containerd/containerd/platforms/defaults_unix.go +++ /dev/null @@ -1,40 +0,0 @@ -//go:build !windows && !darwin && !freebsd - -/* - Copyright The containerd 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 platforms - -import ( - "runtime" - - specs "github.com/opencontainers/image-spec/specs-go/v1" -) - -// DefaultSpec returns the current platform's default platform specification. -func DefaultSpec() specs.Platform { - return specs.Platform{ - OS: runtime.GOOS, - Architecture: runtime.GOARCH, - // The Variant field will be empty if arch != ARM. - Variant: cpuVariant(), - } -} - -// Default returns the default matcher for the platform. -func Default() MatchComparer { - return Only(DefaultSpec()) -} diff --git a/vendor/github.com/containerd/containerd/platforms/defaults_windows.go b/vendor/github.com/containerd/containerd/platforms/defaults_windows.go deleted file mode 100644 index d10fa9012..000000000 --- a/vendor/github.com/containerd/containerd/platforms/defaults_windows.go +++ /dev/null @@ -1,119 +0,0 @@ -/* - Copyright The containerd 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 platforms - -import ( - "fmt" - "runtime" - "strconv" - "strings" - - "github.com/Microsoft/hcsshim/osversion" - specs "github.com/opencontainers/image-spec/specs-go/v1" - "golang.org/x/sys/windows" -) - -// DefaultSpec returns the current platform's default platform specification. -func DefaultSpec() specs.Platform { - major, minor, build := windows.RtlGetNtVersionNumbers() - return specs.Platform{ - OS: runtime.GOOS, - Architecture: runtime.GOARCH, - OSVersion: fmt.Sprintf("%d.%d.%d", major, minor, build), - // The Variant field will be empty if arch != ARM. - Variant: cpuVariant(), - } -} - -type windowsmatcher struct { - specs.Platform - osVersionPrefix string - defaultMatcher Matcher -} - -// Match matches platform with the same windows major, minor -// and build version. -func (m windowsmatcher) Match(p specs.Platform) bool { - match := m.defaultMatcher.Match(p) - - if match && m.OS == "windows" { - // HPC containers do not have OS version filled - if p.OSVersion == "" { - return true - } - - hostOsVersion := GetOsVersion(m.osVersionPrefix) - ctrOsVersion := GetOsVersion(p.OSVersion) - return osversion.CheckHostAndContainerCompat(hostOsVersion, ctrOsVersion) - } - - return match -} - -func GetOsVersion(osVersionPrefix string) osversion.OSVersion { - parts := strings.Split(osVersionPrefix, ".") - if len(parts) < 3 { - return osversion.OSVersion{} - } - - majorVersion, _ := strconv.Atoi(parts[0]) - minorVersion, _ := strconv.Atoi(parts[1]) - buildNumber, _ := strconv.Atoi(parts[2]) - - return osversion.OSVersion{ - MajorVersion: uint8(majorVersion), - MinorVersion: uint8(minorVersion), - Build: uint16(buildNumber), - } -} - -// Less sorts matched platforms in front of other platforms. -// For matched platforms, it puts platforms with larger revision -// number in front. -func (m windowsmatcher) Less(p1, p2 specs.Platform) bool { - m1, m2 := m.Match(p1), m.Match(p2) - if m1 && m2 { - r1, r2 := revision(p1.OSVersion), revision(p2.OSVersion) - return r1 > r2 - } - return m1 && !m2 -} - -func revision(v string) int { - parts := strings.Split(v, ".") - if len(parts) < 4 { - return 0 - } - r, err := strconv.Atoi(parts[3]) - if err != nil { - return 0 - } - return r -} - -func prefix(v string) string { - parts := strings.Split(v, ".") - if len(parts) < 4 { - return v - } - return strings.Join(parts[0:3], ".") -} - -// Default returns the current platform's default platform specification. -func Default() MatchComparer { - return Only(DefaultSpec()) -} diff --git a/vendor/github.com/containerd/containerd/platforms/platforms.go b/vendor/github.com/containerd/containerd/platforms/platforms.go deleted file mode 100644 index 56613b076..000000000 --- a/vendor/github.com/containerd/containerd/platforms/platforms.go +++ /dev/null @@ -1,276 +0,0 @@ -/* - Copyright The containerd 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 platforms provides a toolkit for normalizing, matching and -// specifying container platforms. -// -// Centered around OCI platform specifications, we define a string-based -// specifier syntax that can be used for user input. With a specifier, users -// only need to specify the parts of the platform that are relevant to their -// context, providing an operating system or architecture or both. -// -// How do I use this package? -// -// The vast majority of use cases should simply use the match function with -// user input. The first step is to parse a specifier into a matcher: -// -// m, err := Parse("linux") -// if err != nil { ... } -// -// Once you have a matcher, use it to match against the platform declared by a -// component, typically from an image or runtime. Since extracting an images -// platform is a little more involved, we'll use an example against the -// platform default: -// -// if ok := m.Match(Default()); !ok { /* doesn't match */ } -// -// This can be composed in loops for resolving runtimes or used as a filter for -// fetch and select images. -// -// More details of the specifier syntax and platform spec follow. -// -// # Declaring Platform Support -// -// Components that have strict platform requirements should use the OCI -// platform specification to declare their support. Typically, this will be -// images and runtimes that should make these declaring which platform they -// support specifically. This looks roughly as follows: -// -// type Platform struct { -// Architecture string -// OS string -// Variant string -// } -// -// Most images and runtimes should at least set Architecture and OS, according -// to their GOARCH and GOOS values, respectively (follow the OCI image -// specification when in doubt). ARM should set variant under certain -// discussions, which are outlined below. -// -// # Platform Specifiers -// -// While the OCI platform specifications provide a tool for components to -// specify structured information, user input typically doesn't need the full -// context and much can be inferred. To solve this problem, we introduced -// "specifiers". A specifier has the format -// `||/[/]`. The user can provide either the -// operating system or the architecture or both. -// -// An example of a common specifier is `linux/amd64`. If the host has a default -// of runtime that matches this, the user can simply provide the component that -// matters. For example, if a image provides amd64 and arm64 support, the -// operating system, `linux` can be inferred, so they only have to provide -// `arm64` or `amd64`. Similar behavior is implemented for operating systems, -// where the architecture may be known but a runtime may support images from -// different operating systems. -// -// # Normalization -// -// Because not all users are familiar with the way the Go runtime represents -// platforms, several normalizations have been provided to make this package -// easier to user. -// -// The following are performed for architectures: -// -// Value Normalized -// aarch64 arm64 -// armhf arm -// armel arm/v6 -// i386 386 -// x86_64 amd64 -// x86-64 amd64 -// -// We also normalize the operating system `macos` to `darwin`. -// -// # ARM Support -// -// To qualify ARM architecture, the Variant field is used to qualify the arm -// version. The most common arm version, v7, is represented without the variant -// unless it is explicitly provided. This is treated as equivalent to armhf. A -// previous architecture, armel, will be normalized to arm/v6. -// -// While these normalizations are provided, their support on arm platforms has -// not yet been fully implemented and tested. -package platforms - -import ( - "fmt" - "path" - "regexp" - "runtime" - "strconv" - "strings" - - specs "github.com/opencontainers/image-spec/specs-go/v1" - - "github.com/containerd/containerd/errdefs" -) - -var ( - specifierRe = regexp.MustCompile(`^[A-Za-z0-9_-]+$`) -) - -// Platform is a type alias for convenience, so there is no need to import image-spec package everywhere. -type Platform = specs.Platform - -// Matcher matches platforms specifications, provided by an image or runtime. -type Matcher interface { - Match(platform specs.Platform) bool -} - -// NewMatcher returns a simple matcher based on the provided platform -// specification. The returned matcher only looks for equality based on os, -// architecture and variant. -// -// One may implement their own matcher if this doesn't provide the required -// functionality. -// -// Applications should opt to use `Match` over directly parsing specifiers. -func NewMatcher(platform specs.Platform) Matcher { - return newDefaultMatcher(platform) -} - -type matcher struct { - specs.Platform -} - -func (m *matcher) Match(platform specs.Platform) bool { - normalized := Normalize(platform) - return m.OS == normalized.OS && - m.Architecture == normalized.Architecture && - m.Variant == normalized.Variant -} - -func (m *matcher) String() string { - return Format(m.Platform) -} - -// Parse parses the platform specifier syntax into a platform declaration. -// -// Platform specifiers are in the format `||/[/]`. -// The minimum required information for a platform specifier is the operating -// system or architecture. If there is only a single string (no slashes), the -// value will be matched against the known set of operating systems, then fall -// back to the known set of architectures. The missing component will be -// inferred based on the local environment. -func Parse(specifier string) (specs.Platform, error) { - if strings.Contains(specifier, "*") { - // TODO(stevvooe): need to work out exact wildcard handling - return specs.Platform{}, fmt.Errorf("%q: wildcards not yet supported: %w", specifier, errdefs.ErrInvalidArgument) - } - - parts := strings.Split(specifier, "/") - - for _, part := range parts { - if !specifierRe.MatchString(part) { - return specs.Platform{}, fmt.Errorf("%q is an invalid component of %q: platform specifier component must match %q: %w", part, specifier, specifierRe.String(), errdefs.ErrInvalidArgument) - } - } - - var p specs.Platform - switch len(parts) { - case 1: - // in this case, we will test that the value might be an OS, then look - // it up. If it is not known, we'll treat it as an architecture. Since - // we have very little information about the platform here, we are - // going to be a little more strict if we don't know about the argument - // value. - p.OS = normalizeOS(parts[0]) - if isKnownOS(p.OS) { - // picks a default architecture - p.Architecture = runtime.GOARCH - if p.Architecture == "arm" && cpuVariant() != "v7" { - p.Variant = cpuVariant() - } - - if p.OS == "windows" { - p.OSVersion = GetWindowsOsVersion() - } - - return p, nil - } - - p.Architecture, p.Variant = normalizeArch(parts[0], "") - if p.Architecture == "arm" && p.Variant == "v7" { - p.Variant = "" - } - if isKnownArch(p.Architecture) { - p.OS = runtime.GOOS - return p, nil - } - - return specs.Platform{}, fmt.Errorf("%q: unknown operating system or architecture: %w", specifier, errdefs.ErrInvalidArgument) - case 2: - // In this case, we treat as a regular os/arch pair. We don't care - // about whether or not we know of the platform. - p.OS = normalizeOS(parts[0]) - p.Architecture, p.Variant = normalizeArch(parts[1], "") - if p.Architecture == "arm" && p.Variant == "v7" { - p.Variant = "" - } - - if p.OS == "windows" { - p.OSVersion = GetWindowsOsVersion() - } - - return p, nil - case 3: - // we have a fully specified variant, this is rare - p.OS = normalizeOS(parts[0]) - p.Architecture, p.Variant = normalizeArch(parts[1], parts[2]) - if p.Architecture == "arm64" && p.Variant == "" { - p.Variant = "v8" - } - - if p.OS == "windows" { - p.OSVersion = GetWindowsOsVersion() - } - - return p, nil - } - - return specs.Platform{}, fmt.Errorf("%q: cannot parse platform specifier: %w", specifier, errdefs.ErrInvalidArgument) -} - -// MustParse is like Parses but panics if the specifier cannot be parsed. -// Simplifies initialization of global variables. -func MustParse(specifier string) specs.Platform { - p, err := Parse(specifier) - if err != nil { - panic("platform: Parse(" + strconv.Quote(specifier) + "): " + err.Error()) - } - return p -} - -// Format returns a string specifier from the provided platform specification. -func Format(platform specs.Platform) string { - if platform.OS == "" { - return "unknown" - } - - return path.Join(platform.OS, platform.Architecture, platform.Variant) -} - -// Normalize validates and translate the platform to the canonical value. -// -// For example, if "Aarch64" is encountered, we change it to "arm64" or if -// "x86_64" is encountered, it becomes "amd64". -func Normalize(platform specs.Platform) specs.Platform { - platform.OS = normalizeOS(platform.OS) - platform.Architecture, platform.Variant = normalizeArch(platform.Architecture, platform.Variant) - - return platform -} diff --git a/vendor/github.com/containerd/containerd/platforms/platforms_other.go b/vendor/github.com/containerd/containerd/platforms/platforms_other.go deleted file mode 100644 index 59beeb3d1..000000000 --- a/vendor/github.com/containerd/containerd/platforms/platforms_other.go +++ /dev/null @@ -1,34 +0,0 @@ -//go:build !windows - -/* - Copyright The containerd 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 platforms - -import ( - specs "github.com/opencontainers/image-spec/specs-go/v1" -) - -// NewMatcher returns the default Matcher for containerd -func newDefaultMatcher(platform specs.Platform) Matcher { - return &matcher{ - Platform: Normalize(platform), - } -} - -func GetWindowsOsVersion() string { - return "" -} diff --git a/vendor/github.com/containerd/containerd/platforms/platforms_windows.go b/vendor/github.com/containerd/containerd/platforms/platforms_windows.go deleted file mode 100644 index 733d18dde..000000000 --- a/vendor/github.com/containerd/containerd/platforms/platforms_windows.go +++ /dev/null @@ -1,42 +0,0 @@ -/* - Copyright The containerd 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 platforms - -import ( - "fmt" - - specs "github.com/opencontainers/image-spec/specs-go/v1" - "golang.org/x/sys/windows" -) - -// NewMatcher returns a Windows matcher that will match on osVersionPrefix if -// the platform is Windows otherwise use the default matcher -func newDefaultMatcher(platform specs.Platform) Matcher { - prefix := prefix(platform.OSVersion) - return windowsmatcher{ - Platform: platform, - osVersionPrefix: prefix, - defaultMatcher: &matcher{ - Platform: Normalize(platform), - }, - } -} - -func GetWindowsOsVersion() string { - major, minor, build := windows.RtlGetNtVersionNumbers() - return fmt.Sprintf("%d.%d.%d", major, minor, build) -} diff --git a/vendor/github.com/containerd/containerd/protobuf/any.go b/vendor/github.com/containerd/containerd/protobuf/any.go deleted file mode 100644 index 84da2a33d..000000000 --- a/vendor/github.com/containerd/containerd/protobuf/any.go +++ /dev/null @@ -1,47 +0,0 @@ -/* - Copyright The containerd 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 protobuf - -import ( - "github.com/containerd/typeurl/v2" - "google.golang.org/protobuf/types/known/anypb" -) - -// FromAny converts typeurl.Any to github.com/containerd/containerd/protobuf/types.Any. -func FromAny(from typeurl.Any) *anypb.Any { - if from == nil { - return nil - } - - if pbany, ok := from.(*anypb.Any); ok { - return pbany - } - - return &anypb.Any{ - TypeUrl: from.GetTypeUrl(), - Value: from.GetValue(), - } -} - -// FromAny converts an arbitrary interface to github.com/containerd/containerd/protobuf/types.Any. -func MarshalAnyToProto(from interface{}) (*anypb.Any, error) { - any, err := typeurl.MarshalAny(from) - if err != nil { - return nil, err - } - return FromAny(any), nil -} diff --git a/vendor/github.com/containerd/containerd/protobuf/compare.go b/vendor/github.com/containerd/containerd/protobuf/compare.go deleted file mode 100644 index 602a4bcac..000000000 --- a/vendor/github.com/containerd/containerd/protobuf/compare.go +++ /dev/null @@ -1,41 +0,0 @@ -/* - Copyright The containerd 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 protobuf - -import ( - "github.com/google/go-cmp/cmp" - "google.golang.org/protobuf/proto" -) - -var Compare = cmp.FilterValues( - func(x, y interface{}) bool { - _, xok := x.(proto.Message) - _, yok := y.(proto.Message) - return xok && yok - }, - cmp.Comparer(func(x, y interface{}) bool { - vx, ok := x.(proto.Message) - if !ok { - return false - } - vy, ok := y.(proto.Message) - if !ok { - return false - } - return proto.Equal(vx, vy) - }), -) diff --git a/vendor/github.com/containerd/containerd/protobuf/timestamp.go b/vendor/github.com/containerd/containerd/protobuf/timestamp.go deleted file mode 100644 index 0615f823b..000000000 --- a/vendor/github.com/containerd/containerd/protobuf/timestamp.go +++ /dev/null @@ -1,36 +0,0 @@ -/* - Copyright The containerd 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 protobuf - -import ( - "time" - - "google.golang.org/protobuf/types/known/timestamppb" -) - -// Once we migrate off from gogo/protobuf, we can use the function below, which don't return any errors. -// https://github.com/protocolbuffers/protobuf-go/blob/v1.28.0/types/known/timestamppb/timestamp.pb.go#L200-L208 - -// ToTimestamp creates protobuf's Timestamp from time.Time. -func ToTimestamp(from time.Time) *timestamppb.Timestamp { - return timestamppb.New(from) -} - -// FromTimestamp creates time.Time from protobuf's Timestamp. -func FromTimestamp(from *timestamppb.Timestamp) time.Time { - return from.AsTime() -} diff --git a/vendor/github.com/containerd/containerd/protobuf/types/types.go b/vendor/github.com/containerd/containerd/protobuf/types/types.go deleted file mode 100644 index 1a920a2f9..000000000 --- a/vendor/github.com/containerd/containerd/protobuf/types/types.go +++ /dev/null @@ -1,28 +0,0 @@ -/* - Copyright The containerd 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 types provides convinient aliases that make google.golang.org/protobuf migration easier. -package types - -import ( - "google.golang.org/genproto/protobuf/field_mask" - "google.golang.org/protobuf/types/known/anypb" - "google.golang.org/protobuf/types/known/emptypb" -) - -type Empty = emptypb.Empty -type Any = anypb.Any -type FieldMask = field_mask.FieldMask diff --git a/vendor/github.com/containerd/containerd/reference/docker/helpers.go b/vendor/github.com/containerd/containerd/reference/docker/helpers.go deleted file mode 100644 index 386025104..000000000 --- a/vendor/github.com/containerd/containerd/reference/docker/helpers.go +++ /dev/null @@ -1,58 +0,0 @@ -/* - Copyright The containerd 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 docker - -import "path" - -// IsNameOnly returns true if reference only contains a repo name. -func IsNameOnly(ref Named) bool { - if _, ok := ref.(NamedTagged); ok { - return false - } - if _, ok := ref.(Canonical); ok { - return false - } - return true -} - -// FamiliarName returns the familiar name string -// for the given named, familiarizing if needed. -func FamiliarName(ref Named) string { - if nn, ok := ref.(normalizedNamed); ok { - return nn.Familiar().Name() - } - return ref.Name() -} - -// FamiliarString returns the familiar string representation -// for the given reference, familiarizing if needed. -func FamiliarString(ref Reference) string { - if nn, ok := ref.(normalizedNamed); ok { - return nn.Familiar().String() - } - return ref.String() -} - -// FamiliarMatch reports whether ref matches the specified pattern. -// See https://godoc.org/path#Match for supported patterns. -func FamiliarMatch(pattern string, ref Reference) (bool, error) { - matched, err := path.Match(pattern, FamiliarString(ref)) - if namedRef, isNamed := ref.(Named); isNamed && !matched { - matched, _ = path.Match(pattern, FamiliarName(namedRef)) - } - return matched, err -} diff --git a/vendor/github.com/containerd/containerd/reference/docker/normalize.go b/vendor/github.com/containerd/containerd/reference/docker/normalize.go deleted file mode 100644 index b299bf6c0..000000000 --- a/vendor/github.com/containerd/containerd/reference/docker/normalize.go +++ /dev/null @@ -1,196 +0,0 @@ -/* - Copyright The containerd 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 docker - -import ( - "fmt" - "strings" - - "github.com/opencontainers/go-digest" -) - -var ( - legacyDefaultDomain = "index.docker.io" - defaultDomain = "docker.io" - officialRepoName = "library" - defaultTag = "latest" -) - -// normalizedNamed represents a name which has been -// normalized and has a familiar form. A familiar name -// is what is used in Docker UI. An example normalized -// name is "docker.io/library/ubuntu" and corresponding -// familiar name of "ubuntu". -type normalizedNamed interface { - Named - Familiar() Named -} - -// ParseNormalizedNamed parses a string into a named reference -// transforming a familiar name from Docker UI to a fully -// qualified reference. If the value may be an identifier -// use ParseAnyReference. -func ParseNormalizedNamed(s string) (Named, error) { - if ok := anchoredIdentifierRegexp.MatchString(s); ok { - return nil, fmt.Errorf("invalid repository name (%s), cannot specify 64-byte hexadecimal strings", s) - } - domain, remainder := splitDockerDomain(s) - var remoteName string - if tagSep := strings.IndexRune(remainder, ':'); tagSep > -1 { - remoteName = remainder[:tagSep] - } else { - remoteName = remainder - } - if strings.ToLower(remoteName) != remoteName { - return nil, fmt.Errorf("invalid reference format: repository name (%s) must be lowercase", remoteName) - } - - ref, err := Parse(domain + "/" + remainder) - if err != nil { - return nil, err - } - named, isNamed := ref.(Named) - if !isNamed { - return nil, fmt.Errorf("reference %s has no name", ref.String()) - } - return named, nil -} - -// ParseDockerRef normalizes the image reference following the docker convention. This is added -// mainly for backward compatibility. -// The reference returned can only be either tagged or digested. For reference contains both tag -// and digest, the function returns digested reference, e.g. docker.io/library/busybox:latest@ -// sha256:7cc4b5aefd1d0cadf8d97d4350462ba51c694ebca145b08d7d41b41acc8db5aa will be returned as -// docker.io/library/busybox@sha256:7cc4b5aefd1d0cadf8d97d4350462ba51c694ebca145b08d7d41b41acc8db5aa. -func ParseDockerRef(ref string) (Named, error) { - named, err := ParseNormalizedNamed(ref) - if err != nil { - return nil, err - } - if _, ok := named.(NamedTagged); ok { - if canonical, ok := named.(Canonical); ok { - // The reference is both tagged and digested, only - // return digested. - newNamed, err := WithName(canonical.Name()) - if err != nil { - return nil, err - } - newCanonical, err := WithDigest(newNamed, canonical.Digest()) - if err != nil { - return nil, err - } - return newCanonical, nil - } - } - return TagNameOnly(named), nil -} - -// splitDockerDomain splits a repository name to domain and remotename string. -// If no valid domain is found, the default domain is used. Repository name -// needs to be already validated before. -func splitDockerDomain(name string) (domain, remainder string) { - i := strings.IndexRune(name, '/') - if i == -1 || (!strings.ContainsAny(name[:i], ".:") && name[:i] != "localhost" && strings.ToLower(name[:i]) == name[:i]) { - domain, remainder = defaultDomain, name - } else { - domain, remainder = name[:i], name[i+1:] - } - if domain == legacyDefaultDomain { - domain = defaultDomain - } - if domain == defaultDomain && !strings.ContainsRune(remainder, '/') { - remainder = officialRepoName + "/" + remainder - } - return -} - -// familiarizeName returns a shortened version of the name familiar -// to the Docker UI. Familiar names have the default domain -// "docker.io" and "library/" repository prefix removed. -// For example, "docker.io/library/redis" will have the familiar -// name "redis" and "docker.io/dmcgowan/myapp" will be "dmcgowan/myapp". -// Returns a familiarized named only reference. -func familiarizeName(named namedRepository) repository { - repo := repository{ - domain: named.Domain(), - path: named.Path(), - } - - if repo.domain == defaultDomain { - repo.domain = "" - // Handle official repositories which have the pattern "library/" - if split := strings.Split(repo.path, "/"); len(split) == 2 && split[0] == officialRepoName { - repo.path = split[1] - } - } - return repo -} - -func (r reference) Familiar() Named { - return reference{ - namedRepository: familiarizeName(r.namedRepository), - tag: r.tag, - digest: r.digest, - } -} - -func (r repository) Familiar() Named { - return familiarizeName(r) -} - -func (t taggedReference) Familiar() Named { - return taggedReference{ - namedRepository: familiarizeName(t.namedRepository), - tag: t.tag, - } -} - -func (c canonicalReference) Familiar() Named { - return canonicalReference{ - namedRepository: familiarizeName(c.namedRepository), - digest: c.digest, - } -} - -// TagNameOnly adds the default tag "latest" to a reference if it only has -// a repo name. -func TagNameOnly(ref Named) Named { - if IsNameOnly(ref) { - namedTagged, err := WithTag(ref, defaultTag) - if err != nil { - // Default tag must be valid, to create a NamedTagged - // type with non-validated input the WithTag function - // should be used instead - panic(err) - } - return namedTagged - } - return ref -} - -// ParseAnyReference parses a reference string as a possible identifier, -// full digest, or familiar name. -func ParseAnyReference(ref string) (Reference, error) { - if ok := anchoredIdentifierRegexp.MatchString(ref); ok { - return digestReference("sha256:" + ref), nil - } - if dgst, err := digest.Parse(ref); err == nil { - return digestReference(dgst), nil - } - - return ParseNormalizedNamed(ref) -} diff --git a/vendor/github.com/containerd/containerd/reference/docker/reference.go b/vendor/github.com/containerd/containerd/reference/docker/reference.go deleted file mode 100644 index 4dc00474e..000000000 --- a/vendor/github.com/containerd/containerd/reference/docker/reference.go +++ /dev/null @@ -1,453 +0,0 @@ -/* - Copyright The containerd 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 docker provides a general type to represent any way of referencing images within the registry. -// Its main purpose is to abstract tags and digests (content-addressable hash). -// -// Grammar -// -// reference := name [ ":" tag ] [ "@" digest ] -// name := [domain '/'] path-component ['/' path-component]* -// domain := host [':' port-number] -// host := domain-name | IPv4address | \[ IPv6address \] ; rfc3986 appendix-A -// domain-name := domain-component ['.' domain-component]* -// domain-component := /([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])/ -// port-number := /[0-9]+/ -// path-component := alpha-numeric [separator alpha-numeric]* -// alpha-numeric := /[a-z0-9]+/ -// separator := /[_.]|__|[-]*/ -// -// tag := /[\w][\w.-]{0,127}/ -// -// digest := digest-algorithm ":" digest-hex -// digest-algorithm := digest-algorithm-component [ digest-algorithm-separator digest-algorithm-component ]* -// digest-algorithm-separator := /[+.-_]/ -// digest-algorithm-component := /[A-Za-z][A-Za-z0-9]*/ -// digest-hex := /[0-9a-fA-F]{32,}/ ; At least 128 bit digest value -// -// identifier := /[a-f0-9]{64}/ -// short-identifier := /[a-f0-9]{6,64}/ -package docker - -import ( - "errors" - "fmt" - "strings" - - "github.com/opencontainers/go-digest" -) - -const ( - // NameTotalLengthMax is the maximum total number of characters in a repository name. - NameTotalLengthMax = 255 -) - -var ( - // ErrReferenceInvalidFormat represents an error while trying to parse a string as a reference. - ErrReferenceInvalidFormat = errors.New("invalid reference format") - - // ErrTagInvalidFormat represents an error while trying to parse a string as a tag. - ErrTagInvalidFormat = errors.New("invalid tag format") - - // ErrDigestInvalidFormat represents an error while trying to parse a string as a tag. - ErrDigestInvalidFormat = errors.New("invalid digest format") - - // ErrNameContainsUppercase is returned for invalid repository names that contain uppercase characters. - ErrNameContainsUppercase = errors.New("repository name must be lowercase") - - // ErrNameEmpty is returned for empty, invalid repository names. - ErrNameEmpty = errors.New("repository name must have at least one component") - - // ErrNameTooLong is returned when a repository name is longer than NameTotalLengthMax. - ErrNameTooLong = fmt.Errorf("repository name must not be more than %v characters", NameTotalLengthMax) - - // ErrNameNotCanonical is returned when a name is not canonical. - ErrNameNotCanonical = errors.New("repository name must be canonical") -) - -// Reference is an opaque object reference identifier that may include -// modifiers such as a hostname, name, tag, and digest. -type Reference interface { - // String returns the full reference - String() string -} - -// Field provides a wrapper type for resolving correct reference types when -// working with encoding. -type Field struct { - reference Reference -} - -// AsField wraps a reference in a Field for encoding. -func AsField(reference Reference) Field { - return Field{reference} -} - -// Reference unwraps the reference type from the field to -// return the Reference object. This object should be -// of the appropriate type to further check for different -// reference types. -func (f Field) Reference() Reference { - return f.reference -} - -// MarshalText serializes the field to byte text which -// is the string of the reference. -func (f Field) MarshalText() (p []byte, err error) { - return []byte(f.reference.String()), nil -} - -// UnmarshalText parses text bytes by invoking the -// reference parser to ensure the appropriately -// typed reference object is wrapped by field. -func (f *Field) UnmarshalText(p []byte) error { - r, err := Parse(string(p)) - if err != nil { - return err - } - - f.reference = r - return nil -} - -// Named is an object with a full name -type Named interface { - Reference - Name() string -} - -// Tagged is an object which has a tag -type Tagged interface { - Reference - Tag() string -} - -// NamedTagged is an object including a name and tag. -type NamedTagged interface { - Named - Tag() string -} - -// Digested is an object which has a digest -// in which it can be referenced by -type Digested interface { - Reference - Digest() digest.Digest -} - -// Canonical reference is an object with a fully unique -// name including a name with domain and digest -type Canonical interface { - Named - Digest() digest.Digest -} - -// namedRepository is a reference to a repository with a name. -// A namedRepository has both domain and path components. -type namedRepository interface { - Named - Domain() string - Path() string -} - -// Domain returns the domain part of the Named reference -func Domain(named Named) string { - if r, ok := named.(namedRepository); ok { - return r.Domain() - } - domain, _ := splitDomain(named.Name()) - return domain -} - -// Path returns the name without the domain part of the Named reference -func Path(named Named) (name string) { - if r, ok := named.(namedRepository); ok { - return r.Path() - } - _, path := splitDomain(named.Name()) - return path -} - -func splitDomain(name string) (string, string) { - match := anchoredNameRegexp.FindStringSubmatch(name) - if len(match) != 3 { - return "", name - } - return match[1], match[2] -} - -// SplitHostname splits a named reference into a -// hostname and name string. If no valid hostname is -// found, the hostname is empty and the full value -// is returned as name -// DEPRECATED: Use Domain or Path -func SplitHostname(named Named) (string, string) { - if r, ok := named.(namedRepository); ok { - return r.Domain(), r.Path() - } - return splitDomain(named.Name()) -} - -// Parse parses s and returns a syntactically valid Reference. -// If an error was encountered it is returned, along with a nil Reference. -// NOTE: Parse will not handle short digests. -func Parse(s string) (Reference, error) { - matches := ReferenceRegexp.FindStringSubmatch(s) - if matches == nil { - if s == "" { - return nil, ErrNameEmpty - } - if ReferenceRegexp.FindStringSubmatch(strings.ToLower(s)) != nil { - return nil, ErrNameContainsUppercase - } - return nil, ErrReferenceInvalidFormat - } - - if len(matches[1]) > NameTotalLengthMax { - return nil, ErrNameTooLong - } - - var repo repository - - nameMatch := anchoredNameRegexp.FindStringSubmatch(matches[1]) - if len(nameMatch) == 3 { - repo.domain = nameMatch[1] - repo.path = nameMatch[2] - } else { - repo.domain = "" - repo.path = matches[1] - } - - ref := reference{ - namedRepository: repo, - tag: matches[2], - } - if matches[3] != "" { - var err error - ref.digest, err = digest.Parse(matches[3]) - if err != nil { - return nil, err - } - } - - r := getBestReferenceType(ref) - if r == nil { - return nil, ErrNameEmpty - } - - return r, nil -} - -// ParseNamed parses s and returns a syntactically valid reference implementing -// the Named interface. The reference must have a name and be in the canonical -// form, otherwise an error is returned. -// If an error was encountered it is returned, along with a nil Reference. -// NOTE: ParseNamed will not handle short digests. -func ParseNamed(s string) (Named, error) { - named, err := ParseNormalizedNamed(s) - if err != nil { - return nil, err - } - if named.String() != s { - return nil, ErrNameNotCanonical - } - return named, nil -} - -// WithName returns a named object representing the given string. If the input -// is invalid ErrReferenceInvalidFormat will be returned. -func WithName(name string) (Named, error) { - if len(name) > NameTotalLengthMax { - return nil, ErrNameTooLong - } - - match := anchoredNameRegexp.FindStringSubmatch(name) - if match == nil || len(match) != 3 { - return nil, ErrReferenceInvalidFormat - } - return repository{ - domain: match[1], - path: match[2], - }, nil -} - -// WithTag combines the name from "name" and the tag from "tag" to form a -// reference incorporating both the name and the tag. -func WithTag(name Named, tag string) (NamedTagged, error) { - if !anchoredTagRegexp.MatchString(tag) { - return nil, ErrTagInvalidFormat - } - var repo repository - if r, ok := name.(namedRepository); ok { - repo.domain = r.Domain() - repo.path = r.Path() - } else { - repo.path = name.Name() - } - if canonical, ok := name.(Canonical); ok { - return reference{ - namedRepository: repo, - tag: tag, - digest: canonical.Digest(), - }, nil - } - return taggedReference{ - namedRepository: repo, - tag: tag, - }, nil -} - -// WithDigest combines the name from "name" and the digest from "digest" to form -// a reference incorporating both the name and the digest. -func WithDigest(name Named, digest digest.Digest) (Canonical, error) { - if !anchoredDigestRegexp.MatchString(digest.String()) { - return nil, ErrDigestInvalidFormat - } - var repo repository - if r, ok := name.(namedRepository); ok { - repo.domain = r.Domain() - repo.path = r.Path() - } else { - repo.path = name.Name() - } - if tagged, ok := name.(Tagged); ok { - return reference{ - namedRepository: repo, - tag: tagged.Tag(), - digest: digest, - }, nil - } - return canonicalReference{ - namedRepository: repo, - digest: digest, - }, nil -} - -// TrimNamed removes any tag or digest from the named reference. -func TrimNamed(ref Named) Named { - repo := repository{} - if r, ok := ref.(namedRepository); ok { - repo.domain, repo.path = r.Domain(), r.Path() - } else { - repo.domain, repo.path = splitDomain(ref.Name()) - } - return repo -} - -func getBestReferenceType(ref reference) Reference { - if ref.Name() == "" { - // Allow digest only references - if ref.digest != "" { - return digestReference(ref.digest) - } - return nil - } - if ref.tag == "" { - if ref.digest != "" { - return canonicalReference{ - namedRepository: ref.namedRepository, - digest: ref.digest, - } - } - return ref.namedRepository - } - if ref.digest == "" { - return taggedReference{ - namedRepository: ref.namedRepository, - tag: ref.tag, - } - } - - return ref -} - -type reference struct { - namedRepository - tag string - digest digest.Digest -} - -func (r reference) String() string { - return r.Name() + ":" + r.tag + "@" + r.digest.String() -} - -func (r reference) Tag() string { - return r.tag -} - -func (r reference) Digest() digest.Digest { - return r.digest -} - -type repository struct { - domain string - path string -} - -func (r repository) String() string { - return r.Name() -} - -func (r repository) Name() string { - if r.domain == "" { - return r.path - } - return r.domain + "/" + r.path -} - -func (r repository) Domain() string { - return r.domain -} - -func (r repository) Path() string { - return r.path -} - -type digestReference digest.Digest - -func (d digestReference) String() string { - return digest.Digest(d).String() -} - -func (d digestReference) Digest() digest.Digest { - return digest.Digest(d) -} - -type taggedReference struct { - namedRepository - tag string -} - -func (t taggedReference) String() string { - return t.Name() + ":" + t.tag -} - -func (t taggedReference) Tag() string { - return t.tag -} - -type canonicalReference struct { - namedRepository - digest digest.Digest -} - -func (c canonicalReference) String() string { - return c.Name() + "@" + c.digest.String() -} - -func (c canonicalReference) Digest() digest.Digest { - return c.digest -} diff --git a/vendor/github.com/containerd/containerd/reference/docker/regexp.go b/vendor/github.com/containerd/containerd/reference/docker/regexp.go deleted file mode 100644 index 4be3c575e..000000000 --- a/vendor/github.com/containerd/containerd/reference/docker/regexp.go +++ /dev/null @@ -1,191 +0,0 @@ -/* - Copyright The containerd 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 docker - -import "regexp" - -var ( - // alphaNumeric defines the alpha numeric atom, typically a - // component of names. This only allows lower case characters and digits. - alphaNumeric = `[a-z0-9]+` - - // separator defines the separators allowed to be embedded in name - // components. This allow one period, one or two underscore and multiple - // dashes. Repeated dashes and underscores are intentionally treated - // differently. In order to support valid hostnames as name components, - // supporting repeated dash was added. Additionally double underscore is - // now allowed as a separator to loosen the restriction for previously - // supported names. - separator = `(?:[._]|__|[-]*)` - - // nameComponent restricts registry path component names to start - // with at least one letter or number, with following parts able to be - // separated by one period, one or two underscore and multiple dashes. - nameComponent = expression( - alphaNumeric, - optional(repeated(separator, alphaNumeric))) - - // domainNameComponent restricts the registry domain component of a - // repository name to start with a component as defined by DomainRegexp. - domainNameComponent = `(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])` - - // ipv6address are enclosed between square brackets and may be represented - // in many ways, see rfc5952. Only IPv6 in compressed or uncompressed format - // are allowed, IPv6 zone identifiers (rfc6874) or Special addresses such as - // IPv4-Mapped are deliberately excluded. - ipv6address = expression( - literal(`[`), `(?:[a-fA-F0-9:]+)`, literal(`]`), - ) - - // domainName defines the structure of potential domain components - // that may be part of image names. This is purposely a subset of what is - // allowed by DNS to ensure backwards compatibility with Docker image - // names. This includes IPv4 addresses on decimal format. - domainName = expression( - domainNameComponent, - optional(repeated(literal(`.`), domainNameComponent)), - ) - - // host defines the structure of potential domains based on the URI - // Host subcomponent on rfc3986. It may be a subset of DNS domain name, - // or an IPv4 address in decimal format, or an IPv6 address between square - // brackets (excluding zone identifiers as defined by rfc6874 or special - // addresses such as IPv4-Mapped). - host = `(?:` + domainName + `|` + ipv6address + `)` - - // allowed by the URI Host subcomponent on rfc3986 to ensure backwards - // compatibility with Docker image names. - domain = expression( - host, - optional(literal(`:`), `[0-9]+`)) - - // DomainRegexp defines the structure of potential domain components - // that may be part of image names. This is purposely a subset of what is - // allowed by DNS to ensure backwards compatibility with Docker image - // names. - DomainRegexp = regexp.MustCompile(domain) - - tag = `[\w][\w.-]{0,127}` - // TagRegexp matches valid tag names. From docker/docker:graph/tags.go. - TagRegexp = regexp.MustCompile(tag) - - anchoredTag = anchored(tag) - // anchoredTagRegexp matches valid tag names, anchored at the start and - // end of the matched string. - anchoredTagRegexp = regexp.MustCompile(anchoredTag) - - digestPat = `[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*[:][[:xdigit:]]{32,}` - // DigestRegexp matches valid digests. - DigestRegexp = regexp.MustCompile(digestPat) - - anchoredDigest = anchored(digestPat) - // anchoredDigestRegexp matches valid digests, anchored at the start and - // end of the matched string. - anchoredDigestRegexp = regexp.MustCompile(anchoredDigest) - - namePat = expression( - optional(domain, literal(`/`)), - nameComponent, - optional(repeated(literal(`/`), nameComponent))) - // NameRegexp is the format for the name component of references. The - // regexp has capturing groups for the domain and name part omitting - // the separating forward slash from either. - NameRegexp = regexp.MustCompile(namePat) - - anchoredName = anchored( - optional(capture(domain), literal(`/`)), - capture(nameComponent, - optional(repeated(literal(`/`), nameComponent)))) - // anchoredNameRegexp is used to parse a name value, capturing the - // domain and trailing components. - anchoredNameRegexp = regexp.MustCompile(anchoredName) - - referencePat = anchored(capture(namePat), - optional(literal(":"), capture(tag)), - optional(literal("@"), capture(digestPat))) - // ReferenceRegexp is the full supported format of a reference. The regexp - // is anchored and has capturing groups for name, tag, and digest - // components. - ReferenceRegexp = regexp.MustCompile(referencePat) - - identifier = `([a-f0-9]{64})` - // IdentifierRegexp is the format for string identifier used as a - // content addressable identifier using sha256. These identifiers - // are like digests without the algorithm, since sha256 is used. - IdentifierRegexp = regexp.MustCompile(identifier) - - shortIdentifier = `([a-f0-9]{6,64})` - // ShortIdentifierRegexp is the format used to represent a prefix - // of an identifier. A prefix may be used to match a sha256 identifier - // within a list of trusted identifiers. - ShortIdentifierRegexp = regexp.MustCompile(shortIdentifier) - - anchoredIdentifier = anchored(identifier) - // anchoredIdentifierRegexp is used to check or match an - // identifier value, anchored at start and end of string. - anchoredIdentifierRegexp = regexp.MustCompile(anchoredIdentifier) -) - -// literal compiles s into a literal regular expression, escaping any regexp -// reserved characters. -func literal(s string) string { - re := regexp.MustCompile(regexp.QuoteMeta(s)) - - if _, complete := re.LiteralPrefix(); !complete { - panic("must be a literal") - } - - return re.String() -} - -// expression defines a full expression, where each regular expression must -// follow the previous. -func expression(res ...string) string { - var s string - for _, re := range res { - s += re - } - - return s -} - -// optional wraps the expression in a non-capturing group and makes the -// production optional. -func optional(res ...string) string { - return group(expression(res...)) + `?` -} - -// repeated wraps the regexp in a non-capturing group to get one or more -// matches. -func repeated(res ...string) string { - return group(expression(res...)) + `+` -} - -// group wraps the regexp in a non-capturing group. -func group(res ...string) string { - return `(?:` + expression(res...) + `)` -} - -// capture wraps the expression in a capturing group. -func capture(res ...string) string { - return `(` + expression(res...) + `)` -} - -// anchored anchors the regular expression by adding start and end delimiters. -func anchored(res ...string) string { - return `^` + expression(res...) + `$` -} diff --git a/vendor/github.com/containerd/containerd/reference/docker/sort.go b/vendor/github.com/containerd/containerd/reference/docker/sort.go deleted file mode 100644 index 984e37528..000000000 --- a/vendor/github.com/containerd/containerd/reference/docker/sort.go +++ /dev/null @@ -1,73 +0,0 @@ -/* - Copyright The containerd 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 docker - -import ( - "sort" -) - -// Sort sorts string references preferring higher information references -// The precedence is as follows: -// 1. Name + Tag + Digest -// 2. Name + Tag -// 3. Name + Digest -// 4. Name -// 5. Digest -// 6. Parse error -func Sort(references []string) []string { - var prefs []Reference - var bad []string - - for _, ref := range references { - pref, err := ParseAnyReference(ref) - if err != nil { - bad = append(bad, ref) - } else { - prefs = append(prefs, pref) - } - } - sort.Slice(prefs, func(a, b int) bool { - ar := refRank(prefs[a]) - br := refRank(prefs[b]) - if ar == br { - return prefs[a].String() < prefs[b].String() - } - return ar < br - }) - sort.Strings(bad) - var refs []string - for _, pref := range prefs { - refs = append(refs, pref.String()) - } - return append(refs, bad...) -} - -func refRank(ref Reference) uint8 { - if _, ok := ref.(Named); ok { - if _, ok = ref.(Tagged); ok { - if _, ok = ref.(Digested); ok { - return 1 - } - return 2 - } - if _, ok = ref.(Digested); ok { - return 3 - } - return 4 - } - return 5 -} diff --git a/vendor/github.com/containerd/containerd/reference/reference.go b/vendor/github.com/containerd/containerd/reference/reference.go deleted file mode 100644 index a4bf6da60..000000000 --- a/vendor/github.com/containerd/containerd/reference/reference.go +++ /dev/null @@ -1,166 +0,0 @@ -/* - Copyright The containerd 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 reference - -import ( - "errors" - "fmt" - "net/url" - "path" - "regexp" - "strings" - - digest "github.com/opencontainers/go-digest" -) - -var ( - // ErrInvalid is returned when there is an invalid reference - ErrInvalid = errors.New("invalid reference") - // ErrObjectRequired is returned when the object is required - ErrObjectRequired = errors.New("object required") - // ErrHostnameRequired is returned when the hostname is required - ErrHostnameRequired = errors.New("hostname required") -) - -// Spec defines the main components of a reference specification. -// -// A reference specification is a schema-less URI parsed into common -// components. The two main components, locator and object, are required to be -// supported by remotes. It represents a superset of the naming define in -// docker's reference schema. It aims to be compatible but not prescriptive. -// -// While the interpretation of the components, locator and object, are up to -// the remote, we define a few common parts, accessible via helper methods. -// -// The first is the hostname, which is part of the locator. This doesn't need -// to map to a physical resource, but it must parse as a hostname. We refer to -// this as the namespace. -// -// The other component made accessible by helper method is the digest. This is -// part of the object identifier, always prefixed with an '@'. If present, the -// remote may use the digest portion directly or resolve it against a prefix. -// If the object does not include the `@` symbol, the return value for `Digest` -// will be empty. -type Spec struct { - // Locator is the host and path portion of the specification. The host - // portion may refer to an actual host or just a namespace of related - // images. - // - // Typically, the locator may used to resolve the remote to fetch specific - // resources. - Locator string - - // Object contains the identifier for the remote resource. Classically, - // this is a tag but can refer to anything in a remote. By convention, any - // portion that may be a partial or whole digest will be preceded by an - // `@`. Anything preceding the `@` will be referred to as the "tag". - // - // In practice, we will see this broken down into the following formats: - // - // 1. - // 2. @ - // 3. @ - // - // We define the tag to be anything except '@' and ':'. may - // be a full valid digest or shortened version, possibly with elided - // algorithm. - Object string -} - -var splitRe = regexp.MustCompile(`[:@]`) - -// Parse parses the string into a structured ref. -func Parse(s string) (Spec, error) { - if strings.Contains(s, "://") { - return Spec{}, ErrInvalid - } - - u, err := url.Parse("dummy://" + s) - if err != nil { - return Spec{}, err - } - - if u.Scheme != "dummy" { - return Spec{}, ErrInvalid - } - - if u.Host == "" { - return Spec{}, ErrHostnameRequired - } - - var object string - - if idx := splitRe.FindStringIndex(u.Path); idx != nil { - // This allows us to retain the @ to signify digests or shortened digests in - // the object. - object = u.Path[idx[0]:] - if object[:1] == ":" { - object = object[1:] - } - u.Path = u.Path[:idx[0]] - } - - return Spec{ - Locator: path.Join(u.Host, u.Path), - Object: object, - }, nil -} - -// Hostname returns the hostname portion of the locator. -// -// Remotes are not required to directly access the resources at this host. This -// method is provided for convenience. -func (r Spec) Hostname() string { - i := strings.Index(r.Locator, "/") - - if i < 0 { - return r.Locator - } - return r.Locator[:i] -} - -// Digest returns the digest portion of the reference spec. This may be a -// partial or invalid digest, which may be used to lookup a complete digest. -func (r Spec) Digest() digest.Digest { - _, dgst := SplitObject(r.Object) - return dgst -} - -// String returns the normalized string for the ref. -func (r Spec) String() string { - if r.Object == "" { - return r.Locator - } - if r.Object[:1] == "@" { - return fmt.Sprintf("%v%v", r.Locator, r.Object) - } - - return fmt.Sprintf("%v:%v", r.Locator, r.Object) -} - -// SplitObject provides two parts of the object spec, delimited by an `@` -// symbol. -// -// Either may be empty and it is the callers job to validate them -// appropriately. -func SplitObject(obj string) (tag string, dgst digest.Digest) { - parts := strings.SplitAfterN(obj, "@", 2) - if len(parts) < 2 { - return parts[0], "" - } - return parts[0], digest.Digest(parts[1]) -} diff --git a/vendor/github.com/containerd/containerd/remotes/docker/auth/fetch.go b/vendor/github.com/containerd/containerd/remotes/docker/auth/fetch.go deleted file mode 100644 index 64c6a38f9..000000000 --- a/vendor/github.com/containerd/containerd/remotes/docker/auth/fetch.go +++ /dev/null @@ -1,225 +0,0 @@ -/* - Copyright The containerd 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 auth - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "net/http" - "net/url" - "strings" - "time" - - "github.com/containerd/containerd/log" - remoteserrors "github.com/containerd/containerd/remotes/errors" - "github.com/containerd/containerd/version" -) - -var ( - // ErrNoToken is returned if a request is successful but the body does not - // contain an authorization token. - ErrNoToken = errors.New("authorization server did not include a token in the response") -) - -// GenerateTokenOptions generates options for fetching a token based on a challenge -func GenerateTokenOptions(ctx context.Context, host, username, secret string, c Challenge) (TokenOptions, error) { - realm, ok := c.Parameters["realm"] - if !ok { - return TokenOptions{}, errors.New("no realm specified for token auth challenge") - } - - realmURL, err := url.Parse(realm) - if err != nil { - return TokenOptions{}, fmt.Errorf("invalid token auth challenge realm: %w", err) - } - - to := TokenOptions{ - Realm: realmURL.String(), - Service: c.Parameters["service"], - Username: username, - Secret: secret, - } - - scope, ok := c.Parameters["scope"] - if ok { - to.Scopes = append(to.Scopes, strings.Split(scope, " ")...) - } else { - log.G(ctx).WithField("host", host).Debug("no scope specified for token auth challenge") - } - - return to, nil -} - -// TokenOptions are options for requesting a token -type TokenOptions struct { - Realm string - Service string - Scopes []string - Username string - Secret string - - // FetchRefreshToken enables fetching a refresh token (aka "identity token", "offline token") along with the bearer token. - // - // For HTTP GET mode (FetchToken), FetchRefreshToken sets `offline_token=true` in the request. - // https://docs.docker.com/registry/spec/auth/token/#requesting-a-token - // - // For HTTP POST mode (FetchTokenWithOAuth), FetchRefreshToken sets `access_type=offline` in the request. - // https://docs.docker.com/registry/spec/auth/oauth/#getting-a-token - FetchRefreshToken bool -} - -// OAuthTokenResponse is response from fetching token with a OAuth POST request -type OAuthTokenResponse struct { - AccessToken string `json:"access_token"` - RefreshToken string `json:"refresh_token"` - ExpiresIn int `json:"expires_in"` - IssuedAt time.Time `json:"issued_at"` - Scope string `json:"scope"` -} - -// FetchTokenWithOAuth fetches a token using a POST request -func FetchTokenWithOAuth(ctx context.Context, client *http.Client, headers http.Header, clientID string, to TokenOptions) (*OAuthTokenResponse, error) { - form := url.Values{} - if len(to.Scopes) > 0 { - form.Set("scope", strings.Join(to.Scopes, " ")) - } - form.Set("service", to.Service) - form.Set("client_id", clientID) - - if to.Username == "" { - form.Set("grant_type", "refresh_token") - form.Set("refresh_token", to.Secret) - } else { - form.Set("grant_type", "password") - form.Set("username", to.Username) - form.Set("password", to.Secret) - } - if to.FetchRefreshToken { - form.Set("access_type", "offline") - } - - req, err := http.NewRequestWithContext(ctx, http.MethodPost, to.Realm, strings.NewReader(form.Encode())) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=utf-8") - for k, v := range headers { - req.Header[k] = append(req.Header[k], v...) - } - if len(req.Header.Get("User-Agent")) == 0 { - req.Header.Set("User-Agent", "containerd/"+version.Version) - } - - resp, err := client.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if resp.StatusCode < 200 || resp.StatusCode >= 400 { - return nil, remoteserrors.NewUnexpectedStatusErr(resp) - } - - decoder := json.NewDecoder(resp.Body) - - var tr OAuthTokenResponse - if err = decoder.Decode(&tr); err != nil { - return nil, fmt.Errorf("unable to decode token response: %w", err) - } - - if tr.AccessToken == "" { - return nil, ErrNoToken - } - - return &tr, nil -} - -// FetchTokenResponse is response from fetching token with GET request -type FetchTokenResponse struct { - Token string `json:"token"` - AccessToken string `json:"access_token"` - ExpiresIn int `json:"expires_in"` - IssuedAt time.Time `json:"issued_at"` - RefreshToken string `json:"refresh_token"` -} - -// FetchToken fetches a token using a GET request -func FetchToken(ctx context.Context, client *http.Client, headers http.Header, to TokenOptions) (*FetchTokenResponse, error) { - req, err := http.NewRequestWithContext(ctx, http.MethodGet, to.Realm, nil) - if err != nil { - return nil, err - } - - for k, v := range headers { - req.Header[k] = append(req.Header[k], v...) - } - if len(req.Header.Get("User-Agent")) == 0 { - req.Header.Set("User-Agent", "containerd/"+version.Version) - } - - reqParams := req.URL.Query() - - if to.Service != "" { - reqParams.Add("service", to.Service) - } - - for _, scope := range to.Scopes { - reqParams.Add("scope", scope) - } - - if to.Secret != "" { - req.SetBasicAuth(to.Username, to.Secret) - } - - if to.FetchRefreshToken { - reqParams.Add("offline_token", "true") - } - - req.URL.RawQuery = reqParams.Encode() - - resp, err := client.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if resp.StatusCode < 200 || resp.StatusCode >= 400 { - return nil, remoteserrors.NewUnexpectedStatusErr(resp) - } - - decoder := json.NewDecoder(resp.Body) - - var tr FetchTokenResponse - if err = decoder.Decode(&tr); err != nil { - return nil, fmt.Errorf("unable to decode token response: %w", err) - } - - // `access_token` is equivalent to `token` and if both are specified - // the choice is undefined. Canonicalize `access_token` by sticking - // things in `token`. - if tr.AccessToken != "" { - tr.Token = tr.AccessToken - } - - if tr.Token == "" { - return nil, ErrNoToken - } - - return &tr, nil -} diff --git a/vendor/github.com/containerd/containerd/remotes/docker/auth/parse.go b/vendor/github.com/containerd/containerd/remotes/docker/auth/parse.go deleted file mode 100644 index e4529a776..000000000 --- a/vendor/github.com/containerd/containerd/remotes/docker/auth/parse.go +++ /dev/null @@ -1,200 +0,0 @@ -/* - Copyright The containerd 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 auth - -import ( - "net/http" - "sort" - "strings" -) - -// AuthenticationScheme defines scheme of the authentication method -type AuthenticationScheme byte - -const ( - // BasicAuth is scheme for Basic HTTP Authentication RFC 7617 - BasicAuth AuthenticationScheme = 1 << iota - // DigestAuth is scheme for HTTP Digest Access Authentication RFC 7616 - DigestAuth - // BearerAuth is scheme for OAuth 2.0 Bearer Tokens RFC 6750 - BearerAuth -) - -// Challenge carries information from a WWW-Authenticate response header. -// See RFC 2617. -type Challenge struct { - // scheme is the auth-scheme according to RFC 2617 - Scheme AuthenticationScheme - - // parameters are the auth-params according to RFC 2617 - Parameters map[string]string -} - -type byScheme []Challenge - -func (bs byScheme) Len() int { return len(bs) } -func (bs byScheme) Swap(i, j int) { bs[i], bs[j] = bs[j], bs[i] } - -// Sort in priority order: token > digest > basic -func (bs byScheme) Less(i, j int) bool { return bs[i].Scheme > bs[j].Scheme } - -// Octet types from RFC 2616. -type octetType byte - -var octetTypes [256]octetType - -const ( - isToken octetType = 1 << iota - isSpace -) - -func init() { - // OCTET = - // CHAR = - // CTL = - // CR = - // LF = - // SP = - // HT = - // <"> = - // CRLF = CR LF - // LWS = [CRLF] 1*( SP | HT ) - // TEXT = - // separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <"> - // | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT - // token = 1* - // qdtext = > - - for c := 0; c < 256; c++ { - var t octetType - isCtl := c <= 31 || c == 127 - isChar := 0 <= c && c <= 127 - isSeparator := strings.ContainsRune(" \t\"(),/:;<=>?@[]\\{}", rune(c)) - if strings.ContainsRune(" \t\r\n", rune(c)) { - t |= isSpace - } - if isChar && !isCtl && !isSeparator { - t |= isToken - } - octetTypes[c] = t - } -} - -// ParseAuthHeader parses challenges from WWW-Authenticate header -func ParseAuthHeader(header http.Header) []Challenge { - challenges := []Challenge{} - for _, h := range header[http.CanonicalHeaderKey("WWW-Authenticate")] { - v, p := parseValueAndParams(h) - var s AuthenticationScheme - switch v { - case "basic": - s = BasicAuth - case "digest": - s = DigestAuth - case "bearer": - s = BearerAuth - default: - continue - } - challenges = append(challenges, Challenge{Scheme: s, Parameters: p}) - } - sort.Stable(byScheme(challenges)) - return challenges -} - -func parseValueAndParams(header string) (value string, params map[string]string) { - params = make(map[string]string) - value, s := expectToken(header) - if value == "" { - return - } - value = strings.ToLower(value) - for { - var pkey string - pkey, s = expectToken(skipSpace(s)) - if pkey == "" { - return - } - if !strings.HasPrefix(s, "=") { - return - } - var pvalue string - pvalue, s = expectTokenOrQuoted(s[1:]) - pkey = strings.ToLower(pkey) - params[pkey] = pvalue - s = skipSpace(s) - if !strings.HasPrefix(s, ",") { - return - } - s = s[1:] - } -} - -func skipSpace(s string) (rest string) { - i := 0 - for ; i < len(s); i++ { - if octetTypes[s[i]]&isSpace == 0 { - break - } - } - return s[i:] -} - -func expectToken(s string) (token, rest string) { - i := 0 - for ; i < len(s); i++ { - if octetTypes[s[i]]&isToken == 0 { - break - } - } - return s[:i], s[i:] -} - -func expectTokenOrQuoted(s string) (value string, rest string) { - if !strings.HasPrefix(s, "\"") { - return expectToken(s) - } - s = s[1:] - for i := 0; i < len(s); i++ { - switch s[i] { - case '"': - return s[:i], s[i+1:] - case '\\': - p := make([]byte, len(s)-1) - j := copy(p, s[:i]) - escape := true - for i = i + 1; i < len(s); i++ { - b := s[i] - switch { - case escape: - escape = false - p[j] = b - j++ - case b == '\\': - escape = true - case b == '"': - return string(p[:j]), s[i+1:] - default: - p[j] = b - j++ - } - } - return "", "" - } - } - return "", "" -} diff --git a/vendor/github.com/containerd/containerd/remotes/docker/authorizer.go b/vendor/github.com/containerd/containerd/remotes/docker/authorizer.go deleted file mode 100644 index 9b3663cd1..000000000 --- a/vendor/github.com/containerd/containerd/remotes/docker/authorizer.go +++ /dev/null @@ -1,353 +0,0 @@ -/* - Copyright The containerd 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 docker - -import ( - "context" - "encoding/base64" - "errors" - "fmt" - "net/http" - "strings" - "sync" - - "github.com/containerd/containerd/errdefs" - "github.com/containerd/containerd/log" - "github.com/containerd/containerd/remotes/docker/auth" - remoteerrors "github.com/containerd/containerd/remotes/errors" -) - -type dockerAuthorizer struct { - credentials func(string) (string, string, error) - - client *http.Client - header http.Header - mu sync.RWMutex - - // indexed by host name - handlers map[string]*authHandler - - onFetchRefreshToken OnFetchRefreshToken -} - -type authorizerConfig struct { - credentials func(string) (string, string, error) - client *http.Client - header http.Header - onFetchRefreshToken OnFetchRefreshToken -} - -// AuthorizerOpt configures an authorizer -type AuthorizerOpt func(*authorizerConfig) - -// WithAuthClient provides the HTTP client for the authorizer -func WithAuthClient(client *http.Client) AuthorizerOpt { - return func(opt *authorizerConfig) { - opt.client = client - } -} - -// WithAuthCreds provides a credential function to the authorizer -func WithAuthCreds(creds func(string) (string, string, error)) AuthorizerOpt { - return func(opt *authorizerConfig) { - opt.credentials = creds - } -} - -// WithAuthHeader provides HTTP headers for authorization -func WithAuthHeader(hdr http.Header) AuthorizerOpt { - return func(opt *authorizerConfig) { - opt.header = hdr - } -} - -// OnFetchRefreshToken is called on fetching request token. -type OnFetchRefreshToken func(ctx context.Context, refreshToken string, req *http.Request) - -// WithFetchRefreshToken enables fetching "refresh token" (aka "identity token", "offline token"). -func WithFetchRefreshToken(f OnFetchRefreshToken) AuthorizerOpt { - return func(opt *authorizerConfig) { - opt.onFetchRefreshToken = f - } -} - -// NewDockerAuthorizer creates an authorizer using Docker's registry -// authentication spec. -// See https://docs.docker.com/registry/spec/auth/ -func NewDockerAuthorizer(opts ...AuthorizerOpt) Authorizer { - var ao authorizerConfig - for _, opt := range opts { - opt(&ao) - } - - if ao.client == nil { - ao.client = http.DefaultClient - } - - return &dockerAuthorizer{ - credentials: ao.credentials, - client: ao.client, - header: ao.header, - handlers: make(map[string]*authHandler), - onFetchRefreshToken: ao.onFetchRefreshToken, - } -} - -// Authorize handles auth request. -func (a *dockerAuthorizer) Authorize(ctx context.Context, req *http.Request) error { - // skip if there is no auth handler - ah := a.getAuthHandler(req.URL.Host) - if ah == nil { - return nil - } - - auth, refreshToken, err := ah.authorize(ctx) - if err != nil { - return err - } - - req.Header.Set("Authorization", auth) - - if refreshToken != "" { - a.mu.RLock() - onFetchRefreshToken := a.onFetchRefreshToken - a.mu.RUnlock() - if onFetchRefreshToken != nil { - onFetchRefreshToken(ctx, refreshToken, req) - } - } - return nil -} - -func (a *dockerAuthorizer) getAuthHandler(host string) *authHandler { - a.mu.Lock() - defer a.mu.Unlock() - - return a.handlers[host] -} - -func (a *dockerAuthorizer) AddResponses(ctx context.Context, responses []*http.Response) error { - last := responses[len(responses)-1] - host := last.Request.URL.Host - - a.mu.Lock() - defer a.mu.Unlock() - for _, c := range auth.ParseAuthHeader(last.Header) { - if c.Scheme == auth.BearerAuth { - if err := invalidAuthorization(c, responses); err != nil { - delete(a.handlers, host) - return err - } - - // reuse existing handler - // - // assume that one registry will return the common - // challenge information, including realm and service. - // and the resource scope is only different part - // which can be provided by each request. - if _, ok := a.handlers[host]; ok { - return nil - } - - var username, secret string - if a.credentials != nil { - var err error - username, secret, err = a.credentials(host) - if err != nil { - return err - } - } - - common, err := auth.GenerateTokenOptions(ctx, host, username, secret, c) - if err != nil { - return err - } - common.FetchRefreshToken = a.onFetchRefreshToken != nil - - a.handlers[host] = newAuthHandler(a.client, a.header, c.Scheme, common) - return nil - } else if c.Scheme == auth.BasicAuth && a.credentials != nil { - username, secret, err := a.credentials(host) - if err != nil { - return err - } - - if username == "" || secret == "" { - return fmt.Errorf("%w: no basic auth credentials", ErrInvalidAuthorization) - } - - a.handlers[host] = newAuthHandler(a.client, a.header, c.Scheme, auth.TokenOptions{ - Username: username, - Secret: secret, - }) - return nil - } - } - return fmt.Errorf("failed to find supported auth scheme: %w", errdefs.ErrNotImplemented) -} - -// authResult is used to control limit rate. -type authResult struct { - sync.WaitGroup - token string - refreshToken string - err error -} - -// authHandler is used to handle auth request per registry server. -type authHandler struct { - sync.Mutex - - header http.Header - - client *http.Client - - // only support basic and bearer schemes - scheme auth.AuthenticationScheme - - // common contains common challenge answer - common auth.TokenOptions - - // scopedTokens caches token indexed by scopes, which used in - // bearer auth case - scopedTokens map[string]*authResult -} - -func newAuthHandler(client *http.Client, hdr http.Header, scheme auth.AuthenticationScheme, opts auth.TokenOptions) *authHandler { - return &authHandler{ - header: hdr, - client: client, - scheme: scheme, - common: opts, - scopedTokens: map[string]*authResult{}, - } -} - -func (ah *authHandler) authorize(ctx context.Context) (string, string, error) { - switch ah.scheme { - case auth.BasicAuth: - return ah.doBasicAuth(ctx) - case auth.BearerAuth: - return ah.doBearerAuth(ctx) - default: - return "", "", fmt.Errorf("failed to find supported auth scheme: %s: %w", string(ah.scheme), errdefs.ErrNotImplemented) - } -} - -func (ah *authHandler) doBasicAuth(ctx context.Context) (string, string, error) { - username, secret := ah.common.Username, ah.common.Secret - - if username == "" || secret == "" { - return "", "", fmt.Errorf("failed to handle basic auth because missing username or secret") - } - - auth := base64.StdEncoding.EncodeToString([]byte(username + ":" + secret)) - return fmt.Sprintf("Basic %s", auth), "", nil -} - -func (ah *authHandler) doBearerAuth(ctx context.Context) (token, refreshToken string, err error) { - // copy common tokenOptions - to := ah.common - - to.Scopes = GetTokenScopes(ctx, to.Scopes) - - // Docs: https://docs.docker.com/registry/spec/auth/scope - scoped := strings.Join(to.Scopes, " ") - - ah.Lock() - if r, exist := ah.scopedTokens[scoped]; exist { - ah.Unlock() - r.Wait() - return r.token, r.refreshToken, r.err - } - - // only one fetch token job - r := new(authResult) - r.Add(1) - ah.scopedTokens[scoped] = r - ah.Unlock() - - defer func() { - token = fmt.Sprintf("Bearer %s", token) - r.token, r.refreshToken, r.err = token, refreshToken, err - r.Done() - }() - - // fetch token for the resource scope - if to.Secret != "" { - defer func() { - if err != nil { - err = fmt.Errorf("failed to fetch oauth token: %w", err) - } - }() - // credential information is provided, use oauth POST endpoint - // TODO: Allow setting client_id - resp, err := auth.FetchTokenWithOAuth(ctx, ah.client, ah.header, "containerd-client", to) - if err != nil { - var errStatus remoteerrors.ErrUnexpectedStatus - if errors.As(err, &errStatus) { - // Registries without support for POST may return 404 for POST /v2/token. - // As of September 2017, GCR is known to return 404. - // As of February 2018, JFrog Artifactory is known to return 401. - // As of January 2022, ACR is known to return 400. - if (errStatus.StatusCode == 405 && to.Username != "") || errStatus.StatusCode == 404 || errStatus.StatusCode == 401 || errStatus.StatusCode == 400 { - resp, err := auth.FetchToken(ctx, ah.client, ah.header, to) - if err != nil { - return "", "", err - } - return resp.Token, resp.RefreshToken, nil - } - log.G(ctx).WithFields(log.Fields{ - "status": errStatus.Status, - "body": string(errStatus.Body), - }).Debugf("token request failed") - } - return "", "", err - } - return resp.AccessToken, resp.RefreshToken, nil - } - // do request anonymously - resp, err := auth.FetchToken(ctx, ah.client, ah.header, to) - if err != nil { - return "", "", fmt.Errorf("failed to fetch anonymous token: %w", err) - } - return resp.Token, resp.RefreshToken, nil -} - -func invalidAuthorization(c auth.Challenge, responses []*http.Response) error { - errStr := c.Parameters["error"] - if errStr == "" { - return nil - } - - n := len(responses) - if n == 1 || (n > 1 && !sameRequest(responses[n-2].Request, responses[n-1].Request)) { - return nil - } - - return fmt.Errorf("server message: %s: %w", errStr, ErrInvalidAuthorization) -} - -func sameRequest(r1, r2 *http.Request) bool { - if r1.Method != r2.Method { - return false - } - if *r1.URL != *r2.URL { - return false - } - return true -} diff --git a/vendor/github.com/containerd/containerd/remotes/docker/converter.go b/vendor/github.com/containerd/containerd/remotes/docker/converter.go deleted file mode 100644 index d7dca0d36..000000000 --- a/vendor/github.com/containerd/containerd/remotes/docker/converter.go +++ /dev/null @@ -1,87 +0,0 @@ -/* - Copyright The containerd 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 docker - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - - "github.com/containerd/containerd/content" - "github.com/containerd/containerd/images" - "github.com/containerd/containerd/log" - "github.com/containerd/containerd/remotes" - digest "github.com/opencontainers/go-digest" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" -) - -// LegacyConfigMediaType should be replaced by OCI image spec. -// -// More detail: docker/distribution#1622 -const LegacyConfigMediaType = "application/octet-stream" - -// ConvertManifest changes application/octet-stream to schema2 config media type if need. -// -// NOTE: -// 1. original manifest will be deleted by next gc round. -// 2. don't cover manifest list. -func ConvertManifest(ctx context.Context, store content.Store, desc ocispec.Descriptor) (ocispec.Descriptor, error) { - if !(desc.MediaType == images.MediaTypeDockerSchema2Manifest || - desc.MediaType == ocispec.MediaTypeImageManifest) { - - log.G(ctx).Warnf("do nothing for media type: %s", desc.MediaType) - return desc, nil - } - - // read manifest data - mb, err := content.ReadBlob(ctx, store, desc) - if err != nil { - return ocispec.Descriptor{}, fmt.Errorf("failed to read index data: %w", err) - } - - var manifest ocispec.Manifest - if err := json.Unmarshal(mb, &manifest); err != nil { - return ocispec.Descriptor{}, fmt.Errorf("failed to unmarshal data into manifest: %w", err) - } - - // check config media type - if manifest.Config.MediaType != LegacyConfigMediaType { - return desc, nil - } - - manifest.Config.MediaType = images.MediaTypeDockerSchema2Config - data, err := json.MarshalIndent(manifest, "", " ") - if err != nil { - return ocispec.Descriptor{}, fmt.Errorf("failed to marshal manifest: %w", err) - } - - // update manifest with gc labels - desc.Digest = digest.Canonical.FromBytes(data) - desc.Size = int64(len(data)) - - labels := map[string]string{} - for i, c := range append([]ocispec.Descriptor{manifest.Config}, manifest.Layers...) { - labels[fmt.Sprintf("containerd.io/gc.ref.content.%d", i)] = c.Digest.String() - } - - ref := remotes.MakeRefKey(ctx, desc) - if err := content.WriteBlob(ctx, store, ref, bytes.NewReader(data), desc, content.WithLabels(labels)); err != nil { - return ocispec.Descriptor{}, fmt.Errorf("failed to update content: %w", err) - } - return desc, nil -} diff --git a/vendor/github.com/containerd/containerd/remotes/docker/converter_fuzz.go b/vendor/github.com/containerd/containerd/remotes/docker/converter_fuzz.go deleted file mode 100644 index 908205392..000000000 --- a/vendor/github.com/containerd/containerd/remotes/docker/converter_fuzz.go +++ /dev/null @@ -1,55 +0,0 @@ -//go:build gofuzz - -/* - Copyright The containerd 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 docker - -import ( - "context" - "os" - - fuzz "github.com/AdaLogics/go-fuzz-headers" - "github.com/containerd/containerd/content/local" - "github.com/containerd/containerd/log" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" - "github.com/sirupsen/logrus" -) - -func FuzzConvertManifest(data []byte) int { - ctx := context.Background() - - // Do not log the message below - // level=warning msg="do nothing for media type: ..." - log.G(ctx).Logger.SetLevel(logrus.PanicLevel) - - f := fuzz.NewConsumer(data) - desc := ocispec.Descriptor{} - err := f.GenerateStruct(&desc) - if err != nil { - return 0 - } - tmpdir, err := os.MkdirTemp("", "fuzzing-") - if err != nil { - return 0 - } - cs, err := local.NewStore(tmpdir) - if err != nil { - return 0 - } - _, _ = ConvertManifest(ctx, cs, desc) - return 1 -} diff --git a/vendor/github.com/containerd/containerd/remotes/docker/errcode.go b/vendor/github.com/containerd/containerd/remotes/docker/errcode.go deleted file mode 100644 index 8c623bcbe..000000000 --- a/vendor/github.com/containerd/containerd/remotes/docker/errcode.go +++ /dev/null @@ -1,283 +0,0 @@ -/* - Copyright The containerd 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 docker - -import ( - "encoding/json" - "fmt" - "strings" -) - -// ErrorCoder is the base interface for ErrorCode and Error allowing -// users of each to just call ErrorCode to get the real ID of each -type ErrorCoder interface { - ErrorCode() ErrorCode -} - -// ErrorCode represents the error type. The errors are serialized via strings -// and the integer format may change and should *never* be exported. -type ErrorCode int - -var _ error = ErrorCode(0) - -// ErrorCode just returns itself -func (ec ErrorCode) ErrorCode() ErrorCode { - return ec -} - -// Error returns the ID/Value -func (ec ErrorCode) Error() string { - // NOTE(stevvooe): Cannot use message here since it may have unpopulated args. - return strings.ToLower(strings.Replace(ec.String(), "_", " ", -1)) -} - -// Descriptor returns the descriptor for the error code. -func (ec ErrorCode) Descriptor() ErrorDescriptor { - d, ok := errorCodeToDescriptors[ec] - - if !ok { - return ErrorCodeUnknown.Descriptor() - } - - return d -} - -// String returns the canonical identifier for this error code. -func (ec ErrorCode) String() string { - return ec.Descriptor().Value -} - -// Message returned the human-readable error message for this error code. -func (ec ErrorCode) Message() string { - return ec.Descriptor().Message -} - -// MarshalText encodes the receiver into UTF-8-encoded text and returns the -// result. -func (ec ErrorCode) MarshalText() (text []byte, err error) { - return []byte(ec.String()), nil -} - -// UnmarshalText decodes the form generated by MarshalText. -func (ec *ErrorCode) UnmarshalText(text []byte) error { - desc, ok := idToDescriptors[string(text)] - - if !ok { - desc = ErrorCodeUnknown.Descriptor() - } - - *ec = desc.Code - - return nil -} - -// WithMessage creates a new Error struct based on the passed-in info and -// overrides the Message property. -func (ec ErrorCode) WithMessage(message string) Error { - return Error{ - Code: ec, - Message: message, - } -} - -// WithDetail creates a new Error struct based on the passed-in info and -// set the Detail property appropriately -func (ec ErrorCode) WithDetail(detail interface{}) Error { - return Error{ - Code: ec, - Message: ec.Message(), - }.WithDetail(detail) -} - -// WithArgs creates a new Error struct and sets the Args slice -func (ec ErrorCode) WithArgs(args ...interface{}) Error { - return Error{ - Code: ec, - Message: ec.Message(), - }.WithArgs(args...) -} - -// Error provides a wrapper around ErrorCode with extra Details provided. -type Error struct { - Code ErrorCode `json:"code"` - Message string `json:"message"` - Detail interface{} `json:"detail,omitempty"` - - // TODO(duglin): See if we need an "args" property so we can do the - // variable substitution right before showing the message to the user -} - -var _ error = Error{} - -// ErrorCode returns the ID/Value of this Error -func (e Error) ErrorCode() ErrorCode { - return e.Code -} - -// Error returns a human readable representation of the error. -func (e Error) Error() string { - return fmt.Sprintf("%s: %s", e.Code.Error(), e.Message) -} - -// WithDetail will return a new Error, based on the current one, but with -// some Detail info added -func (e Error) WithDetail(detail interface{}) Error { - return Error{ - Code: e.Code, - Message: e.Message, - Detail: detail, - } -} - -// WithArgs uses the passed-in list of interface{} as the substitution -// variables in the Error's Message string, but returns a new Error -func (e Error) WithArgs(args ...interface{}) Error { - return Error{ - Code: e.Code, - Message: fmt.Sprintf(e.Code.Message(), args...), - Detail: e.Detail, - } -} - -// ErrorDescriptor provides relevant information about a given error code. -type ErrorDescriptor struct { - // Code is the error code that this descriptor describes. - Code ErrorCode - - // Value provides a unique, string key, often captilized with - // underscores, to identify the error code. This value is used as the - // keyed value when serializing api errors. - Value string - - // Message is a short, human readable description of the error condition - // included in API responses. - Message string - - // Description provides a complete account of the errors purpose, suitable - // for use in documentation. - Description string - - // HTTPStatusCode provides the http status code that is associated with - // this error condition. - HTTPStatusCode int -} - -// ParseErrorCode returns the value by the string error code. -// `ErrorCodeUnknown` will be returned if the error is not known. -func ParseErrorCode(value string) ErrorCode { - ed, ok := idToDescriptors[value] - if ok { - return ed.Code - } - - return ErrorCodeUnknown -} - -// Errors provides the envelope for multiple errors and a few sugar methods -// for use within the application. -type Errors []error - -var _ error = Errors{} - -func (errs Errors) Error() string { - switch len(errs) { - case 0: - return "" - case 1: - return errs[0].Error() - default: - msg := "errors:\n" - for _, err := range errs { - msg += err.Error() + "\n" - } - return msg - } -} - -// Len returns the current number of errors. -func (errs Errors) Len() int { - return len(errs) -} - -// MarshalJSON converts slice of error, ErrorCode or Error into a -// slice of Error - then serializes -func (errs Errors) MarshalJSON() ([]byte, error) { - var tmpErrs struct { - Errors []Error `json:"errors,omitempty"` - } - - for _, daErr := range errs { - var err Error - - switch daErr := daErr.(type) { - case ErrorCode: - err = daErr.WithDetail(nil) - case Error: - err = daErr - default: - err = ErrorCodeUnknown.WithDetail(daErr) - - } - - // If the Error struct was setup and they forgot to set the - // Message field (meaning its "") then grab it from the ErrCode - msg := err.Message - if msg == "" { - msg = err.Code.Message() - } - - tmpErrs.Errors = append(tmpErrs.Errors, Error{ - Code: err.Code, - Message: msg, - Detail: err.Detail, - }) - } - - return json.Marshal(tmpErrs) -} - -// UnmarshalJSON deserializes []Error and then converts it into slice of -// Error or ErrorCode -func (errs *Errors) UnmarshalJSON(data []byte) error { - var tmpErrs struct { - Errors []Error - } - - if err := json.Unmarshal(data, &tmpErrs); err != nil { - return err - } - - var newErrs Errors - for _, daErr := range tmpErrs.Errors { - // If Message is empty or exactly matches the Code's message string - // then just use the Code, no need for a full Error struct - if daErr.Detail == nil && (daErr.Message == "" || daErr.Message == daErr.Code.Message()) { - // Error's w/o details get converted to ErrorCode - newErrs = append(newErrs, daErr.Code) - } else { - // Error's w/ details are untouched - newErrs = append(newErrs, Error{ - Code: daErr.Code, - Message: daErr.Message, - Detail: daErr.Detail, - }) - } - } - - *errs = newErrs - return nil -} diff --git a/vendor/github.com/containerd/containerd/remotes/docker/errdesc.go b/vendor/github.com/containerd/containerd/remotes/docker/errdesc.go deleted file mode 100644 index b2bd4d82b..000000000 --- a/vendor/github.com/containerd/containerd/remotes/docker/errdesc.go +++ /dev/null @@ -1,154 +0,0 @@ -/* - Copyright The containerd 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 docker - -import ( - "fmt" - "net/http" - "sort" - "sync" -) - -var ( - errorCodeToDescriptors = map[ErrorCode]ErrorDescriptor{} - idToDescriptors = map[string]ErrorDescriptor{} - groupToDescriptors = map[string][]ErrorDescriptor{} -) - -var ( - // ErrorCodeUnknown is a generic error that can be used as a last - // resort if there is no situation-specific error message that can be used - ErrorCodeUnknown = Register("errcode", ErrorDescriptor{ - Value: "UNKNOWN", - Message: "unknown error", - Description: `Generic error returned when the error does not have an - API classification.`, - HTTPStatusCode: http.StatusInternalServerError, - }) - - // ErrorCodeUnsupported is returned when an operation is not supported. - ErrorCodeUnsupported = Register("errcode", ErrorDescriptor{ - Value: "UNSUPPORTED", - Message: "The operation is unsupported.", - Description: `The operation was unsupported due to a missing - implementation or invalid set of parameters.`, - HTTPStatusCode: http.StatusMethodNotAllowed, - }) - - // ErrorCodeUnauthorized is returned if a request requires - // authentication. - ErrorCodeUnauthorized = Register("errcode", ErrorDescriptor{ - Value: "UNAUTHORIZED", - Message: "authentication required", - Description: `The access controller was unable to authenticate - the client. Often this will be accompanied by a - Www-Authenticate HTTP response header indicating how to - authenticate.`, - HTTPStatusCode: http.StatusUnauthorized, - }) - - // ErrorCodeDenied is returned if a client does not have sufficient - // permission to perform an action. - ErrorCodeDenied = Register("errcode", ErrorDescriptor{ - Value: "DENIED", - Message: "requested access to the resource is denied", - Description: `The access controller denied access for the - operation on a resource.`, - HTTPStatusCode: http.StatusForbidden, - }) - - // ErrorCodeUnavailable provides a common error to report unavailability - // of a service or endpoint. - ErrorCodeUnavailable = Register("errcode", ErrorDescriptor{ - Value: "UNAVAILABLE", - Message: "service unavailable", - Description: "Returned when a service is not available", - HTTPStatusCode: http.StatusServiceUnavailable, - }) - - // ErrorCodeTooManyRequests is returned if a client attempts too many - // times to contact a service endpoint. - ErrorCodeTooManyRequests = Register("errcode", ErrorDescriptor{ - Value: "TOOMANYREQUESTS", - Message: "too many requests", - Description: `Returned when a client attempts to contact a - service too many times`, - HTTPStatusCode: http.StatusTooManyRequests, - }) -) - -var nextCode = 1000 -var registerLock sync.Mutex - -// Register will make the passed-in error known to the environment and -// return a new ErrorCode -func Register(group string, descriptor ErrorDescriptor) ErrorCode { - registerLock.Lock() - defer registerLock.Unlock() - - descriptor.Code = ErrorCode(nextCode) - - if _, ok := idToDescriptors[descriptor.Value]; ok { - panic(fmt.Sprintf("ErrorValue %q is already registered", descriptor.Value)) - } - if _, ok := errorCodeToDescriptors[descriptor.Code]; ok { - panic(fmt.Sprintf("ErrorCode %v is already registered", descriptor.Code)) - } - - groupToDescriptors[group] = append(groupToDescriptors[group], descriptor) - errorCodeToDescriptors[descriptor.Code] = descriptor - idToDescriptors[descriptor.Value] = descriptor - - nextCode++ - return descriptor.Code -} - -type byValue []ErrorDescriptor - -func (a byValue) Len() int { return len(a) } -func (a byValue) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a byValue) Less(i, j int) bool { return a[i].Value < a[j].Value } - -// GetGroupNames returns the list of Error group names that are registered -func GetGroupNames() []string { - keys := []string{} - - for k := range groupToDescriptors { - keys = append(keys, k) - } - sort.Strings(keys) - return keys -} - -// GetErrorCodeGroup returns the named group of error descriptors -func GetErrorCodeGroup(name string) []ErrorDescriptor { - desc := groupToDescriptors[name] - sort.Sort(byValue(desc)) - return desc -} - -// GetErrorAllDescriptors returns a slice of all ErrorDescriptors that are -// registered, irrespective of what group they're in -func GetErrorAllDescriptors() []ErrorDescriptor { - result := []ErrorDescriptor{} - - for _, group := range GetGroupNames() { - result = append(result, GetErrorCodeGroup(group)...) - } - sort.Sort(byValue(result)) - return result -} diff --git a/vendor/github.com/containerd/containerd/remotes/docker/fetcher.go b/vendor/github.com/containerd/containerd/remotes/docker/fetcher.go deleted file mode 100644 index ecf245933..000000000 --- a/vendor/github.com/containerd/containerd/remotes/docker/fetcher.go +++ /dev/null @@ -1,313 +0,0 @@ -/* - Copyright The containerd 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 docker - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "io" - "net/http" - "net/url" - "strings" - - "github.com/containerd/containerd/errdefs" - "github.com/containerd/containerd/images" - "github.com/containerd/containerd/log" - digest "github.com/opencontainers/go-digest" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" -) - -type dockerFetcher struct { - *dockerBase -} - -func (r dockerFetcher) Fetch(ctx context.Context, desc ocispec.Descriptor) (io.ReadCloser, error) { - ctx = log.WithLogger(ctx, log.G(ctx).WithField("digest", desc.Digest)) - - hosts := r.filterHosts(HostCapabilityPull) - if len(hosts) == 0 { - return nil, fmt.Errorf("no pull hosts: %w", errdefs.ErrNotFound) - } - - ctx, err := ContextWithRepositoryScope(ctx, r.refspec, false) - if err != nil { - return nil, err - } - - return newHTTPReadSeeker(desc.Size, func(offset int64) (io.ReadCloser, error) { - // firstly try fetch via external urls - for _, us := range desc.URLs { - u, err := url.Parse(us) - if err != nil { - log.G(ctx).WithError(err).Debugf("failed to parse %q", us) - continue - } - if u.Scheme != "http" && u.Scheme != "https" { - log.G(ctx).Debug("non-http(s) alternative url is unsupported") - continue - } - ctx = log.WithLogger(ctx, log.G(ctx).WithField("url", u)) - log.G(ctx).Info("request") - - // Try this first, parse it - host := RegistryHost{ - Client: http.DefaultClient, - Host: u.Host, - Scheme: u.Scheme, - Path: u.Path, - Capabilities: HostCapabilityPull, - } - req := r.request(host, http.MethodGet) - // Strip namespace from base - req.path = u.Path - if u.RawQuery != "" { - req.path = req.path + "?" + u.RawQuery - } - - rc, err := r.open(ctx, req, desc.MediaType, offset) - if err != nil { - if errdefs.IsNotFound(err) { - continue // try one of the other urls. - } - - return nil, err - } - - return rc, nil - } - - // Try manifests endpoints for manifests types - switch desc.MediaType { - case images.MediaTypeDockerSchema2Manifest, images.MediaTypeDockerSchema2ManifestList, - images.MediaTypeDockerSchema1Manifest, - ocispec.MediaTypeImageManifest, ocispec.MediaTypeImageIndex: - - var firstErr error - for _, host := range r.hosts { - req := r.request(host, http.MethodGet, "manifests", desc.Digest.String()) - if err := req.addNamespace(r.refspec.Hostname()); err != nil { - return nil, err - } - - rc, err := r.open(ctx, req, desc.MediaType, offset) - if err != nil { - // Store the error for referencing later - if firstErr == nil { - firstErr = err - } - continue // try another host - } - - return rc, nil - } - - return nil, firstErr - } - - // Finally use blobs endpoints - var firstErr error - for _, host := range r.hosts { - req := r.request(host, http.MethodGet, "blobs", desc.Digest.String()) - if err := req.addNamespace(r.refspec.Hostname()); err != nil { - return nil, err - } - - rc, err := r.open(ctx, req, desc.MediaType, offset) - if err != nil { - // Store the error for referencing later - if firstErr == nil { - firstErr = err - } - continue // try another host - } - - return rc, nil - } - - if errdefs.IsNotFound(firstErr) { - firstErr = fmt.Errorf("could not fetch content descriptor %v (%v) from remote: %w", - desc.Digest, desc.MediaType, errdefs.ErrNotFound, - ) - } - - return nil, firstErr - - }) -} - -func (r dockerFetcher) createGetReq(ctx context.Context, host RegistryHost, ps ...string) (*request, int64, error) { - headReq := r.request(host, http.MethodHead, ps...) - if err := headReq.addNamespace(r.refspec.Hostname()); err != nil { - return nil, 0, err - } - - headResp, err := headReq.doWithRetries(ctx, nil) - if err != nil { - return nil, 0, err - } - if headResp.Body != nil { - headResp.Body.Close() - } - if headResp.StatusCode > 299 { - return nil, 0, fmt.Errorf("unexpected HEAD status code %v: %s", headReq.String(), headResp.Status) - } - - getReq := r.request(host, http.MethodGet, ps...) - if err := getReq.addNamespace(r.refspec.Hostname()); err != nil { - return nil, 0, err - } - return getReq, headResp.ContentLength, nil -} - -func (r dockerFetcher) FetchByDigest(ctx context.Context, dgst digest.Digest) (io.ReadCloser, ocispec.Descriptor, error) { - var desc ocispec.Descriptor - ctx = log.WithLogger(ctx, log.G(ctx).WithField("digest", dgst)) - - hosts := r.filterHosts(HostCapabilityPull) - if len(hosts) == 0 { - return nil, desc, fmt.Errorf("no pull hosts: %w", errdefs.ErrNotFound) - } - - ctx, err := ContextWithRepositoryScope(ctx, r.refspec, false) - if err != nil { - return nil, desc, err - } - - var ( - getReq *request - sz int64 - firstErr error - ) - - for _, host := range r.hosts { - getReq, sz, err = r.createGetReq(ctx, host, "blobs", dgst.String()) - if err == nil { - break - } - // Store the error for referencing later - if firstErr == nil { - firstErr = err - } - } - - if getReq == nil { - // Fall back to the "manifests" endpoint - for _, host := range r.hosts { - getReq, sz, err = r.createGetReq(ctx, host, "manifests", dgst.String()) - if err == nil { - break - } - // Store the error for referencing later - if firstErr == nil { - firstErr = err - } - } - } - - if getReq == nil { - if errdefs.IsNotFound(firstErr) { - firstErr = fmt.Errorf("could not fetch content %v from remote: %w", dgst, errdefs.ErrNotFound) - } - if firstErr == nil { - firstErr = fmt.Errorf("could not fetch content %v from remote: (unknown)", dgst) - } - return nil, desc, firstErr - } - - seeker, err := newHTTPReadSeeker(sz, func(offset int64) (io.ReadCloser, error) { - return r.open(ctx, getReq, "", offset) - }) - if err != nil { - return nil, desc, err - } - - desc = ocispec.Descriptor{ - MediaType: "application/octet-stream", - Digest: dgst, - Size: sz, - } - return seeker, desc, nil -} - -func (r dockerFetcher) open(ctx context.Context, req *request, mediatype string, offset int64) (_ io.ReadCloser, retErr error) { - if mediatype == "" { - req.header.Set("Accept", "*/*") - } else { - req.header.Set("Accept", strings.Join([]string{mediatype, `*/*`}, ", ")) - } - - if offset > 0 { - // Note: "Accept-Ranges: bytes" cannot be trusted as some endpoints - // will return the header without supporting the range. The content - // range must always be checked. - req.header.Set("Range", fmt.Sprintf("bytes=%d-", offset)) - } - - resp, err := req.doWithRetries(ctx, nil) - if err != nil { - return nil, err - } - defer func() { - if retErr != nil { - resp.Body.Close() - } - }() - - if resp.StatusCode > 299 { - // TODO(stevvooe): When doing a offset specific request, we should - // really distinguish between a 206 and a 200. In the case of 200, we - // can discard the bytes, hiding the seek behavior from the - // implementation. - - if resp.StatusCode == http.StatusNotFound { - return nil, fmt.Errorf("content at %v not found: %w", req.String(), errdefs.ErrNotFound) - } - var registryErr Errors - if err := json.NewDecoder(resp.Body).Decode(®istryErr); err != nil || registryErr.Len() < 1 { - return nil, fmt.Errorf("unexpected status code %v: %v", req.String(), resp.Status) - } - return nil, fmt.Errorf("unexpected status code %v: %s - Server message: %s", req.String(), resp.Status, registryErr.Error()) - } - if offset > 0 { - cr := resp.Header.Get("content-range") - if cr != "" { - if !strings.HasPrefix(cr, fmt.Sprintf("bytes %d-", offset)) { - return nil, fmt.Errorf("unhandled content range in response: %v", cr) - - } - } else { - // TODO: Should any cases where use of content range - // without the proper header be considered? - // 206 responses? - - // Discard up to offset - // Could use buffer pool here but this case should be rare - n, err := io.Copy(io.Discard, io.LimitReader(resp.Body, offset)) - if err != nil { - return nil, fmt.Errorf("failed to discard to offset: %w", err) - } - if n != offset { - return nil, errors.New("unable to discard to offset") - } - - } - } - - return resp.Body, nil -} diff --git a/vendor/github.com/containerd/containerd/remotes/docker/fetcher_fuzz.go b/vendor/github.com/containerd/containerd/remotes/docker/fetcher_fuzz.go deleted file mode 100644 index b98886c59..000000000 --- a/vendor/github.com/containerd/containerd/remotes/docker/fetcher_fuzz.go +++ /dev/null @@ -1,81 +0,0 @@ -//go:build gofuzz - -/* - Copyright The containerd 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 docker - -import ( - "context" - "fmt" - "io" - "net/http" - "net/http/httptest" - "net/url" - - refDocker "github.com/containerd/containerd/reference/docker" -) - -func FuzzFetcher(data []byte) int { - dataLen := len(data) - if dataLen == 0 { - return -1 - } - - s := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - rw.Header().Set("content-range", fmt.Sprintf("bytes %d-%d/%d", 0, dataLen-1, dataLen)) - rw.Header().Set("content-length", fmt.Sprintf("%d", dataLen)) - rw.Write(data) - })) - defer s.Close() - - u, err := url.Parse(s.URL) - if err != nil { - return 0 - } - - f := dockerFetcher{&dockerBase{ - repository: "nonempty", - }} - host := RegistryHost{ - Client: s.Client(), - Host: u.Host, - Scheme: u.Scheme, - Path: u.Path, - } - - ctx := context.Background() - req := f.request(host, http.MethodGet) - rc, err := f.open(ctx, req, "", 0) - if err != nil { - return 0 - } - b, err := io.ReadAll(rc) - if err != nil { - return 0 - } - - expected := data - if len(b) != len(expected) { - panic("len of request is not equal to len of expected but should be") - } - return 1 -} - -func FuzzParseDockerRef(data []byte) int { - _, _ = refDocker.ParseDockerRef(string(data)) - return 1 -} diff --git a/vendor/github.com/containerd/containerd/remotes/docker/handler.go b/vendor/github.com/containerd/containerd/remotes/docker/handler.go deleted file mode 100644 index 27638ccc0..000000000 --- a/vendor/github.com/containerd/containerd/remotes/docker/handler.go +++ /dev/null @@ -1,149 +0,0 @@ -/* - Copyright The containerd 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 docker - -import ( - "context" - "fmt" - "net/url" - "strings" - - "github.com/containerd/containerd/content" - "github.com/containerd/containerd/images" - "github.com/containerd/containerd/labels" - "github.com/containerd/containerd/log" - "github.com/containerd/containerd/reference" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" -) - -// AppendDistributionSourceLabel updates the label of blob with distribution source. -func AppendDistributionSourceLabel(manager content.Manager, ref string) (images.HandlerFunc, error) { - refspec, err := reference.Parse(ref) - if err != nil { - return nil, err - } - - u, err := url.Parse("dummy://" + refspec.Locator) - if err != nil { - return nil, err - } - - source, repo := u.Hostname(), strings.TrimPrefix(u.Path, "/") - return func(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) { - info, err := manager.Info(ctx, desc.Digest) - if err != nil { - return nil, err - } - - key := distributionSourceLabelKey(source) - - originLabel := "" - if info.Labels != nil { - originLabel = info.Labels[key] - } - value := appendDistributionSourceLabel(originLabel, repo) - - // The repo name has been limited under 256 and the distribution - // label might hit the limitation of label size, when blob data - // is used as the very, very common layer. - if err := labels.Validate(key, value); err != nil { - log.G(ctx).Warnf("skip to append distribution label: %s", err) - return nil, nil - } - - info = content.Info{ - Digest: desc.Digest, - Labels: map[string]string{ - key: value, - }, - } - _, err = manager.Update(ctx, info, fmt.Sprintf("labels.%s", key)) - return nil, err - }, nil -} - -func appendDistributionSourceLabel(originLabel, repo string) string { - repos := []string{} - if originLabel != "" { - repos = strings.Split(originLabel, ",") - } - repos = append(repos, repo) - - // use empty string to present duplicate items - for i := 1; i < len(repos); i++ { - tmp, j := repos[i], i-1 - for ; j >= 0 && repos[j] >= tmp; j-- { - if repos[j] == tmp { - tmp = "" - } - repos[j+1] = repos[j] - } - repos[j+1] = tmp - } - - i := 0 - for ; i < len(repos) && repos[i] == ""; i++ { - } - - return strings.Join(repos[i:], ",") -} - -func distributionSourceLabelKey(source string) string { - return fmt.Sprintf("%s.%s", labels.LabelDistributionSource, source) -} - -// selectRepositoryMountCandidate will select the repo which has longest -// common prefix components as the candidate. -func selectRepositoryMountCandidate(refspec reference.Spec, sources map[string]string) string { - u, err := url.Parse("dummy://" + refspec.Locator) - if err != nil { - // NOTE: basically, it won't be error here - return "" - } - - source, target := u.Hostname(), strings.TrimPrefix(u.Path, "/") - repoLabel, ok := sources[distributionSourceLabelKey(source)] - if !ok || repoLabel == "" { - return "" - } - - n, match := 0, "" - components := strings.Split(target, "/") - for _, repo := range strings.Split(repoLabel, ",") { - // the target repo is not a candidate - if repo == target { - continue - } - - if l := commonPrefixComponents(components, repo); l >= n { - n, match = l, repo - } - } - return match -} - -func commonPrefixComponents(components []string, target string) int { - targetComponents := strings.Split(target, "/") - - i := 0 - for ; i < len(components) && i < len(targetComponents); i++ { - if components[i] != targetComponents[i] { - break - } - } - return i -} diff --git a/vendor/github.com/containerd/containerd/remotes/docker/httpreadseeker.go b/vendor/github.com/containerd/containerd/remotes/docker/httpreadseeker.go deleted file mode 100644 index 824359339..000000000 --- a/vendor/github.com/containerd/containerd/remotes/docker/httpreadseeker.go +++ /dev/null @@ -1,178 +0,0 @@ -/* - Copyright The containerd 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 docker - -import ( - "bytes" - "fmt" - "io" - - "github.com/containerd/containerd/errdefs" - "github.com/containerd/containerd/log" -) - -const maxRetry = 3 - -type httpReadSeeker struct { - size int64 - offset int64 - rc io.ReadCloser - open func(offset int64) (io.ReadCloser, error) - closed bool - - errsWithNoProgress int -} - -func newHTTPReadSeeker(size int64, open func(offset int64) (io.ReadCloser, error)) (io.ReadCloser, error) { - return &httpReadSeeker{ - size: size, - open: open, - }, nil -} - -func (hrs *httpReadSeeker) Read(p []byte) (n int, err error) { - if hrs.closed { - return 0, io.EOF - } - - rd, err := hrs.reader() - if err != nil { - return 0, err - } - - n, err = rd.Read(p) - hrs.offset += int64(n) - if n > 0 || err == nil { - hrs.errsWithNoProgress = 0 - } - if err == io.ErrUnexpectedEOF { - // connection closed unexpectedly. try reconnecting. - if n == 0 { - hrs.errsWithNoProgress++ - if hrs.errsWithNoProgress > maxRetry { - return // too many retries for this offset with no progress - } - } - if hrs.rc != nil { - if clsErr := hrs.rc.Close(); clsErr != nil { - log.L.WithError(clsErr).Error("httpReadSeeker: failed to close ReadCloser") - } - hrs.rc = nil - } - if _, err2 := hrs.reader(); err2 == nil { - return n, nil - } - } else if err == io.EOF { - // The CRI's imagePullProgressTimeout relies on responseBody.Close to - // update the process monitor's status. If the err is io.EOF, close - // the connection since there is no more available data. - if hrs.rc != nil { - if clsErr := hrs.rc.Close(); clsErr != nil { - log.L.WithError(clsErr).Error("httpReadSeeker: failed to close ReadCloser after io.EOF") - } - hrs.rc = nil - } - } - return -} - -func (hrs *httpReadSeeker) Close() error { - if hrs.closed { - return nil - } - hrs.closed = true - if hrs.rc != nil { - return hrs.rc.Close() - } - - return nil -} - -func (hrs *httpReadSeeker) Seek(offset int64, whence int) (int64, error) { - if hrs.closed { - return 0, fmt.Errorf("Fetcher.Seek: closed: %w", errdefs.ErrUnavailable) - } - - abs := hrs.offset - switch whence { - case io.SeekStart: - abs = offset - case io.SeekCurrent: - abs += offset - case io.SeekEnd: - if hrs.size == -1 { - return 0, fmt.Errorf("Fetcher.Seek: unknown size, cannot seek from end: %w", errdefs.ErrUnavailable) - } - abs = hrs.size + offset - default: - return 0, fmt.Errorf("Fetcher.Seek: invalid whence: %w", errdefs.ErrInvalidArgument) - } - - if abs < 0 { - return 0, fmt.Errorf("Fetcher.Seek: negative offset: %w", errdefs.ErrInvalidArgument) - } - - if abs != hrs.offset { - if hrs.rc != nil { - if err := hrs.rc.Close(); err != nil { - log.L.WithError(err).Error("Fetcher.Seek: failed to close ReadCloser") - } - - hrs.rc = nil - } - - hrs.offset = abs - } - - return hrs.offset, nil -} - -func (hrs *httpReadSeeker) reader() (io.Reader, error) { - if hrs.rc != nil { - return hrs.rc, nil - } - - if hrs.size == -1 || hrs.offset < hrs.size { - // only try to reopen the body request if we are seeking to a value - // less than the actual size. - if hrs.open == nil { - return nil, fmt.Errorf("cannot open: %w", errdefs.ErrNotImplemented) - } - - rc, err := hrs.open(hrs.offset) - if err != nil { - return nil, fmt.Errorf("httpReadSeeker: failed open: %w", err) - } - - if hrs.rc != nil { - if err := hrs.rc.Close(); err != nil { - log.L.WithError(err).Error("httpReadSeeker: failed to close ReadCloser") - } - } - hrs.rc = rc - } else { - // There is an edge case here where offset == size of the content. If - // we seek, we will probably get an error for content that cannot be - // sought (?). In that case, we should err on committing the content, - // as the length is already satisfied but we just return the empty - // reader instead. - - hrs.rc = io.NopCloser(bytes.NewReader([]byte{})) - } - - return hrs.rc, nil -} diff --git a/vendor/github.com/containerd/containerd/remotes/docker/pusher.go b/vendor/github.com/containerd/containerd/remotes/docker/pusher.go deleted file mode 100644 index 678e17e12..000000000 --- a/vendor/github.com/containerd/containerd/remotes/docker/pusher.go +++ /dev/null @@ -1,545 +0,0 @@ -/* - Copyright The containerd 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 docker - -import ( - "context" - "errors" - "fmt" - "io" - "net/http" - "net/url" - "path" - "strings" - "sync" - "time" - - "github.com/containerd/containerd/content" - "github.com/containerd/containerd/errdefs" - "github.com/containerd/containerd/images" - "github.com/containerd/containerd/log" - "github.com/containerd/containerd/remotes" - remoteserrors "github.com/containerd/containerd/remotes/errors" - digest "github.com/opencontainers/go-digest" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" -) - -type dockerPusher struct { - *dockerBase - object string - - // TODO: namespace tracker - tracker StatusTracker -} - -// Writer implements Ingester API of content store. This allows the client -// to receive ErrUnavailable when there is already an on-going upload. -// Note that the tracker MUST implement StatusTrackLocker interface to avoid -// race condition on StatusTracker. -func (p dockerPusher) Writer(ctx context.Context, opts ...content.WriterOpt) (content.Writer, error) { - var wOpts content.WriterOpts - for _, opt := range opts { - if err := opt(&wOpts); err != nil { - return nil, err - } - } - if wOpts.Ref == "" { - return nil, fmt.Errorf("ref must not be empty: %w", errdefs.ErrInvalidArgument) - } - return p.push(ctx, wOpts.Desc, wOpts.Ref, true) -} - -func (p dockerPusher) Push(ctx context.Context, desc ocispec.Descriptor) (content.Writer, error) { - return p.push(ctx, desc, remotes.MakeRefKey(ctx, desc), false) -} - -func (p dockerPusher) push(ctx context.Context, desc ocispec.Descriptor, ref string, unavailableOnFail bool) (content.Writer, error) { - if l, ok := p.tracker.(StatusTrackLocker); ok { - l.Lock(ref) - defer l.Unlock(ref) - } - ctx, err := ContextWithRepositoryScope(ctx, p.refspec, true) - if err != nil { - return nil, err - } - status, err := p.tracker.GetStatus(ref) - if err == nil { - if status.Committed && status.Offset == status.Total { - return nil, fmt.Errorf("ref %v: %w", ref, errdefs.ErrAlreadyExists) - } - if unavailableOnFail && status.ErrClosed == nil { - // Another push of this ref is happening elsewhere. The rest of function - // will continue only when `errdefs.IsNotFound(err) == true` (i.e. there - // is no actively-tracked ref already). - return nil, fmt.Errorf("push is on-going: %w", errdefs.ErrUnavailable) - } - // TODO: Handle incomplete status - } else if !errdefs.IsNotFound(err) { - return nil, fmt.Errorf("failed to get status: %w", err) - } - - hosts := p.filterHosts(HostCapabilityPush) - if len(hosts) == 0 { - return nil, fmt.Errorf("no push hosts: %w", errdefs.ErrNotFound) - } - - var ( - isManifest bool - existCheck []string - host = hosts[0] - ) - - switch desc.MediaType { - case images.MediaTypeDockerSchema2Manifest, images.MediaTypeDockerSchema2ManifestList, - ocispec.MediaTypeImageManifest, ocispec.MediaTypeImageIndex: - isManifest = true - existCheck = getManifestPath(p.object, desc.Digest) - default: - existCheck = []string{"blobs", desc.Digest.String()} - } - - req := p.request(host, http.MethodHead, existCheck...) - req.header.Set("Accept", strings.Join([]string{desc.MediaType, `*/*`}, ", ")) - - log.G(ctx).WithField("url", req.String()).Debugf("checking and pushing to") - - resp, err := req.doWithRetries(ctx, nil) - if err != nil { - if !errors.Is(err, ErrInvalidAuthorization) { - return nil, err - } - log.G(ctx).WithError(err).Debugf("Unable to check existence, continuing with push") - } else { - if resp.StatusCode == http.StatusOK { - var exists bool - if isManifest && existCheck[1] != desc.Digest.String() { - dgstHeader := digest.Digest(resp.Header.Get("Docker-Content-Digest")) - if dgstHeader == desc.Digest { - exists = true - } - } else { - exists = true - } - - if exists { - p.tracker.SetStatus(ref, Status{ - Committed: true, - PushStatus: PushStatus{ - Exists: true, - }, - Status: content.Status{ - Ref: ref, - Total: desc.Size, - Offset: desc.Size, - // TODO: Set updated time? - }, - }) - resp.Body.Close() - return nil, fmt.Errorf("content %v on remote: %w", desc.Digest, errdefs.ErrAlreadyExists) - } - } else if resp.StatusCode != http.StatusNotFound { - err := remoteserrors.NewUnexpectedStatusErr(resp) - log.G(ctx).WithField("resp", resp).WithField("body", string(err.(remoteserrors.ErrUnexpectedStatus).Body)).Debug("unexpected response") - resp.Body.Close() - return nil, err - } - resp.Body.Close() - } - - if isManifest { - putPath := getManifestPath(p.object, desc.Digest) - req = p.request(host, http.MethodPut, putPath...) - req.header.Add("Content-Type", desc.MediaType) - } else { - // Start upload request - req = p.request(host, http.MethodPost, "blobs", "uploads/") - - mountedFrom := "" - var resp *http.Response - if fromRepo := selectRepositoryMountCandidate(p.refspec, desc.Annotations); fromRepo != "" { - preq := requestWithMountFrom(req, desc.Digest.String(), fromRepo) - pctx := ContextWithAppendPullRepositoryScope(ctx, fromRepo) - - // NOTE: the fromRepo might be private repo and - // auth service still can grant token without error. - // but the post request will fail because of 401. - // - // for the private repo, we should remove mount-from - // query and send the request again. - resp, err = preq.doWithRetries(pctx, nil) - if err != nil { - return nil, err - } - - switch resp.StatusCode { - case http.StatusUnauthorized: - log.G(ctx).Debugf("failed to mount from repository %s", fromRepo) - - resp.Body.Close() - resp = nil - case http.StatusCreated: - mountedFrom = path.Join(p.refspec.Hostname(), fromRepo) - } - } - - if resp == nil { - resp, err = req.doWithRetries(ctx, nil) - if err != nil { - if errors.Is(err, ErrInvalidAuthorization) { - return nil, fmt.Errorf("push access denied, repository does not exist or may require authorization: %w", err) - } - return nil, err - } - } - defer resp.Body.Close() - - switch resp.StatusCode { - case http.StatusOK, http.StatusAccepted, http.StatusNoContent: - case http.StatusCreated: - p.tracker.SetStatus(ref, Status{ - Committed: true, - PushStatus: PushStatus{ - MountedFrom: mountedFrom, - }, - Status: content.Status{ - Ref: ref, - Total: desc.Size, - Offset: desc.Size, - }, - }) - return nil, fmt.Errorf("content %v on remote: %w", desc.Digest, errdefs.ErrAlreadyExists) - default: - err := remoteserrors.NewUnexpectedStatusErr(resp) - log.G(ctx).WithField("resp", resp).WithField("body", string(err.(remoteserrors.ErrUnexpectedStatus).Body)).Debug("unexpected response") - return nil, err - } - - var ( - location = resp.Header.Get("Location") - lurl *url.URL - lhost = host - ) - // Support paths without host in location - if strings.HasPrefix(location, "/") { - lurl, err = url.Parse(lhost.Scheme + "://" + lhost.Host + location) - if err != nil { - return nil, fmt.Errorf("unable to parse location %v: %w", location, err) - } - } else { - if !strings.Contains(location, "://") { - location = lhost.Scheme + "://" + location - } - lurl, err = url.Parse(location) - if err != nil { - return nil, fmt.Errorf("unable to parse location %v: %w", location, err) - } - - if lurl.Host != lhost.Host || lhost.Scheme != lurl.Scheme { - lhost.Scheme = lurl.Scheme - lhost.Host = lurl.Host - - // Check if different than what was requested, accounting for fallback in the transport layer - requested := resp.Request.URL - if requested.Host != lhost.Host || requested.Scheme != lhost.Scheme { - // Strip authorizer if change to host or scheme - lhost.Authorizer = nil - log.G(ctx).WithField("host", lhost.Host).WithField("scheme", lhost.Scheme).Debug("upload changed destination, authorizer removed") - } - } - } - q := lurl.Query() - q.Add("digest", desc.Digest.String()) - - req = p.request(lhost, http.MethodPut) - req.header.Set("Content-Type", "application/octet-stream") - req.path = lurl.Path + "?" + q.Encode() - } - p.tracker.SetStatus(ref, Status{ - Status: content.Status{ - Ref: ref, - Total: desc.Size, - Expected: desc.Digest, - StartedAt: time.Now(), - }, - }) - - // TODO: Support chunked upload - - pushw := newPushWriter(p.dockerBase, ref, desc.Digest, p.tracker, isManifest) - - req.body = func() (io.ReadCloser, error) { - pr, pw := io.Pipe() - pushw.setPipe(pw) - return io.NopCloser(pr), nil - } - req.size = desc.Size - - go func() { - resp, err := req.doWithRetries(ctx, nil) - if err != nil { - pushw.setError(err) - pushw.Close() - return - } - - switch resp.StatusCode { - case http.StatusOK, http.StatusCreated, http.StatusNoContent: - default: - err := remoteserrors.NewUnexpectedStatusErr(resp) - log.G(ctx).WithField("resp", resp).WithField("body", string(err.(remoteserrors.ErrUnexpectedStatus).Body)).Debug("unexpected response") - pushw.setError(err) - pushw.Close() - } - pushw.setResponse(resp) - }() - - return pushw, nil -} - -func getManifestPath(object string, dgst digest.Digest) []string { - if i := strings.IndexByte(object, '@'); i >= 0 { - if object[i+1:] != dgst.String() { - // use digest, not tag - object = "" - } else { - // strip @ for registry path to make tag - object = object[:i] - } - - } - - if object == "" { - return []string{"manifests", dgst.String()} - } - - return []string{"manifests", object} -} - -type pushWriter struct { - base *dockerBase - ref string - - pipe *io.PipeWriter - - pipeC chan *io.PipeWriter - respC chan *http.Response - closeOnce sync.Once - errC chan error - - isManifest bool - - expected digest.Digest - tracker StatusTracker -} - -func newPushWriter(db *dockerBase, ref string, expected digest.Digest, tracker StatusTracker, isManifest bool) *pushWriter { - // Initialize and create response - return &pushWriter{ - base: db, - ref: ref, - expected: expected, - tracker: tracker, - pipeC: make(chan *io.PipeWriter, 1), - respC: make(chan *http.Response, 1), - errC: make(chan error, 1), - isManifest: isManifest, - } -} - -func (pw *pushWriter) setPipe(p *io.PipeWriter) { - pw.pipeC <- p -} - -func (pw *pushWriter) setError(err error) { - pw.errC <- err -} -func (pw *pushWriter) setResponse(resp *http.Response) { - pw.respC <- resp -} - -func (pw *pushWriter) Write(p []byte) (n int, err error) { - status, err := pw.tracker.GetStatus(pw.ref) - if err != nil { - return n, err - } - - if pw.pipe == nil { - p, ok := <-pw.pipeC - if !ok { - return 0, io.ErrClosedPipe - } - pw.pipe = p - } else { - select { - case p, ok := <-pw.pipeC: - if !ok { - return 0, io.ErrClosedPipe - } - pw.pipe.CloseWithError(content.ErrReset) - pw.pipe = p - - // If content has already been written, the bytes - // cannot be written and the caller must reset - status.Offset = 0 - status.UpdatedAt = time.Now() - pw.tracker.SetStatus(pw.ref, status) - return 0, content.ErrReset - default: - } - } - - n, err = pw.pipe.Write(p) - if errors.Is(err, io.ErrClosedPipe) { - // if the pipe is closed, we might have the original error on the error - // channel - so we should try and get it - select { - case err2 := <-pw.errC: - err = err2 - default: - } - } - status.Offset += int64(n) - status.UpdatedAt = time.Now() - pw.tracker.SetStatus(pw.ref, status) - return -} - -func (pw *pushWriter) Close() error { - // Ensure pipeC is closed but handle `Close()` being - // called multiple times without panicking - pw.closeOnce.Do(func() { - close(pw.pipeC) - }) - if pw.pipe != nil { - status, err := pw.tracker.GetStatus(pw.ref) - if err == nil && !status.Committed { - // Closing an incomplete writer. Record this as an error so that following write can retry it. - status.ErrClosed = errors.New("closed incomplete writer") - pw.tracker.SetStatus(pw.ref, status) - } - return pw.pipe.Close() - } - return nil -} - -func (pw *pushWriter) Status() (content.Status, error) { - status, err := pw.tracker.GetStatus(pw.ref) - if err != nil { - return content.Status{}, err - } - return status.Status, nil - -} - -func (pw *pushWriter) Digest() digest.Digest { - // TODO: Get rid of this function? - return pw.expected -} - -func (pw *pushWriter) Commit(ctx context.Context, size int64, expected digest.Digest, opts ...content.Opt) error { - // Check whether read has already thrown an error - if _, err := pw.pipe.Write([]byte{}); err != nil && !errors.Is(err, io.ErrClosedPipe) { - return fmt.Errorf("pipe error before commit: %w", err) - } - - if err := pw.pipe.Close(); err != nil { - return err - } - // TODO: timeout waiting for response - var resp *http.Response - select { - case err := <-pw.errC: - return err - case resp = <-pw.respC: - defer resp.Body.Close() - case p, ok := <-pw.pipeC: - // check whether the pipe has changed in the commit, because sometimes Write - // can complete successfully, but the pipe may have changed. In that case, the - // content needs to be reset. - if !ok { - return io.ErrClosedPipe - } - pw.pipe.CloseWithError(content.ErrReset) - pw.pipe = p - - // If content has already been written, the bytes - // cannot be written again and the caller must reset - status, err := pw.tracker.GetStatus(pw.ref) - if err != nil { - return err - } - status.Offset = 0 - status.UpdatedAt = time.Now() - pw.tracker.SetStatus(pw.ref, status) - return content.ErrReset - } - - // 201 is specified return status, some registries return - // 200, 202 or 204. - switch resp.StatusCode { - case http.StatusOK, http.StatusCreated, http.StatusNoContent, http.StatusAccepted: - default: - return remoteserrors.NewUnexpectedStatusErr(resp) - } - - status, err := pw.tracker.GetStatus(pw.ref) - if err != nil { - return fmt.Errorf("failed to get status: %w", err) - } - - if size > 0 && size != status.Offset { - return fmt.Errorf("unexpected size %d, expected %d", status.Offset, size) - } - - if expected == "" { - expected = status.Expected - } - - actual, err := digest.Parse(resp.Header.Get("Docker-Content-Digest")) - if err != nil { - return fmt.Errorf("invalid content digest in response: %w", err) - } - - if actual != expected { - return fmt.Errorf("got digest %s, expected %s", actual, expected) - } - - status.Committed = true - status.UpdatedAt = time.Now() - pw.tracker.SetStatus(pw.ref, status) - - return nil -} - -func (pw *pushWriter) Truncate(size int64) error { - // TODO: if blob close request and start new request at offset - // TODO: always error on manifest - return errors.New("cannot truncate remote upload") -} - -func requestWithMountFrom(req *request, mount, from string) *request { - creq := *req - - sep := "?" - if strings.Contains(creq.path, sep) { - sep = "&" - } - - creq.path = creq.path + sep + "mount=" + mount + "&from=" + from - - return &creq -} diff --git a/vendor/github.com/containerd/containerd/remotes/docker/registry.go b/vendor/github.com/containerd/containerd/remotes/docker/registry.go deleted file mode 100644 index 98cafcd06..000000000 --- a/vendor/github.com/containerd/containerd/remotes/docker/registry.go +++ /dev/null @@ -1,244 +0,0 @@ -/* - Copyright The containerd 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 docker - -import ( - "errors" - "net" - "net/http" -) - -// HostCapabilities represent the capabilities of the registry -// host. This also represents the set of operations for which -// the registry host may be trusted to perform. -// -// For example pushing is a capability which should only be -// performed on an upstream source, not a mirror. -// Resolving (the process of converting a name into a digest) -// must be considered a trusted operation and only done by -// a host which is trusted (or more preferably by secure process -// which can prove the provenance of the mapping). A public -// mirror should never be trusted to do a resolve action. -// -// | Registry Type | Pull | Resolve | Push | -// |------------------|------|---------|------| -// | Public Registry | yes | yes | yes | -// | Private Registry | yes | yes | yes | -// | Public Mirror | yes | no | no | -// | Private Mirror | yes | yes | no | -type HostCapabilities uint8 - -const ( - // HostCapabilityPull represents the capability to fetch manifests - // and blobs by digest - HostCapabilityPull HostCapabilities = 1 << iota - - // HostCapabilityResolve represents the capability to fetch manifests - // by name - HostCapabilityResolve - - // HostCapabilityPush represents the capability to push blobs and - // manifests - HostCapabilityPush - - // Reserved for future capabilities (i.e. search, catalog, remove) -) - -// Has checks whether the capabilities list has the provide capability -func (c HostCapabilities) Has(t HostCapabilities) bool { - return c&t == t -} - -// RegistryHost represents a complete configuration for a registry -// host, representing the capabilities, authorizations, connection -// configuration, and location. -type RegistryHost struct { - Client *http.Client - Authorizer Authorizer - Host string - Scheme string - Path string - Capabilities HostCapabilities - Header http.Header -} - -func (h RegistryHost) isProxy(refhost string) bool { - if refhost != h.Host { - if refhost != "docker.io" || h.Host != "registry-1.docker.io" { - return true - } - } - return false -} - -// RegistryHosts fetches the registry hosts for a given namespace, -// provided by the host component of an distribution image reference. -type RegistryHosts func(string) ([]RegistryHost, error) - -// Registries joins multiple registry configuration functions, using the same -// order as provided within the arguments. When an empty registry configuration -// is returned with a nil error, the next function will be called. -// NOTE: This function will not join configurations, as soon as a non-empty -// configuration is returned from a configuration function, it will be returned -// to the caller. -func Registries(registries ...RegistryHosts) RegistryHosts { - return func(host string) ([]RegistryHost, error) { - for _, registry := range registries { - config, err := registry(host) - if err != nil { - return config, err - } - if len(config) > 0 { - return config, nil - } - } - return nil, nil - } -} - -type registryOpts struct { - authorizer Authorizer - plainHTTP func(string) (bool, error) - host func(string) (string, error) - client *http.Client -} - -// RegistryOpt defines a registry default option -type RegistryOpt func(*registryOpts) - -// WithPlainHTTP configures registries to use plaintext http scheme -// for the provided host match function. -func WithPlainHTTP(f func(string) (bool, error)) RegistryOpt { - return func(opts *registryOpts) { - opts.plainHTTP = f - } -} - -// WithAuthorizer configures the default authorizer for a registry -func WithAuthorizer(a Authorizer) RegistryOpt { - return func(opts *registryOpts) { - opts.authorizer = a - } -} - -// WithHostTranslator defines the default translator to use for registry hosts -func WithHostTranslator(h func(string) (string, error)) RegistryOpt { - return func(opts *registryOpts) { - opts.host = h - } -} - -// WithClient configures the default http client for a registry -func WithClient(c *http.Client) RegistryOpt { - return func(opts *registryOpts) { - opts.client = c - } -} - -// ConfigureDefaultRegistries is used to create a default configuration for -// registries. For more advanced configurations or per-domain setups, -// the RegistryHosts interface should be used directly. -// NOTE: This function will always return a non-empty value or error -func ConfigureDefaultRegistries(ropts ...RegistryOpt) RegistryHosts { - var opts registryOpts - for _, opt := range ropts { - opt(&opts) - } - - return func(host string) ([]RegistryHost, error) { - config := RegistryHost{ - Client: opts.client, - Authorizer: opts.authorizer, - Host: host, - Scheme: "https", - Path: "/v2", - Capabilities: HostCapabilityPull | HostCapabilityResolve | HostCapabilityPush, - } - - if config.Client == nil { - config.Client = http.DefaultClient - } - - if opts.plainHTTP != nil { - match, err := opts.plainHTTP(host) - if err != nil { - return nil, err - } - if match { - config.Scheme = "http" - } - } - - if opts.host != nil { - var err error - config.Host, err = opts.host(config.Host) - if err != nil { - return nil, err - } - } else if host == "docker.io" { - config.Host = "registry-1.docker.io" - } - - return []RegistryHost{config}, nil - } -} - -// MatchAllHosts is a host match function which is always true. -func MatchAllHosts(string) (bool, error) { - return true, nil -} - -// MatchLocalhost is a host match function which returns true for -// localhost. -// -// Note: this does not handle matching of ip addresses in octal, -// decimal or hex form. -func MatchLocalhost(host string) (bool, error) { - switch { - case host == "::1": - return true, nil - case host == "[::1]": - return true, nil - } - h, p, err := net.SplitHostPort(host) - - // addrError helps distinguish between errors of form - // "no colon in address" and "too many colons in address". - // The former is fine as the host string need not have a - // port. Latter needs to be handled. - addrError := &net.AddrError{ - Err: "missing port in address", - Addr: host, - } - if err != nil { - if err.Error() != addrError.Error() { - return false, err - } - // host string without any port specified - h = host - } else if len(p) == 0 { - return false, errors.New("invalid host name format") - } - - // use ipv4 dotted decimal for further checking - if h == "localhost" { - h = "127.0.0.1" - } - ip := net.ParseIP(h) - - return ip.IsLoopback(), nil -} diff --git a/vendor/github.com/containerd/containerd/remotes/docker/resolver.go b/vendor/github.com/containerd/containerd/remotes/docker/resolver.go deleted file mode 100644 index cca4ca6a2..000000000 --- a/vendor/github.com/containerd/containerd/remotes/docker/resolver.go +++ /dev/null @@ -1,729 +0,0 @@ -/* - Copyright The containerd 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 docker - -import ( - "context" - "crypto/tls" - "errors" - "fmt" - "io" - "net" - "net/http" - "net/url" - "path" - "strings" - - "github.com/containerd/containerd/errdefs" - "github.com/containerd/containerd/images" - "github.com/containerd/containerd/log" - "github.com/containerd/containerd/reference" - "github.com/containerd/containerd/remotes" - "github.com/containerd/containerd/remotes/docker/schema1" //nolint:staticcheck // Ignore SA1019. Need to keep deprecated package for compatibility. - remoteerrors "github.com/containerd/containerd/remotes/errors" - "github.com/containerd/containerd/tracing" - "github.com/containerd/containerd/version" - "github.com/opencontainers/go-digest" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" -) - -var ( - // ErrInvalidAuthorization is used when credentials are passed to a server but - // those credentials are rejected. - ErrInvalidAuthorization = errors.New("authorization failed") - - // MaxManifestSize represents the largest size accepted from a registry - // during resolution. Larger manifests may be accepted using a - // resolution method other than the registry. - // - // NOTE: The max supported layers by some runtimes is 128 and individual - // layers will not contribute more than 256 bytes, making a - // reasonable limit for a large image manifests of 32K bytes. - // 4M bytes represents a much larger upper bound for images which may - // contain large annotations or be non-images. A proper manifest - // design puts large metadata in subobjects, as is consistent the - // intent of the manifest design. - MaxManifestSize int64 = 4 * 1048 * 1048 -) - -// Authorizer is used to authorize HTTP requests based on 401 HTTP responses. -// An Authorizer is responsible for caching tokens or credentials used by -// requests. -type Authorizer interface { - // Authorize sets the appropriate `Authorization` header on the given - // request. - // - // If no authorization is found for the request, the request remains - // unmodified. It may also add an `Authorization` header as - // "bearer " - // "basic " - // - // It may return remotes/errors.ErrUnexpectedStatus, which for example, - // can be used by the caller to find out the status code returned by the registry. - Authorize(context.Context, *http.Request) error - - // AddResponses adds a 401 response for the authorizer to consider when - // authorizing requests. The last response should be unauthorized and - // the previous requests are used to consider redirects and retries - // that may have led to the 401. - // - // If response is not handled, returns `ErrNotImplemented` - AddResponses(context.Context, []*http.Response) error -} - -// ResolverOptions are used to configured a new Docker register resolver -type ResolverOptions struct { - // Hosts returns registry host configurations for a namespace. - Hosts RegistryHosts - - // Headers are the HTTP request header fields sent by the resolver - Headers http.Header - - // Tracker is used to track uploads to the registry. This is used - // since the registry does not have upload tracking and the existing - // mechanism for getting blob upload status is expensive. - Tracker StatusTracker - - // Authorizer is used to authorize registry requests - // - // Deprecated: use Hosts. - Authorizer Authorizer - - // Credentials provides username and secret given a host. - // If username is empty but a secret is given, that secret - // is interpreted as a long lived token. - // - // Deprecated: use Hosts. - Credentials func(string) (string, string, error) - - // Host provides the hostname given a namespace. - // - // Deprecated: use Hosts. - Host func(string) (string, error) - - // PlainHTTP specifies to use plain http and not https - // - // Deprecated: use Hosts. - PlainHTTP bool - - // Client is the http client to used when making registry requests - // - // Deprecated: use Hosts. - Client *http.Client -} - -// DefaultHost is the default host function. -func DefaultHost(ns string) (string, error) { - if ns == "docker.io" { - return "registry-1.docker.io", nil - } - return ns, nil -} - -type dockerResolver struct { - hosts RegistryHosts - header http.Header - resolveHeader http.Header - tracker StatusTracker -} - -// NewResolver returns a new resolver to a Docker registry -func NewResolver(options ResolverOptions) remotes.Resolver { - if options.Tracker == nil { - options.Tracker = NewInMemoryTracker() - } - - if options.Headers == nil { - options.Headers = make(http.Header) - } else { - // make a copy of the headers to avoid race due to concurrent map write - options.Headers = options.Headers.Clone() - } - if _, ok := options.Headers["User-Agent"]; !ok { - options.Headers.Set("User-Agent", "containerd/"+version.Version) - } - - resolveHeader := http.Header{} - if _, ok := options.Headers["Accept"]; !ok { - // set headers for all the types we support for resolution. - resolveHeader.Set("Accept", strings.Join([]string{ - images.MediaTypeDockerSchema2Manifest, - images.MediaTypeDockerSchema2ManifestList, - ocispec.MediaTypeImageManifest, - ocispec.MediaTypeImageIndex, "*/*", - }, ", ")) - } else { - resolveHeader["Accept"] = options.Headers["Accept"] - delete(options.Headers, "Accept") - } - - if options.Hosts == nil { - opts := []RegistryOpt{} - if options.Host != nil { - opts = append(opts, WithHostTranslator(options.Host)) - } - - if options.Authorizer == nil { - options.Authorizer = NewDockerAuthorizer( - WithAuthClient(options.Client), - WithAuthHeader(options.Headers), - WithAuthCreds(options.Credentials)) - } - opts = append(opts, WithAuthorizer(options.Authorizer)) - - if options.Client != nil { - opts = append(opts, WithClient(options.Client)) - } - if options.PlainHTTP { - opts = append(opts, WithPlainHTTP(MatchAllHosts)) - } else { - opts = append(opts, WithPlainHTTP(MatchLocalhost)) - } - options.Hosts = ConfigureDefaultRegistries(opts...) - } - return &dockerResolver{ - hosts: options.Hosts, - header: options.Headers, - resolveHeader: resolveHeader, - tracker: options.Tracker, - } -} - -func getManifestMediaType(resp *http.Response) string { - // Strip encoding data (manifests should always be ascii JSON) - contentType := resp.Header.Get("Content-Type") - if sp := strings.IndexByte(contentType, ';'); sp != -1 { - contentType = contentType[0:sp] - } - - // As of Apr 30 2019 the registry.access.redhat.com registry does not specify - // the content type of any data but uses schema1 manifests. - if contentType == "text/plain" { - contentType = images.MediaTypeDockerSchema1Manifest - } - return contentType -} - -type countingReader struct { - reader io.Reader - bytesRead int64 -} - -func (r *countingReader) Read(p []byte) (int, error) { - n, err := r.reader.Read(p) - r.bytesRead += int64(n) - return n, err -} - -var _ remotes.Resolver = &dockerResolver{} - -func (r *dockerResolver) Resolve(ctx context.Context, ref string) (string, ocispec.Descriptor, error) { - base, err := r.resolveDockerBase(ref) - if err != nil { - return "", ocispec.Descriptor{}, err - } - refspec := base.refspec - if refspec.Object == "" { - return "", ocispec.Descriptor{}, reference.ErrObjectRequired - } - - var ( - firstErr error - paths [][]string - dgst = refspec.Digest() - caps = HostCapabilityPull - ) - - if dgst != "" { - if err := dgst.Validate(); err != nil { - // need to fail here, since we can't actually resolve the invalid - // digest. - return "", ocispec.Descriptor{}, err - } - - // turns out, we have a valid digest, make a url. - paths = append(paths, []string{"manifests", dgst.String()}) - - // fallback to blobs on not found. - paths = append(paths, []string{"blobs", dgst.String()}) - } else { - // Add - paths = append(paths, []string{"manifests", refspec.Object}) - caps |= HostCapabilityResolve - } - - hosts := base.filterHosts(caps) - if len(hosts) == 0 { - return "", ocispec.Descriptor{}, fmt.Errorf("no resolve hosts: %w", errdefs.ErrNotFound) - } - - ctx, err = ContextWithRepositoryScope(ctx, refspec, false) - if err != nil { - return "", ocispec.Descriptor{}, err - } - - for _, u := range paths { - for _, host := range hosts { - ctx := log.WithLogger(ctx, log.G(ctx).WithField("host", host.Host)) - - req := base.request(host, http.MethodHead, u...) - if err := req.addNamespace(base.refspec.Hostname()); err != nil { - return "", ocispec.Descriptor{}, err - } - - for key, value := range r.resolveHeader { - req.header[key] = append(req.header[key], value...) - } - - log.G(ctx).Debug("resolving") - resp, err := req.doWithRetries(ctx, nil) - if err != nil { - if errors.Is(err, ErrInvalidAuthorization) { - err = fmt.Errorf("pull access denied, repository does not exist or may require authorization: %w", err) - } - // Store the error for referencing later - if firstErr == nil { - firstErr = err - } - log.G(ctx).WithError(err).Info("trying next host") - continue // try another host - } - resp.Body.Close() // don't care about body contents. - - if resp.StatusCode > 299 { - if resp.StatusCode == http.StatusNotFound { - log.G(ctx).Info("trying next host - response was http.StatusNotFound") - continue - } - if resp.StatusCode > 399 { - // Set firstErr when encountering the first non-404 status code. - if firstErr == nil { - firstErr = remoteerrors.NewUnexpectedStatusErr(resp) - } - continue // try another host - } - return "", ocispec.Descriptor{}, remoteerrors.NewUnexpectedStatusErr(resp) - } - size := resp.ContentLength - contentType := getManifestMediaType(resp) - - // if no digest was provided, then only a resolve - // trusted registry was contacted, in this case use - // the digest header (or content from GET) - if dgst == "" { - // this is the only point at which we trust the registry. we use the - // content headers to assemble a descriptor for the name. when this becomes - // more robust, we mostly get this information from a secure trust store. - dgstHeader := digest.Digest(resp.Header.Get("Docker-Content-Digest")) - - if dgstHeader != "" && size != -1 { - if err := dgstHeader.Validate(); err != nil { - return "", ocispec.Descriptor{}, fmt.Errorf("%q in header not a valid digest: %w", dgstHeader, err) - } - dgst = dgstHeader - } - } - if dgst == "" || size == -1 { - log.G(ctx).Debug("no Docker-Content-Digest header, fetching manifest instead") - - req = base.request(host, http.MethodGet, u...) - if err := req.addNamespace(base.refspec.Hostname()); err != nil { - return "", ocispec.Descriptor{}, err - } - - for key, value := range r.resolveHeader { - req.header[key] = append(req.header[key], value...) - } - - resp, err := req.doWithRetries(ctx, nil) - if err != nil { - return "", ocispec.Descriptor{}, err - } - - bodyReader := countingReader{reader: resp.Body} - - contentType = getManifestMediaType(resp) - err = func() error { - defer resp.Body.Close() - if dgst != "" { - _, err = io.Copy(io.Discard, &bodyReader) - return err - } - - if contentType == images.MediaTypeDockerSchema1Manifest { - b, err := schema1.ReadStripSignature(&bodyReader) - if err != nil { - return err - } - - dgst = digest.FromBytes(b) - return nil - } - - dgst, err = digest.FromReader(&bodyReader) - return err - }() - if err != nil { - return "", ocispec.Descriptor{}, err - } - size = bodyReader.bytesRead - } - // Prevent resolving to excessively large manifests - if size > MaxManifestSize { - if firstErr == nil { - firstErr = fmt.Errorf("rejecting %d byte manifest for %s: %w", size, ref, errdefs.ErrNotFound) - } - continue - } - - desc := ocispec.Descriptor{ - Digest: dgst, - MediaType: contentType, - Size: size, - } - - log.G(ctx).WithField("desc.digest", desc.Digest).Debug("resolved") - return ref, desc, nil - } - } - - // If above loop terminates without return, then there was an error. - // "firstErr" contains the first non-404 error. That is, "firstErr == nil" - // means that either no registries were given or each registry returned 404. - - if firstErr == nil { - firstErr = fmt.Errorf("%s: %w", ref, errdefs.ErrNotFound) - } - - return "", ocispec.Descriptor{}, firstErr -} - -func (r *dockerResolver) Fetcher(ctx context.Context, ref string) (remotes.Fetcher, error) { - base, err := r.resolveDockerBase(ref) - if err != nil { - return nil, err - } - - return dockerFetcher{ - dockerBase: base, - }, nil -} - -func (r *dockerResolver) Pusher(ctx context.Context, ref string) (remotes.Pusher, error) { - base, err := r.resolveDockerBase(ref) - if err != nil { - return nil, err - } - - return dockerPusher{ - dockerBase: base, - object: base.refspec.Object, - tracker: r.tracker, - }, nil -} - -func (r *dockerResolver) resolveDockerBase(ref string) (*dockerBase, error) { - refspec, err := reference.Parse(ref) - if err != nil { - return nil, err - } - - return r.base(refspec) -} - -type dockerBase struct { - refspec reference.Spec - repository string - hosts []RegistryHost - header http.Header -} - -func (r *dockerResolver) base(refspec reference.Spec) (*dockerBase, error) { - host := refspec.Hostname() - hosts, err := r.hosts(host) - if err != nil { - return nil, err - } - return &dockerBase{ - refspec: refspec, - repository: strings.TrimPrefix(refspec.Locator, host+"/"), - hosts: hosts, - header: r.header, - }, nil -} - -func (r *dockerBase) filterHosts(caps HostCapabilities) (hosts []RegistryHost) { - for _, host := range r.hosts { - if host.Capabilities.Has(caps) { - hosts = append(hosts, host) - } - } - return -} - -func (r *dockerBase) request(host RegistryHost, method string, ps ...string) *request { - header := r.header.Clone() - if header == nil { - header = http.Header{} - } - - for key, value := range host.Header { - header[key] = append(header[key], value...) - } - parts := append([]string{"/", host.Path, r.repository}, ps...) - p := path.Join(parts...) - // Join strips trailing slash, re-add ending "/" if included - if len(parts) > 0 && strings.HasSuffix(parts[len(parts)-1], "/") { - p = p + "/" - } - return &request{ - method: method, - path: p, - header: header, - host: host, - } -} - -func (r *request) authorize(ctx context.Context, req *http.Request) error { - // Check if has header for host - if r.host.Authorizer != nil { - if err := r.host.Authorizer.Authorize(ctx, req); err != nil { - return err - } - } - - return nil -} - -func (r *request) addNamespace(ns string) (err error) { - if !r.host.isProxy(ns) { - return nil - } - var q url.Values - // Parse query - if i := strings.IndexByte(r.path, '?'); i > 0 { - r.path = r.path[:i+1] - q, err = url.ParseQuery(r.path[i+1:]) - if err != nil { - return - } - } else { - r.path = r.path + "?" - q = url.Values{} - } - q.Add("ns", ns) - - r.path = r.path + q.Encode() - - return -} - -type request struct { - method string - path string - header http.Header - host RegistryHost - body func() (io.ReadCloser, error) - size int64 -} - -func (r *request) do(ctx context.Context) (*http.Response, error) { - u := r.host.Scheme + "://" + r.host.Host + r.path - req, err := http.NewRequestWithContext(ctx, r.method, u, nil) - if err != nil { - return nil, err - } - if r.header == nil { - req.Header = http.Header{} - } else { - req.Header = r.header.Clone() // headers need to be copied to avoid concurrent map access - } - if r.body != nil { - body, err := r.body() - if err != nil { - return nil, err - } - req.Body = body - req.GetBody = r.body - if r.size > 0 { - req.ContentLength = r.size - } - } - - ctx = log.WithLogger(ctx, log.G(ctx).WithField("url", u)) - log.G(ctx).WithFields(requestFields(req)).Debug("do request") - if err := r.authorize(ctx, req); err != nil { - return nil, fmt.Errorf("failed to authorize: %w", err) - } - - client := &http.Client{} - if r.host.Client != nil { - *client = *r.host.Client - } - if client.CheckRedirect == nil { - client.CheckRedirect = func(req *http.Request, via []*http.Request) error { - if len(via) >= 10 { - return errors.New("stopped after 10 redirects") - } - if err := r.authorize(ctx, req); err != nil { - return fmt.Errorf("failed to authorize redirect: %w", err) - } - return nil - } - } - - tracing.UpdateHTTPClient(client, tracing.Name("remotes.docker.resolver", "HTTPRequest")) - - resp, err := client.Do(req) - if err != nil { - return nil, fmt.Errorf("failed to do request: %w", err) - } - log.G(ctx).WithFields(responseFields(resp)).Debug("fetch response received") - return resp, nil -} - -func (r *request) doWithRetries(ctx context.Context, responses []*http.Response) (*http.Response, error) { - resp, err := r.do(ctx) - if err != nil { - return nil, err - } - - responses = append(responses, resp) - retry, err := r.retryRequest(ctx, responses) - if err != nil { - resp.Body.Close() - return nil, err - } - if retry { - resp.Body.Close() - return r.doWithRetries(ctx, responses) - } - return resp, err -} - -func (r *request) retryRequest(ctx context.Context, responses []*http.Response) (bool, error) { - if len(responses) > 5 { - return false, nil - } - last := responses[len(responses)-1] - switch last.StatusCode { - case http.StatusUnauthorized: - log.G(ctx).WithField("header", last.Header.Get("WWW-Authenticate")).Debug("Unauthorized") - if r.host.Authorizer != nil { - if err := r.host.Authorizer.AddResponses(ctx, responses); err == nil { - return true, nil - } else if !errdefs.IsNotImplemented(err) { - return false, err - } - } - - return false, nil - case http.StatusMethodNotAllowed: - // Support registries which have not properly implemented the HEAD method for - // manifests endpoint - if r.method == http.MethodHead && strings.Contains(r.path, "/manifests/") { - r.method = http.MethodGet - return true, nil - } - case http.StatusRequestTimeout, http.StatusTooManyRequests: - return true, nil - } - - // TODO: Handle 50x errors accounting for attempt history - return false, nil -} - -func (r *request) String() string { - return r.host.Scheme + "://" + r.host.Host + r.path -} - -func requestFields(req *http.Request) log.Fields { - fields := map[string]interface{}{ - "request.method": req.Method, - } - for k, vals := range req.Header { - k = strings.ToLower(k) - if k == "authorization" { - continue - } - for i, v := range vals { - field := "request.header." + k - if i > 0 { - field = fmt.Sprintf("%s.%d", field, i) - } - fields[field] = v - } - } - - return fields -} - -func responseFields(resp *http.Response) log.Fields { - fields := map[string]interface{}{ - "response.status": resp.Status, - } - for k, vals := range resp.Header { - k = strings.ToLower(k) - for i, v := range vals { - field := "response.header." + k - if i > 0 { - field = fmt.Sprintf("%s.%d", field, i) - } - fields[field] = v - } - } - - return fields -} - -// IsLocalhost checks if the registry host is local. -func IsLocalhost(host string) bool { - if h, _, err := net.SplitHostPort(host); err == nil { - host = h - } - - if host == "localhost" { - return true - } - - ip := net.ParseIP(host) - return ip.IsLoopback() -} - -// HTTPFallback is an http.RoundTripper which allows fallback from https to http -// for registry endpoints with configurations for both http and TLS, such as -// defaulted localhost endpoints. -type HTTPFallback struct { - http.RoundTripper -} - -func (f HTTPFallback) RoundTrip(r *http.Request) (*http.Response, error) { - resp, err := f.RoundTripper.RoundTrip(r) - var tlsErr tls.RecordHeaderError - if errors.As(err, &tlsErr) && string(tlsErr.RecordHeader[:]) == "HTTP/" { - // server gave HTTP response to HTTPS client - plainHTTPUrl := *r.URL - plainHTTPUrl.Scheme = "http" - - plainHTTPRequest := *r - plainHTTPRequest.URL = &plainHTTPUrl - - return f.RoundTripper.RoundTrip(&plainHTTPRequest) - } - - return resp, err -} diff --git a/vendor/github.com/containerd/containerd/remotes/docker/schema1/converter.go b/vendor/github.com/containerd/containerd/remotes/docker/schema1/converter.go deleted file mode 100644 index 8c9e520cd..000000000 --- a/vendor/github.com/containerd/containerd/remotes/docker/schema1/converter.go +++ /dev/null @@ -1,608 +0,0 @@ -/* - Copyright The containerd 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 schema1 provides a converter to fetch an image formatted in Docker Image Manifest v2, Schema 1. -// -// Deprecated: use images formatted in Docker Image Manifest v2, Schema 2, or OCI Image Spec v1. -package schema1 - -import ( - "bytes" - "context" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "io" - "strconv" - "strings" - "sync" - "time" - - "github.com/containerd/containerd/archive/compression" - "github.com/containerd/containerd/content" - "github.com/containerd/containerd/errdefs" - "github.com/containerd/containerd/images" - "github.com/containerd/containerd/labels" - "github.com/containerd/containerd/log" - "github.com/containerd/containerd/remotes" - digest "github.com/opencontainers/go-digest" - specs "github.com/opencontainers/image-spec/specs-go" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" - "golang.org/x/sync/errgroup" -) - -const ( - manifestSizeLimit = 8e6 // 8MB - labelDockerSchema1EmptyLayer = "containerd.io/docker.schema1.empty-layer" -) - -type blobState struct { - diffID digest.Digest - empty bool -} - -// Converter converts schema1 manifests to schema2 on fetch -type Converter struct { - contentStore content.Store - fetcher remotes.Fetcher - - pulledManifest *manifest - - mu sync.Mutex - blobMap map[digest.Digest]blobState - layerBlobs map[digest.Digest]ocispec.Descriptor -} - -// NewConverter returns a new converter -func NewConverter(contentStore content.Store, fetcher remotes.Fetcher) *Converter { - return &Converter{ - contentStore: contentStore, - fetcher: fetcher, - blobMap: map[digest.Digest]blobState{}, - layerBlobs: map[digest.Digest]ocispec.Descriptor{}, - } -} - -// Handle fetching descriptors for a docker media type -func (c *Converter) Handle(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) { - switch desc.MediaType { - case images.MediaTypeDockerSchema1Manifest: - if err := c.fetchManifest(ctx, desc); err != nil { - return nil, err - } - - m := c.pulledManifest - if len(m.FSLayers) != len(m.History) { - return nil, errors.New("invalid schema 1 manifest, history and layer mismatch") - } - descs := make([]ocispec.Descriptor, 0, len(c.pulledManifest.FSLayers)) - - for i := range m.FSLayers { - if _, ok := c.blobMap[c.pulledManifest.FSLayers[i].BlobSum]; !ok { - empty, err := isEmptyLayer([]byte(m.History[i].V1Compatibility)) - if err != nil { - return nil, err - } - - // Do no attempt to download a known empty blob - if !empty { - descs = append([]ocispec.Descriptor{ - { - MediaType: images.MediaTypeDockerSchema2LayerGzip, - Digest: c.pulledManifest.FSLayers[i].BlobSum, - Size: -1, - }, - }, descs...) - } - c.blobMap[c.pulledManifest.FSLayers[i].BlobSum] = blobState{ - empty: empty, - } - } - } - return descs, nil - case images.MediaTypeDockerSchema2LayerGzip: - if c.pulledManifest == nil { - return nil, errors.New("manifest required for schema 1 blob pull") - } - return nil, c.fetchBlob(ctx, desc) - default: - return nil, fmt.Errorf("%v not support for schema 1 manifests", desc.MediaType) - } -} - -// ConvertOptions provides options on converting a docker schema1 manifest. -type ConvertOptions struct { - // ManifestMediaType specifies the media type of the manifest OCI descriptor. - ManifestMediaType string - - // ConfigMediaType specifies the media type of the manifest config OCI - // descriptor. - ConfigMediaType string -} - -// ConvertOpt allows configuring a convert operation. -type ConvertOpt func(context.Context, *ConvertOptions) error - -// UseDockerSchema2 is used to indicate that a schema1 manifest should be -// converted into the media types for a docker schema2 manifest. -func UseDockerSchema2() ConvertOpt { - return func(ctx context.Context, o *ConvertOptions) error { - o.ManifestMediaType = images.MediaTypeDockerSchema2Manifest - o.ConfigMediaType = images.MediaTypeDockerSchema2Config - return nil - } -} - -// Convert a docker manifest to an OCI descriptor -func (c *Converter) Convert(ctx context.Context, opts ...ConvertOpt) (ocispec.Descriptor, error) { - co := ConvertOptions{ - ManifestMediaType: ocispec.MediaTypeImageManifest, - ConfigMediaType: ocispec.MediaTypeImageConfig, - } - for _, opt := range opts { - if err := opt(ctx, &co); err != nil { - return ocispec.Descriptor{}, err - } - } - - history, diffIDs, err := c.schema1ManifestHistory() - if err != nil { - return ocispec.Descriptor{}, fmt.Errorf("schema 1 conversion failed: %w", err) - } - - var img ocispec.Image - if err := json.Unmarshal([]byte(c.pulledManifest.History[0].V1Compatibility), &img); err != nil { - return ocispec.Descriptor{}, fmt.Errorf("failed to unmarshal image from schema 1 history: %w", err) - } - - img.History = history - img.RootFS = ocispec.RootFS{ - Type: "layers", - DiffIDs: diffIDs, - } - - b, err := json.MarshalIndent(img, "", " ") - if err != nil { - return ocispec.Descriptor{}, fmt.Errorf("failed to marshal image: %w", err) - } - - config := ocispec.Descriptor{ - MediaType: co.ConfigMediaType, - Digest: digest.Canonical.FromBytes(b), - Size: int64(len(b)), - } - - layers := make([]ocispec.Descriptor, len(diffIDs)) - for i, diffID := range diffIDs { - layers[i] = c.layerBlobs[diffID] - } - - manifest := ocispec.Manifest{ - Versioned: specs.Versioned{ - SchemaVersion: 2, - }, - Config: config, - Layers: layers, - } - - mb, err := json.MarshalIndent(manifest, "", " ") - if err != nil { - return ocispec.Descriptor{}, fmt.Errorf("failed to marshal image: %w", err) - } - - desc := ocispec.Descriptor{ - MediaType: co.ManifestMediaType, - Digest: digest.Canonical.FromBytes(mb), - Size: int64(len(mb)), - } - - labels := map[string]string{} - labels["containerd.io/gc.ref.content.0"] = manifest.Config.Digest.String() - for i, ch := range manifest.Layers { - labels[fmt.Sprintf("containerd.io/gc.ref.content.%d", i+1)] = ch.Digest.String() - } - - ref := remotes.MakeRefKey(ctx, desc) - if err := content.WriteBlob(ctx, c.contentStore, ref, bytes.NewReader(mb), desc, content.WithLabels(labels)); err != nil { - return ocispec.Descriptor{}, fmt.Errorf("failed to write image manifest: %w", err) - } - - ref = remotes.MakeRefKey(ctx, config) - if err := content.WriteBlob(ctx, c.contentStore, ref, bytes.NewReader(b), config); err != nil { - return ocispec.Descriptor{}, fmt.Errorf("failed to write image config: %w", err) - } - - return desc, nil -} - -// ReadStripSignature reads in a schema1 manifest and returns a byte array -// with the "signatures" field stripped -func ReadStripSignature(schema1Blob io.Reader) ([]byte, error) { - b, err := io.ReadAll(io.LimitReader(schema1Blob, manifestSizeLimit)) // limit to 8MB - if err != nil { - return nil, err - } - - return stripSignature(b) -} - -func (c *Converter) fetchManifest(ctx context.Context, desc ocispec.Descriptor) error { - log.G(ctx).Debug("fetch schema 1") - - rc, err := c.fetcher.Fetch(ctx, desc) - if err != nil { - return err - } - - b, err := ReadStripSignature(rc) - rc.Close() - if err != nil { - return err - } - - var m manifest - if err := json.Unmarshal(b, &m); err != nil { - return err - } - if len(m.Manifests) != 0 || len(m.Layers) != 0 { - return errors.New("converter: expected schema1 document but found extra keys") - } - c.pulledManifest = &m - - return nil -} - -func (c *Converter) fetchBlob(ctx context.Context, desc ocispec.Descriptor) error { - log.G(ctx).Debug("fetch blob") - - var ( - ref = remotes.MakeRefKey(ctx, desc) - calc = newBlobStateCalculator() - compressMethod = compression.Gzip - ) - - // size may be unknown, set to zero for content ingest - ingestDesc := desc - if ingestDesc.Size == -1 { - ingestDesc.Size = 0 - } - - cw, err := content.OpenWriter(ctx, c.contentStore, content.WithRef(ref), content.WithDescriptor(ingestDesc)) - if err != nil { - if !errdefs.IsAlreadyExists(err) { - return err - } - - reuse, err := c.reuseLabelBlobState(ctx, desc) - if err != nil { - return err - } - - if reuse { - return nil - } - - ra, err := c.contentStore.ReaderAt(ctx, desc) - if err != nil { - return err - } - defer ra.Close() - - r, err := compression.DecompressStream(content.NewReader(ra)) - if err != nil { - return err - } - - compressMethod = r.GetCompression() - _, err = io.Copy(calc, r) - r.Close() - if err != nil { - return err - } - } else { - defer cw.Close() - - rc, err := c.fetcher.Fetch(ctx, desc) - if err != nil { - return err - } - defer rc.Close() - - eg, _ := errgroup.WithContext(ctx) - pr, pw := io.Pipe() - - eg.Go(func() error { - r, err := compression.DecompressStream(pr) - if err != nil { - return err - } - - compressMethod = r.GetCompression() - _, err = io.Copy(calc, r) - r.Close() - pr.CloseWithError(err) - return err - }) - - eg.Go(func() error { - defer pw.Close() - - return content.Copy(ctx, cw, io.TeeReader(rc, pw), ingestDesc.Size, ingestDesc.Digest) - }) - - if err := eg.Wait(); err != nil { - return err - } - } - - if desc.Size == -1 { - info, err := c.contentStore.Info(ctx, desc.Digest) - if err != nil { - return fmt.Errorf("failed to get blob info: %w", err) - } - desc.Size = info.Size - } - - if compressMethod == compression.Uncompressed { - log.G(ctx).WithField("id", desc.Digest).Debugf("changed media type for uncompressed schema1 layer blob") - desc.MediaType = images.MediaTypeDockerSchema2Layer - } - - state := calc.State() - - cinfo := content.Info{ - Digest: desc.Digest, - Labels: map[string]string{ - labels.LabelUncompressed: state.diffID.String(), - labelDockerSchema1EmptyLayer: strconv.FormatBool(state.empty), - }, - } - - if _, err := c.contentStore.Update(ctx, cinfo, "labels."+labels.LabelUncompressed, fmt.Sprintf("labels.%s", labelDockerSchema1EmptyLayer)); err != nil { - return fmt.Errorf("failed to update uncompressed label: %w", err) - } - - c.mu.Lock() - c.blobMap[desc.Digest] = state - c.layerBlobs[state.diffID] = desc - c.mu.Unlock() - - return nil -} - -func (c *Converter) reuseLabelBlobState(ctx context.Context, desc ocispec.Descriptor) (bool, error) { - cinfo, err := c.contentStore.Info(ctx, desc.Digest) - if err != nil { - return false, fmt.Errorf("failed to get blob info: %w", err) - } - desc.Size = cinfo.Size - - diffID, ok := cinfo.Labels[labels.LabelUncompressed] - if !ok { - return false, nil - } - - emptyVal, ok := cinfo.Labels[labelDockerSchema1EmptyLayer] - if !ok { - return false, nil - } - - isEmpty, err := strconv.ParseBool(emptyVal) - if err != nil { - log.G(ctx).WithField("id", desc.Digest).Warnf("failed to parse bool from label %s: %v", labelDockerSchema1EmptyLayer, isEmpty) - return false, nil - } - - bState := blobState{empty: isEmpty} - - if bState.diffID, err = digest.Parse(diffID); err != nil { - log.G(ctx).WithField("id", desc.Digest).Warnf("failed to parse digest from label %s: %v", labels.LabelUncompressed, diffID) - return false, nil - } - - // NOTE: there is no need to read header to get compression method - // because there are only two kinds of methods. - if bState.diffID == desc.Digest { - desc.MediaType = images.MediaTypeDockerSchema2Layer - } else { - desc.MediaType = images.MediaTypeDockerSchema2LayerGzip - } - - c.mu.Lock() - c.blobMap[desc.Digest] = bState - c.layerBlobs[bState.diffID] = desc - c.mu.Unlock() - return true, nil -} - -func (c *Converter) schema1ManifestHistory() ([]ocispec.History, []digest.Digest, error) { - if c.pulledManifest == nil { - return nil, nil, errors.New("missing schema 1 manifest for conversion") - } - m := *c.pulledManifest - - if len(m.History) == 0 { - return nil, nil, errors.New("no history") - } - - history := make([]ocispec.History, len(m.History)) - diffIDs := []digest.Digest{} - for i := range m.History { - var h v1History - if err := json.Unmarshal([]byte(m.History[i].V1Compatibility), &h); err != nil { - return nil, nil, fmt.Errorf("failed to unmarshal history: %w", err) - } - - blobSum := m.FSLayers[i].BlobSum - - state := c.blobMap[blobSum] - - history[len(history)-i-1] = ocispec.History{ - Author: h.Author, - Comment: h.Comment, - Created: &h.Created, - CreatedBy: strings.Join(h.ContainerConfig.Cmd, " "), - EmptyLayer: state.empty, - } - - if !state.empty { - diffIDs = append([]digest.Digest{state.diffID}, diffIDs...) - - } - } - - return history, diffIDs, nil -} - -type fsLayer struct { - BlobSum digest.Digest `json:"blobSum"` -} - -type history struct { - V1Compatibility string `json:"v1Compatibility"` -} - -type manifest struct { - FSLayers []fsLayer `json:"fsLayers"` - History []history `json:"history"` - Layers json.RawMessage `json:"layers,omitempty"` // OCI manifest - Manifests json.RawMessage `json:"manifests,omitempty"` // OCI index -} - -type v1History struct { - Author string `json:"author,omitempty"` - Created time.Time `json:"created"` - Comment string `json:"comment,omitempty"` - ThrowAway *bool `json:"throwaway,omitempty"` - Size *int `json:"Size,omitempty"` // used before ThrowAway field - ContainerConfig struct { - Cmd []string `json:"Cmd,omitempty"` - } `json:"container_config,omitempty"` -} - -// isEmptyLayer returns whether the v1 compatibility history describes an -// empty layer. A return value of true indicates the layer is empty, -// however false does not indicate non-empty. -func isEmptyLayer(compatHistory []byte) (bool, error) { - var h v1History - if err := json.Unmarshal(compatHistory, &h); err != nil { - return false, err - } - - if h.ThrowAway != nil { - return *h.ThrowAway, nil - } - if h.Size != nil { - return *h.Size == 0, nil - } - - // If no `Size` or `throwaway` field is given, then - // it cannot be determined whether the layer is empty - // from the history, return false - return false, nil -} - -type signature struct { - Signatures []jsParsedSignature `json:"signatures"` -} - -type jsParsedSignature struct { - Protected string `json:"protected"` -} - -type protectedBlock struct { - Length int `json:"formatLength"` - Tail string `json:"formatTail"` -} - -// joseBase64UrlDecode decodes the given string using the standard base64 url -// decoder but first adds the appropriate number of trailing '=' characters in -// accordance with the jose specification. -// http://tools.ietf.org/html/draft-ietf-jose-json-web-signature-31#section-2 -func joseBase64UrlDecode(s string) ([]byte, error) { - switch len(s) % 4 { - case 0: - case 2: - s += "==" - case 3: - s += "=" - default: - return nil, errors.New("illegal base64url string") - } - return base64.URLEncoding.DecodeString(s) -} - -func stripSignature(b []byte) ([]byte, error) { - var sig signature - if err := json.Unmarshal(b, &sig); err != nil { - return nil, err - } - if len(sig.Signatures) == 0 { - return nil, errors.New("no signatures") - } - pb, err := joseBase64UrlDecode(sig.Signatures[0].Protected) - if err != nil { - return nil, fmt.Errorf("could not decode %s: %w", sig.Signatures[0].Protected, err) - } - - var protected protectedBlock - if err := json.Unmarshal(pb, &protected); err != nil { - return nil, err - } - - if protected.Length > len(b) { - return nil, errors.New("invalid protected length block") - } - - tail, err := joseBase64UrlDecode(protected.Tail) - if err != nil { - return nil, fmt.Errorf("invalid tail base 64 value: %w", err) - } - - return append(b[:protected.Length], tail...), nil -} - -type blobStateCalculator struct { - empty bool - digester digest.Digester -} - -func newBlobStateCalculator() *blobStateCalculator { - return &blobStateCalculator{ - empty: true, - digester: digest.Canonical.Digester(), - } -} - -func (c *blobStateCalculator) Write(p []byte) (int, error) { - if c.empty { - for _, b := range p { - if b != 0x00 { - c.empty = false - break - } - } - } - return c.digester.Hash().Write(p) -} - -func (c *blobStateCalculator) State() blobState { - return blobState{ - empty: c.empty, - diffID: c.digester.Digest(), - } -} diff --git a/vendor/github.com/containerd/containerd/remotes/docker/scope.go b/vendor/github.com/containerd/containerd/remotes/docker/scope.go deleted file mode 100644 index 95b4810ab..000000000 --- a/vendor/github.com/containerd/containerd/remotes/docker/scope.go +++ /dev/null @@ -1,101 +0,0 @@ -/* - Copyright The containerd 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 docker - -import ( - "context" - "fmt" - "net/url" - "sort" - "strings" - - "github.com/containerd/containerd/reference" -) - -// RepositoryScope returns a repository scope string such as "repository:foo/bar:pull" -// for "host/foo/bar:baz". -// When push is true, both pull and push are added to the scope. -func RepositoryScope(refspec reference.Spec, push bool) (string, error) { - u, err := url.Parse("dummy://" + refspec.Locator) - if err != nil { - return "", err - } - s := "repository:" + strings.TrimPrefix(u.Path, "/") + ":pull" - if push { - s += ",push" - } - return s, nil -} - -// tokenScopesKey is used for the key for context.WithValue(). -// value: []string (e.g. {"registry:foo/bar:pull"}) -type tokenScopesKey struct{} - -// ContextWithRepositoryScope returns a context with tokenScopesKey{} and the repository scope value. -func ContextWithRepositoryScope(ctx context.Context, refspec reference.Spec, push bool) (context.Context, error) { - s, err := RepositoryScope(refspec, push) - if err != nil { - return nil, err - } - return WithScope(ctx, s), nil -} - -// WithScope appends a custom registry auth scope to the context. -func WithScope(ctx context.Context, scope string) context.Context { - var scopes []string - if v := ctx.Value(tokenScopesKey{}); v != nil { - scopes = v.([]string) - scopes = append(scopes, scope) - } else { - scopes = []string{scope} - } - return context.WithValue(ctx, tokenScopesKey{}, scopes) -} - -// ContextWithAppendPullRepositoryScope is used to append repository pull -// scope into existing scopes indexed by the tokenScopesKey{}. -func ContextWithAppendPullRepositoryScope(ctx context.Context, repo string) context.Context { - return WithScope(ctx, fmt.Sprintf("repository:%s:pull", repo)) -} - -// GetTokenScopes returns deduplicated and sorted scopes from ctx.Value(tokenScopesKey{}) and common scopes. -func GetTokenScopes(ctx context.Context, common []string) []string { - scopes := []string{} - if x := ctx.Value(tokenScopesKey{}); x != nil { - scopes = append(scopes, x.([]string)...) - } - - scopes = append(scopes, common...) - sort.Strings(scopes) - - if len(scopes) == 0 { - return scopes - } - - l := 0 - for idx := 1; idx < len(scopes); idx++ { - // Note: this comparison is unaware of the scope grammar (https://docs.docker.com/registry/spec/auth/scope/) - // So, "repository:foo/bar:pull,push" != "repository:foo/bar:push,pull", although semantically they are equal. - if scopes[l] == scopes[idx] { - continue - } - - l++ - scopes[l] = scopes[idx] - } - return scopes[:l+1] -} diff --git a/vendor/github.com/containerd/containerd/remotes/docker/status.go b/vendor/github.com/containerd/containerd/remotes/docker/status.go deleted file mode 100644 index 1a9227725..000000000 --- a/vendor/github.com/containerd/containerd/remotes/docker/status.go +++ /dev/null @@ -1,101 +0,0 @@ -/* - Copyright The containerd 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 docker - -import ( - "fmt" - "sync" - - "github.com/containerd/containerd/content" - "github.com/containerd/containerd/errdefs" - "github.com/moby/locker" -) - -// Status of a content operation -type Status struct { - content.Status - - Committed bool - - // ErrClosed contains error encountered on close. - ErrClosed error - - // UploadUUID is used by the Docker registry to reference blob uploads - UploadUUID string - - // PushStatus contains status related to push. - PushStatus -} - -type PushStatus struct { - // MountedFrom is the source content was cross-repo mounted from (empty if no cross-repo mount was performed). - MountedFrom string - - // Exists indicates whether content already exists in the repository and wasn't uploaded. - Exists bool -} - -// StatusTracker to track status of operations -type StatusTracker interface { - GetStatus(string) (Status, error) - SetStatus(string, Status) -} - -// StatusTrackLocker to track status of operations with lock -type StatusTrackLocker interface { - StatusTracker - Lock(string) - Unlock(string) -} - -type memoryStatusTracker struct { - statuses map[string]Status - m sync.Mutex - locker *locker.Locker -} - -// NewInMemoryTracker returns a StatusTracker that tracks content status in-memory -func NewInMemoryTracker() StatusTrackLocker { - return &memoryStatusTracker{ - statuses: map[string]Status{}, - locker: locker.New(), - } -} - -func (t *memoryStatusTracker) GetStatus(ref string) (Status, error) { - t.m.Lock() - defer t.m.Unlock() - status, ok := t.statuses[ref] - if !ok { - return Status{}, fmt.Errorf("status for ref %v: %w", ref, errdefs.ErrNotFound) - } - return status, nil -} - -func (t *memoryStatusTracker) SetStatus(ref string, status Status) { - t.m.Lock() - t.statuses[ref] = status - t.m.Unlock() -} - -func (t *memoryStatusTracker) Lock(ref string) { - t.locker.Lock(ref) -} - -func (t *memoryStatusTracker) Unlock(ref string) { - t.locker.Unlock(ref) -} diff --git a/vendor/github.com/containerd/containerd/remotes/errors/errors.go b/vendor/github.com/containerd/containerd/remotes/errors/errors.go deleted file mode 100644 index f60ff0fc2..000000000 --- a/vendor/github.com/containerd/containerd/remotes/errors/errors.go +++ /dev/null @@ -1,55 +0,0 @@ -/* - Copyright The containerd 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 errors - -import ( - "fmt" - "io" - "net/http" -) - -var _ error = ErrUnexpectedStatus{} - -// ErrUnexpectedStatus is returned if a registry API request returned with unexpected HTTP status -type ErrUnexpectedStatus struct { - Status string - StatusCode int - Body []byte - RequestURL, RequestMethod string -} - -func (e ErrUnexpectedStatus) Error() string { - return fmt.Sprintf("unexpected status from %s request to %s: %s", e.RequestMethod, e.RequestURL, e.Status) -} - -// NewUnexpectedStatusErr creates an ErrUnexpectedStatus from HTTP response -func NewUnexpectedStatusErr(resp *http.Response) error { - var b []byte - if resp.Body != nil { - b, _ = io.ReadAll(io.LimitReader(resp.Body, 64000)) // 64KB - } - err := ErrUnexpectedStatus{ - Body: b, - Status: resp.Status, - StatusCode: resp.StatusCode, - RequestMethod: resp.Request.Method, - } - if resp.Request.URL != nil { - err.RequestURL = resp.Request.URL.String() - } - return err -} diff --git a/vendor/github.com/containerd/containerd/remotes/handlers.go b/vendor/github.com/containerd/containerd/remotes/handlers.go deleted file mode 100644 index f24669dc4..000000000 --- a/vendor/github.com/containerd/containerd/remotes/handlers.go +++ /dev/null @@ -1,413 +0,0 @@ -/* - Copyright The containerd 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 remotes - -import ( - "bytes" - "context" - "errors" - "fmt" - "io" - "strings" - "sync" - - "github.com/containerd/containerd/content" - "github.com/containerd/containerd/errdefs" - "github.com/containerd/containerd/images" - "github.com/containerd/containerd/labels" - "github.com/containerd/containerd/log" - "github.com/containerd/containerd/platforms" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" - "golang.org/x/sync/semaphore" -) - -type refKeyPrefix struct{} - -// WithMediaTypeKeyPrefix adds a custom key prefix for a media type which is used when storing -// data in the content store from the FetchHandler. -// -// Used in `MakeRefKey` to determine what the key prefix should be. -func WithMediaTypeKeyPrefix(ctx context.Context, mediaType, prefix string) context.Context { - var values map[string]string - if v := ctx.Value(refKeyPrefix{}); v != nil { - values = v.(map[string]string) - } else { - values = make(map[string]string) - } - - values[mediaType] = prefix - return context.WithValue(ctx, refKeyPrefix{}, values) -} - -// MakeRefKey returns a unique reference for the descriptor. This reference can be -// used to lookup ongoing processes related to the descriptor. This function -// may look to the context to namespace the reference appropriately. -func MakeRefKey(ctx context.Context, desc ocispec.Descriptor) string { - key := desc.Digest.String() - if desc.Annotations != nil { - if name, ok := desc.Annotations[ocispec.AnnotationRefName]; ok { - key = fmt.Sprintf("%s@%s", name, desc.Digest.String()) - } - } - - if v := ctx.Value(refKeyPrefix{}); v != nil { - values := v.(map[string]string) - if prefix := values[desc.MediaType]; prefix != "" { - return prefix + "-" + key - } - } - - switch mt := desc.MediaType; { - case mt == images.MediaTypeDockerSchema2Manifest || mt == ocispec.MediaTypeImageManifest: - return "manifest-" + key - case mt == images.MediaTypeDockerSchema2ManifestList || mt == ocispec.MediaTypeImageIndex: - return "index-" + key - case images.IsLayerType(mt): - return "layer-" + key - case images.IsKnownConfig(mt): - return "config-" + key - default: - log.G(ctx).Warnf("reference for unknown type: %s", mt) - return "unknown-" + key - } -} - -// FetchHandler returns a handler that will fetch all content into the ingester -// discovered in a call to Dispatch. Use with ChildrenHandler to do a full -// recursive fetch. -func FetchHandler(ingester content.Ingester, fetcher Fetcher) images.HandlerFunc { - return func(ctx context.Context, desc ocispec.Descriptor) (subdescs []ocispec.Descriptor, err error) { - ctx = log.WithLogger(ctx, log.G(ctx).WithFields(log.Fields{ - "digest": desc.Digest, - "mediatype": desc.MediaType, - "size": desc.Size, - })) - - switch desc.MediaType { - case images.MediaTypeDockerSchema1Manifest: - return nil, fmt.Errorf("%v not supported", desc.MediaType) - default: - err := Fetch(ctx, ingester, fetcher, desc) - if errdefs.IsAlreadyExists(err) { - return nil, nil - } - return nil, err - } - } -} - -// Fetch fetches the given digest into the provided ingester -func Fetch(ctx context.Context, ingester content.Ingester, fetcher Fetcher, desc ocispec.Descriptor) error { - log.G(ctx).Debug("fetch") - - cw, err := content.OpenWriter(ctx, ingester, content.WithRef(MakeRefKey(ctx, desc)), content.WithDescriptor(desc)) - if err != nil { - return err - } - defer cw.Close() - - ws, err := cw.Status() - if err != nil { - return err - } - - if desc.Size == 0 { - // most likely a poorly configured registry/web front end which responded with no - // Content-Length header; unable (not to mention useless) to commit a 0-length entry - // into the content store. Error out here otherwise the error sent back is confusing - return fmt.Errorf("unable to fetch descriptor (%s) which reports content size of zero: %w", desc.Digest, errdefs.ErrInvalidArgument) - } - if ws.Offset == desc.Size { - // If writer is already complete, commit and return - err := cw.Commit(ctx, desc.Size, desc.Digest) - if err != nil && !errdefs.IsAlreadyExists(err) { - return fmt.Errorf("failed commit on ref %q: %w", ws.Ref, err) - } - return err - } - - if desc.Size == int64(len(desc.Data)) { - return content.Copy(ctx, cw, bytes.NewReader(desc.Data), desc.Size, desc.Digest) - } - - rc, err := fetcher.Fetch(ctx, desc) - if err != nil { - return err - } - defer rc.Close() - - return content.Copy(ctx, cw, rc, desc.Size, desc.Digest) -} - -// PushHandler returns a handler that will push all content from the provider -// using a writer from the pusher. -func PushHandler(pusher Pusher, provider content.Provider) images.HandlerFunc { - return func(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) { - ctx = log.WithLogger(ctx, log.G(ctx).WithFields(log.Fields{ - "digest": desc.Digest, - "mediatype": desc.MediaType, - "size": desc.Size, - })) - - err := push(ctx, provider, pusher, desc) - return nil, err - } -} - -func push(ctx context.Context, provider content.Provider, pusher Pusher, desc ocispec.Descriptor) error { - log.G(ctx).Debug("push") - - var ( - cw content.Writer - err error - ) - if cs, ok := pusher.(content.Ingester); ok { - cw, err = content.OpenWriter(ctx, cs, content.WithRef(MakeRefKey(ctx, desc)), content.WithDescriptor(desc)) - } else { - cw, err = pusher.Push(ctx, desc) - } - if err != nil { - if !errdefs.IsAlreadyExists(err) { - return err - } - - return nil - } - defer cw.Close() - - ra, err := provider.ReaderAt(ctx, desc) - if err != nil { - return err - } - defer ra.Close() - - rd := io.NewSectionReader(ra, 0, desc.Size) - return content.Copy(ctx, cw, rd, desc.Size, desc.Digest) -} - -// PushContent pushes content specified by the descriptor from the provider. -// -// Base handlers can be provided which will be called before any push specific -// handlers. -// -// If the passed in content.Provider is also a content.InfoProvider (such as -// content.Manager) then this will also annotate the distribution sources using -// labels prefixed with "containerd.io/distribution.source". -func PushContent(ctx context.Context, pusher Pusher, desc ocispec.Descriptor, store content.Provider, limiter *semaphore.Weighted, platform platforms.MatchComparer, wrapper func(h images.Handler) images.Handler) error { - - var m sync.Mutex - manifests := []ocispec.Descriptor{} - indexStack := []ocispec.Descriptor{} - - filterHandler := images.HandlerFunc(func(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) { - switch desc.MediaType { - case images.MediaTypeDockerSchema2Manifest, ocispec.MediaTypeImageManifest: - m.Lock() - manifests = append(manifests, desc) - m.Unlock() - return nil, images.ErrStopHandler - case images.MediaTypeDockerSchema2ManifestList, ocispec.MediaTypeImageIndex: - m.Lock() - indexStack = append(indexStack, desc) - m.Unlock() - return nil, images.ErrStopHandler - default: - return nil, nil - } - }) - - pushHandler := PushHandler(pusher, store) - - platformFilterhandler := images.FilterPlatforms(images.ChildrenHandler(store), platform) - - var handler images.Handler - if m, ok := store.(content.InfoProvider); ok { - annotateHandler := annotateDistributionSourceHandler(platformFilterhandler, m) - handler = images.Handlers(annotateHandler, filterHandler, pushHandler) - } else { - handler = images.Handlers(platformFilterhandler, filterHandler, pushHandler) - } - - if wrapper != nil { - handler = wrapper(handler) - } - - if err := images.Dispatch(ctx, handler, limiter, desc); err != nil { - return err - } - - if err := images.Dispatch(ctx, pushHandler, limiter, manifests...); err != nil { - return err - } - - // Iterate in reverse order as seen, parent always uploaded after child - for i := len(indexStack) - 1; i >= 0; i-- { - err := images.Dispatch(ctx, pushHandler, limiter, indexStack[i]) - if err != nil { - // TODO(estesp): until we have a more complete method for index push, we need to report - // missing dependencies in an index/manifest list by sensing the "400 Bad Request" - // as a marker for this problem - if errors.Unwrap(err) != nil && strings.Contains(errors.Unwrap(err).Error(), "400 Bad Request") { - return fmt.Errorf("manifest list/index references to blobs and/or manifests are missing in your target registry: %w", err) - } - return err - } - } - - return nil -} - -// SkipNonDistributableBlobs returns a handler that skips blobs that have a media type that is "non-distributeable". -// An example of this kind of content would be a Windows base layer, which is not supposed to be redistributed. -// -// This is based on the media type of the content: -// - application/vnd.oci.image.layer.nondistributable -// - application/vnd.docker.image.rootfs.foreign -func SkipNonDistributableBlobs(f images.HandlerFunc) images.HandlerFunc { - return func(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) { - if images.IsNonDistributable(desc.MediaType) { - log.G(ctx).WithField("digest", desc.Digest).WithField("mediatype", desc.MediaType).Debug("Skipping non-distributable blob") - return nil, images.ErrSkipDesc - } - - if images.IsLayerType(desc.MediaType) { - return nil, nil - } - - children, err := f(ctx, desc) - if err != nil { - return nil, err - } - if len(children) == 0 { - return nil, nil - } - - out := make([]ocispec.Descriptor, 0, len(children)) - for _, child := range children { - if !images.IsNonDistributable(child.MediaType) { - out = append(out, child) - } else { - log.G(ctx).WithField("digest", child.Digest).WithField("mediatype", child.MediaType).Debug("Skipping non-distributable blob") - } - } - return out, nil - } -} - -// FilterManifestByPlatformHandler allows Handler to handle non-target -// platform's manifest and configuration data. -func FilterManifestByPlatformHandler(f images.HandlerFunc, m platforms.Matcher) images.HandlerFunc { - return func(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) { - children, err := f(ctx, desc) - if err != nil { - return nil, err - } - - // no platform information - if desc.Platform == nil || m == nil { - return children, nil - } - - var descs []ocispec.Descriptor - switch desc.MediaType { - case images.MediaTypeDockerSchema2Manifest, ocispec.MediaTypeImageManifest: - if m.Match(*desc.Platform) { - descs = children - } else { - for _, child := range children { - if child.MediaType == images.MediaTypeDockerSchema2Config || - child.MediaType == ocispec.MediaTypeImageConfig { - - descs = append(descs, child) - } - } - } - default: - descs = children - } - return descs, nil - } -} - -// annotateDistributionSourceHandler add distribution source label into -// annotation of config or blob descriptor. -func annotateDistributionSourceHandler(f images.HandlerFunc, provider content.InfoProvider) images.HandlerFunc { - return func(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) { - children, err := f(ctx, desc) - if err != nil { - return nil, err - } - - // Distribution source is only used for config or blob but may be inherited from - // a manifest or manifest list - switch desc.MediaType { - case images.MediaTypeDockerSchema2Manifest, ocispec.MediaTypeImageManifest, - images.MediaTypeDockerSchema2ManifestList, ocispec.MediaTypeImageIndex: - default: - return children, nil - } - - parentSourceAnnotations := desc.Annotations - var parentLabels map[string]string - if pi, err := provider.Info(ctx, desc.Digest); err != nil { - if !errdefs.IsNotFound(err) { - return nil, err - } - } else { - parentLabels = pi.Labels - } - - for i := range children { - child := children[i] - - info, err := provider.Info(ctx, child.Digest) - if err != nil { - if !errdefs.IsNotFound(err) { - return nil, err - } - } - copyDistributionSourceLabels(info.Labels, &child) - - // Annotate with parent labels for cross repo mount or fetch. - // Parent sources may apply to all children since most registries - // enforce that children exist before the manifests. - copyDistributionSourceLabels(parentSourceAnnotations, &child) - copyDistributionSourceLabels(parentLabels, &child) - - children[i] = child - } - return children, nil - } -} - -func copyDistributionSourceLabels(from map[string]string, to *ocispec.Descriptor) { - for k, v := range from { - if !strings.HasPrefix(k, labels.LabelDistributionSource+".") { - continue - } - - if to.Annotations == nil { - to.Annotations = make(map[string]string) - } else { - // Only propagate the parent label if the child doesn't already have it. - if _, has := to.Annotations[k]; has { - continue - } - } - to.Annotations[k] = v - } -} diff --git a/vendor/github.com/containerd/containerd/remotes/resolver.go b/vendor/github.com/containerd/containerd/remotes/resolver.go deleted file mode 100644 index f200c84bc..000000000 --- a/vendor/github.com/containerd/containerd/remotes/resolver.go +++ /dev/null @@ -1,94 +0,0 @@ -/* - Copyright The containerd 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 remotes - -import ( - "context" - "io" - - "github.com/containerd/containerd/content" - "github.com/opencontainers/go-digest" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" -) - -// Resolver provides remotes based on a locator. -type Resolver interface { - // Resolve attempts to resolve the reference into a name and descriptor. - // - // The argument `ref` should be a scheme-less URI representing the remote. - // Structurally, it has a host and path. The "host" can be used to directly - // reference a specific host or be matched against a specific handler. - // - // The returned name should be used to identify the referenced entity. - // Depending on the remote namespace, this may be immutable or mutable. - // While the name may differ from ref, it should itself be a valid ref. - // - // If the resolution fails, an error will be returned. - Resolve(ctx context.Context, ref string) (name string, desc ocispec.Descriptor, err error) - - // Fetcher returns a new fetcher for the provided reference. - // All content fetched from the returned fetcher will be - // from the namespace referred to by ref. - Fetcher(ctx context.Context, ref string) (Fetcher, error) - - // Pusher returns a new pusher for the provided reference - // The returned Pusher should satisfy content.Ingester and concurrent attempts - // to push the same blob using the Ingester API should result in ErrUnavailable. - Pusher(ctx context.Context, ref string) (Pusher, error) -} - -// Fetcher fetches content. -// A fetcher implementation may implement the FetcherByDigest interface too. -type Fetcher interface { - // Fetch the resource identified by the descriptor. - Fetch(ctx context.Context, desc ocispec.Descriptor) (io.ReadCloser, error) -} - -// FetcherByDigest fetches content by the digest. -type FetcherByDigest interface { - // FetchByDigest fetches the resource identified by the digest. - // - // FetcherByDigest usually returns an incomplete descriptor. - // Typically, the media type is always set to "application/octet-stream", - // and the annotations are unset. - FetchByDigest(ctx context.Context, dgst digest.Digest) (io.ReadCloser, ocispec.Descriptor, error) -} - -// Pusher pushes content -type Pusher interface { - // Push returns a content writer for the given resource identified - // by the descriptor. - Push(ctx context.Context, d ocispec.Descriptor) (content.Writer, error) -} - -// FetcherFunc allows package users to implement a Fetcher with just a -// function. -type FetcherFunc func(ctx context.Context, desc ocispec.Descriptor) (io.ReadCloser, error) - -// Fetch content -func (fn FetcherFunc) Fetch(ctx context.Context, desc ocispec.Descriptor) (io.ReadCloser, error) { - return fn(ctx, desc) -} - -// PusherFunc allows package users to implement a Pusher with just a -// function. -type PusherFunc func(ctx context.Context, desc ocispec.Descriptor) (content.Writer, error) - -// Push content -func (fn PusherFunc) Push(ctx context.Context, desc ocispec.Descriptor) (content.Writer, error) { - return fn(ctx, desc) -} diff --git a/vendor/github.com/containerd/containerd/services/content/contentserver/contentserver.go b/vendor/github.com/containerd/containerd/services/content/contentserver/contentserver.go deleted file mode 100644 index 76a9e6eea..000000000 --- a/vendor/github.com/containerd/containerd/services/content/contentserver/contentserver.go +++ /dev/null @@ -1,473 +0,0 @@ -/* - Copyright The containerd 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 contentserver - -import ( - "context" - "fmt" - "io" - "sync" - - api "github.com/containerd/containerd/api/services/content/v1" - "github.com/containerd/containerd/content" - "github.com/containerd/containerd/errdefs" - "github.com/containerd/containerd/log" - "github.com/containerd/containerd/protobuf" - ptypes "github.com/containerd/containerd/protobuf/types" - digest "github.com/opencontainers/go-digest" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" -) - -type service struct { - store content.Store - api.UnimplementedContentServer -} - -var bufPool = sync.Pool{ - New: func() interface{} { - buffer := make([]byte, 1<<20) - return &buffer - }, -} - -// New returns the content GRPC server -func New(cs content.Store) api.ContentServer { - return &service{store: cs} -} - -func (s *service) Register(server *grpc.Server) error { - api.RegisterContentServer(server, s) - return nil -} - -func (s *service) Info(ctx context.Context, req *api.InfoRequest) (*api.InfoResponse, error) { - dg, err := digest.Parse(req.Digest) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "%q failed validation", req.Digest) - } - - bi, err := s.store.Info(ctx, dg) - if err != nil { - return nil, errdefs.ToGRPC(err) - } - - return &api.InfoResponse{ - Info: infoToGRPC(bi), - }, nil -} - -func (s *service) Update(ctx context.Context, req *api.UpdateRequest) (*api.UpdateResponse, error) { - _, err := digest.Parse(req.Info.Digest) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "%q failed validation", req.Info.Digest) - } - - info, err := s.store.Update(ctx, infoFromGRPC(req.Info), req.UpdateMask.GetPaths()...) - if err != nil { - return nil, errdefs.ToGRPC(err) - } - - return &api.UpdateResponse{ - Info: infoToGRPC(info), - }, nil -} - -func (s *service) List(req *api.ListContentRequest, session api.Content_ListServer) error { - var ( - buffer []*api.Info - sendBlock = func(block []*api.Info) error { - // send last block - return session.Send(&api.ListContentResponse{ - Info: block, - }) - } - ) - - if err := s.store.Walk(session.Context(), func(info content.Info) error { - buffer = append(buffer, &api.Info{ - Digest: info.Digest.String(), - Size: info.Size, - CreatedAt: protobuf.ToTimestamp(info.CreatedAt), - Labels: info.Labels, - }) - - if len(buffer) >= 100 { - if err := sendBlock(buffer); err != nil { - return err - } - - buffer = buffer[:0] - } - - return nil - }, req.Filters...); err != nil { - return errdefs.ToGRPC(err) - } - - if len(buffer) > 0 { - // send last block - if err := sendBlock(buffer); err != nil { - return err - } - } - - return nil -} - -func (s *service) Delete(ctx context.Context, req *api.DeleteContentRequest) (*ptypes.Empty, error) { - log.G(ctx).WithField("digest", req.Digest).Debugf("delete content") - dg, err := digest.Parse(req.Digest) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, err.Error()) - } - - if err := s.store.Delete(ctx, dg); err != nil { - return nil, errdefs.ToGRPC(err) - } - - return &ptypes.Empty{}, nil -} - -func (s *service) Read(req *api.ReadContentRequest, session api.Content_ReadServer) error { - dg, err := digest.Parse(req.Digest) - if err != nil { - return status.Errorf(codes.InvalidArgument, "%v: %v", req.Digest, err) - } - - oi, err := s.store.Info(session.Context(), dg) - if err != nil { - return errdefs.ToGRPC(err) - } - - ra, err := s.store.ReaderAt(session.Context(), ocispec.Descriptor{Digest: dg}) - if err != nil { - return errdefs.ToGRPC(err) - } - defer ra.Close() - - var ( - offset = req.Offset - // size is read size, not the expected size of the blob (oi.Size), which the caller might not be aware of. - // offset+size can be larger than oi.Size. - size = req.Size - - // TODO(stevvooe): Using the global buffer pool. At 32KB, it is probably - // little inefficient for work over a fast network. We can tune this later. - p = bufPool.Get().(*[]byte) - ) - defer bufPool.Put(p) - - if offset < 0 { - offset = 0 - } - - if offset > oi.Size { - return status.Errorf(codes.OutOfRange, "read past object length %v bytes", oi.Size) - } - - if size <= 0 || offset+size > oi.Size { - size = oi.Size - offset - } - - _, err = io.CopyBuffer( - &readResponseWriter{session: session}, - io.NewSectionReader(ra, offset, size), *p) - return errdefs.ToGRPC(err) -} - -// readResponseWriter is a writer that places the output into ReadContentRequest messages. -// -// This allows io.CopyBuffer to do the heavy lifting of chunking the responses -// into the buffer size. -type readResponseWriter struct { - offset int64 - session api.Content_ReadServer -} - -func (rw *readResponseWriter) Write(p []byte) (n int, err error) { - if err := rw.session.Send(&api.ReadContentResponse{ - Offset: rw.offset, - Data: p, - }); err != nil { - return 0, err - } - - rw.offset += int64(len(p)) - return len(p), nil -} - -func (s *service) Status(ctx context.Context, req *api.StatusRequest) (*api.StatusResponse, error) { - status, err := s.store.Status(ctx, req.Ref) - if err != nil { - return nil, errdefs.ToGRPCf(err, "could not get status for ref %q", req.Ref) - } - - var resp api.StatusResponse - resp.Status = &api.Status{ - StartedAt: protobuf.ToTimestamp(status.StartedAt), - UpdatedAt: protobuf.ToTimestamp(status.UpdatedAt), - Ref: status.Ref, - Offset: status.Offset, - Total: status.Total, - Expected: status.Expected.String(), - } - - return &resp, nil -} - -func (s *service) ListStatuses(ctx context.Context, req *api.ListStatusesRequest) (*api.ListStatusesResponse, error) { - statuses, err := s.store.ListStatuses(ctx, req.Filters...) - if err != nil { - return nil, errdefs.ToGRPC(err) - } - - var resp api.ListStatusesResponse - for _, status := range statuses { - resp.Statuses = append(resp.Statuses, &api.Status{ - StartedAt: protobuf.ToTimestamp(status.StartedAt), - UpdatedAt: protobuf.ToTimestamp(status.UpdatedAt), - Ref: status.Ref, - Offset: status.Offset, - Total: status.Total, - Expected: status.Expected.String(), - }) - } - - return &resp, nil -} - -func (s *service) Write(session api.Content_WriteServer) (err error) { - var ( - ctx = session.Context() - msg api.WriteContentResponse - req *api.WriteContentRequest - ref string - total int64 - expected digest.Digest - ) - - defer func(msg *api.WriteContentResponse) { - // pump through the last message if no error was encountered - if err != nil { - if s, ok := status.FromError(err); ok && s.Code() != codes.AlreadyExists { - // TODO(stevvooe): Really need a log line here to track which - // errors are actually causing failure on the server side. May want - // to configure the service with an interceptor to make this work - // identically across all GRPC methods. - // - // This is pretty noisy, so we can remove it but leave it for now. - log.G(ctx).WithError(err).Error("(*service).Write failed") - } - - return - } - - err = session.Send(msg) - }(&msg) - - // handle the very first request! - req, err = session.Recv() - if err != nil { - return err - } - - ref = req.Ref - - if ref == "" { - return status.Errorf(codes.InvalidArgument, "first message must have a reference") - } - - fields := log.Fields{ - "ref": ref, - } - total = req.Total - expected = digest.Digest(req.Expected) - if total > 0 { - fields["total"] = total - } - - if expected != "" { - fields["expected"] = expected - } - - ctx = log.WithLogger(ctx, log.G(ctx).WithFields(fields)) - - log.G(ctx).Debug("(*service).Write started") - // this action locks the writer for the session. - wr, err := s.store.Writer(ctx, - content.WithRef(ref), - content.WithDescriptor(ocispec.Descriptor{Size: total, Digest: expected})) - if err != nil { - return errdefs.ToGRPC(err) - } - defer wr.Close() - - for { - msg.Action = req.Action - ws, err := wr.Status() - if err != nil { - return errdefs.ToGRPC(err) - } - - msg.Offset = ws.Offset // always set the offset. - - // NOTE(stevvooe): In general, there are two cases underwhich a remote - // writer is used. - // - // For pull, we almost always have this before fetching large content, - // through descriptors. We allow predeclaration of the expected size - // and digest. - // - // For push, it is more complex. If we want to cut through content into - // storage, we may have no expectation until we are done processing the - // content. The case here is the following: - // - // 1. Start writing content. - // 2. Compress inline. - // 3. Validate digest and size (maybe). - // - // Supporting these two paths is quite awkward but it lets both API - // users use the same writer style for each with a minimum of overhead. - if req.Expected != "" { - dg := digest.Digest(req.Expected) - if expected != "" && expected != dg { - log.G(ctx).Debugf("commit digest differs from writer digest: %v != %v", dg, expected) - } - expected = dg - - if _, err := s.store.Info(session.Context(), dg); err == nil { - if err := wr.Close(); err != nil { - log.G(ctx).WithError(err).Error("failed to close writer") - } - if err := s.store.Abort(session.Context(), ref); err != nil { - log.G(ctx).WithError(err).Error("failed to abort write") - } - - return status.Errorf(codes.AlreadyExists, "blob with expected digest %v exists", req.Expected) - } - } - - if req.Total > 0 { - // Update the expected total. Typically, this could be seen at - // negotiation time or on a commit message. - if total > 0 && req.Total != total { - log.G(ctx).Debugf("commit size differs from writer size: %v != %v", req.Total, total) - } - total = req.Total - } - - switch req.Action { - case api.WriteAction_STAT: - msg.Digest = wr.Digest().String() - msg.StartedAt = protobuf.ToTimestamp(ws.StartedAt) - msg.UpdatedAt = protobuf.ToTimestamp(ws.UpdatedAt) - msg.Total = total - case api.WriteAction_WRITE, api.WriteAction_COMMIT: - if req.Offset > 0 { - // validate the offset if provided - if req.Offset != ws.Offset { - return status.Errorf(codes.OutOfRange, "write @%v must occur at current offset %v", req.Offset, ws.Offset) - } - } - - if req.Offset == 0 && ws.Offset > 0 { - if err := wr.Truncate(req.Offset); err != nil { - return fmt.Errorf("truncate failed: %w", err) - } - msg.Offset = req.Offset - } - - // issue the write if we actually have data. - if len(req.Data) > 0 { - // While this looks like we could use io.WriterAt here, because we - // maintain the offset as append only, we just issue the write. - n, err := wr.Write(req.Data) - if err != nil { - return errdefs.ToGRPC(err) - } - - if n != len(req.Data) { - // TODO(stevvooe): Perhaps, we can recover this by including it - // in the offset on the write return. - return status.Errorf(codes.DataLoss, "wrote %v of %v bytes", n, len(req.Data)) - } - - msg.Offset += int64(n) - } - - if req.Action == api.WriteAction_COMMIT { - var opts []content.Opt - if req.Labels != nil { - opts = append(opts, content.WithLabels(req.Labels)) - } - if err := wr.Commit(ctx, total, expected, opts...); err != nil { - return errdefs.ToGRPC(err) - } - } - - msg.Digest = wr.Digest().String() - } - - if err := session.Send(&msg); err != nil { - return err - } - - if req.Action == api.WriteAction_COMMIT { - return nil - } - - req, err = session.Recv() - if err != nil { - if err == io.EOF { - return nil - } - - return err - } - } -} - -func (s *service) Abort(ctx context.Context, req *api.AbortRequest) (*ptypes.Empty, error) { - if err := s.store.Abort(ctx, req.Ref); err != nil { - return nil, errdefs.ToGRPC(err) - } - - return &ptypes.Empty{}, nil -} - -func infoToGRPC(info content.Info) *api.Info { - return &api.Info{ - Digest: info.Digest.String(), - Size: info.Size, - CreatedAt: protobuf.ToTimestamp(info.CreatedAt), - UpdatedAt: protobuf.ToTimestamp(info.UpdatedAt), - Labels: info.Labels, - } -} - -func infoFromGRPC(info *api.Info) content.Info { - return content.Info{ - Digest: digest.Digest(info.Digest), - Size: info.Size, - CreatedAt: protobuf.FromTimestamp(info.CreatedAt), - UpdatedAt: protobuf.FromTimestamp(info.UpdatedAt), - Labels: info.Labels, - } -} diff --git a/vendor/github.com/containerd/containerd/tracing/helpers.go b/vendor/github.com/containerd/containerd/tracing/helpers.go deleted file mode 100644 index 981da6c79..000000000 --- a/vendor/github.com/containerd/containerd/tracing/helpers.go +++ /dev/null @@ -1,94 +0,0 @@ -/* - Copyright The containerd 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 tracing - -import ( - "encoding/json" - "fmt" - "strings" - - "go.opentelemetry.io/otel/attribute" -) - -const ( - spanDelimiter = "." -) - -func makeSpanName(names ...string) string { - return strings.Join(names, spanDelimiter) -} - -func any(k string, v interface{}) attribute.KeyValue { - if v == nil { - return attribute.String(k, "") - } - - switch typed := v.(type) { - case bool: - return attribute.Bool(k, typed) - case []bool: - return attribute.BoolSlice(k, typed) - case int: - return attribute.Int(k, typed) - case []int: - return attribute.IntSlice(k, typed) - case int8: - return attribute.Int(k, int(typed)) - case []int8: - ls := make([]int, 0, len(typed)) - for _, i := range typed { - ls = append(ls, int(i)) - } - return attribute.IntSlice(k, ls) - case int16: - return attribute.Int(k, int(typed)) - case []int16: - ls := make([]int, 0, len(typed)) - for _, i := range typed { - ls = append(ls, int(i)) - } - return attribute.IntSlice(k, ls) - case int32: - return attribute.Int64(k, int64(typed)) - case []int32: - ls := make([]int64, 0, len(typed)) - for _, i := range typed { - ls = append(ls, int64(i)) - } - return attribute.Int64Slice(k, ls) - case int64: - return attribute.Int64(k, typed) - case []int64: - return attribute.Int64Slice(k, typed) - case float64: - return attribute.Float64(k, typed) - case []float64: - return attribute.Float64Slice(k, typed) - case string: - return attribute.String(k, typed) - case []string: - return attribute.StringSlice(k, typed) - } - - if stringer, ok := v.(fmt.Stringer); ok { - return attribute.String(k, stringer.String()) - } - if b, err := json.Marshal(v); b != nil && err == nil { - return attribute.String(k, string(b)) - } - return attribute.String(k, fmt.Sprintf("%v", v)) -} diff --git a/vendor/github.com/containerd/containerd/tracing/log.go b/vendor/github.com/containerd/containerd/tracing/log.go deleted file mode 100644 index 98fa16f93..000000000 --- a/vendor/github.com/containerd/containerd/tracing/log.go +++ /dev/null @@ -1,66 +0,0 @@ -/* - Copyright The containerd 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 tracing - -import ( - "github.com/sirupsen/logrus" - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/trace" -) - -// NewLogrusHook creates a new logrus hook -func NewLogrusHook() *LogrusHook { - return &LogrusHook{} -} - -// LogrusHook is a logrus hook which adds logrus events to active spans. -// If the span is not recording or the span context is invalid, the hook is a no-op. -type LogrusHook struct{} - -// Levels returns the logrus levels that this hook is interested in. -func (h *LogrusHook) Levels() []logrus.Level { - return logrus.AllLevels -} - -// Fire is called when a log event occurs. -func (h *LogrusHook) Fire(entry *logrus.Entry) error { - span := trace.SpanFromContext(entry.Context) - if span == nil { - return nil - } - - if !span.SpanContext().IsValid() || !span.IsRecording() { - return nil - } - - span.AddEvent( - entry.Message, - trace.WithAttributes(logrusDataToAttrs(entry.Data)...), - trace.WithAttributes(attribute.String("level", entry.Level.String())), - trace.WithTimestamp(entry.Time), - ) - - return nil -} - -func logrusDataToAttrs(data logrus.Fields) []attribute.KeyValue { - attrs := make([]attribute.KeyValue, 0, len(data)) - for k, v := range data { - attrs = append(attrs, any(k, v)) - } - return attrs -} diff --git a/vendor/github.com/containerd/containerd/tracing/tracing.go b/vendor/github.com/containerd/containerd/tracing/tracing.go deleted file mode 100644 index 80d2b95c0..000000000 --- a/vendor/github.com/containerd/containerd/tracing/tracing.go +++ /dev/null @@ -1,129 +0,0 @@ -/* - Copyright The containerd 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 tracing - -import ( - "context" - "net/http" - - "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" - "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/codes" - semconv "go.opentelemetry.io/otel/semconv/v1.21.0" - "go.opentelemetry.io/otel/trace" -) - -// StartConfig defines configuration for a new span object. -type StartConfig struct { - spanOpts []trace.SpanStartOption -} - -type SpanOpt func(config *StartConfig) - -// WithHTTPRequest marks span as a HTTP request operation from client to server. -// It'll append attributes from the HTTP request object and mark it with `SpanKindClient` type. -// -// Deprecated: use upstream functionality from otelhttp directly instead. This function is kept for API compatibility -// but no longer works as expected due to required functionality no longer exported in OpenTelemetry libraries. -func WithHTTPRequest(_ *http.Request) SpanOpt { - return func(config *StartConfig) { - config.spanOpts = append(config.spanOpts, - trace.WithSpanKind(trace.SpanKindClient), // A client making a request to a server - ) - } -} - -// UpdateHTTPClient updates the http client with the necessary otel transport -func UpdateHTTPClient(client *http.Client, name string) { - client.Transport = otelhttp.NewTransport( - client.Transport, - otelhttp.WithSpanNameFormatter(func(operation string, r *http.Request) string { - return name - }), - ) -} - -// StartSpan starts child span in a context. -func StartSpan(ctx context.Context, opName string, opts ...SpanOpt) (context.Context, *Span) { - config := StartConfig{} - for _, fn := range opts { - fn(&config) - } - tracer := otel.Tracer("") - if parent := trace.SpanFromContext(ctx); parent != nil && parent.SpanContext().IsValid() { - tracer = parent.TracerProvider().Tracer("") - } - ctx, span := tracer.Start(ctx, opName, config.spanOpts...) - return ctx, &Span{otelSpan: span} -} - -// SpanFromContext returns the current Span from the context. -func SpanFromContext(ctx context.Context) *Span { - return &Span{ - otelSpan: trace.SpanFromContext(ctx), - } -} - -// Span is wrapper around otel trace.Span. -// Span is the individual component of a trace. It represents a -// single named and timed operation of a workflow that is traced. -type Span struct { - otelSpan trace.Span -} - -// End completes the span. -func (s *Span) End() { - s.otelSpan.End() -} - -// AddEvent adds an event with provided name and options. -func (s *Span) AddEvent(name string, options ...trace.EventOption) { - s.otelSpan.AddEvent(name, options...) -} - -// SetStatus sets the status of the current span. -// If an error is encountered, it records the error and sets span status to Error. -func (s *Span) SetStatus(err error) { - if err != nil { - s.otelSpan.RecordError(err) - s.otelSpan.SetStatus(codes.Error, err.Error()) - } else { - s.otelSpan.SetStatus(codes.Ok, "") - } -} - -// SetAttributes sets kv as attributes of the span. -func (s *Span) SetAttributes(kv ...attribute.KeyValue) { - s.otelSpan.SetAttributes(kv...) -} - -// Name sets the span name by joining a list of strings in dot separated format. -func Name(names ...string) string { - return makeSpanName(names...) -} - -// Attribute takes a key value pair and returns attribute.KeyValue type. -func Attribute(k string, v interface{}) attribute.KeyValue { - return any(k, v) -} - -// HTTPStatusCodeAttributes generates attributes of the HTTP namespace as specified by the OpenTelemetry -// specification for a span. -func HTTPStatusCodeAttributes(code int) []attribute.KeyValue { - return []attribute.KeyValue{semconv.HTTPStatusCodeKey.Int(code)} -} diff --git a/vendor/github.com/containerd/containerd/version/version.go b/vendor/github.com/containerd/containerd/version/version.go deleted file mode 100644 index 45767163c..000000000 --- a/vendor/github.com/containerd/containerd/version/version.go +++ /dev/null @@ -1,34 +0,0 @@ -/* - Copyright The containerd 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 version - -import "runtime" - -var ( - // Package is filled at linking time - Package = "github.com/containerd/containerd" - - // Version holds the complete version number. Filled in at linking time. - Version = "1.7.11+unknown" - - // Revision is filled with the VCS (e.g. git) revision being used to build - // the program at linking time. - Revision = "" - - // GoVersion is Go tree's version. - GoVersion = runtime.Version() -) diff --git a/vendor/github.com/containerd/continuity/AUTHORS b/vendor/github.com/containerd/continuity/AUTHORS deleted file mode 100644 index 0b4a03cd4..000000000 --- a/vendor/github.com/containerd/continuity/AUTHORS +++ /dev/null @@ -1,40 +0,0 @@ -Aaron Lehmann -Akash Gupta -Akihiro Suda -Andrew Pennebaker -Brandon Philips -Brian Goff -Christopher Jones -Daniel, Dao Quang Minh -Darren Stahl -Derek McGowan -Edward Pilatowicz -Fu Wei -Gabriel Adrian Samfira -Hajime Tazaki -Ian Campbell -Ivan Markin -Jacob Blain Christen -Justin Cormack -Justin Cummins -Kasper Fabæch Brandt -Kazuyoshi Kato -Kir Kolyshkin -Michael Crosby -Michael Wan -Mike Brown -Niels de Vos -Phil Estes -Sam Whited -Samuel Karp -Sebastiaan van Stijn -Shengjing Zhu -Stephen J Day -Tibor Vass -Tobias Klauser -Tom Faulhaber -Tonis Tiigi -Trevor Porter -Wei Fu -Wilbert van de Ridder -Xiaodong Ye diff --git a/vendor/github.com/containerd/continuity/LICENSE b/vendor/github.com/containerd/continuity/LICENSE deleted file mode 100644 index 584149b6e..000000000 --- a/vendor/github.com/containerd/continuity/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright The containerd 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 - - https://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/containerd/continuity/fs/copy.go b/vendor/github.com/containerd/continuity/fs/copy.go deleted file mode 100644 index a3fef3c05..000000000 --- a/vendor/github.com/containerd/continuity/fs/copy.go +++ /dev/null @@ -1,211 +0,0 @@ -/* - Copyright The containerd 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 fs - -import ( - "fmt" - "io" - "os" - "path/filepath" - - "github.com/sirupsen/logrus" -) - -// XAttrErrorHandler transform a non-nil xattr error. -// Return nil to ignore an error. -// xattrKey can be empty for listxattr operation. -type XAttrErrorHandler func(dst, src, xattrKey string, err error) error - -type copyDirOpts struct { - xeh XAttrErrorHandler - // xex contains a set of xattrs to exclude when copying - xex map[string]struct{} -} - -type CopyDirOpt func(*copyDirOpts) error - -// WithXAttrErrorHandler allows specifying XAttrErrorHandler -// If nil XAttrErrorHandler is specified (default), CopyDir stops -// on a non-nil xattr error. -func WithXAttrErrorHandler(xeh XAttrErrorHandler) CopyDirOpt { - return func(o *copyDirOpts) error { - o.xeh = xeh - return nil - } -} - -// WithAllowXAttrErrors allows ignoring xattr errors. -func WithAllowXAttrErrors() CopyDirOpt { - xeh := func(dst, src, xattrKey string, err error) error { - return nil - } - return WithXAttrErrorHandler(xeh) -} - -// WithXAttrExclude allows for exclusion of specified xattr during CopyDir operation. -func WithXAttrExclude(keys ...string) CopyDirOpt { - return func(o *copyDirOpts) error { - if o.xex == nil { - o.xex = make(map[string]struct{}, len(keys)) - } - for _, key := range keys { - o.xex[key] = struct{}{} - } - return nil - } -} - -// CopyDir copies the directory from src to dst. -// Most efficient copy of files is attempted. -func CopyDir(dst, src string, opts ...CopyDirOpt) error { - var o copyDirOpts - for _, opt := range opts { - if err := opt(&o); err != nil { - return err - } - } - inodes := map[uint64]string{} - return copyDirectory(dst, src, inodes, &o) -} - -func copyDirectory(dst, src string, inodes map[uint64]string, o *copyDirOpts) error { - stat, err := os.Stat(src) - if err != nil { - return fmt.Errorf("failed to stat %s: %w", src, err) - } - if !stat.IsDir() { - return fmt.Errorf("source %s is not directory", src) - } - - if st, err := os.Stat(dst); err != nil { - if err := os.Mkdir(dst, stat.Mode()); err != nil { - return fmt.Errorf("failed to mkdir %s: %w", dst, err) - } - } else if !st.IsDir() { - return fmt.Errorf("cannot copy to non-directory: %s", dst) - } else { - if err := os.Chmod(dst, stat.Mode()); err != nil { - return fmt.Errorf("failed to chmod on %s: %w", dst, err) - } - } - - if err := copyFileInfo(stat, src, dst); err != nil { - return fmt.Errorf("failed to copy file info for %s: %w", dst, err) - } - - if err := copyXAttrs(dst, src, o.xex, o.xeh); err != nil { - return fmt.Errorf("failed to copy xattrs: %w", err) - } - - f, err := os.Open(src) - if err != nil { - return err - } - defer f.Close() - - dr := &dirReader{f: f} - - handleEntry := func(entry os.DirEntry) error { - source := filepath.Join(src, entry.Name()) - target := filepath.Join(dst, entry.Name()) - - fileInfo, err := entry.Info() - if err != nil { - return fmt.Errorf("failed to get file info for %s: %w", entry.Name(), err) - } - - switch { - case entry.IsDir(): - if err := copyDirectory(target, source, inodes, o); err != nil { - return err - } - return nil - case (fileInfo.Mode() & os.ModeType) == 0: - link, err := getLinkSource(target, fileInfo, inodes) - if err != nil { - return fmt.Errorf("failed to get hardlink: %w", err) - } - if link != "" { - if err := os.Link(link, target); err != nil { - return fmt.Errorf("failed to create hard link: %w", err) - } - } else if err := CopyFile(target, source); err != nil { - return fmt.Errorf("failed to copy files: %w", err) - } - case (fileInfo.Mode() & os.ModeSymlink) == os.ModeSymlink: - link, err := os.Readlink(source) - if err != nil { - return fmt.Errorf("failed to read link: %s: %w", source, err) - } - if err := os.Symlink(link, target); err != nil { - return fmt.Errorf("failed to create symlink: %s: %w", target, err) - } - case (fileInfo.Mode() & os.ModeDevice) == os.ModeDevice, - (fileInfo.Mode() & os.ModeNamedPipe) == os.ModeNamedPipe, - (fileInfo.Mode() & os.ModeSocket) == os.ModeSocket: - if err := copyIrregular(target, fileInfo); err != nil { - return fmt.Errorf("failed to create irregular file: %w", err) - } - default: - logrus.Warnf("unsupported mode: %s: %s", source, fileInfo.Mode()) - return nil - } - - if err := copyFileInfo(fileInfo, source, target); err != nil { - return fmt.Errorf("failed to copy file info: %w", err) - } - - if err := copyXAttrs(target, source, o.xex, o.xeh); err != nil { - return fmt.Errorf("failed to copy xattrs: %w", err) - } - return nil - } - - for { - entry := dr.Next() - if entry == nil { - break - } - - if err := handleEntry(entry); err != nil { - return err - } - } - return dr.Err() -} - -// CopyFile copies the source file to the target. -// The most efficient means of copying is used for the platform. -func CopyFile(target, source string) error { - return copyFile(target, source) -} - -func openAndCopyFile(target, source string) error { - src, err := os.Open(source) - if err != nil { - return fmt.Errorf("failed to open source %s: %w", source, err) - } - defer src.Close() - tgt, err := os.Create(target) - if err != nil { - return fmt.Errorf("failed to open target %s: %w", target, err) - } - defer tgt.Close() - - _, err = io.Copy(tgt, src) - return err -} diff --git a/vendor/github.com/containerd/continuity/fs/copy_darwin.go b/vendor/github.com/containerd/continuity/fs/copy_darwin.go deleted file mode 100644 index 97fc2e8ea..000000000 --- a/vendor/github.com/containerd/continuity/fs/copy_darwin.go +++ /dev/null @@ -1,35 +0,0 @@ -/* - Copyright The containerd 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 fs - -import ( - "errors" - "fmt" - - "golang.org/x/sys/unix" -) - -func copyFile(target, source string) error { - if err := unix.Clonefile(source, target, unix.CLONE_NOFOLLOW); err != nil { - if !errors.Is(err, unix.ENOTSUP) && !errors.Is(err, unix.EXDEV) { - return fmt.Errorf("clonefile failed: %w", err) - } - - return openAndCopyFile(target, source) - } - return nil -} diff --git a/vendor/github.com/containerd/continuity/fs/copy_irregular_freebsd.go b/vendor/github.com/containerd/continuity/fs/copy_irregular_freebsd.go deleted file mode 100644 index cfe9d8020..000000000 --- a/vendor/github.com/containerd/continuity/fs/copy_irregular_freebsd.go +++ /dev/null @@ -1,36 +0,0 @@ -/* - Copyright The containerd 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 fs - -import ( - "fmt" - "os" - "syscall" -) - -// copyIrregular covers devices, pipes, and sockets -func copyIrregular(dst string, fi os.FileInfo) error { - st, ok := fi.Sys().(*syscall.Stat_t) // not *unix.Stat_t - if !ok { - return fmt.Errorf("unsupported stat type: %s: %v", dst, fi.Mode()) - } - var rDev uint64 // uint64 on FreeBSD, int on other unixen - if fi.Mode()&os.ModeDevice == os.ModeDevice { - rDev = st.Rdev - } - return syscall.Mknod(dst, uint32(st.Mode), rDev) -} diff --git a/vendor/github.com/containerd/continuity/fs/copy_irregular_unix.go b/vendor/github.com/containerd/continuity/fs/copy_irregular_unix.go deleted file mode 100644 index 99fc8a965..000000000 --- a/vendor/github.com/containerd/continuity/fs/copy_irregular_unix.go +++ /dev/null @@ -1,40 +0,0 @@ -//go:build !windows && !freebsd -// +build !windows,!freebsd - -/* - Copyright The containerd 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 fs - -import ( - "fmt" - "os" - "syscall" -) - -// copyIrregular covers devices, pipes, and sockets -func copyIrregular(dst string, fi os.FileInfo) error { - st, ok := fi.Sys().(*syscall.Stat_t) // not *unix.Stat_t - if !ok { - return fmt.Errorf("unsupported stat type: %s: %v", dst, fi.Mode()) - } - var rDev int - if fi.Mode()&os.ModeDevice == os.ModeDevice { - rDev = int(st.Rdev) - } - //nolint:unconvert - return syscall.Mknod(dst, uint32(st.Mode), rDev) -} diff --git a/vendor/github.com/containerd/continuity/fs/copy_linux.go b/vendor/github.com/containerd/continuity/fs/copy_linux.go deleted file mode 100644 index 48ac3fbd3..000000000 --- a/vendor/github.com/containerd/continuity/fs/copy_linux.go +++ /dev/null @@ -1,99 +0,0 @@ -/* - Copyright The containerd 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 fs - -import ( - "fmt" - "os" - "syscall" - - "github.com/containerd/continuity/sysx" - "golang.org/x/sys/unix" -) - -func copyFileInfo(fi os.FileInfo, src, name string) error { - st := fi.Sys().(*syscall.Stat_t) - if err := os.Lchown(name, int(st.Uid), int(st.Gid)); err != nil { - if os.IsPermission(err) { - // Normally if uid/gid are the same this would be a no-op, but some - // filesystems may still return EPERM... for instance NFS does this. - // In such a case, this is not an error. - if dstStat, err2 := os.Lstat(name); err2 == nil { - st2 := dstStat.Sys().(*syscall.Stat_t) - if st.Uid == st2.Uid && st.Gid == st2.Gid { - err = nil - } - } - } - if err != nil { - return fmt.Errorf("failed to chown %s: %w", name, err) - } - } - - if (fi.Mode() & os.ModeSymlink) != os.ModeSymlink { - if err := os.Chmod(name, fi.Mode()); err != nil { - return fmt.Errorf("failed to chmod %s: %w", name, err) - } - } - - timespec := []unix.Timespec{ - unix.NsecToTimespec(syscall.TimespecToNsec(StatAtime(st))), - unix.NsecToTimespec(syscall.TimespecToNsec(StatMtime(st))), - } - if err := unix.UtimesNanoAt(unix.AT_FDCWD, name, timespec, unix.AT_SYMLINK_NOFOLLOW); err != nil { - return fmt.Errorf("failed to utime %s: %w", name, err) - } - - return nil -} - -func copyXAttrs(dst, src string, excludes map[string]struct{}, errorHandler XAttrErrorHandler) error { - xattrKeys, err := sysx.LListxattr(src) - if err != nil { - e := fmt.Errorf("failed to list xattrs on %s: %w", src, err) - if errorHandler != nil { - e = errorHandler(dst, src, "", e) - } - return e - } - for _, xattr := range xattrKeys { - if _, exclude := excludes[xattr]; exclude { - continue - } - data, err := sysx.LGetxattr(src, xattr) - if err != nil { - e := fmt.Errorf("failed to get xattr %q on %s: %w", xattr, src, err) - if errorHandler != nil { - if e = errorHandler(dst, src, xattr, e); e == nil { - continue - } - } - return e - } - if err := sysx.LSetxattr(dst, xattr, data, 0); err != nil { - e := fmt.Errorf("failed to set xattr %q on %s: %w", xattr, dst, err) - if errorHandler != nil { - if e = errorHandler(dst, src, xattr, e); e == nil { - continue - } - } - return e - } - } - - return nil -} diff --git a/vendor/github.com/containerd/continuity/fs/copy_nondarwin.go b/vendor/github.com/containerd/continuity/fs/copy_nondarwin.go deleted file mode 100644 index 275b64c04..000000000 --- a/vendor/github.com/containerd/continuity/fs/copy_nondarwin.go +++ /dev/null @@ -1,22 +0,0 @@ -//go:build !darwin -// +build !darwin - -/* - Copyright The containerd 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 fs - -var copyFile = openAndCopyFile diff --git a/vendor/github.com/containerd/continuity/fs/copy_unix.go b/vendor/github.com/containerd/continuity/fs/copy_unix.go deleted file mode 100644 index 2e25914d3..000000000 --- a/vendor/github.com/containerd/continuity/fs/copy_unix.go +++ /dev/null @@ -1,102 +0,0 @@ -//go:build darwin || freebsd || openbsd || netbsd || dragonfly || solaris -// +build darwin freebsd openbsd netbsd dragonfly solaris - -/* - Copyright The containerd 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 fs - -import ( - "fmt" - "os" - "runtime" - "syscall" - - "github.com/containerd/continuity/sysx" -) - -func copyFileInfo(fi os.FileInfo, src, name string) error { - st := fi.Sys().(*syscall.Stat_t) - if err := os.Lchown(name, int(st.Uid), int(st.Gid)); err != nil { - if os.IsPermission(err) { - // Normally if uid/gid are the same this would be a no-op, but some - // filesystems may still return EPERM... for instance NFS does this. - // In such a case, this is not an error. - if dstStat, err2 := os.Lstat(name); err2 == nil { - st2 := dstStat.Sys().(*syscall.Stat_t) - if st.Uid == st2.Uid && st.Gid == st2.Gid { - err = nil - } - } - } - if err != nil { - return fmt.Errorf("failed to chown %s: %w", name, err) - } - } - - if (fi.Mode() & os.ModeSymlink) != os.ModeSymlink { - if err := os.Chmod(name, fi.Mode()); err != nil { - return fmt.Errorf("failed to chmod %s: %w", name, err) - } - } - - if err := utimesNano(name, StatAtime(st), StatMtime(st)); err != nil { - return fmt.Errorf("failed to utime %s: %w", name, err) - } - - return nil -} - -func copyXAttrs(dst, src string, excludes map[string]struct{}, errorHandler XAttrErrorHandler) error { - xattrKeys, err := sysx.LListxattr(src) - if err != nil { - if os.IsPermission(err) && runtime.GOOS == "darwin" { - // On darwin, character devices do not permit listing xattrs - return nil - } - e := fmt.Errorf("failed to list xattrs on %s: %w", src, err) - if errorHandler != nil { - e = errorHandler(dst, src, "", e) - } - return e - } - for _, xattr := range xattrKeys { - if _, exclude := excludes[xattr]; exclude { - continue - } - data, err := sysx.LGetxattr(src, xattr) - if err != nil { - e := fmt.Errorf("failed to get xattr %q on %s: %w", xattr, src, err) - if errorHandler != nil { - if e = errorHandler(dst, src, xattr, e); e == nil { - continue - } - } - return e - } - if err := sysx.LSetxattr(dst, xattr, data, 0); err != nil { - e := fmt.Errorf("failed to set xattr %q on %s: %w", xattr, dst, err) - if errorHandler != nil { - if e = errorHandler(dst, src, xattr, e); e == nil { - continue - } - } - return e - } - } - - return nil -} diff --git a/vendor/github.com/containerd/continuity/fs/copy_windows.go b/vendor/github.com/containerd/continuity/fs/copy_windows.go deleted file mode 100644 index 1fad4c3ad..000000000 --- a/vendor/github.com/containerd/continuity/fs/copy_windows.go +++ /dev/null @@ -1,80 +0,0 @@ -/* - Copyright The containerd 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 fs - -import ( - "errors" - "fmt" - "os" - - winio "github.com/Microsoft/go-winio" - "golang.org/x/sys/windows" -) - -const ( - seTakeOwnershipPrivilege = "SeTakeOwnershipPrivilege" -) - -func copyFileInfo(fi os.FileInfo, src, name string) error { - if err := os.Chmod(name, fi.Mode()); err != nil { - return fmt.Errorf("failed to chmod %s: %w", name, err) - } - - // Copy file ownership and ACL - // We need SeRestorePrivilege and SeTakeOwnershipPrivilege in order - // to restore security info on a file, especially if we're trying to - // apply security info which includes SIDs not necessarily present on - // the host. - privileges := []string{winio.SeRestorePrivilege, seTakeOwnershipPrivilege} - if err := winio.EnableProcessPrivileges(privileges); err != nil { - return err - } - defer winio.DisableProcessPrivileges(privileges) - - secInfo, err := windows.GetNamedSecurityInfo( - src, windows.SE_FILE_OBJECT, - windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION) - if err != nil { - return err - } - - dacl, _, err := secInfo.DACL() - if err != nil { - return err - } - - sid, _, err := secInfo.Owner() - if err != nil { - return err - } - - if err := windows.SetNamedSecurityInfo( - name, windows.SE_FILE_OBJECT, - windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION, - sid, nil, dacl, nil); err != nil { - return err - } - return nil -} - -func copyXAttrs(dst, src string, excludes map[string]struct{}, errorHandler XAttrErrorHandler) error { - return nil -} - -func copyIrregular(dst string, fi os.FileInfo) error { - return errors.New("irregular copy not supported") -} diff --git a/vendor/github.com/containerd/continuity/fs/diff.go b/vendor/github.com/containerd/continuity/fs/diff.go deleted file mode 100644 index d2c3c568e..000000000 --- a/vendor/github.com/containerd/continuity/fs/diff.go +++ /dev/null @@ -1,326 +0,0 @@ -/* - Copyright The containerd 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 fs - -import ( - "context" - "os" - "path/filepath" - "strings" - - "github.com/sirupsen/logrus" - "golang.org/x/sync/errgroup" -) - -// ChangeKind is the type of modification that -// a change is making. -type ChangeKind int - -const ( - // ChangeKindUnmodified represents an unmodified - // file - ChangeKindUnmodified = iota - - // ChangeKindAdd represents an addition of - // a file - ChangeKindAdd - - // ChangeKindModify represents a change to - // an existing file - ChangeKindModify - - // ChangeKindDelete represents a delete of - // a file - ChangeKindDelete -) - -func (k ChangeKind) String() string { - switch k { - case ChangeKindUnmodified: - return "unmodified" - case ChangeKindAdd: - return "add" - case ChangeKindModify: - return "modify" - case ChangeKindDelete: - return "delete" - default: - return "" - } -} - -// Change represents single change between a diff and its parent. -type Change struct { - Kind ChangeKind - Path string -} - -// ChangeFunc is the type of function called for each change -// computed during a directory changes calculation. -type ChangeFunc func(ChangeKind, string, os.FileInfo, error) error - -// Changes computes changes between two directories calling the -// given change function for each computed change. The first -// directory is intended to the base directory and second -// directory the changed directory. -// -// The change callback is called by the order of path names and -// should be appliable in that order. -// -// Due to this apply ordering, the following is true -// - Removed directory trees only create a single change for the root -// directory removed. Remaining changes are implied. -// - A directory which is modified to become a file will not have -// delete entries for sub-path items, their removal is implied -// by the removal of the parent directory. -// -// Opaque directories will not be treated specially and each file -// removed from the base directory will show up as a removal. -// -// File content comparisons will be done on files which have timestamps -// which may have been truncated. If either of the files being compared -// has a zero value nanosecond value, each byte will be compared for -// differences. If 2 files have the same seconds value but different -// nanosecond values where one of those values is zero, the files will -// be considered unchanged if the content is the same. This behavior -// is to account for timestamp truncation during archiving. -func Changes(ctx context.Context, a, b string, changeFn ChangeFunc) error { - if a == "" { - logrus.Debugf("Using single walk diff for %s", b) - return addDirChanges(ctx, changeFn, b) - } else if diffOptions := detectDirDiff(b, a); diffOptions != nil { - logrus.Debugf("Using single walk diff for %s from %s", diffOptions.diffDir, a) - return diffDirChanges(ctx, changeFn, a, diffOptions) - } - - logrus.Debugf("Using double walk diff for %s from %s", b, a) - return doubleWalkDiff(ctx, changeFn, a, b) -} - -func addDirChanges(ctx context.Context, changeFn ChangeFunc, root string) error { - return filepath.Walk(root, func(path string, f os.FileInfo, err error) error { - if err != nil { - return err - } - - // Rebase path - path, err = filepath.Rel(root, path) - if err != nil { - return err - } - - path = filepath.Join(string(os.PathSeparator), path) - - // Skip root - if path == string(os.PathSeparator) { - return nil - } - - return changeFn(ChangeKindAdd, path, f, nil) - }) -} - -// diffDirOptions is used when the diff can be directly calculated from -// a diff directory to its base, without walking both trees. -type diffDirOptions struct { - diffDir string - skipChange func(string) (bool, error) - deleteChange func(string, string, os.FileInfo) (string, error) -} - -// diffDirChanges walks the diff directory and compares changes against the base. -func diffDirChanges(ctx context.Context, changeFn ChangeFunc, base string, o *diffDirOptions) error { - changedDirs := make(map[string]struct{}) - return filepath.Walk(o.diffDir, func(path string, f os.FileInfo, err error) error { - if err != nil { - return err - } - - // Rebase path - path, err = filepath.Rel(o.diffDir, path) - if err != nil { - return err - } - - path = filepath.Join(string(os.PathSeparator), path) - - // Skip root - if path == string(os.PathSeparator) { - return nil - } - - // TODO: handle opaqueness, start new double walker at this - // location to get deletes, and skip tree in single walker - - if o.skipChange != nil { - if skip, err := o.skipChange(path); skip { - return err - } - } - - var kind ChangeKind - - deletedFile, err := o.deleteChange(o.diffDir, path, f) - if err != nil { - return err - } - - // Find out what kind of modification happened - if deletedFile != "" { - path = deletedFile - kind = ChangeKindDelete - f = nil - } else { - // Otherwise, the file was added - kind = ChangeKindAdd - - // ...Unless it already existed in a base, in which case, it's a modification - stat, err := os.Stat(filepath.Join(base, path)) - if err != nil && !os.IsNotExist(err) { - return err - } - if err == nil { - // The file existed in the base, so that's a modification - - // However, if it's a directory, maybe it wasn't actually modified. - // If you modify /foo/bar/baz, then /foo will be part of the changed files only because it's the parent of bar - if stat.IsDir() && f.IsDir() { - if f.Size() == stat.Size() && f.Mode() == stat.Mode() && sameFsTime(f.ModTime(), stat.ModTime()) { - // Both directories are the same, don't record the change - return nil - } - } - kind = ChangeKindModify - } - } - - // If /foo/bar/file.txt is modified, then /foo/bar must be part of the changed files. - // This block is here to ensure the change is recorded even if the - // modify time, mode and size of the parent directory in the rw and ro layers are all equal. - // Check https://github.com/docker/docker/pull/13590 for details. - if f.IsDir() { - changedDirs[path] = struct{}{} - } - if kind == ChangeKindAdd || kind == ChangeKindDelete { - parent := filepath.Dir(path) - if _, ok := changedDirs[parent]; !ok && parent != "/" { - pi, err := os.Stat(filepath.Join(o.diffDir, parent)) - if err := changeFn(ChangeKindModify, parent, pi, err); err != nil { - return err - } - changedDirs[parent] = struct{}{} - } - } - - return changeFn(kind, path, f, nil) - }) -} - -// doubleWalkDiff walks both directories to create a diff -func doubleWalkDiff(ctx context.Context, changeFn ChangeFunc, a, b string) (err error) { - g, ctx := errgroup.WithContext(ctx) - - var ( - c1 = make(chan *currentPath) - c2 = make(chan *currentPath) - - f1, f2 *currentPath - rmdir string - ) - g.Go(func() error { - defer close(c1) - return pathWalk(ctx, a, c1) - }) - g.Go(func() error { - defer close(c2) - return pathWalk(ctx, b, c2) - }) - g.Go(func() error { - for c1 != nil || c2 != nil { - if f1 == nil && c1 != nil { - f1, err = nextPath(ctx, c1) - if err != nil { - return err - } - if f1 == nil { - c1 = nil - } - } - - if f2 == nil && c2 != nil { - f2, err = nextPath(ctx, c2) - if err != nil { - return err - } - if f2 == nil { - c2 = nil - } - } - if f1 == nil && f2 == nil { - continue - } - - var f os.FileInfo - k, p := pathChange(f1, f2) - switch k { - case ChangeKindAdd: - if rmdir != "" { - rmdir = "" - } - f = f2.f - f2 = nil - case ChangeKindDelete: - // Check if this file is already removed by being - // under of a removed directory - if rmdir != "" && strings.HasPrefix(f1.path, rmdir) { - f1 = nil - continue - } else if f1.f.IsDir() { - rmdir = f1.path + string(os.PathSeparator) - } else if rmdir != "" { - rmdir = "" - } - f1 = nil - case ChangeKindModify: - same, err := sameFile(f1, f2) - if err != nil { - return err - } - if f1.f.IsDir() && !f2.f.IsDir() { - rmdir = f1.path + string(os.PathSeparator) - } else if rmdir != "" { - rmdir = "" - } - f = f2.f - f1 = nil - f2 = nil - if same { - if !isLinked(f) { - continue - } - k = ChangeKindUnmodified - } - } - if err := changeFn(k, p, f, nil); err != nil { - return err - } - } - return nil - }) - - return g.Wait() -} diff --git a/vendor/github.com/containerd/continuity/fs/diff_unix.go b/vendor/github.com/containerd/continuity/fs/diff_unix.go deleted file mode 100644 index 5de9b6b48..000000000 --- a/vendor/github.com/containerd/continuity/fs/diff_unix.go +++ /dev/null @@ -1,75 +0,0 @@ -//go:build !windows -// +build !windows - -/* - Copyright The containerd 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 fs - -import ( - "bytes" - "fmt" - "os" - "syscall" - - "github.com/containerd/continuity/sysx" -) - -// detectDirDiff returns diff dir options if a directory could -// be found in the mount info for upper which is the direct -// diff with the provided lower directory -func detectDirDiff(upper, lower string) *diffDirOptions { - // TODO: get mount options for upper - // TODO: detect AUFS - // TODO: detect overlay - return nil -} - -// compareSysStat returns whether the stats are equivalent, -// whether the files are considered the same file, and -// an error -func compareSysStat(s1, s2 interface{}) (bool, error) { - ls1, ok := s1.(*syscall.Stat_t) - if !ok { - return false, nil - } - ls2, ok := s2.(*syscall.Stat_t) - if !ok { - return false, nil - } - - return ls1.Mode == ls2.Mode && ls1.Uid == ls2.Uid && ls1.Gid == ls2.Gid && ls1.Rdev == ls2.Rdev, nil -} - -func compareCapabilities(p1, p2 string) (bool, error) { - c1, err := sysx.LGetxattr(p1, "security.capability") - if err != nil && err != sysx.ENODATA { - return false, fmt.Errorf("failed to get xattr for %s: %w", p1, err) - } - c2, err := sysx.LGetxattr(p2, "security.capability") - if err != nil && err != sysx.ENODATA { - return false, fmt.Errorf("failed to get xattr for %s: %w", p2, err) - } - return bytes.Equal(c1, c2), nil -} - -func isLinked(f os.FileInfo) bool { - s, ok := f.Sys().(*syscall.Stat_t) - if !ok { - return false - } - return !f.IsDir() && s.Nlink > 1 -} diff --git a/vendor/github.com/containerd/continuity/fs/diff_windows.go b/vendor/github.com/containerd/continuity/fs/diff_windows.go deleted file mode 100644 index 4bfa72d3a..000000000 --- a/vendor/github.com/containerd/continuity/fs/diff_windows.go +++ /dev/null @@ -1,48 +0,0 @@ -/* - Copyright The containerd 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 fs - -import ( - "os" - - "golang.org/x/sys/windows" -) - -func detectDirDiff(upper, lower string) *diffDirOptions { - return nil -} - -func compareSysStat(s1, s2 interface{}) (bool, error) { - f1, ok := s1.(windows.Win32FileAttributeData) - if !ok { - return false, nil - } - f2, ok := s2.(windows.Win32FileAttributeData) - if !ok { - return false, nil - } - return f1.FileAttributes == f2.FileAttributes, nil -} - -func compareCapabilities(p1, p2 string) (bool, error) { - // TODO: Use windows equivalent - return true, nil -} - -func isLinked(os.FileInfo) bool { - return false -} diff --git a/vendor/github.com/containerd/continuity/fs/dir.go b/vendor/github.com/containerd/continuity/fs/dir.go deleted file mode 100644 index 6c7e32e95..000000000 --- a/vendor/github.com/containerd/continuity/fs/dir.go +++ /dev/null @@ -1,53 +0,0 @@ -/* - Copyright The containerd 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 fs - -import ( - "io" - "os" -) - -type dirReader struct { - buf []os.DirEntry - f *os.File - err error -} - -func (r *dirReader) Next() os.DirEntry { - if len(r.buf) == 0 { - infos, err := r.f.ReadDir(32) - if err != nil { - if err != io.EOF { - r.err = err - } - return nil - } - r.buf = infos - } - - if len(r.buf) == 0 { - return nil - } - out := r.buf[0] - r.buf[0] = nil - r.buf = r.buf[1:] - return out -} - -func (r *dirReader) Err() error { - return r.err -} diff --git a/vendor/github.com/containerd/continuity/fs/dtype_linux.go b/vendor/github.com/containerd/continuity/fs/dtype_linux.go deleted file mode 100644 index 9f55e7980..000000000 --- a/vendor/github.com/containerd/continuity/fs/dtype_linux.go +++ /dev/null @@ -1,103 +0,0 @@ -//go:build linux -// +build linux - -/* - Copyright The containerd 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 fs - -import ( - "fmt" - "os" - "syscall" - "unsafe" -) - -func locateDummyIfEmpty(path string) (string, error) { - children, err := os.ReadDir(path) - if err != nil { - return "", err - } - if len(children) != 0 { - return "", nil - } - dummyFile, err := os.CreateTemp(path, "fsutils-dummy") - if err != nil { - return "", err - } - name := dummyFile.Name() - err = dummyFile.Close() - return name, err -} - -// SupportsDType returns whether the filesystem mounted on path supports d_type -func SupportsDType(path string) (bool, error) { - // locate dummy so that we have at least one dirent - dummy, err := locateDummyIfEmpty(path) - if err != nil { - return false, err - } - if dummy != "" { - defer os.Remove(dummy) - } - - visited := 0 - supportsDType := true - fn := func(ent *syscall.Dirent) bool { - visited++ - if ent.Type == syscall.DT_UNKNOWN { - supportsDType = false - // stop iteration - return true - } - // continue iteration - return false - } - if err = iterateReadDir(path, fn); err != nil { - return false, err - } - if visited == 0 { - return false, fmt.Errorf("did not hit any dirent during iteration %s", path) - } - return supportsDType, nil -} - -func iterateReadDir(path string, fn func(*syscall.Dirent) bool) error { - d, err := os.Open(path) - if err != nil { - return err - } - defer d.Close() - fd := int(d.Fd()) - buf := make([]byte, 4096) - for { - nbytes, err := syscall.ReadDirent(fd, buf) - if err != nil { - return err - } - if nbytes == 0 { - break - } - for off := 0; off < nbytes; { - ent := (*syscall.Dirent)(unsafe.Pointer(&buf[off])) - if stop := fn(ent); stop { - return nil - } - off += int(ent.Reclen) - } - } - return nil -} diff --git a/vendor/github.com/containerd/continuity/fs/du.go b/vendor/github.com/containerd/continuity/fs/du.go deleted file mode 100644 index fccc985dc..000000000 --- a/vendor/github.com/containerd/continuity/fs/du.go +++ /dev/null @@ -1,38 +0,0 @@ -/* - Copyright The containerd 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 fs - -import "context" - -// Usage of disk information -type Usage struct { - Inodes int64 - Size int64 -} - -// DiskUsage counts the number of inodes and disk usage for the resources under -// path. -func DiskUsage(ctx context.Context, roots ...string) (Usage, error) { - return diskUsage(ctx, roots...) -} - -// DiffUsage counts the numbers of inodes and disk usage in the -// diff between the 2 directories. The first path is intended -// as the base directory and the second as the changed directory. -func DiffUsage(ctx context.Context, a, b string) (Usage, error) { - return diffUsage(ctx, a, b) -} diff --git a/vendor/github.com/containerd/continuity/fs/du_unix.go b/vendor/github.com/containerd/continuity/fs/du_unix.go deleted file mode 100644 index 51a08a1d7..000000000 --- a/vendor/github.com/containerd/continuity/fs/du_unix.go +++ /dev/null @@ -1,119 +0,0 @@ -//go:build !windows -// +build !windows - -/* - Copyright The containerd 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 fs - -import ( - "context" - "os" - "path/filepath" - "syscall" -) - -// blocksUnitSize is the unit used by `st_blocks` in `stat` in bytes. -// See https://man7.org/linux/man-pages/man2/stat.2.html -// -// st_blocks -// This field indicates the number of blocks allocated to the -// file, in 512-byte units. (This may be smaller than -// st_size/512 when the file has holes.) -const blocksUnitSize = 512 - -type inode struct { - // TODO(stevvooe): Can probably reduce memory usage by not tracking - // device, but we can leave this right for now. - dev, ino uint64 -} - -func newInode(stat *syscall.Stat_t) inode { - return inode{ - dev: uint64(stat.Dev), //nolint: unconvert // dev is uint32 on darwin/bsd, uint64 on linux/solaris/freebsd - ino: uint64(stat.Ino), //nolint: unconvert // ino is uint32 on bsd, uint64 on darwin/linux/solaris/freebsd - } -} - -func diskUsage(ctx context.Context, roots ...string) (Usage, error) { - var ( - size int64 - inodes = map[inode]struct{}{} // expensive! - ) - - for _, root := range roots { - if err := filepath.Walk(root, func(path string, fi os.FileInfo, err error) error { - if err != nil { - return err - } - - select { - case <-ctx.Done(): - return ctx.Err() - default: - } - - stat := fi.Sys().(*syscall.Stat_t) - inoKey := newInode(stat) - if _, ok := inodes[inoKey]; !ok { - inodes[inoKey] = struct{}{} - size += stat.Blocks * blocksUnitSize - } - - return nil - }); err != nil { - return Usage{}, err - } - } - - return Usage{ - Inodes: int64(len(inodes)), - Size: size, - }, nil -} - -func diffUsage(ctx context.Context, a, b string) (Usage, error) { - var ( - size int64 - inodes = map[inode]struct{}{} // expensive! - ) - - if err := Changes(ctx, a, b, func(kind ChangeKind, _ string, fi os.FileInfo, err error) error { - if err != nil { - return err - } - - if kind == ChangeKindAdd || kind == ChangeKindModify { - stat := fi.Sys().(*syscall.Stat_t) - inoKey := newInode(stat) - if _, ok := inodes[inoKey]; !ok { - inodes[inoKey] = struct{}{} - size += stat.Blocks * blocksUnitSize - } - - return nil - - } - return nil - }); err != nil { - return Usage{}, err - } - - return Usage{ - Inodes: int64(len(inodes)), - Size: size, - }, nil -} diff --git a/vendor/github.com/containerd/continuity/fs/du_windows.go b/vendor/github.com/containerd/continuity/fs/du_windows.go deleted file mode 100644 index ea721f826..000000000 --- a/vendor/github.com/containerd/continuity/fs/du_windows.go +++ /dev/null @@ -1,79 +0,0 @@ -//go:build windows -// +build windows - -/* - Copyright The containerd 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 fs - -import ( - "context" - "os" - "path/filepath" -) - -func diskUsage(ctx context.Context, roots ...string) (Usage, error) { - var size int64 - - // TODO(stevvooe): Support inodes (or equivalent) for windows. - - for _, root := range roots { - if err := filepath.Walk(root, func(path string, fi os.FileInfo, err error) error { - if err != nil { - return err - } - - select { - case <-ctx.Done(): - return ctx.Err() - default: - } - - size += fi.Size() - return nil - }); err != nil { - return Usage{}, err - } - } - - return Usage{ - Size: size, - }, nil -} - -func diffUsage(ctx context.Context, a, b string) (Usage, error) { - var size int64 - - if err := Changes(ctx, a, b, func(kind ChangeKind, _ string, fi os.FileInfo, err error) error { - if err != nil { - return err - } - - if kind == ChangeKindAdd || kind == ChangeKindModify { - size += fi.Size() - - return nil - - } - return nil - }); err != nil { - return Usage{}, err - } - - return Usage{ - Size: size, - }, nil -} diff --git a/vendor/github.com/containerd/continuity/fs/hardlink.go b/vendor/github.com/containerd/continuity/fs/hardlink.go deleted file mode 100644 index 762aa45e6..000000000 --- a/vendor/github.com/containerd/continuity/fs/hardlink.go +++ /dev/null @@ -1,43 +0,0 @@ -/* - Copyright The containerd 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 fs - -import "os" - -// GetLinkInfo returns an identifier representing the node a hardlink is pointing -// to. If the file is not hard linked then 0 will be returned. -func GetLinkInfo(fi os.FileInfo) (uint64, bool) { - return getLinkInfo(fi) -} - -// getLinkSource returns a path for the given name and -// file info to its link source in the provided inode -// map. If the given file name is not in the map and -// has other links, it is added to the inode map -// to be a source for other link locations. -func getLinkSource(name string, fi os.FileInfo, inodes map[uint64]string) (string, error) { - inode, isHardlink := getLinkInfo(fi) - if !isHardlink { - return "", nil - } - - path, ok := inodes[inode] - if !ok { - inodes[inode] = name - } - return path, nil -} diff --git a/vendor/github.com/containerd/continuity/fs/hardlink_unix.go b/vendor/github.com/containerd/continuity/fs/hardlink_unix.go deleted file mode 100644 index cce8902f3..000000000 --- a/vendor/github.com/containerd/continuity/fs/hardlink_unix.go +++ /dev/null @@ -1,34 +0,0 @@ -//go:build !windows -// +build !windows - -/* - Copyright The containerd 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 fs - -import ( - "os" - "syscall" -) - -func getLinkInfo(fi os.FileInfo) (uint64, bool) { - s, ok := fi.Sys().(*syscall.Stat_t) - if !ok { - return 0, false - } - - return uint64(s.Ino), !fi.IsDir() && s.Nlink > 1 //nolint: unconvert // ino is uint32 on bsd, uint64 on darwin/linux/solaris -} diff --git a/vendor/github.com/containerd/continuity/fs/hardlink_windows.go b/vendor/github.com/containerd/continuity/fs/hardlink_windows.go deleted file mode 100644 index 748554714..000000000 --- a/vendor/github.com/containerd/continuity/fs/hardlink_windows.go +++ /dev/null @@ -1,23 +0,0 @@ -/* - Copyright The containerd 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 fs - -import "os" - -func getLinkInfo(fi os.FileInfo) (uint64, bool) { - return 0, false -} diff --git a/vendor/github.com/containerd/continuity/fs/path.go b/vendor/github.com/containerd/continuity/fs/path.go deleted file mode 100644 index ec6e6a2fa..000000000 --- a/vendor/github.com/containerd/continuity/fs/path.go +++ /dev/null @@ -1,308 +0,0 @@ -/* - Copyright The containerd 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 fs - -import ( - "bytes" - "context" - "errors" - "io" - "os" - "path/filepath" -) - -var errTooManyLinks = errors.New("too many links") - -type currentPath struct { - path string - f os.FileInfo - fullPath string -} - -func pathChange(lower, upper *currentPath) (ChangeKind, string) { - if lower == nil { - if upper == nil { - panic("cannot compare nil paths") - } - return ChangeKindAdd, upper.path - } - if upper == nil { - return ChangeKindDelete, lower.path - } - - switch i := directoryCompare(lower.path, upper.path); { - case i < 0: - // File in lower that is not in upper - return ChangeKindDelete, lower.path - case i > 0: - // File in upper that is not in lower - return ChangeKindAdd, upper.path - default: - return ChangeKindModify, upper.path - } -} - -func directoryCompare(a, b string) int { - l := len(a) - if len(b) < l { - l = len(b) - } - for i := 0; i < l; i++ { - c1, c2 := a[i], b[i] - if c1 == filepath.Separator { - c1 = byte(0) - } - if c2 == filepath.Separator { - c2 = byte(0) - } - if c1 < c2 { - return -1 - } - if c1 > c2 { - return +1 - } - } - if len(a) < len(b) { - return -1 - } - if len(a) > len(b) { - return +1 - } - return 0 -} - -func sameFile(f1, f2 *currentPath) (bool, error) { - if os.SameFile(f1.f, f2.f) { - return true, nil - } - - equalStat, err := compareSysStat(f1.f.Sys(), f2.f.Sys()) - if err != nil || !equalStat { - return equalStat, err - } - - if eq, err := compareCapabilities(f1.fullPath, f2.fullPath); err != nil || !eq { - return eq, err - } - - // If not a directory also check size, modtime, and content - if !f1.f.IsDir() { - if f1.f.Size() != f2.f.Size() { - return false, nil - } - t1 := f1.f.ModTime() - t2 := f2.f.ModTime() - - if t1.Unix() != t2.Unix() { - return false, nil - } - - // If the timestamp may have been truncated in both of the - // files, check content of file to determine difference - if t1.Nanosecond() == 0 && t2.Nanosecond() == 0 { - if (f1.f.Mode() & os.ModeSymlink) == os.ModeSymlink { - return compareSymlinkTarget(f1.fullPath, f2.fullPath) - } - if f1.f.Size() == 0 { // if file sizes are zero length, the files are the same by definition - return true, nil - } - return compareFileContent(f1.fullPath, f2.fullPath) - } else if t1.Nanosecond() != t2.Nanosecond() { - return false, nil - } - } - - return true, nil -} - -func compareSymlinkTarget(p1, p2 string) (bool, error) { - t1, err := os.Readlink(p1) - if err != nil { - return false, err - } - t2, err := os.Readlink(p2) - if err != nil { - return false, err - } - return t1 == t2, nil -} - -const compareChuckSize = 32 * 1024 - -// compareFileContent compares the content of 2 same sized files -// by comparing each byte. -func compareFileContent(p1, p2 string) (bool, error) { - f1, err := os.Open(p1) - if err != nil { - return false, err - } - defer f1.Close() - f2, err := os.Open(p2) - if err != nil { - return false, err - } - defer f2.Close() - - b1 := make([]byte, compareChuckSize) - b2 := make([]byte, compareChuckSize) - for { - n1, err1 := f1.Read(b1) - if err1 != nil && err1 != io.EOF { - return false, err1 - } - n2, err2 := f2.Read(b2) - if err2 != nil && err2 != io.EOF { - return false, err2 - } - if n1 != n2 || !bytes.Equal(b1[:n1], b2[:n2]) { - return false, nil - } - if err1 == io.EOF && err2 == io.EOF { - return true, nil - } - } -} - -func pathWalk(ctx context.Context, root string, pathC chan<- *currentPath) error { - return filepath.Walk(root, func(path string, f os.FileInfo, err error) error { - if err != nil { - return err - } - - // Rebase path - path, err = filepath.Rel(root, path) - if err != nil { - return err - } - - path = filepath.Join(string(os.PathSeparator), path) - - // Skip root - if path == string(os.PathSeparator) { - return nil - } - - p := ¤tPath{ - path: path, - f: f, - fullPath: filepath.Join(root, path), - } - - select { - case <-ctx.Done(): - return ctx.Err() - case pathC <- p: - return nil - } - }) -} - -func nextPath(ctx context.Context, pathC <-chan *currentPath) (*currentPath, error) { - select { - case <-ctx.Done(): - return nil, ctx.Err() - case p := <-pathC: - return p, nil - } -} - -// RootPath joins a path with a root, evaluating and bounding any -// symlink to the root directory. -func RootPath(root, path string) (string, error) { - if path == "" { - return root, nil - } - var linksWalked int // to protect against cycles - for { - i := linksWalked - newpath, err := walkLinks(root, path, &linksWalked) - if err != nil { - return "", err - } - path = newpath - if i == linksWalked { - newpath = filepath.Join("/", newpath) - if path == newpath { - return filepath.Join(root, newpath), nil - } - path = newpath - } - } -} - -func walkLink(root, path string, linksWalked *int) (newpath string, islink bool, err error) { - if *linksWalked > 255 { - return "", false, errTooManyLinks - } - - path = filepath.Join("/", path) - if path == "/" { - return path, false, nil - } - realPath := filepath.Join(root, path) - - fi, err := os.Lstat(realPath) - if err != nil { - // If path does not yet exist, treat as non-symlink - if os.IsNotExist(err) { - return path, false, nil - } - return "", false, err - } - if fi.Mode()&os.ModeSymlink == 0 { - return path, false, nil - } - newpath, err = os.Readlink(realPath) - if err != nil { - return "", false, err - } - *linksWalked++ - return newpath, true, nil -} - -func walkLinks(root, path string, linksWalked *int) (string, error) { - switch dir, file := filepath.Split(path); { - case dir == "": - newpath, _, err := walkLink(root, file, linksWalked) - return newpath, err - case file == "": - if os.IsPathSeparator(dir[len(dir)-1]) { - if dir == "/" { - return dir, nil - } - return walkLinks(root, dir[:len(dir)-1], linksWalked) - } - newpath, _, err := walkLink(root, dir, linksWalked) - return newpath, err - default: - newdir, err := walkLinks(root, dir, linksWalked) - if err != nil { - return "", err - } - newpath, islink, err := walkLink(root, filepath.Join(newdir, file), linksWalked) - if err != nil { - return "", err - } - if !islink { - return newpath, nil - } - if filepath.IsAbs(newpath) { - return newpath, nil - } - return filepath.Join(newdir, newpath), nil - } -} diff --git a/vendor/github.com/containerd/continuity/fs/stat_atim.go b/vendor/github.com/containerd/continuity/fs/stat_atim.go deleted file mode 100644 index ade7bec6c..000000000 --- a/vendor/github.com/containerd/continuity/fs/stat_atim.go +++ /dev/null @@ -1,45 +0,0 @@ -//go:build linux || openbsd || dragonfly || solaris -// +build linux openbsd dragonfly solaris - -/* - Copyright The containerd 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 fs - -import ( - "syscall" - "time" -) - -// StatAtime returns the Atim -func StatAtime(st *syscall.Stat_t) syscall.Timespec { - return st.Atim -} - -// StatCtime returns the Ctim -func StatCtime(st *syscall.Stat_t) syscall.Timespec { - return st.Ctim -} - -// StatMtime returns the Mtim -func StatMtime(st *syscall.Stat_t) syscall.Timespec { - return st.Mtim -} - -// StatATimeAsTime returns st.Atim as a time.Time -func StatATimeAsTime(st *syscall.Stat_t) time.Time { - return time.Unix(st.Atim.Unix()) -} diff --git a/vendor/github.com/containerd/continuity/fs/stat_darwinbsd.go b/vendor/github.com/containerd/continuity/fs/stat_darwinbsd.go deleted file mode 100644 index dbdb90ec8..000000000 --- a/vendor/github.com/containerd/continuity/fs/stat_darwinbsd.go +++ /dev/null @@ -1,45 +0,0 @@ -//go:build darwin || freebsd || netbsd -// +build darwin freebsd netbsd - -/* - Copyright The containerd 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 fs - -import ( - "syscall" - "time" -) - -// StatAtime returns the access time from a stat struct -func StatAtime(st *syscall.Stat_t) syscall.Timespec { - return st.Atimespec -} - -// StatCtime returns the created time from a stat struct -func StatCtime(st *syscall.Stat_t) syscall.Timespec { - return st.Ctimespec -} - -// StatMtime returns the modified time from a stat struct -func StatMtime(st *syscall.Stat_t) syscall.Timespec { - return st.Mtimespec -} - -// StatATimeAsTime returns the access time as a time.Time -func StatATimeAsTime(st *syscall.Stat_t) time.Time { - return time.Unix(st.Atimespec.Unix()) -} diff --git a/vendor/github.com/containerd/continuity/fs/time.go b/vendor/github.com/containerd/continuity/fs/time.go deleted file mode 100644 index cde456123..000000000 --- a/vendor/github.com/containerd/continuity/fs/time.go +++ /dev/null @@ -1,29 +0,0 @@ -/* - Copyright The containerd 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 fs - -import "time" - -// Gnu tar and the go tar writer don't have sub-second mtime -// precision, which is problematic when we apply changes via tar -// files, we handle this by comparing for exact times, *or* same -// second count and either a or b having exactly 0 nanoseconds -func sameFsTime(a, b time.Time) bool { - return a == b || - (a.Unix() == b.Unix() && - (a.Nanosecond() == 0 || b.Nanosecond() == 0)) -} diff --git a/vendor/github.com/containerd/continuity/fs/utimesnanoat.go b/vendor/github.com/containerd/continuity/fs/utimesnanoat.go deleted file mode 100644 index 5435398d4..000000000 --- a/vendor/github.com/containerd/continuity/fs/utimesnanoat.go +++ /dev/null @@ -1,33 +0,0 @@ -//go:build !(windows || linux) -// +build !windows,!linux - -/* - Copyright The containerd 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 fs - -import ( - "syscall" - - "golang.org/x/sys/unix" -) - -func utimesNano(name string, atime, mtime syscall.Timespec) error { - at := unix.NsecToTimespec(atime.Nano()) - mt := unix.NsecToTimespec(mtime.Nano()) - utimes := [2]unix.Timespec{at, mt} - return unix.UtimesNanoAt(unix.AT_FDCWD, name, utimes[0:], unix.AT_SYMLINK_NOFOLLOW) -} diff --git a/vendor/github.com/containerd/continuity/sysx/README.md b/vendor/github.com/containerd/continuity/sysx/README.md deleted file mode 100644 index ad7aee533..000000000 --- a/vendor/github.com/containerd/continuity/sysx/README.md +++ /dev/null @@ -1,3 +0,0 @@ -This package is for internal use only. It is intended to only have -temporary changes before they are upstreamed to golang.org/x/sys/ -(a.k.a. https://github.com/golang/sys). diff --git a/vendor/github.com/containerd/continuity/sysx/nodata_linux.go b/vendor/github.com/containerd/continuity/sysx/nodata_linux.go deleted file mode 100644 index 28ce5d8de..000000000 --- a/vendor/github.com/containerd/continuity/sysx/nodata_linux.go +++ /dev/null @@ -1,23 +0,0 @@ -/* - Copyright The containerd 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 sysx - -import ( - "syscall" -) - -const ENODATA = syscall.ENODATA diff --git a/vendor/github.com/containerd/continuity/sysx/nodata_solaris.go b/vendor/github.com/containerd/continuity/sysx/nodata_solaris.go deleted file mode 100644 index e0575f446..000000000 --- a/vendor/github.com/containerd/continuity/sysx/nodata_solaris.go +++ /dev/null @@ -1,24 +0,0 @@ -/* - Copyright The containerd 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 sysx - -import ( - "syscall" -) - -// This should actually be a set that contains ENOENT and EPERM -const ENODATA = syscall.ENOENT diff --git a/vendor/github.com/containerd/continuity/sysx/nodata_unix.go b/vendor/github.com/containerd/continuity/sysx/nodata_unix.go deleted file mode 100644 index e78f77f6a..000000000 --- a/vendor/github.com/containerd/continuity/sysx/nodata_unix.go +++ /dev/null @@ -1,26 +0,0 @@ -//go:build !(linux || solaris || windows) -// +build !linux,!solaris,!windows - -/* - Copyright The containerd 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 sysx - -import ( - "syscall" -) - -const ENODATA = syscall.ENOATTR diff --git a/vendor/github.com/containerd/continuity/sysx/xattr.go b/vendor/github.com/containerd/continuity/sysx/xattr.go deleted file mode 100644 index 149739855..000000000 --- a/vendor/github.com/containerd/continuity/sysx/xattr.go +++ /dev/null @@ -1,118 +0,0 @@ -//go:build linux || darwin -// +build linux darwin - -/* - Copyright The containerd 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 sysx - -import ( - "bytes" - - "golang.org/x/sys/unix" -) - -// Listxattr calls syscall listxattr and reads all content -// and returns a string array -func Listxattr(path string) ([]string, error) { - return listxattrAll(path, unix.Listxattr) -} - -// Removexattr calls syscall removexattr -func Removexattr(path string, attr string) (err error) { - return unix.Removexattr(path, attr) -} - -// Setxattr calls syscall setxattr -func Setxattr(path string, attr string, data []byte, flags int) (err error) { - return unix.Setxattr(path, attr, data, flags) -} - -// Getxattr calls syscall getxattr -func Getxattr(path, attr string) ([]byte, error) { - return getxattrAll(path, attr, unix.Getxattr) -} - -// LListxattr lists xattrs, not following symlinks -func LListxattr(path string) ([]string, error) { - return listxattrAll(path, unix.Llistxattr) -} - -// LRemovexattr removes an xattr, not following symlinks -func LRemovexattr(path string, attr string) (err error) { - return unix.Lremovexattr(path, attr) -} - -// LSetxattr sets an xattr, not following symlinks -func LSetxattr(path string, attr string, data []byte, flags int) (err error) { - return unix.Lsetxattr(path, attr, data, flags) -} - -// LGetxattr gets an xattr, not following symlinks -func LGetxattr(path, attr string) ([]byte, error) { - return getxattrAll(path, attr, unix.Lgetxattr) -} - -const defaultXattrBufferSize = 128 - -type listxattrFunc func(path string, dest []byte) (int, error) - -func listxattrAll(path string, listFunc listxattrFunc) ([]string, error) { - buf := make([]byte, defaultXattrBufferSize) - n, err := listFunc(path, buf) - for err == unix.ERANGE { - // Buffer too small, use zero-sized buffer to get the actual size - n, err = listFunc(path, []byte{}) - if err != nil { - return nil, err - } - buf = make([]byte, n) - n, err = listFunc(path, buf) - } - if err != nil { - return nil, err - } - - ps := bytes.Split(bytes.TrimSuffix(buf[:n], []byte{0}), []byte{0}) - var entries []string - for _, p := range ps { - if len(p) > 0 { - entries = append(entries, string(p)) - } - } - - return entries, nil -} - -type getxattrFunc func(string, string, []byte) (int, error) - -func getxattrAll(path, attr string, getFunc getxattrFunc) ([]byte, error) { - buf := make([]byte, defaultXattrBufferSize) - n, err := getFunc(path, attr, buf) - for err == unix.ERANGE { - // Buffer too small, use zero-sized buffer to get the actual size - n, err = getFunc(path, attr, []byte{}) - if err != nil { - return nil, err - } - buf = make([]byte, n) - n, err = getFunc(path, attr, buf) - } - if err != nil { - return nil, err - } - return buf[:n], nil -} diff --git a/vendor/github.com/containerd/continuity/sysx/xattr_unsupported.go b/vendor/github.com/containerd/continuity/sysx/xattr_unsupported.go deleted file mode 100644 index da1e940d6..000000000 --- a/vendor/github.com/containerd/continuity/sysx/xattr_unsupported.go +++ /dev/null @@ -1,68 +0,0 @@ -//go:build !linux && !darwin -// +build !linux,!darwin - -/* - Copyright The containerd 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 sysx - -import ( - "errors" - "runtime" -) - -var errUnsupported = errors.New("extended attributes unsupported on " + runtime.GOOS) - -// Listxattr calls syscall listxattr and reads all content -// and returns a string array -func Listxattr(path string) ([]string, error) { - return []string{}, nil -} - -// Removexattr calls syscall removexattr -func Removexattr(path string, attr string) (err error) { - return errUnsupported -} - -// Setxattr calls syscall setxattr -func Setxattr(path string, attr string, data []byte, flags int) (err error) { - return errUnsupported -} - -// Getxattr calls syscall getxattr -func Getxattr(path, attr string) ([]byte, error) { - return []byte{}, errUnsupported -} - -// LListxattr lists xattrs, not following symlinks -func LListxattr(path string) ([]string, error) { - return []string{}, nil -} - -// LRemovexattr removes an xattr, not following symlinks -func LRemovexattr(path string, attr string) (err error) { - return errUnsupported -} - -// LSetxattr sets an xattr, not following symlinks -func LSetxattr(path string, attr string, data []byte, flags int) (err error) { - return errUnsupported -} - -// LGetxattr gets an xattr, not following symlinks -func LGetxattr(path, attr string) ([]byte, error) { - return []byte{}, nil -} diff --git a/vendor/github.com/containerd/log/.golangci.yml b/vendor/github.com/containerd/log/.golangci.yml deleted file mode 100644 index a695775df..000000000 --- a/vendor/github.com/containerd/log/.golangci.yml +++ /dev/null @@ -1,30 +0,0 @@ -linters: - enable: - - exportloopref # Checks for pointers to enclosing loop variables - - gofmt - - goimports - - gosec - - ineffassign - - misspell - - nolintlint - - revive - - staticcheck - - tenv # Detects using os.Setenv instead of t.Setenv since Go 1.17 - - unconvert - - unused - - vet - - dupword # Checks for duplicate words in the source code - disable: - - errcheck - -run: - timeout: 5m - skip-dirs: - - api - - cluster - - design - - docs - - docs/man - - releases - - reports - - test # e2e scripts diff --git a/vendor/github.com/containerd/log/LICENSE b/vendor/github.com/containerd/log/LICENSE deleted file mode 100644 index 584149b6e..000000000 --- a/vendor/github.com/containerd/log/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright The containerd 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 - - https://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/containerd/log/README.md b/vendor/github.com/containerd/log/README.md deleted file mode 100644 index 00e084988..000000000 --- a/vendor/github.com/containerd/log/README.md +++ /dev/null @@ -1,17 +0,0 @@ -# log - -A Go package providing a common logging interface across containerd repositories and a way for clients to use and configure logging in containerd packages. - -This package is not intended to be used as a standalone logging package outside of the containerd ecosystem and is intended as an interface wrapper around a logging implementation. -In the future this package may be replaced with a common go logging interface. - -## Project details - -**log** is a containerd sub-project, licensed under the [Apache 2.0 license](./LICENSE). -As a containerd sub-project, you will find the: - * [Project governance](https://github.com/containerd/project/blob/main/GOVERNANCE.md), - * [Maintainers](https://github.com/containerd/project/blob/main/MAINTAINERS), - * and [Contributing guidelines](https://github.com/containerd/project/blob/main/CONTRIBUTING.md) - -information in our [`containerd/project`](https://github.com/containerd/project) repository. - diff --git a/vendor/github.com/containerd/log/context.go b/vendor/github.com/containerd/log/context.go deleted file mode 100644 index 20153066f..000000000 --- a/vendor/github.com/containerd/log/context.go +++ /dev/null @@ -1,182 +0,0 @@ -/* - Copyright The containerd 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 log provides types and functions related to logging, passing -// loggers through a context, and attaching context to the logger. -// -// # Transitional types -// -// This package contains various types that are aliases for types in [logrus]. -// These aliases are intended for transitioning away from hard-coding logrus -// as logging implementation. Consumers of this package are encouraged to use -// the type-aliases from this package instead of directly using their logrus -// equivalent. -// -// The intent is to replace these aliases with locally defined types and -// interfaces once all consumers are no longer directly importing logrus -// types. -// -// IMPORTANT: due to the transitional purpose of this package, it is not -// guaranteed for the full logrus API to be provided in the future. As -// outlined, these aliases are provided as a step to transition away from -// a specific implementation which, as a result, exposes the full logrus API. -// While no decisions have been made on the ultimate design and interface -// provided by this package, we do not expect carrying "less common" features. -package log - -import ( - "context" - "fmt" - - "github.com/sirupsen/logrus" -) - -// G is a shorthand for [GetLogger]. -// -// We may want to define this locally to a package to get package tagged log -// messages. -var G = GetLogger - -// L is an alias for the standard logger. -var L = &Entry{ - Logger: logrus.StandardLogger(), - // Default is three fields plus a little extra room. - Data: make(Fields, 6), -} - -type loggerKey struct{} - -// Fields type to pass to "WithFields". -type Fields = map[string]any - -// Entry is a logging entry. It contains all the fields passed with -// [Entry.WithFields]. It's finally logged when Trace, Debug, Info, Warn, -// Error, Fatal or Panic is called on it. These objects can be reused and -// passed around as much as you wish to avoid field duplication. -// -// Entry is a transitional type, and currently an alias for [logrus.Entry]. -type Entry = logrus.Entry - -// RFC3339NanoFixed is [time.RFC3339Nano] with nanoseconds padded using -// zeros to ensure the formatted time is always the same number of -// characters. -const RFC3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00" - -// Level is a logging level. -type Level = logrus.Level - -// Supported log levels. -const ( - // TraceLevel level. Designates finer-grained informational events - // than [DebugLevel]. - TraceLevel Level = logrus.TraceLevel - - // DebugLevel level. Usually only enabled when debugging. Very verbose - // logging. - DebugLevel Level = logrus.DebugLevel - - // InfoLevel level. General operational entries about what's going on - // inside the application. - InfoLevel Level = logrus.InfoLevel - - // WarnLevel level. Non-critical entries that deserve eyes. - WarnLevel Level = logrus.WarnLevel - - // ErrorLevel level. Logs errors that should definitely be noted. - // Commonly used for hooks to send errors to an error tracking service. - ErrorLevel Level = logrus.ErrorLevel - - // FatalLevel level. Logs and then calls "logger.Exit(1)". It exits - // even if the logging level is set to Panic. - FatalLevel Level = logrus.FatalLevel - - // PanicLevel level. This is the highest level of severity. Logs and - // then calls panic with the message passed to Debug, Info, ... - PanicLevel Level = logrus.PanicLevel -) - -// SetLevel sets log level globally. It returns an error if the given -// level is not supported. -// -// level can be one of: -// -// - "trace" ([TraceLevel]) -// - "debug" ([DebugLevel]) -// - "info" ([InfoLevel]) -// - "warn" ([WarnLevel]) -// - "error" ([ErrorLevel]) -// - "fatal" ([FatalLevel]) -// - "panic" ([PanicLevel]) -func SetLevel(level string) error { - lvl, err := logrus.ParseLevel(level) - if err != nil { - return err - } - - L.Logger.SetLevel(lvl) - return nil -} - -// GetLevel returns the current log level. -func GetLevel() Level { - return L.Logger.GetLevel() -} - -// OutputFormat specifies a log output format. -type OutputFormat string - -// Supported log output formats. -const ( - // TextFormat represents the text logging format. - TextFormat OutputFormat = "text" - - // JSONFormat represents the JSON logging format. - JSONFormat OutputFormat = "json" -) - -// SetFormat sets the log output format ([TextFormat] or [JSONFormat]). -func SetFormat(format OutputFormat) error { - switch format { - case TextFormat: - L.Logger.SetFormatter(&logrus.TextFormatter{ - TimestampFormat: RFC3339NanoFixed, - FullTimestamp: true, - }) - return nil - case JSONFormat: - L.Logger.SetFormatter(&logrus.JSONFormatter{ - TimestampFormat: RFC3339NanoFixed, - }) - return nil - default: - return fmt.Errorf("unknown log format: %s", format) - } -} - -// WithLogger returns a new context with the provided logger. Use in -// combination with logger.WithField(s) for great effect. -func WithLogger(ctx context.Context, logger *Entry) context.Context { - return context.WithValue(ctx, loggerKey{}, logger.WithContext(ctx)) -} - -// GetLogger retrieves the current logger from the context. If no logger is -// available, the default logger is returned. -func GetLogger(ctx context.Context) *Entry { - if logger := ctx.Value(loggerKey{}); logger != nil { - return logger.(*Entry) - } - return L.WithContext(ctx) -} diff --git a/vendor/github.com/containerd/typeurl/v2/.gitignore b/vendor/github.com/containerd/typeurl/v2/.gitignore deleted file mode 100644 index d53846778..000000000 --- a/vendor/github.com/containerd/typeurl/v2/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -*.test -coverage.txt diff --git a/vendor/github.com/containerd/typeurl/v2/LICENSE b/vendor/github.com/containerd/typeurl/v2/LICENSE deleted file mode 100644 index 584149b6e..000000000 --- a/vendor/github.com/containerd/typeurl/v2/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright The containerd 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 - - https://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/containerd/typeurl/v2/README.md b/vendor/github.com/containerd/typeurl/v2/README.md deleted file mode 100644 index e3d0742f4..000000000 --- a/vendor/github.com/containerd/typeurl/v2/README.md +++ /dev/null @@ -1,20 +0,0 @@ -# typeurl - -[![PkgGoDev](https://pkg.go.dev/badge/github.com/containerd/typeurl)](https://pkg.go.dev/github.com/containerd/typeurl) -[![Build Status](https://github.com/containerd/typeurl/workflows/CI/badge.svg)](https://github.com/containerd/typeurl/actions?query=workflow%3ACI) -[![codecov](https://codecov.io/gh/containerd/typeurl/branch/master/graph/badge.svg)](https://codecov.io/gh/containerd/typeurl) -[![Go Report Card](https://goreportcard.com/badge/github.com/containerd/typeurl)](https://goreportcard.com/report/github.com/containerd/typeurl) - -A Go package for managing the registration, marshaling, and unmarshaling of encoded types. - -This package helps when types are sent over a ttrpc/GRPC API and marshaled as a protobuf [Any](https://pkg.go.dev/google.golang.org/protobuf@v1.27.1/types/known/anypb#Any) - -## Project details - -**typeurl** is a containerd sub-project, licensed under the [Apache 2.0 license](./LICENSE). -As a containerd sub-project, you will find the: - * [Project governance](https://github.com/containerd/project/blob/master/GOVERNANCE.md), - * [Maintainers](https://github.com/containerd/project/blob/master/MAINTAINERS), - * and [Contributing guidelines](https://github.com/containerd/project/blob/master/CONTRIBUTING.md) - -information in our [`containerd/project`](https://github.com/containerd/project) repository. diff --git a/vendor/github.com/containerd/typeurl/v2/doc.go b/vendor/github.com/containerd/typeurl/v2/doc.go deleted file mode 100644 index c0d0fd205..000000000 --- a/vendor/github.com/containerd/typeurl/v2/doc.go +++ /dev/null @@ -1,83 +0,0 @@ -/* - Copyright The containerd 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 typeurl - -// Package typeurl assists with managing the registration, marshaling, and -// unmarshaling of types encoded as protobuf.Any. -// -// A protobuf.Any is a proto message that can contain any arbitrary data. It -// consists of two components, a TypeUrl and a Value, and its proto definition -// looks like this: -// -// message Any { -// string type_url = 1; -// bytes value = 2; -// } -// -// The TypeUrl is used to distinguish the contents from other proto.Any -// messages. This typeurl library manages these URLs to enable automagic -// marshaling and unmarshaling of the contents. -// -// For example, consider this go struct: -// -// type Foo struct { -// Field1 string -// Field2 string -// } -// -// To use typeurl, types must first be registered. This is typically done in -// the init function -// -// func init() { -// typeurl.Register(&Foo{}, "Foo") -// } -// -// This will register the type Foo with the url path "Foo". The arguments to -// Register are variadic, and are used to construct a url path. Consider this -// example, from the github.com/containerd/containerd/client package: -// -// func init() { -// const prefix = "types.containerd.io" -// // register TypeUrls for commonly marshaled external types -// major := strconv.Itoa(specs.VersionMajor) -// typeurl.Register(&specs.Spec{}, prefix, "opencontainers/runtime-spec", major, "Spec") -// // this function has more Register calls, which are elided. -// } -// -// This registers several types under a more complex url, which ends up mapping -// to `types.containerd.io/opencontainers/runtime-spec/1/Spec` (or some other -// value for major). -// -// Once a type is registered, it can be marshaled to a proto.Any message simply -// by calling `MarshalAny`, like this: -// -// foo := &Foo{Field1: "value1", Field2: "value2"} -// anyFoo, err := typeurl.MarshalAny(foo) -// -// MarshalAny will resolve the correct URL for the type. If the type in -// question implements the proto.Message interface, then it will be marshaled -// as a proto message. Otherwise, it will be marshaled as json. This means that -// typeurl will work on any arbitrary data, whether or not it has a proto -// definition, as long as it can be serialized to json. -// -// To unmarshal, the process is simply inverse: -// -// iface, err := typeurl.UnmarshalAny(anyFoo) -// foo := iface.(*Foo) -// -// The correct type is automatically chosen from the type registry, and the -// returned interface can be cast straight to that type. diff --git a/vendor/github.com/containerd/typeurl/v2/types.go b/vendor/github.com/containerd/typeurl/v2/types.go deleted file mode 100644 index 8d6665bb5..000000000 --- a/vendor/github.com/containerd/typeurl/v2/types.go +++ /dev/null @@ -1,269 +0,0 @@ -/* - Copyright The containerd 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 typeurl - -import ( - "encoding/json" - "errors" - "fmt" - "path" - "reflect" - "sync" - - gogoproto "github.com/gogo/protobuf/proto" - "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/reflect/protoregistry" -) - -var ( - mu sync.RWMutex - registry = make(map[reflect.Type]string) -) - -// Definitions of common error types used throughout typeurl. -// -// These error types are used with errors.Wrap and errors.Wrapf to add context -// to an error. -// -// To detect an error class, use errors.Is() functions to tell whether an -// error is of this type. - -var ( - ErrNotFound = errors.New("not found") -) - -// Any contains an arbitrary protcol buffer message along with its type. -// -// While there is google.golang.org/protobuf/types/known/anypb.Any, -// we'd like to have our own to hide the underlying protocol buffer -// implementations from containerd clients. -// -// https://developers.google.com/protocol-buffers/docs/proto3#any -type Any interface { - // GetTypeUrl returns a URL/resource name that uniquely identifies - // the type of the serialized protocol buffer message. - GetTypeUrl() string - - // GetValue returns a valid serialized protocol buffer of the type that - // GetTypeUrl() indicates. - GetValue() []byte -} - -type anyType struct { - typeURL string - value []byte -} - -func (a *anyType) GetTypeUrl() string { - if a == nil { - return "" - } - return a.typeURL -} - -func (a *anyType) GetValue() []byte { - if a == nil { - return nil - } - return a.value -} - -// Register a type with a base URL for JSON marshaling. When the MarshalAny and -// UnmarshalAny functions are called they will treat the Any type value as JSON. -// To use protocol buffers for handling the Any value the proto.Register -// function should be used instead of this function. -func Register(v interface{}, args ...string) { - var ( - t = tryDereference(v) - p = path.Join(args...) - ) - mu.Lock() - defer mu.Unlock() - if et, ok := registry[t]; ok { - if et != p { - panic(fmt.Errorf("type registered with alternate path %q != %q", et, p)) - } - return - } - registry[t] = p -} - -// TypeURL returns the type url for a registered type. -func TypeURL(v interface{}) (string, error) { - mu.RLock() - u, ok := registry[tryDereference(v)] - mu.RUnlock() - if !ok { - switch t := v.(type) { - case proto.Message: - return string(t.ProtoReflect().Descriptor().FullName()), nil - case gogoproto.Message: - return gogoproto.MessageName(t), nil - default: - return "", fmt.Errorf("type %s: %w", reflect.TypeOf(v), ErrNotFound) - } - } - return u, nil -} - -// Is returns true if the type of the Any is the same as v. -func Is(any Any, v interface{}) bool { - // call to check that v is a pointer - tryDereference(v) - url, err := TypeURL(v) - if err != nil { - return false - } - return any.GetTypeUrl() == url -} - -// MarshalAny marshals the value v into an any with the correct TypeUrl. -// If the provided object is already a proto.Any message, then it will be -// returned verbatim. If it is of type proto.Message, it will be marshaled as a -// protocol buffer. Otherwise, the object will be marshaled to json. -func MarshalAny(v interface{}) (Any, error) { - var marshal func(v interface{}) ([]byte, error) - switch t := v.(type) { - case Any: - // avoid reserializing the type if we have an any. - return t, nil - case proto.Message: - marshal = func(v interface{}) ([]byte, error) { - return proto.Marshal(t) - } - case gogoproto.Message: - marshal = func(v interface{}) ([]byte, error) { - return gogoproto.Marshal(t) - } - default: - marshal = json.Marshal - } - - url, err := TypeURL(v) - if err != nil { - return nil, err - } - - data, err := marshal(v) - if err != nil { - return nil, err - } - return &anyType{ - typeURL: url, - value: data, - }, nil -} - -// UnmarshalAny unmarshals the any type into a concrete type. -func UnmarshalAny(any Any) (interface{}, error) { - return UnmarshalByTypeURL(any.GetTypeUrl(), any.GetValue()) -} - -// UnmarshalByTypeURL unmarshals the given type and value to into a concrete type. -func UnmarshalByTypeURL(typeURL string, value []byte) (interface{}, error) { - return unmarshal(typeURL, value, nil) -} - -// UnmarshalTo unmarshals the any type into a concrete type passed in the out -// argument. It is identical to UnmarshalAny, but lets clients provide a -// destination type through the out argument. -func UnmarshalTo(any Any, out interface{}) error { - return UnmarshalToByTypeURL(any.GetTypeUrl(), any.GetValue(), out) -} - -// UnmarshalToByTypeURL unmarshals the given type and value into a concrete type passed -// in the out argument. It is identical to UnmarshalByTypeURL, but lets clients -// provide a destination type through the out argument. -func UnmarshalToByTypeURL(typeURL string, value []byte, out interface{}) error { - _, err := unmarshal(typeURL, value, out) - return err -} - -func unmarshal(typeURL string, value []byte, v interface{}) (interface{}, error) { - t, err := getTypeByUrl(typeURL) - if err != nil { - return nil, err - } - - if v == nil { - v = reflect.New(t.t).Interface() - } else { - // Validate interface type provided by client - vURL, err := TypeURL(v) - if err != nil { - return nil, err - } - if typeURL != vURL { - return nil, fmt.Errorf("can't unmarshal type %q to output %q", typeURL, vURL) - } - } - - if t.isProto { - switch t := v.(type) { - case proto.Message: - err = proto.Unmarshal(value, t) - case gogoproto.Message: - err = gogoproto.Unmarshal(value, t) - } - } else { - err = json.Unmarshal(value, v) - } - - return v, err -} - -type urlType struct { - t reflect.Type - isProto bool -} - -func getTypeByUrl(url string) (urlType, error) { - mu.RLock() - for t, u := range registry { - if u == url { - mu.RUnlock() - return urlType{ - t: t, - }, nil - } - } - mu.RUnlock() - // fallback to proto registry - t := gogoproto.MessageType(url) - if t != nil { - return urlType{ - // get the underlying Elem because proto returns a pointer to the type - t: t.Elem(), - isProto: true, - }, nil - } - mt, err := protoregistry.GlobalTypes.FindMessageByURL(url) - if err != nil { - return urlType{}, fmt.Errorf("type with url %s: %w", url, ErrNotFound) - } - empty := mt.New().Interface() - return urlType{t: reflect.TypeOf(empty).Elem(), isProto: true}, nil -} - -func tryDereference(v interface{}) reflect.Type { - t := reflect.TypeOf(v) - if t.Kind() == reflect.Ptr { - // require check of pointer but dereference to register - return t.Elem() - } - panic("v is not a pointer to a type") -} diff --git a/vendor/github.com/cpuguy83/dockercfg/LICENSE b/vendor/github.com/cpuguy83/dockercfg/LICENSE deleted file mode 100644 index 8ed681804..000000000 --- a/vendor/github.com/cpuguy83/dockercfg/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2020 Brian Goff - -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/cpuguy83/dockercfg/README.md b/vendor/github.com/cpuguy83/dockercfg/README.md deleted file mode 100644 index 880ab8010..000000000 --- a/vendor/github.com/cpuguy83/dockercfg/README.md +++ /dev/null @@ -1,8 +0,0 @@ -### github.com/cpuguy83/dockercfg -Go library to load docker CLI configs, auths, etc. with minimal deps. -So far the only deps are on the stdlib. - -### Usage -See the [godoc](https://godoc.org/github.com/cpuguy83/dockercfg) for API details. - -I'm currently using this in [zapp](https://github.com/cpuguy83/zapp/blob/d25c43d4cd7ccf29fba184aafbc720a753e1a15d/main.go#L58-L83) to handle registry auth instead of always asking the user to enter it. \ No newline at end of file diff --git a/vendor/github.com/cpuguy83/dockercfg/auth.go b/vendor/github.com/cpuguy83/dockercfg/auth.go deleted file mode 100644 index 5a9891b87..000000000 --- a/vendor/github.com/cpuguy83/dockercfg/auth.go +++ /dev/null @@ -1,184 +0,0 @@ -package dockercfg - -import ( - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "os" - "os/exec" - "runtime" - "strings" -) - -// This is used by the docker CLI in casses where an oauth identity token is used. -// In that case the username is stored litterally as `` -// When fetching the credentials we check for this value to determine if -const tokenUsername = "" - -// GetRegistryCredentials gets registry credentials for the passed in registry host. -// -// This will use `LoadDefaultConfig` to read registry auth details from the config. -// If the config doesn't exist, it will attempt to load registry credentials using the default credential helper for the platform. -func GetRegistryCredentials(hostname string) (string, string, error) { - cfg, err := LoadDefaultConfig() - if err != nil { - if !os.IsNotExist(err) { - return "", "", err - } - return GetCredentialsFromHelper("", hostname) - } - return cfg.GetRegistryCredentials(hostname) -} - -// ResolveRegistryHost can be used to transform a docker registry host name into what is used for the docker config/cred helpers -// -// This is useful for using with containerd authorizers. -// Natrually this only transforms docker hub URLs. -func ResolveRegistryHost(host string) string { - switch host { - case "index.docker.io", "docker.io", "https://index.docker.io/v1/", "registry-1.docker.io": - return "https://index.docker.io/v1/" - } - return host -} - -// GetRegistryCredentials gets credentials, if any, for the provided hostname -// -// Hostnames should already be resolved using `ResolveRegistryAuth` -// -// If the returned username string is empty, the password is an identity token. -func (c *Config) GetRegistryCredentials(hostname string) (string, string, error) { - h, ok := c.CredentialHelpers[hostname] - if ok { - return GetCredentialsFromHelper(h, hostname) - } - - if c.CredentialsStore != "" { - return GetCredentialsFromHelper(c.CredentialsStore, hostname) - } - - auth, ok := c.AuthConfigs[hostname] - if !ok { - return GetCredentialsFromHelper("", hostname) - } - - if auth.IdentityToken != "" { - return "", auth.IdentityToken, nil - } - - if auth.Username != "" && auth.Password != "" { - return auth.Username, auth.Password, nil - } - - return DecodeBase64Auth(auth) -} - -// DecodeBase64Auth decodes the legacy file-based auth storage from the docker CLI. -// It takes the "Auth" filed from AuthConfig and decodes that into a username and password. -// -// If "Auth" is empty, an empty user/pass will be returned, but not an error. -func DecodeBase64Auth(auth AuthConfig) (string, string, error) { - if auth.Auth == "" { - return "", "", nil - } - - decLen := base64.StdEncoding.DecodedLen(len(auth.Auth)) - decoded := make([]byte, decLen) - n, err := base64.StdEncoding.Decode(decoded, []byte(auth.Auth)) - if err != nil { - return "", "", fmt.Errorf("error decoding auth from file: %w", err) - } - - if n > decLen { - return "", "", fmt.Errorf("decoded value is longer than expected length, expected: %d, actual: %d", decLen, n) - } - - split := strings.SplitN(string(decoded), ":", 2) - if len(split) != 2 { - return "", "", errors.New("invalid auth string") - } - - return split[0], strings.Trim(split[1], "\x00"), nil -} - -// Errors from credential helpers -var ( - ErrCredentialsNotFound = errors.New("credentials not found in native keychain") - ErrCredentialsMissingServerURL = errors.New("no credentials server URL") -) - -// GetCredentialsFromHelper attempts to lookup credentials from the passed in docker credential helper. -// -// The credential helpoer should just be the suffix name (no "docker-credential-"). -// If the passed in helper program is empty this will look up the default helper for the platform. -// -// If the credentials are not found, no error is returned, only empty credentials. -// -// Hostnames should already be resolved using `ResolveRegistryAuth` -// -// If the username string is empty, the password string is an identity token. -func GetCredentialsFromHelper(helper, hostname string) (string, string, error) { - if helper == "" { - helper = getCredentialHelper() - } - if helper == "" { - return "", "", nil - } - - p, err := exec.LookPath("docker-credential-" + helper) - if err != nil { - return "", "", nil - } - - cmd := exec.Command(p, "get") - cmd.Stdin = strings.NewReader(hostname) - - b, err := cmd.Output() - if err != nil { - s := strings.TrimSpace(string(b)) - - switch s { - case ErrCredentialsNotFound.Error(): - return "", "", nil - case ErrCredentialsMissingServerURL.Error(): - return "", "", errors.New(s) - default: - } - - return "", "", err - } - - var creds struct { - Username string - Secret string - } - - if err := json.Unmarshal(b, &creds); err != nil { - return "", "", err - } - - // When tokenUsername is used, the output is an identity token and the username is garbage - if creds.Username == tokenUsername { - creds.Username = "" - } - - return creds.Username, creds.Secret, nil -} - -// getCredentialHelper gets the default credential helper name for the current platform. -func getCredentialHelper() string { - switch runtime.GOOS { - case "linux": - if _, err := exec.LookPath("pass"); err == nil { - return "pass" - } - return "secretservice" - case "darwin": - return "osxkeychain" - case "windows": - return "wincred" - default: - return "" - } -} diff --git a/vendor/github.com/cpuguy83/dockercfg/config.go b/vendor/github.com/cpuguy83/dockercfg/config.go deleted file mode 100644 index 88736cabc..000000000 --- a/vendor/github.com/cpuguy83/dockercfg/config.go +++ /dev/null @@ -1,65 +0,0 @@ -package dockercfg - -// Config represents the on disk format of the docker CLI's config file. -type Config struct { - AuthConfigs map[string]AuthConfig `json:"auths"` - HTTPHeaders map[string]string `json:"HttpHeaders,omitempty"` - PsFormat string `json:"psFormat,omitempty"` - ImagesFormat string `json:"imagesFormat,omitempty"` - NetworksFormat string `json:"networksFormat,omitempty"` - PluginsFormat string `json:"pluginsFormat,omitempty"` - VolumesFormat string `json:"volumesFormat,omitempty"` - StatsFormat string `json:"statsFormat,omitempty"` - DetachKeys string `json:"detachKeys,omitempty"` - CredentialsStore string `json:"credsStore,omitempty"` - CredentialHelpers map[string]string `json:"credHelpers,omitempty"` - Filename string `json:"-"` // Note: for internal use only - ServiceInspectFormat string `json:"serviceInspectFormat,omitempty"` - ServicesFormat string `json:"servicesFormat,omitempty"` - TasksFormat string `json:"tasksFormat,omitempty"` - SecretFormat string `json:"secretFormat,omitempty"` - ConfigFormat string `json:"configFormat,omitempty"` - NodesFormat string `json:"nodesFormat,omitempty"` - PruneFilters []string `json:"pruneFilters,omitempty"` - Proxies map[string]ProxyConfig `json:"proxies,omitempty"` - Experimental string `json:"experimental,omitempty"` - StackOrchestrator string `json:"stackOrchestrator,omitempty"` - Kubernetes *KubernetesConfig `json:"kubernetes,omitempty"` - CurrentContext string `json:"currentContext,omitempty"` - CLIPluginsExtraDirs []string `json:"cliPluginsExtraDirs,omitempty"` - Aliases map[string]string `json:"aliases,omitempty"` -} - -// ProxyConfig contains proxy configuration settings -type ProxyConfig struct { - HTTPProxy string `json:"httpProxy,omitempty"` - HTTPSProxy string `json:"httpsProxy,omitempty"` - NoProxy string `json:"noProxy,omitempty"` - FTPProxy string `json:"ftpProxy,omitempty"` -} - -// AuthConfig contains authorization information for connecting to a Registry -type AuthConfig struct { - Username string `json:"username,omitempty"` - Password string `json:"password,omitempty"` - Auth string `json:"auth,omitempty"` - - // Email is an optional value associated with the username. - // This field is deprecated and will be removed in a later - // version of docker. - Email string `json:"email,omitempty"` - - ServerAddress string `json:"serveraddress,omitempty"` - - // IdentityToken is used to authenticate the user and get - // an access token for the registry. - IdentityToken string `json:"identitytoken,omitempty"` - - // RegistryToken is a bearer token to be sent to a registry - RegistryToken string `json:"registrytoken,omitempty"` -} - -// KubernetesConfig contains Kubernetes orchestrator settings -type KubernetesConfig struct { - AllNamespaces string `json:"allNamespaces,omitempty"` -} diff --git a/vendor/github.com/cpuguy83/dockercfg/load.go b/vendor/github.com/cpuguy83/dockercfg/load.go deleted file mode 100644 index 262545b9d..000000000 --- a/vendor/github.com/cpuguy83/dockercfg/load.go +++ /dev/null @@ -1,51 +0,0 @@ -package dockercfg - -import ( - "encoding/json" - "fmt" - "os" - "path/filepath" -) - -// UserHomeConfigPath returns the path to the docker config in the current user's home dir. -func UserHomeConfigPath() (string, error) { - home, err := os.UserHomeDir() - if err != nil { - return "", fmt.Errorf("error looking up user home dir: %w", err) - } - - return filepath.Join(home, ".docker", "config.json"), nil -} - -// ConfigPath returns the path to the docker cli config. -// -// It will either use the DOCKER_CONFIG env var if set, or the value from `UserHomeConfigPath` -// DOCKER_CONFIG would be the dir path where `config.json` is stored, this returns the path to config.json. -func ConfigPath() (string, error) { - if p := os.Getenv("DOCKER_CONFIG"); p != "" { - return filepath.Join(p, "config.json"), nil - } - return UserHomeConfigPath() -} - -// LoadDefaultConfig loads the docker cli config from the path returned from `ConfigPath` -func LoadDefaultConfig() (Config, error) { - var cfg Config - p, err := ConfigPath() - if err != nil { - return cfg, err - } - return cfg, FromFile(p, &cfg) -} - -// FromFile loads config from the specified path into cfg -func FromFile(configPath string, cfg *Config) error { - f, err := os.Open(configPath) - if err != nil { - return err - } - - err = json.NewDecoder(f).Decode(&cfg) - f.Close() - return err -} diff --git a/vendor/github.com/distribution/distribution/v3/LICENSE b/vendor/github.com/distribution/distribution/v3/LICENSE deleted file mode 100644 index e06d20818..000000000 --- a/vendor/github.com/distribution/distribution/v3/LICENSE +++ /dev/null @@ -1,202 +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/distribution/distribution/v3/reference/helpers.go b/vendor/github.com/distribution/distribution/v3/reference/helpers.go deleted file mode 100644 index d10c7ef83..000000000 --- a/vendor/github.com/distribution/distribution/v3/reference/helpers.go +++ /dev/null @@ -1,42 +0,0 @@ -package reference - -import "path" - -// IsNameOnly returns true if reference only contains a repo name. -func IsNameOnly(ref Named) bool { - if _, ok := ref.(NamedTagged); ok { - return false - } - if _, ok := ref.(Canonical); ok { - return false - } - return true -} - -// FamiliarName returns the familiar name string -// for the given named, familiarizing if needed. -func FamiliarName(ref Named) string { - if nn, ok := ref.(normalizedNamed); ok { - return nn.Familiar().Name() - } - return ref.Name() -} - -// FamiliarString returns the familiar string representation -// for the given reference, familiarizing if needed. -func FamiliarString(ref Reference) string { - if nn, ok := ref.(normalizedNamed); ok { - return nn.Familiar().String() - } - return ref.String() -} - -// FamiliarMatch reports whether ref matches the specified pattern. -// See [path.Match] for supported patterns. -func FamiliarMatch(pattern string, ref Reference) (bool, error) { - matched, err := path.Match(pattern, FamiliarString(ref)) - if namedRef, isNamed := ref.(Named); isNamed && !matched { - matched, _ = path.Match(pattern, FamiliarName(namedRef)) - } - return matched, err -} diff --git a/vendor/github.com/distribution/distribution/v3/reference/normalize.go b/vendor/github.com/distribution/distribution/v3/reference/normalize.go deleted file mode 100644 index f2ce13ada..000000000 --- a/vendor/github.com/distribution/distribution/v3/reference/normalize.go +++ /dev/null @@ -1,224 +0,0 @@ -package reference - -import ( - "fmt" - "strings" - - "github.com/opencontainers/go-digest" -) - -const ( - // legacyDefaultDomain is the legacy domain for Docker Hub (which was - // originally named "the Docker Index"). This domain is still used for - // authentication and image search, which were part of the "v1" Docker - // registry specification. - // - // This domain will continue to be supported, but there are plans to consolidate - // legacy domains to new "canonical" domains. Once those domains are decided - // on, we must update the normalization functions, but preserve compatibility - // with existing installs, clients, and user configuration. - legacyDefaultDomain = "index.docker.io" - - // defaultDomain is the default domain used for images on Docker Hub. - // It is used to normalize "familiar" names to canonical names, for example, - // to convert "ubuntu" to "docker.io/library/ubuntu:latest". - // - // Note that actual domain of Docker Hub's registry is registry-1.docker.io. - // This domain will continue to be supported, but there are plans to consolidate - // legacy domains to new "canonical" domains. Once those domains are decided - // on, we must update the normalization functions, but preserve compatibility - // with existing installs, clients, and user configuration. - defaultDomain = "docker.io" - - // officialRepoPrefix is the namespace used for official images on Docker Hub. - // It is used to normalize "familiar" names to canonical names, for example, - // to convert "ubuntu" to "docker.io/library/ubuntu:latest". - officialRepoPrefix = "library/" - - // defaultTag is the default tag if no tag is provided. - defaultTag = "latest" -) - -// normalizedNamed represents a name which has been -// normalized and has a familiar form. A familiar name -// is what is used in Docker UI. An example normalized -// name is "docker.io/library/ubuntu" and corresponding -// familiar name of "ubuntu". -type normalizedNamed interface { - Named - Familiar() Named -} - -// ParseNormalizedNamed parses a string into a named reference -// transforming a familiar name from Docker UI to a fully -// qualified reference. If the value may be an identifier -// use ParseAnyReference. -func ParseNormalizedNamed(s string) (Named, error) { - if ok := anchoredIdentifierRegexp.MatchString(s); ok { - return nil, fmt.Errorf("invalid repository name (%s), cannot specify 64-byte hexadecimal strings", s) - } - domain, remainder := splitDockerDomain(s) - var remote string - if tagSep := strings.IndexRune(remainder, ':'); tagSep > -1 { - remote = remainder[:tagSep] - } else { - remote = remainder - } - if strings.ToLower(remote) != remote { - return nil, fmt.Errorf("invalid reference format: repository name (%s) must be lowercase", remote) - } - - ref, err := Parse(domain + "/" + remainder) - if err != nil { - return nil, err - } - named, isNamed := ref.(Named) - if !isNamed { - return nil, fmt.Errorf("reference %s has no name", ref.String()) - } - return named, nil -} - -// namedTaggedDigested is a reference that has both a tag and a digest. -type namedTaggedDigested interface { - NamedTagged - Digested -} - -// ParseDockerRef normalizes the image reference following the docker convention, -// which allows for references to contain both a tag and a digest. It returns a -// reference that is either tagged or digested. For references containing both -// a tag and a digest, it returns a digested reference. For example, the following -// reference: -// -// docker.io/library/busybox:latest@sha256:7cc4b5aefd1d0cadf8d97d4350462ba51c694ebca145b08d7d41b41acc8db5aa -// -// Is returned as a digested reference (with the ":latest" tag removed): -// -// docker.io/library/busybox@sha256:7cc4b5aefd1d0cadf8d97d4350462ba51c694ebca145b08d7d41b41acc8db5aa -// -// References that are already "tagged" or "digested" are returned unmodified: -// -// // Already a digested reference -// docker.io/library/busybox@sha256:7cc4b5aefd1d0cadf8d97d4350462ba51c694ebca145b08d7d41b41acc8db5aa -// -// // Already a named reference -// docker.io/library/busybox:latest -func ParseDockerRef(ref string) (Named, error) { - named, err := ParseNormalizedNamed(ref) - if err != nil { - return nil, err - } - if canonical, ok := named.(namedTaggedDigested); ok { - // The reference is both tagged and digested; only return digested. - newNamed, err := WithName(canonical.Name()) - if err != nil { - return nil, err - } - return WithDigest(newNamed, canonical.Digest()) - } - return TagNameOnly(named), nil -} - -// splitDockerDomain splits a repository name to domain and remote-name. -// If no valid domain is found, the default domain is used. Repository name -// needs to be already validated before. -func splitDockerDomain(name string) (domain, remainder string) { - i := strings.IndexRune(name, '/') - if i == -1 || (!strings.ContainsAny(name[:i], ".:") && name[:i] != localhost && strings.ToLower(name[:i]) == name[:i]) { - domain, remainder = defaultDomain, name - } else { - domain, remainder = name[:i], name[i+1:] - } - if domain == legacyDefaultDomain { - domain = defaultDomain - } - if domain == defaultDomain && !strings.ContainsRune(remainder, '/') { - remainder = officialRepoPrefix + remainder - } - return -} - -// familiarizeName returns a shortened version of the name familiar -// to to the Docker UI. Familiar names have the default domain -// "docker.io" and "library/" repository prefix removed. -// For example, "docker.io/library/redis" will have the familiar -// name "redis" and "docker.io/dmcgowan/myapp" will be "dmcgowan/myapp". -// Returns a familiarized named only reference. -func familiarizeName(named namedRepository) repository { - repo := repository{ - domain: named.Domain(), - path: named.Path(), - } - - if repo.domain == defaultDomain { - repo.domain = "" - // Handle official repositories which have the pattern "library/" - if strings.HasPrefix(repo.path, officialRepoPrefix) { - // TODO(thaJeztah): this check may be too strict, as it assumes the - // "library/" namespace does not have nested namespaces. While this - // is true (currently), technically it would be possible for Docker - // Hub to use those (e.g. "library/distros/ubuntu:latest"). - // See https://github.com/distribution/distribution/pull/3769#issuecomment-1302031785. - if remainder := strings.TrimPrefix(repo.path, officialRepoPrefix); !strings.ContainsRune(remainder, '/') { - repo.path = remainder - } - } - } - return repo -} - -func (r reference) Familiar() Named { - return reference{ - namedRepository: familiarizeName(r.namedRepository), - tag: r.tag, - digest: r.digest, - } -} - -func (r repository) Familiar() Named { - return familiarizeName(r) -} - -func (t taggedReference) Familiar() Named { - return taggedReference{ - namedRepository: familiarizeName(t.namedRepository), - tag: t.tag, - } -} - -func (c canonicalReference) Familiar() Named { - return canonicalReference{ - namedRepository: familiarizeName(c.namedRepository), - digest: c.digest, - } -} - -// TagNameOnly adds the default tag "latest" to a reference if it only has -// a repo name. -func TagNameOnly(ref Named) Named { - if IsNameOnly(ref) { - namedTagged, err := WithTag(ref, defaultTag) - if err != nil { - // Default tag must be valid, to create a NamedTagged - // type with non-validated input the WithTag function - // should be used instead - panic(err) - } - return namedTagged - } - return ref -} - -// ParseAnyReference parses a reference string as a possible identifier, -// full digest, or familiar name. -func ParseAnyReference(ref string) (Reference, error) { - if ok := anchoredIdentifierRegexp.MatchString(ref); ok { - return digestReference("sha256:" + ref), nil - } - if dgst, err := digest.Parse(ref); err == nil { - return digestReference(dgst), nil - } - - return ParseNormalizedNamed(ref) -} diff --git a/vendor/github.com/distribution/distribution/v3/reference/reference.go b/vendor/github.com/distribution/distribution/v3/reference/reference.go deleted file mode 100644 index e98c44daa..000000000 --- a/vendor/github.com/distribution/distribution/v3/reference/reference.go +++ /dev/null @@ -1,436 +0,0 @@ -// Package reference provides a general type to represent any way of referencing images within the registry. -// Its main purpose is to abstract tags and digests (content-addressable hash). -// -// Grammar -// -// reference := name [ ":" tag ] [ "@" digest ] -// name := [domain '/'] remote-name -// domain := host [':' port-number] -// host := domain-name | IPv4address | \[ IPv6address \] ; rfc3986 appendix-A -// domain-name := domain-component ['.' domain-component]* -// domain-component := /([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])/ -// port-number := /[0-9]+/ -// path-component := alpha-numeric [separator alpha-numeric]* -// path (or "remote-name") := path-component ['/' path-component]* -// alpha-numeric := /[a-z0-9]+/ -// separator := /[_.]|__|[-]*/ -// -// tag := /[\w][\w.-]{0,127}/ -// -// digest := digest-algorithm ":" digest-hex -// digest-algorithm := digest-algorithm-component [ digest-algorithm-separator digest-algorithm-component ]* -// digest-algorithm-separator := /[+.-_]/ -// digest-algorithm-component := /[A-Za-z][A-Za-z0-9]*/ -// digest-hex := /[0-9a-fA-F]{32,}/ ; At least 128 bit digest value -// -// identifier := /[a-f0-9]{64}/ -package reference - -import ( - "errors" - "fmt" - "strings" - - "github.com/opencontainers/go-digest" -) - -const ( - // NameTotalLengthMax is the maximum total number of characters in a repository name. - NameTotalLengthMax = 255 -) - -var ( - // ErrReferenceInvalidFormat represents an error while trying to parse a string as a reference. - ErrReferenceInvalidFormat = errors.New("invalid reference format") - - // ErrTagInvalidFormat represents an error while trying to parse a string as a tag. - ErrTagInvalidFormat = errors.New("invalid tag format") - - // ErrDigestInvalidFormat represents an error while trying to parse a string as a tag. - ErrDigestInvalidFormat = errors.New("invalid digest format") - - // ErrNameContainsUppercase is returned for invalid repository names that contain uppercase characters. - ErrNameContainsUppercase = errors.New("repository name must be lowercase") - - // ErrNameEmpty is returned for empty, invalid repository names. - ErrNameEmpty = errors.New("repository name must have at least one component") - - // ErrNameTooLong is returned when a repository name is longer than NameTotalLengthMax. - ErrNameTooLong = fmt.Errorf("repository name must not be more than %v characters", NameTotalLengthMax) - - // ErrNameNotCanonical is returned when a name is not canonical. - ErrNameNotCanonical = errors.New("repository name must be canonical") -) - -// Reference is an opaque object reference identifier that may include -// modifiers such as a hostname, name, tag, and digest. -type Reference interface { - // String returns the full reference - String() string -} - -// Field provides a wrapper type for resolving correct reference types when -// working with encoding. -type Field struct { - reference Reference -} - -// AsField wraps a reference in a Field for encoding. -func AsField(reference Reference) Field { - return Field{reference} -} - -// Reference unwraps the reference type from the field to -// return the Reference object. This object should be -// of the appropriate type to further check for different -// reference types. -func (f Field) Reference() Reference { - return f.reference -} - -// MarshalText serializes the field to byte text which -// is the string of the reference. -func (f Field) MarshalText() (p []byte, err error) { - return []byte(f.reference.String()), nil -} - -// UnmarshalText parses text bytes by invoking the -// reference parser to ensure the appropriately -// typed reference object is wrapped by field. -func (f *Field) UnmarshalText(p []byte) error { - r, err := Parse(string(p)) - if err != nil { - return err - } - - f.reference = r - return nil -} - -// Named is an object with a full name -type Named interface { - Reference - Name() string -} - -// Tagged is an object which has a tag -type Tagged interface { - Reference - Tag() string -} - -// NamedTagged is an object including a name and tag. -type NamedTagged interface { - Named - Tag() string -} - -// Digested is an object which has a digest -// in which it can be referenced by -type Digested interface { - Reference - Digest() digest.Digest -} - -// Canonical reference is an object with a fully unique -// name including a name with domain and digest -type Canonical interface { - Named - Digest() digest.Digest -} - -// namedRepository is a reference to a repository with a name. -// A namedRepository has both domain and path components. -type namedRepository interface { - Named - Domain() string - Path() string -} - -// Domain returns the domain part of the [Named] reference. -func Domain(named Named) string { - if r, ok := named.(namedRepository); ok { - return r.Domain() - } - domain, _ := splitDomain(named.Name()) - return domain -} - -// Path returns the name without the domain part of the [Named] reference. -func Path(named Named) (name string) { - if r, ok := named.(namedRepository); ok { - return r.Path() - } - _, path := splitDomain(named.Name()) - return path -} - -func splitDomain(name string) (string, string) { - match := anchoredNameRegexp.FindStringSubmatch(name) - if len(match) != 3 { - return "", name - } - return match[1], match[2] -} - -// SplitHostname splits a named reference into a -// hostname and name string. If no valid hostname is -// found, the hostname is empty and the full value -// is returned as name -// -// Deprecated: Use [Domain] or [Path]. -func SplitHostname(named Named) (string, string) { - if r, ok := named.(namedRepository); ok { - return r.Domain(), r.Path() - } - return splitDomain(named.Name()) -} - -// Parse parses s and returns a syntactically valid Reference. -// If an error was encountered it is returned, along with a nil Reference. -func Parse(s string) (Reference, error) { - matches := ReferenceRegexp.FindStringSubmatch(s) - if matches == nil { - if s == "" { - return nil, ErrNameEmpty - } - if ReferenceRegexp.FindStringSubmatch(strings.ToLower(s)) != nil { - return nil, ErrNameContainsUppercase - } - return nil, ErrReferenceInvalidFormat - } - - if len(matches[1]) > NameTotalLengthMax { - return nil, ErrNameTooLong - } - - var repo repository - - nameMatch := anchoredNameRegexp.FindStringSubmatch(matches[1]) - if len(nameMatch) == 3 { - repo.domain = nameMatch[1] - repo.path = nameMatch[2] - } else { - repo.domain = "" - repo.path = matches[1] - } - - ref := reference{ - namedRepository: repo, - tag: matches[2], - } - if matches[3] != "" { - var err error - ref.digest, err = digest.Parse(matches[3]) - if err != nil { - return nil, err - } - } - - r := getBestReferenceType(ref) - if r == nil { - return nil, ErrNameEmpty - } - - return r, nil -} - -// ParseNamed parses s and returns a syntactically valid reference implementing -// the Named interface. The reference must have a name and be in the canonical -// form, otherwise an error is returned. -// If an error was encountered it is returned, along with a nil Reference. -func ParseNamed(s string) (Named, error) { - named, err := ParseNormalizedNamed(s) - if err != nil { - return nil, err - } - if named.String() != s { - return nil, ErrNameNotCanonical - } - return named, nil -} - -// WithName returns a named object representing the given string. If the input -// is invalid ErrReferenceInvalidFormat will be returned. -func WithName(name string) (Named, error) { - if len(name) > NameTotalLengthMax { - return nil, ErrNameTooLong - } - - match := anchoredNameRegexp.FindStringSubmatch(name) - if match == nil || len(match) != 3 { - return nil, ErrReferenceInvalidFormat - } - return repository{ - domain: match[1], - path: match[2], - }, nil -} - -// WithTag combines the name from "name" and the tag from "tag" to form a -// reference incorporating both the name and the tag. -func WithTag(name Named, tag string) (NamedTagged, error) { - if !anchoredTagRegexp.MatchString(tag) { - return nil, ErrTagInvalidFormat - } - var repo repository - if r, ok := name.(namedRepository); ok { - repo.domain = r.Domain() - repo.path = r.Path() - } else { - repo.path = name.Name() - } - if canonical, ok := name.(Canonical); ok { - return reference{ - namedRepository: repo, - tag: tag, - digest: canonical.Digest(), - }, nil - } - return taggedReference{ - namedRepository: repo, - tag: tag, - }, nil -} - -// WithDigest combines the name from "name" and the digest from "digest" to form -// a reference incorporating both the name and the digest. -func WithDigest(name Named, digest digest.Digest) (Canonical, error) { - if !anchoredDigestRegexp.MatchString(digest.String()) { - return nil, ErrDigestInvalidFormat - } - var repo repository - if r, ok := name.(namedRepository); ok { - repo.domain = r.Domain() - repo.path = r.Path() - } else { - repo.path = name.Name() - } - if tagged, ok := name.(Tagged); ok { - return reference{ - namedRepository: repo, - tag: tagged.Tag(), - digest: digest, - }, nil - } - return canonicalReference{ - namedRepository: repo, - digest: digest, - }, nil -} - -// TrimNamed removes any tag or digest from the named reference. -func TrimNamed(ref Named) Named { - repo := repository{} - if r, ok := ref.(namedRepository); ok { - repo.domain, repo.path = r.Domain(), r.Path() - } else { - repo.domain, repo.path = splitDomain(ref.Name()) - } - return repo -} - -func getBestReferenceType(ref reference) Reference { - if ref.Name() == "" { - // Allow digest only references - if ref.digest != "" { - return digestReference(ref.digest) - } - return nil - } - if ref.tag == "" { - if ref.digest != "" { - return canonicalReference{ - namedRepository: ref.namedRepository, - digest: ref.digest, - } - } - return ref.namedRepository - } - if ref.digest == "" { - return taggedReference{ - namedRepository: ref.namedRepository, - tag: ref.tag, - } - } - - return ref -} - -type reference struct { - namedRepository - tag string - digest digest.Digest -} - -func (r reference) String() string { - return r.Name() + ":" + r.tag + "@" + r.digest.String() -} - -func (r reference) Tag() string { - return r.tag -} - -func (r reference) Digest() digest.Digest { - return r.digest -} - -type repository struct { - domain string - path string -} - -func (r repository) String() string { - return r.Name() -} - -func (r repository) Name() string { - if r.domain == "" { - return r.path - } - return r.domain + "/" + r.path -} - -func (r repository) Domain() string { - return r.domain -} - -func (r repository) Path() string { - return r.path -} - -type digestReference digest.Digest - -func (d digestReference) String() string { - return digest.Digest(d).String() -} - -func (d digestReference) Digest() digest.Digest { - return digest.Digest(d) -} - -type taggedReference struct { - namedRepository - tag string -} - -func (t taggedReference) String() string { - return t.Name() + ":" + t.tag -} - -func (t taggedReference) Tag() string { - return t.tag -} - -type canonicalReference struct { - namedRepository - digest digest.Digest -} - -func (c canonicalReference) String() string { - return c.Name() + "@" + c.digest.String() -} - -func (c canonicalReference) Digest() digest.Digest { - return c.digest -} diff --git a/vendor/github.com/distribution/distribution/v3/reference/regexp.go b/vendor/github.com/distribution/distribution/v3/reference/regexp.go deleted file mode 100644 index 65bc49d79..000000000 --- a/vendor/github.com/distribution/distribution/v3/reference/regexp.go +++ /dev/null @@ -1,163 +0,0 @@ -package reference - -import ( - "regexp" - "strings" -) - -// DigestRegexp matches well-formed digests, including algorithm (e.g. "sha256:"). -var DigestRegexp = regexp.MustCompile(digestPat) - -// DomainRegexp matches hostname or IP-addresses, optionally including a port -// number. It defines the structure of potential domain components that may be -// part of image names. This is purposely a subset of what is allowed by DNS to -// ensure backwards compatibility with Docker image names. It may be a subset of -// DNS domain name, an IPv4 address in decimal format, or an IPv6 address between -// square brackets (excluding zone identifiers as defined by [RFC 6874] or special -// addresses such as IPv4-Mapped). -// -// [RFC 6874]: https://www.rfc-editor.org/rfc/rfc6874. -var DomainRegexp = regexp.MustCompile(domainAndPort) - -// IdentifierRegexp is the format for string identifier used as a -// content addressable identifier using sha256. These identifiers -// are like digests without the algorithm, since sha256 is used. -var IdentifierRegexp = regexp.MustCompile(identifier) - -// NameRegexp is the format for the name component of references, including -// an optional domain and port, but without tag or digest suffix. -var NameRegexp = regexp.MustCompile(namePat) - -// ReferenceRegexp is the full supported format of a reference. The regexp -// is anchored and has capturing groups for name, tag, and digest -// components. -var ReferenceRegexp = regexp.MustCompile(referencePat) - -// TagRegexp matches valid tag names. From [docker/docker:graph/tags.go]. -// -// [docker/docker:graph/tags.go]: https://github.com/moby/moby/blob/v1.6.0/graph/tags.go#L26-L28 -var TagRegexp = regexp.MustCompile(tag) - -const ( - // alphanumeric defines the alphanumeric atom, typically a - // component of names. This only allows lower case characters and digits. - alphanumeric = `[a-z0-9]+` - - // separator defines the separators allowed to be embedded in name - // components. This allows one period, one or two underscore and multiple - // dashes. Repeated dashes and underscores are intentionally treated - // differently. In order to support valid hostnames as name components, - // supporting repeated dash was added. Additionally double underscore is - // now allowed as a separator to loosen the restriction for previously - // supported names. - separator = `(?:[._]|__|[-]+)` - - // localhost is treated as a special value for domain-name. Any other - // domain-name without a "." or a ":port" are considered a path component. - localhost = `localhost` - - // domainNameComponent restricts the registry domain component of a - // repository name to start with a component as defined by DomainRegexp. - domainNameComponent = `(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])` - - // optionalPort matches an optional port-number including the port separator - // (e.g. ":80"). - optionalPort = `(?::[0-9]+)?` - - // tag matches valid tag names. From docker/docker:graph/tags.go. - tag = `[\w][\w.-]{0,127}` - - // digestPat matches well-formed digests, including algorithm (e.g. "sha256:"). - // - // TODO(thaJeztah): this should follow the same rules as https://pkg.go.dev/github.com/opencontainers/go-digest@v1.0.0#DigestRegexp - // so that go-digest defines the canonical format. Note that the go-digest is - // more relaxed: - // - it allows multiple algorithms (e.g. "sha256+b64:") to allow - // future expansion of supported algorithms. - // - it allows the "" value to use urlsafe base64 encoding as defined - // in [rfc4648, section 5]. - // - // [rfc4648, section 5]: https://www.rfc-editor.org/rfc/rfc4648#section-5. - digestPat = `[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*[:][[:xdigit:]]{32,}` - - // identifier is the format for a content addressable identifier using sha256. - // These identifiers are like digests without the algorithm, since sha256 is used. - identifier = `([a-f0-9]{64})` - - // ipv6address are enclosed between square brackets and may be represented - // in many ways, see rfc5952. Only IPv6 in compressed or uncompressed format - // are allowed, IPv6 zone identifiers (rfc6874) or Special addresses such as - // IPv4-Mapped are deliberately excluded. - ipv6address = `\[(?:[a-fA-F0-9:]+)\]` -) - -var ( - // domainName defines the structure of potential domain components - // that may be part of image names. This is purposely a subset of what is - // allowed by DNS to ensure backwards compatibility with Docker image - // names. This includes IPv4 addresses on decimal format. - domainName = domainNameComponent + anyTimes(`\.`+domainNameComponent) - - // host defines the structure of potential domains based on the URI - // Host subcomponent on rfc3986. It may be a subset of DNS domain name, - // or an IPv4 address in decimal format, or an IPv6 address between square - // brackets (excluding zone identifiers as defined by rfc6874 or special - // addresses such as IPv4-Mapped). - host = `(?:` + domainName + `|` + ipv6address + `)` - - // allowed by the URI Host subcomponent on rfc3986 to ensure backwards - // compatibility with Docker image names. - domainAndPort = host + optionalPort - - // anchoredTagRegexp matches valid tag names, anchored at the start and - // end of the matched string. - anchoredTagRegexp = regexp.MustCompile(anchored(tag)) - - // anchoredDigestRegexp matches valid digests, anchored at the start and - // end of the matched string. - anchoredDigestRegexp = regexp.MustCompile(anchored(digestPat)) - - // pathComponent restricts path-components to start with an alphanumeric - // character, with following parts able to be separated by a separator - // (one period, one or two underscore and multiple dashes). - pathComponent = alphanumeric + anyTimes(separator+alphanumeric) - - // remoteName matches the remote-name of a repository. It consists of one - // or more forward slash (/) delimited path-components: - // - // pathComponent[[/pathComponent] ...] // e.g., "library/ubuntu" - remoteName = pathComponent + anyTimes(`/`+pathComponent) - namePat = optional(domainAndPort+`/`) + remoteName - - // anchoredNameRegexp is used to parse a name value, capturing the - // domain and trailing components. - anchoredNameRegexp = regexp.MustCompile(anchored(optional(capture(domainAndPort), `/`), capture(remoteName))) - - referencePat = anchored(capture(namePat), optional(`:`, capture(tag)), optional(`@`, capture(digestPat))) - - // anchoredIdentifierRegexp is used to check or match an - // identifier value, anchored at start and end of string. - anchoredIdentifierRegexp = regexp.MustCompile(anchored(identifier)) -) - -// optional wraps the expression in a non-capturing group and makes the -// production optional. -func optional(res ...string) string { - return `(?:` + strings.Join(res, "") + `)?` -} - -// anyTimes wraps the expression in a non-capturing group that can occur -// any number of times. -func anyTimes(res ...string) string { - return `(?:` + strings.Join(res, "") + `)*` -} - -// capture wraps the expression in a capturing group. -func capture(res ...string) string { - return `(` + strings.Join(res, "") + `)` -} - -// anchored anchors the regular expression by adding start and end delimiters. -func anchored(res ...string) string { - return `^` + strings.Join(res, "") + `$` -} diff --git a/vendor/github.com/distribution/distribution/v3/reference/sort.go b/vendor/github.com/distribution/distribution/v3/reference/sort.go deleted file mode 100644 index 416c37b07..000000000 --- a/vendor/github.com/distribution/distribution/v3/reference/sort.go +++ /dev/null @@ -1,75 +0,0 @@ -/* - Copyright The containerd 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 reference - -import ( - "sort" -) - -// Sort sorts string references preferring higher information references. -// -// The precedence is as follows: -// -// 1. [Named] + [Tagged] + [Digested] (e.g., "docker.io/library/busybox:latest@sha256:") -// 2. [Named] + [Tagged] (e.g., "docker.io/library/busybox:latest") -// 3. [Named] + [Digested] (e.g., "docker.io/library/busybo@sha256:") -// 4. [Named] (e.g., "docker.io/library/busybox") -// 5. [Digested] (e.g., "docker.io@sha256:") -// 6. Parse error -func Sort(references []string) []string { - var prefs []Reference - var bad []string - - for _, ref := range references { - pref, err := ParseAnyReference(ref) - if err != nil { - bad = append(bad, ref) - } else { - prefs = append(prefs, pref) - } - } - sort.Slice(prefs, func(a, b int) bool { - ar := refRank(prefs[a]) - br := refRank(prefs[b]) - if ar == br { - return prefs[a].String() < prefs[b].String() - } - return ar < br - }) - sort.Strings(bad) - var refs []string - for _, pref := range prefs { - refs = append(refs, pref.String()) - } - return append(refs, bad...) -} - -func refRank(ref Reference) uint8 { - if _, ok := ref.(Named); ok { - if _, ok = ref.(Tagged); ok { - if _, ok = ref.(Digested); ok { - return 1 - } - return 2 - } - if _, ok = ref.(Digested); ok { - return 3 - } - return 4 - } - return 5 -} diff --git a/vendor/github.com/distribution/distribution/v3/uuid/uuid.go b/vendor/github.com/distribution/distribution/v3/uuid/uuid.go deleted file mode 100644 index d433ccaf5..000000000 --- a/vendor/github.com/distribution/distribution/v3/uuid/uuid.go +++ /dev/null @@ -1,126 +0,0 @@ -// Package uuid provides simple UUID generation. Only version 4 style UUIDs -// can be generated. -// -// Please see http://tools.ietf.org/html/rfc4122 for details on UUIDs. -package uuid - -import ( - "crypto/rand" - "fmt" - "io" - "os" - "syscall" - "time" -) - -const ( - // Bits is the number of bits in a UUID - Bits = 128 - - // Size is the number of bytes in a UUID - Size = Bits / 8 - - format = "%08x-%04x-%04x-%04x-%012x" -) - -var ( - // ErrUUIDInvalid indicates a parsed string is not a valid uuid. - ErrUUIDInvalid = fmt.Errorf("invalid uuid") - - // Loggerf can be used to override the default logging destination. Such - // log messages in this library should be logged at warning or higher. - Loggerf = func(format string, args ...interface{}) {} -) - -// UUID represents a UUID value. UUIDs can be compared and set to other values -// and accessed by byte. -type UUID [Size]byte - -// Generate creates a new, version 4 uuid. -func Generate() (u UUID) { - const ( - // ensures we backoff for less than 450ms total. Use the following to - // select new value, in units of 10ms: - // n*(n+1)/2 = d -> n^2 + n - 2d -> n = (sqrt(8d + 1) - 1)/2 - maxretries = 9 - backoff = time.Millisecond * 10 - ) - - var ( - totalBackoff time.Duration - count int - retries int - ) - - for { - // This should never block but the read may fail. Because of this, - // we just try to read the random number generator until we get - // something. This is a very rare condition but may happen. - b := time.Duration(retries) * backoff - time.Sleep(b) - totalBackoff += b - - n, err := io.ReadFull(rand.Reader, u[count:]) - if err != nil { - if retryOnError(err) && retries < maxretries { - count += n - retries++ - Loggerf("error generating version 4 uuid, retrying: %v", err) - continue - } - - // Any other errors represent a system problem. What did someone - // do to /dev/urandom? - panic(fmt.Errorf("error reading random number generator, retried for %v: %v", totalBackoff.String(), err)) - } - - break - } - - u[6] = (u[6] & 0x0f) | 0x40 // set version byte - u[8] = (u[8] & 0x3f) | 0x80 // set high order byte 0b10{8,9,a,b} - - return u -} - -// Parse attempts to extract a uuid from the string or returns an error. -func Parse(s string) (u UUID, err error) { - if len(s) != 36 { - return UUID{}, ErrUUIDInvalid - } - - // create stack addresses for each section of the uuid. - p := make([][]byte, 5) - - if _, err := fmt.Sscanf(s, format, &p[0], &p[1], &p[2], &p[3], &p[4]); err != nil { - return u, err - } - - copy(u[0:4], p[0]) - copy(u[4:6], p[1]) - copy(u[6:8], p[2]) - copy(u[8:10], p[3]) - copy(u[10:16], p[4]) - - return -} - -func (u UUID) String() string { - return fmt.Sprintf(format, u[:4], u[4:6], u[6:8], u[8:10], u[10:]) -} - -// retryOnError tries to detect whether or not retrying would be fruitful. -func retryOnError(err error) bool { - switch err := err.(type) { - case *os.PathError: - return retryOnError(err.Err) // unpack the target error - case syscall.Errno: - if err == syscall.EPERM { - // EPERM represents an entropy pool exhaustion, a condition under - // which we backoff and retry. - return true - } - } - - return false -} diff --git a/vendor/github.com/distribution/reference/.gitattributes b/vendor/github.com/distribution/reference/.gitattributes deleted file mode 100644 index d207b1802..000000000 --- a/vendor/github.com/distribution/reference/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -*.go text eol=lf diff --git a/vendor/github.com/distribution/reference/.gitignore b/vendor/github.com/distribution/reference/.gitignore deleted file mode 100644 index dc07e6b04..000000000 --- a/vendor/github.com/distribution/reference/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -# Cover profiles -*.out diff --git a/vendor/github.com/distribution/reference/.golangci.yml b/vendor/github.com/distribution/reference/.golangci.yml deleted file mode 100644 index 793f0bb7e..000000000 --- a/vendor/github.com/distribution/reference/.golangci.yml +++ /dev/null @@ -1,18 +0,0 @@ -linters: - enable: - - bodyclose - - dupword # Checks for duplicate words in the source code - - gofmt - - goimports - - ineffassign - - misspell - - revive - - staticcheck - - unconvert - - unused - - vet - disable: - - errcheck - -run: - deadline: 2m diff --git a/vendor/github.com/distribution/reference/CODE-OF-CONDUCT.md b/vendor/github.com/distribution/reference/CODE-OF-CONDUCT.md deleted file mode 100644 index 48f6704c6..000000000 --- a/vendor/github.com/distribution/reference/CODE-OF-CONDUCT.md +++ /dev/null @@ -1,5 +0,0 @@ -# Code of Conduct - -We follow the [CNCF Code of Conduct](https://github.com/cncf/foundation/blob/main/code-of-conduct.md). - -Please contact the [CNCF Code of Conduct Committee](mailto:conduct@cncf.io) in order to report violations of the Code of Conduct. diff --git a/vendor/github.com/distribution/reference/CONTRIBUTING.md b/vendor/github.com/distribution/reference/CONTRIBUTING.md deleted file mode 100644 index ab2194665..000000000 --- a/vendor/github.com/distribution/reference/CONTRIBUTING.md +++ /dev/null @@ -1,114 +0,0 @@ -# Contributing to the reference library - -## Community help - -If you need help, please ask in the [#distribution](https://cloud-native.slack.com/archives/C01GVR8SY4R) channel on CNCF community slack. -[Click here for an invite to the CNCF community slack](https://slack.cncf.io/) - -## Reporting security issues - -The maintainers take security seriously. If you discover a security -issue, please bring it to their attention right away! - -Please **DO NOT** file a public issue, instead send your report privately to -[cncf-distribution-security@lists.cncf.io](mailto:cncf-distribution-security@lists.cncf.io). - -## Reporting an issue properly - -By following these simple rules you will get better and faster feedback on your issue. - - - search the bugtracker for an already reported issue - -### If you found an issue that describes your problem: - - - please read other user comments first, and confirm this is the same issue: a given error condition might be indicative of different problems - you may also find a workaround in the comments - - please refrain from adding "same thing here" or "+1" comments - - you don't need to comment on an issue to get notified of updates: just hit the "subscribe" button - - comment if you have some new, technical and relevant information to add to the case - - __DO NOT__ comment on closed issues or merged PRs. If you think you have a related problem, open up a new issue and reference the PR or issue. - -### If you have not found an existing issue that describes your problem: - - 1. create a new issue, with a succinct title that describes your issue: - - bad title: "It doesn't work with my docker" - - good title: "Private registry push fail: 400 error with E_INVALID_DIGEST" - 2. copy the output of (or similar for other container tools): - - `docker version` - - `docker info` - - `docker exec registry --version` - 3. copy the command line you used to launch your Registry - 4. restart your docker daemon in debug mode (add `-D` to the daemon launch arguments) - 5. reproduce your problem and get your docker daemon logs showing the error - 6. if relevant, copy your registry logs that show the error - 7. provide any relevant detail about your specific Registry configuration (e.g., storage backend used) - 8. indicate if you are using an enterprise proxy, Nginx, or anything else between you and your Registry - -## Contributing Code - -Contributions should be made via pull requests. Pull requests will be reviewed -by one or more maintainers or reviewers and merged when acceptable. - -You should follow the basic GitHub workflow: - - 1. Use your own [fork](https://help.github.com/en/articles/about-forks) - 2. Create your [change](https://github.com/containerd/project/blob/master/CONTRIBUTING.md#successful-changes) - 3. Test your code - 4. [Commit](https://github.com/containerd/project/blob/master/CONTRIBUTING.md#commit-messages) your work, always [sign your commits](https://github.com/containerd/project/blob/master/CONTRIBUTING.md#commit-messages) - 5. Push your change to your fork and create a [Pull Request](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request-from-a-fork) - -Refer to [containerd's contribution guide](https://github.com/containerd/project/blob/master/CONTRIBUTING.md#successful-changes) -for tips on creating a successful contribution. - -## Sign your work - -The sign-off is a simple line at the end of the explanation for the patch. Your -signature certifies that you wrote the patch or otherwise have the right to pass -it on as an open-source patch. The rules are pretty simple: if you can certify -the below (from [developercertificate.org](http://developercertificate.org/)): - -``` -Developer Certificate of Origin -Version 1.1 - -Copyright (C) 2004, 2006 The Linux Foundation and its contributors. -660 York Street, Suite 102, -San Francisco, CA 94110 USA - -Everyone is permitted to copy and distribute verbatim copies of this -license document, but changing it is not allowed. - -Developer's Certificate of Origin 1.1 - -By making a contribution to this project, I certify that: - -(a) The contribution was created in whole or in part by me and I - have the right to submit it under the open source license - indicated in the file; or - -(b) The contribution is based upon previous work that, to the best - of my knowledge, is covered under an appropriate open source - license and I have the right under that license to submit that - work with modifications, whether created in whole or in part - by me, under the same open source license (unless I am - permitted to submit under a different license), as indicated - in the file; or - -(c) The contribution was provided directly to me by some other - person who certified (a), (b) or (c) and I have not modified - it. - -(d) I understand and agree that this project and the contribution - are public and that a record of the contribution (including all - personal information I submit with it, including my sign-off) is - maintained indefinitely and may be redistributed consistent with - this project or the open source license(s) involved. -``` - -Then you just add a line to every git commit message: - - Signed-off-by: Joe Smith - -Use your real name (sorry, no pseudonyms or anonymous contributions.) - -If you set your `user.name` and `user.email` git configs, you can sign your -commit automatically with `git commit -s`. diff --git a/vendor/github.com/distribution/reference/GOVERNANCE.md b/vendor/github.com/distribution/reference/GOVERNANCE.md deleted file mode 100644 index 200045b05..000000000 --- a/vendor/github.com/distribution/reference/GOVERNANCE.md +++ /dev/null @@ -1,144 +0,0 @@ -# distribution/reference Project Governance - -Distribution [Code of Conduct](./CODE-OF-CONDUCT.md) can be found here. - -For specific guidance on practical contribution steps please -see our [CONTRIBUTING.md](./CONTRIBUTING.md) guide. - -## Maintainership - -There are different types of maintainers, with different responsibilities, but -all maintainers have 3 things in common: - -1) They share responsibility in the project's success. -2) They have made a long-term, recurring time investment to improve the project. -3) They spend that time doing whatever needs to be done, not necessarily what -is the most interesting or fun. - -Maintainers are often under-appreciated, because their work is harder to appreciate. -It's easy to appreciate a really cool and technically advanced feature. It's harder -to appreciate the absence of bugs, the slow but steady improvement in stability, -or the reliability of a release process. But those things distinguish a good -project from a great one. - -## Reviewers - -A reviewer is a core role within the project. -They share in reviewing issues and pull requests and their LGTM counts towards the -required LGTM count to merge a code change into the project. - -Reviewers are part of the organization but do not have write access. -Becoming a reviewer is a core aspect in the journey to becoming a maintainer. - -## Adding maintainers - -Maintainers are first and foremost contributors that have shown they are -committed to the long term success of a project. Contributors wanting to become -maintainers are expected to be deeply involved in contributing code, pull -request review, and triage of issues in the project for more than three months. - -Just contributing does not make you a maintainer, it is about building trust -with the current maintainers of the project and being a person that they can -depend on and trust to make decisions in the best interest of the project. - -Periodically, the existing maintainers curate a list of contributors that have -shown regular activity on the project over the prior months. From this list, -maintainer candidates are selected and proposed in a pull request or a -maintainers communication channel. - -After a candidate has been announced to the maintainers, the existing -maintainers are given five business days to discuss the candidate, raise -objections and cast their vote. Votes may take place on the communication -channel or via pull request comment. Candidates must be approved by at least 66% -of the current maintainers by adding their vote on the mailing list. The -reviewer role has the same process but only requires 33% of current maintainers. -Only maintainers of the repository that the candidate is proposed for are -allowed to vote. - -If a candidate is approved, a maintainer will contact the candidate to invite -the candidate to open a pull request that adds the contributor to the -MAINTAINERS file. The voting process may take place inside a pull request if a -maintainer has already discussed the candidacy with the candidate and a -maintainer is willing to be a sponsor by opening the pull request. The candidate -becomes a maintainer once the pull request is merged. - -## Stepping down policy - -Life priorities, interests, and passions can change. If you're a maintainer but -feel you must remove yourself from the list, inform other maintainers that you -intend to step down, and if possible, help find someone to pick up your work. -At the very least, ensure your work can be continued where you left off. - -After you've informed other maintainers, create a pull request to remove -yourself from the MAINTAINERS file. - -## Removal of inactive maintainers - -Similar to the procedure for adding new maintainers, existing maintainers can -be removed from the list if they do not show significant activity on the -project. Periodically, the maintainers review the list of maintainers and their -activity over the last three months. - -If a maintainer has shown insufficient activity over this period, a neutral -person will contact the maintainer to ask if they want to continue being -a maintainer. If the maintainer decides to step down as a maintainer, they -open a pull request to be removed from the MAINTAINERS file. - -If the maintainer wants to remain a maintainer, but is unable to perform the -required duties they can be removed with a vote of at least 66% of the current -maintainers. In this case, maintainers should first propose the change to -maintainers via the maintainers communication channel, then open a pull request -for voting. The voting period is five business days. The voting pull request -should not come as a surpise to any maintainer and any discussion related to -performance must not be discussed on the pull request. - -## How are decisions made? - -Docker distribution is an open-source project with an open design philosophy. -This means that the repository is the source of truth for EVERY aspect of the -project, including its philosophy, design, road map, and APIs. *If it's part of -the project, it's in the repo. If it's in the repo, it's part of the project.* - -As a result, all decisions can be expressed as changes to the repository. An -implementation change is a change to the source code. An API change is a change -to the API specification. A philosophy change is a change to the philosophy -manifesto, and so on. - -All decisions affecting distribution, big and small, follow the same 3 steps: - -* Step 1: Open a pull request. Anyone can do this. - -* Step 2: Discuss the pull request. Anyone can do this. - -* Step 3: Merge or refuse the pull request. Who does this depends on the nature -of the pull request and which areas of the project it affects. - -## Helping contributors with the DCO - -The [DCO or `Sign your work`](./CONTRIBUTING.md#sign-your-work) -requirement is not intended as a roadblock or speed bump. - -Some contributors are not as familiar with `git`, or have used a web -based editor, and thus asking them to `git commit --amend -s` is not the best -way forward. - -In this case, maintainers can update the commits based on clause (c) of the DCO. -The most trivial way for a contributor to allow the maintainer to do this, is to -add a DCO signature in a pull requests's comment, or a maintainer can simply -note that the change is sufficiently trivial that it does not substantially -change the existing contribution - i.e., a spelling change. - -When you add someone's DCO, please also add your own to keep a log. - -## I'm a maintainer. Should I make pull requests too? - -Yes. Nobody should ever push to master directly. All changes should be -made through a pull request. - -## Conflict Resolution - -If you have a technical dispute that you feel has reached an impasse with a -subset of the community, any contributor may open an issue, specifically -calling for a resolution vote of the current core maintainers to resolve the -dispute. The same voting quorums required (2/3) for adding and removing -maintainers will apply to conflict resolution. diff --git a/vendor/github.com/distribution/reference/LICENSE b/vendor/github.com/distribution/reference/LICENSE deleted file mode 100644 index e06d20818..000000000 --- a/vendor/github.com/distribution/reference/LICENSE +++ /dev/null @@ -1,202 +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/distribution/reference/MAINTAINERS b/vendor/github.com/distribution/reference/MAINTAINERS deleted file mode 100644 index 9e0a60c8b..000000000 --- a/vendor/github.com/distribution/reference/MAINTAINERS +++ /dev/null @@ -1,26 +0,0 @@ -# Distribution project maintainers & reviewers -# -# See GOVERNANCE.md for maintainer versus reviewer roles -# -# MAINTAINERS (cncf-distribution-maintainers@lists.cncf.io) -# GitHub ID, Name, Email address -"chrispat","Chris Patterson","chrispat@github.com" -"clarkbw","Bryan Clark","clarkbw@github.com" -"corhere","Cory Snider","csnider@mirantis.com" -"deleteriousEffect","Hayley Swimelar","hswimelar@gitlab.com" -"heww","He Weiwei","hweiwei@vmware.com" -"joaodrp","João Pereira","jpereira@gitlab.com" -"justincormack","Justin Cormack","justin.cormack@docker.com" -"squizzi","Kyle Squizzato","ksquizzato@mirantis.com" -"milosgajdos","Milos Gajdos","milosthegajdos@gmail.com" -"sargun","Sargun Dhillon","sargun@sargun.me" -"wy65701436","Wang Yan","wangyan@vmware.com" -"stevelasker","Steve Lasker","steve.lasker@microsoft.com" -# -# REVIEWERS -# GitHub ID, Name, Email address -"dmcgowan","Derek McGowan","derek@mcgstyle.net" -"stevvooe","Stephen Day","stevvooe@gmail.com" -"thajeztah","Sebastiaan van Stijn","github@gone.nl" -"DavidSpek", "David van der Spek", "vanderspek.david@gmail.com" -"Jamstah", "James Hewitt", "james.hewitt@gmail.com" diff --git a/vendor/github.com/distribution/reference/Makefile b/vendor/github.com/distribution/reference/Makefile deleted file mode 100644 index c78576b75..000000000 --- a/vendor/github.com/distribution/reference/Makefile +++ /dev/null @@ -1,25 +0,0 @@ -# Project packages. -PACKAGES=$(shell go list ./...) - -# Flags passed to `go test` -BUILDFLAGS ?= -TESTFLAGS ?= - -.PHONY: all build test coverage -.DEFAULT: all - -all: build - -build: ## no binaries to build, so just check compilation suceeds - go build ${BUILDFLAGS} ./... - -test: ## run tests - go test ${TESTFLAGS} ./... - -coverage: ## generate coverprofiles from the unit tests - rm -f coverage.txt - go test ${TESTFLAGS} -cover -coverprofile=cover.out ./... - -.PHONY: help -help: - @awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make \033[36m\033[0m\n"} /^[a-zA-Z_\/%-]+:.*?##/ { printf " \033[36m%-27s\033[0m %s\n", $$1, $$2 } /^##@/ { printf "\n\033[1m%s\033[0m\n", substr($$0, 5) } ' $(MAKEFILE_LIST) diff --git a/vendor/github.com/distribution/reference/README.md b/vendor/github.com/distribution/reference/README.md deleted file mode 100644 index e2531e49c..000000000 --- a/vendor/github.com/distribution/reference/README.md +++ /dev/null @@ -1,30 +0,0 @@ -# Distribution reference - -Go library to handle references to container images. - - - -[![Build Status](https://github.com/distribution/reference/actions/workflows/test.yml/badge.svg?branch=main&event=push)](https://github.com/distribution/reference/actions?query=workflow%3ACI) -[![GoDoc](https://img.shields.io/badge/go.dev-reference-007d9c?logo=go&logoColor=white&style=flat-square)](https://pkg.go.dev/github.com/distribution/reference) -[![License: Apache-2.0](https://img.shields.io/badge/License-Apache--2.0-blue.svg)](LICENSE) -[![codecov](https://codecov.io/gh/distribution/reference/branch/main/graph/badge.svg)](https://codecov.io/gh/distribution/reference) -[![FOSSA Status](https://app.fossa.com/api/projects/custom%2B162%2Fgithub.com%2Fdistribution%2Freference.svg?type=shield)](https://app.fossa.com/projects/custom%2B162%2Fgithub.com%2Fdistribution%2Freference?ref=badge_shield) - -This repository contains a library for handling refrences to container images held in container registries. Please see [godoc](https://pkg.go.dev/github.com/distribution/reference) for details. - -## Contribution - -Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details on how to contribute -issues, fixes, and patches to this project. - -## Communication - -For async communication and long running discussions please use issues and pull requests on the github repo. -This will be the best place to discuss design and implementation. - -For sync communication we have a #distribution channel in the [CNCF Slack](https://slack.cncf.io/) -that everyone is welcome to join and chat about development. - -## Licenses - -The distribution codebase is released under the [Apache 2.0 license](LICENSE). diff --git a/vendor/github.com/distribution/reference/SECURITY.md b/vendor/github.com/distribution/reference/SECURITY.md deleted file mode 100644 index aaf983c0f..000000000 --- a/vendor/github.com/distribution/reference/SECURITY.md +++ /dev/null @@ -1,7 +0,0 @@ -# Security Policy - -## Reporting a Vulnerability - -The maintainers take security seriously. If you discover a security issue, please bring it to their attention right away! - -Please DO NOT file a public issue, instead send your report privately to cncf-distribution-security@lists.cncf.io. diff --git a/vendor/github.com/distribution/reference/distribution-logo.svg b/vendor/github.com/distribution/reference/distribution-logo.svg deleted file mode 100644 index cc9f4073b..000000000 --- a/vendor/github.com/distribution/reference/distribution-logo.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/vendor/github.com/distribution/reference/helpers.go b/vendor/github.com/distribution/reference/helpers.go deleted file mode 100644 index d10c7ef83..000000000 --- a/vendor/github.com/distribution/reference/helpers.go +++ /dev/null @@ -1,42 +0,0 @@ -package reference - -import "path" - -// IsNameOnly returns true if reference only contains a repo name. -func IsNameOnly(ref Named) bool { - if _, ok := ref.(NamedTagged); ok { - return false - } - if _, ok := ref.(Canonical); ok { - return false - } - return true -} - -// FamiliarName returns the familiar name string -// for the given named, familiarizing if needed. -func FamiliarName(ref Named) string { - if nn, ok := ref.(normalizedNamed); ok { - return nn.Familiar().Name() - } - return ref.Name() -} - -// FamiliarString returns the familiar string representation -// for the given reference, familiarizing if needed. -func FamiliarString(ref Reference) string { - if nn, ok := ref.(normalizedNamed); ok { - return nn.Familiar().String() - } - return ref.String() -} - -// FamiliarMatch reports whether ref matches the specified pattern. -// See [path.Match] for supported patterns. -func FamiliarMatch(pattern string, ref Reference) (bool, error) { - matched, err := path.Match(pattern, FamiliarString(ref)) - if namedRef, isNamed := ref.(Named); isNamed && !matched { - matched, _ = path.Match(pattern, FamiliarName(namedRef)) - } - return matched, err -} diff --git a/vendor/github.com/distribution/reference/normalize.go b/vendor/github.com/distribution/reference/normalize.go deleted file mode 100644 index a30229d01..000000000 --- a/vendor/github.com/distribution/reference/normalize.go +++ /dev/null @@ -1,224 +0,0 @@ -package reference - -import ( - "fmt" - "strings" - - "github.com/opencontainers/go-digest" -) - -const ( - // legacyDefaultDomain is the legacy domain for Docker Hub (which was - // originally named "the Docker Index"). This domain is still used for - // authentication and image search, which were part of the "v1" Docker - // registry specification. - // - // This domain will continue to be supported, but there are plans to consolidate - // legacy domains to new "canonical" domains. Once those domains are decided - // on, we must update the normalization functions, but preserve compatibility - // with existing installs, clients, and user configuration. - legacyDefaultDomain = "index.docker.io" - - // defaultDomain is the default domain used for images on Docker Hub. - // It is used to normalize "familiar" names to canonical names, for example, - // to convert "ubuntu" to "docker.io/library/ubuntu:latest". - // - // Note that actual domain of Docker Hub's registry is registry-1.docker.io. - // This domain will continue to be supported, but there are plans to consolidate - // legacy domains to new "canonical" domains. Once those domains are decided - // on, we must update the normalization functions, but preserve compatibility - // with existing installs, clients, and user configuration. - defaultDomain = "docker.io" - - // officialRepoPrefix is the namespace used for official images on Docker Hub. - // It is used to normalize "familiar" names to canonical names, for example, - // to convert "ubuntu" to "docker.io/library/ubuntu:latest". - officialRepoPrefix = "library/" - - // defaultTag is the default tag if no tag is provided. - defaultTag = "latest" -) - -// normalizedNamed represents a name which has been -// normalized and has a familiar form. A familiar name -// is what is used in Docker UI. An example normalized -// name is "docker.io/library/ubuntu" and corresponding -// familiar name of "ubuntu". -type normalizedNamed interface { - Named - Familiar() Named -} - -// ParseNormalizedNamed parses a string into a named reference -// transforming a familiar name from Docker UI to a fully -// qualified reference. If the value may be an identifier -// use ParseAnyReference. -func ParseNormalizedNamed(s string) (Named, error) { - if ok := anchoredIdentifierRegexp.MatchString(s); ok { - return nil, fmt.Errorf("invalid repository name (%s), cannot specify 64-byte hexadecimal strings", s) - } - domain, remainder := splitDockerDomain(s) - var remote string - if tagSep := strings.IndexRune(remainder, ':'); tagSep > -1 { - remote = remainder[:tagSep] - } else { - remote = remainder - } - if strings.ToLower(remote) != remote { - return nil, fmt.Errorf("invalid reference format: repository name (%s) must be lowercase", remote) - } - - ref, err := Parse(domain + "/" + remainder) - if err != nil { - return nil, err - } - named, isNamed := ref.(Named) - if !isNamed { - return nil, fmt.Errorf("reference %s has no name", ref.String()) - } - return named, nil -} - -// namedTaggedDigested is a reference that has both a tag and a digest. -type namedTaggedDigested interface { - NamedTagged - Digested -} - -// ParseDockerRef normalizes the image reference following the docker convention, -// which allows for references to contain both a tag and a digest. It returns a -// reference that is either tagged or digested. For references containing both -// a tag and a digest, it returns a digested reference. For example, the following -// reference: -// -// docker.io/library/busybox:latest@sha256:7cc4b5aefd1d0cadf8d97d4350462ba51c694ebca145b08d7d41b41acc8db5aa -// -// Is returned as a digested reference (with the ":latest" tag removed): -// -// docker.io/library/busybox@sha256:7cc4b5aefd1d0cadf8d97d4350462ba51c694ebca145b08d7d41b41acc8db5aa -// -// References that are already "tagged" or "digested" are returned unmodified: -// -// // Already a digested reference -// docker.io/library/busybox@sha256:7cc4b5aefd1d0cadf8d97d4350462ba51c694ebca145b08d7d41b41acc8db5aa -// -// // Already a named reference -// docker.io/library/busybox:latest -func ParseDockerRef(ref string) (Named, error) { - named, err := ParseNormalizedNamed(ref) - if err != nil { - return nil, err - } - if canonical, ok := named.(namedTaggedDigested); ok { - // The reference is both tagged and digested; only return digested. - newNamed, err := WithName(canonical.Name()) - if err != nil { - return nil, err - } - return WithDigest(newNamed, canonical.Digest()) - } - return TagNameOnly(named), nil -} - -// splitDockerDomain splits a repository name to domain and remote-name. -// If no valid domain is found, the default domain is used. Repository name -// needs to be already validated before. -func splitDockerDomain(name string) (domain, remainder string) { - i := strings.IndexRune(name, '/') - if i == -1 || (!strings.ContainsAny(name[:i], ".:") && name[:i] != localhost && strings.ToLower(name[:i]) == name[:i]) { - domain, remainder = defaultDomain, name - } else { - domain, remainder = name[:i], name[i+1:] - } - if domain == legacyDefaultDomain { - domain = defaultDomain - } - if domain == defaultDomain && !strings.ContainsRune(remainder, '/') { - remainder = officialRepoPrefix + remainder - } - return -} - -// familiarizeName returns a shortened version of the name familiar -// to the Docker UI. Familiar names have the default domain -// "docker.io" and "library/" repository prefix removed. -// For example, "docker.io/library/redis" will have the familiar -// name "redis" and "docker.io/dmcgowan/myapp" will be "dmcgowan/myapp". -// Returns a familiarized named only reference. -func familiarizeName(named namedRepository) repository { - repo := repository{ - domain: named.Domain(), - path: named.Path(), - } - - if repo.domain == defaultDomain { - repo.domain = "" - // Handle official repositories which have the pattern "library/" - if strings.HasPrefix(repo.path, officialRepoPrefix) { - // TODO(thaJeztah): this check may be too strict, as it assumes the - // "library/" namespace does not have nested namespaces. While this - // is true (currently), technically it would be possible for Docker - // Hub to use those (e.g. "library/distros/ubuntu:latest"). - // See https://github.com/distribution/distribution/pull/3769#issuecomment-1302031785. - if remainder := strings.TrimPrefix(repo.path, officialRepoPrefix); !strings.ContainsRune(remainder, '/') { - repo.path = remainder - } - } - } - return repo -} - -func (r reference) Familiar() Named { - return reference{ - namedRepository: familiarizeName(r.namedRepository), - tag: r.tag, - digest: r.digest, - } -} - -func (r repository) Familiar() Named { - return familiarizeName(r) -} - -func (t taggedReference) Familiar() Named { - return taggedReference{ - namedRepository: familiarizeName(t.namedRepository), - tag: t.tag, - } -} - -func (c canonicalReference) Familiar() Named { - return canonicalReference{ - namedRepository: familiarizeName(c.namedRepository), - digest: c.digest, - } -} - -// TagNameOnly adds the default tag "latest" to a reference if it only has -// a repo name. -func TagNameOnly(ref Named) Named { - if IsNameOnly(ref) { - namedTagged, err := WithTag(ref, defaultTag) - if err != nil { - // Default tag must be valid, to create a NamedTagged - // type with non-validated input the WithTag function - // should be used instead - panic(err) - } - return namedTagged - } - return ref -} - -// ParseAnyReference parses a reference string as a possible identifier, -// full digest, or familiar name. -func ParseAnyReference(ref string) (Reference, error) { - if ok := anchoredIdentifierRegexp.MatchString(ref); ok { - return digestReference("sha256:" + ref), nil - } - if dgst, err := digest.Parse(ref); err == nil { - return digestReference(dgst), nil - } - - return ParseNormalizedNamed(ref) -} diff --git a/vendor/github.com/distribution/reference/reference.go b/vendor/github.com/distribution/reference/reference.go deleted file mode 100644 index e98c44daa..000000000 --- a/vendor/github.com/distribution/reference/reference.go +++ /dev/null @@ -1,436 +0,0 @@ -// Package reference provides a general type to represent any way of referencing images within the registry. -// Its main purpose is to abstract tags and digests (content-addressable hash). -// -// Grammar -// -// reference := name [ ":" tag ] [ "@" digest ] -// name := [domain '/'] remote-name -// domain := host [':' port-number] -// host := domain-name | IPv4address | \[ IPv6address \] ; rfc3986 appendix-A -// domain-name := domain-component ['.' domain-component]* -// domain-component := /([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])/ -// port-number := /[0-9]+/ -// path-component := alpha-numeric [separator alpha-numeric]* -// path (or "remote-name") := path-component ['/' path-component]* -// alpha-numeric := /[a-z0-9]+/ -// separator := /[_.]|__|[-]*/ -// -// tag := /[\w][\w.-]{0,127}/ -// -// digest := digest-algorithm ":" digest-hex -// digest-algorithm := digest-algorithm-component [ digest-algorithm-separator digest-algorithm-component ]* -// digest-algorithm-separator := /[+.-_]/ -// digest-algorithm-component := /[A-Za-z][A-Za-z0-9]*/ -// digest-hex := /[0-9a-fA-F]{32,}/ ; At least 128 bit digest value -// -// identifier := /[a-f0-9]{64}/ -package reference - -import ( - "errors" - "fmt" - "strings" - - "github.com/opencontainers/go-digest" -) - -const ( - // NameTotalLengthMax is the maximum total number of characters in a repository name. - NameTotalLengthMax = 255 -) - -var ( - // ErrReferenceInvalidFormat represents an error while trying to parse a string as a reference. - ErrReferenceInvalidFormat = errors.New("invalid reference format") - - // ErrTagInvalidFormat represents an error while trying to parse a string as a tag. - ErrTagInvalidFormat = errors.New("invalid tag format") - - // ErrDigestInvalidFormat represents an error while trying to parse a string as a tag. - ErrDigestInvalidFormat = errors.New("invalid digest format") - - // ErrNameContainsUppercase is returned for invalid repository names that contain uppercase characters. - ErrNameContainsUppercase = errors.New("repository name must be lowercase") - - // ErrNameEmpty is returned for empty, invalid repository names. - ErrNameEmpty = errors.New("repository name must have at least one component") - - // ErrNameTooLong is returned when a repository name is longer than NameTotalLengthMax. - ErrNameTooLong = fmt.Errorf("repository name must not be more than %v characters", NameTotalLengthMax) - - // ErrNameNotCanonical is returned when a name is not canonical. - ErrNameNotCanonical = errors.New("repository name must be canonical") -) - -// Reference is an opaque object reference identifier that may include -// modifiers such as a hostname, name, tag, and digest. -type Reference interface { - // String returns the full reference - String() string -} - -// Field provides a wrapper type for resolving correct reference types when -// working with encoding. -type Field struct { - reference Reference -} - -// AsField wraps a reference in a Field for encoding. -func AsField(reference Reference) Field { - return Field{reference} -} - -// Reference unwraps the reference type from the field to -// return the Reference object. This object should be -// of the appropriate type to further check for different -// reference types. -func (f Field) Reference() Reference { - return f.reference -} - -// MarshalText serializes the field to byte text which -// is the string of the reference. -func (f Field) MarshalText() (p []byte, err error) { - return []byte(f.reference.String()), nil -} - -// UnmarshalText parses text bytes by invoking the -// reference parser to ensure the appropriately -// typed reference object is wrapped by field. -func (f *Field) UnmarshalText(p []byte) error { - r, err := Parse(string(p)) - if err != nil { - return err - } - - f.reference = r - return nil -} - -// Named is an object with a full name -type Named interface { - Reference - Name() string -} - -// Tagged is an object which has a tag -type Tagged interface { - Reference - Tag() string -} - -// NamedTagged is an object including a name and tag. -type NamedTagged interface { - Named - Tag() string -} - -// Digested is an object which has a digest -// in which it can be referenced by -type Digested interface { - Reference - Digest() digest.Digest -} - -// Canonical reference is an object with a fully unique -// name including a name with domain and digest -type Canonical interface { - Named - Digest() digest.Digest -} - -// namedRepository is a reference to a repository with a name. -// A namedRepository has both domain and path components. -type namedRepository interface { - Named - Domain() string - Path() string -} - -// Domain returns the domain part of the [Named] reference. -func Domain(named Named) string { - if r, ok := named.(namedRepository); ok { - return r.Domain() - } - domain, _ := splitDomain(named.Name()) - return domain -} - -// Path returns the name without the domain part of the [Named] reference. -func Path(named Named) (name string) { - if r, ok := named.(namedRepository); ok { - return r.Path() - } - _, path := splitDomain(named.Name()) - return path -} - -func splitDomain(name string) (string, string) { - match := anchoredNameRegexp.FindStringSubmatch(name) - if len(match) != 3 { - return "", name - } - return match[1], match[2] -} - -// SplitHostname splits a named reference into a -// hostname and name string. If no valid hostname is -// found, the hostname is empty and the full value -// is returned as name -// -// Deprecated: Use [Domain] or [Path]. -func SplitHostname(named Named) (string, string) { - if r, ok := named.(namedRepository); ok { - return r.Domain(), r.Path() - } - return splitDomain(named.Name()) -} - -// Parse parses s and returns a syntactically valid Reference. -// If an error was encountered it is returned, along with a nil Reference. -func Parse(s string) (Reference, error) { - matches := ReferenceRegexp.FindStringSubmatch(s) - if matches == nil { - if s == "" { - return nil, ErrNameEmpty - } - if ReferenceRegexp.FindStringSubmatch(strings.ToLower(s)) != nil { - return nil, ErrNameContainsUppercase - } - return nil, ErrReferenceInvalidFormat - } - - if len(matches[1]) > NameTotalLengthMax { - return nil, ErrNameTooLong - } - - var repo repository - - nameMatch := anchoredNameRegexp.FindStringSubmatch(matches[1]) - if len(nameMatch) == 3 { - repo.domain = nameMatch[1] - repo.path = nameMatch[2] - } else { - repo.domain = "" - repo.path = matches[1] - } - - ref := reference{ - namedRepository: repo, - tag: matches[2], - } - if matches[3] != "" { - var err error - ref.digest, err = digest.Parse(matches[3]) - if err != nil { - return nil, err - } - } - - r := getBestReferenceType(ref) - if r == nil { - return nil, ErrNameEmpty - } - - return r, nil -} - -// ParseNamed parses s and returns a syntactically valid reference implementing -// the Named interface. The reference must have a name and be in the canonical -// form, otherwise an error is returned. -// If an error was encountered it is returned, along with a nil Reference. -func ParseNamed(s string) (Named, error) { - named, err := ParseNormalizedNamed(s) - if err != nil { - return nil, err - } - if named.String() != s { - return nil, ErrNameNotCanonical - } - return named, nil -} - -// WithName returns a named object representing the given string. If the input -// is invalid ErrReferenceInvalidFormat will be returned. -func WithName(name string) (Named, error) { - if len(name) > NameTotalLengthMax { - return nil, ErrNameTooLong - } - - match := anchoredNameRegexp.FindStringSubmatch(name) - if match == nil || len(match) != 3 { - return nil, ErrReferenceInvalidFormat - } - return repository{ - domain: match[1], - path: match[2], - }, nil -} - -// WithTag combines the name from "name" and the tag from "tag" to form a -// reference incorporating both the name and the tag. -func WithTag(name Named, tag string) (NamedTagged, error) { - if !anchoredTagRegexp.MatchString(tag) { - return nil, ErrTagInvalidFormat - } - var repo repository - if r, ok := name.(namedRepository); ok { - repo.domain = r.Domain() - repo.path = r.Path() - } else { - repo.path = name.Name() - } - if canonical, ok := name.(Canonical); ok { - return reference{ - namedRepository: repo, - tag: tag, - digest: canonical.Digest(), - }, nil - } - return taggedReference{ - namedRepository: repo, - tag: tag, - }, nil -} - -// WithDigest combines the name from "name" and the digest from "digest" to form -// a reference incorporating both the name and the digest. -func WithDigest(name Named, digest digest.Digest) (Canonical, error) { - if !anchoredDigestRegexp.MatchString(digest.String()) { - return nil, ErrDigestInvalidFormat - } - var repo repository - if r, ok := name.(namedRepository); ok { - repo.domain = r.Domain() - repo.path = r.Path() - } else { - repo.path = name.Name() - } - if tagged, ok := name.(Tagged); ok { - return reference{ - namedRepository: repo, - tag: tagged.Tag(), - digest: digest, - }, nil - } - return canonicalReference{ - namedRepository: repo, - digest: digest, - }, nil -} - -// TrimNamed removes any tag or digest from the named reference. -func TrimNamed(ref Named) Named { - repo := repository{} - if r, ok := ref.(namedRepository); ok { - repo.domain, repo.path = r.Domain(), r.Path() - } else { - repo.domain, repo.path = splitDomain(ref.Name()) - } - return repo -} - -func getBestReferenceType(ref reference) Reference { - if ref.Name() == "" { - // Allow digest only references - if ref.digest != "" { - return digestReference(ref.digest) - } - return nil - } - if ref.tag == "" { - if ref.digest != "" { - return canonicalReference{ - namedRepository: ref.namedRepository, - digest: ref.digest, - } - } - return ref.namedRepository - } - if ref.digest == "" { - return taggedReference{ - namedRepository: ref.namedRepository, - tag: ref.tag, - } - } - - return ref -} - -type reference struct { - namedRepository - tag string - digest digest.Digest -} - -func (r reference) String() string { - return r.Name() + ":" + r.tag + "@" + r.digest.String() -} - -func (r reference) Tag() string { - return r.tag -} - -func (r reference) Digest() digest.Digest { - return r.digest -} - -type repository struct { - domain string - path string -} - -func (r repository) String() string { - return r.Name() -} - -func (r repository) Name() string { - if r.domain == "" { - return r.path - } - return r.domain + "/" + r.path -} - -func (r repository) Domain() string { - return r.domain -} - -func (r repository) Path() string { - return r.path -} - -type digestReference digest.Digest - -func (d digestReference) String() string { - return digest.Digest(d).String() -} - -func (d digestReference) Digest() digest.Digest { - return digest.Digest(d) -} - -type taggedReference struct { - namedRepository - tag string -} - -func (t taggedReference) String() string { - return t.Name() + ":" + t.tag -} - -func (t taggedReference) Tag() string { - return t.tag -} - -type canonicalReference struct { - namedRepository - digest digest.Digest -} - -func (c canonicalReference) String() string { - return c.Name() + "@" + c.digest.String() -} - -func (c canonicalReference) Digest() digest.Digest { - return c.digest -} diff --git a/vendor/github.com/distribution/reference/regexp.go b/vendor/github.com/distribution/reference/regexp.go deleted file mode 100644 index 65bc49d79..000000000 --- a/vendor/github.com/distribution/reference/regexp.go +++ /dev/null @@ -1,163 +0,0 @@ -package reference - -import ( - "regexp" - "strings" -) - -// DigestRegexp matches well-formed digests, including algorithm (e.g. "sha256:"). -var DigestRegexp = regexp.MustCompile(digestPat) - -// DomainRegexp matches hostname or IP-addresses, optionally including a port -// number. It defines the structure of potential domain components that may be -// part of image names. This is purposely a subset of what is allowed by DNS to -// ensure backwards compatibility with Docker image names. It may be a subset of -// DNS domain name, an IPv4 address in decimal format, or an IPv6 address between -// square brackets (excluding zone identifiers as defined by [RFC 6874] or special -// addresses such as IPv4-Mapped). -// -// [RFC 6874]: https://www.rfc-editor.org/rfc/rfc6874. -var DomainRegexp = regexp.MustCompile(domainAndPort) - -// IdentifierRegexp is the format for string identifier used as a -// content addressable identifier using sha256. These identifiers -// are like digests without the algorithm, since sha256 is used. -var IdentifierRegexp = regexp.MustCompile(identifier) - -// NameRegexp is the format for the name component of references, including -// an optional domain and port, but without tag or digest suffix. -var NameRegexp = regexp.MustCompile(namePat) - -// ReferenceRegexp is the full supported format of a reference. The regexp -// is anchored and has capturing groups for name, tag, and digest -// components. -var ReferenceRegexp = regexp.MustCompile(referencePat) - -// TagRegexp matches valid tag names. From [docker/docker:graph/tags.go]. -// -// [docker/docker:graph/tags.go]: https://github.com/moby/moby/blob/v1.6.0/graph/tags.go#L26-L28 -var TagRegexp = regexp.MustCompile(tag) - -const ( - // alphanumeric defines the alphanumeric atom, typically a - // component of names. This only allows lower case characters and digits. - alphanumeric = `[a-z0-9]+` - - // separator defines the separators allowed to be embedded in name - // components. This allows one period, one or two underscore and multiple - // dashes. Repeated dashes and underscores are intentionally treated - // differently. In order to support valid hostnames as name components, - // supporting repeated dash was added. Additionally double underscore is - // now allowed as a separator to loosen the restriction for previously - // supported names. - separator = `(?:[._]|__|[-]+)` - - // localhost is treated as a special value for domain-name. Any other - // domain-name without a "." or a ":port" are considered a path component. - localhost = `localhost` - - // domainNameComponent restricts the registry domain component of a - // repository name to start with a component as defined by DomainRegexp. - domainNameComponent = `(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])` - - // optionalPort matches an optional port-number including the port separator - // (e.g. ":80"). - optionalPort = `(?::[0-9]+)?` - - // tag matches valid tag names. From docker/docker:graph/tags.go. - tag = `[\w][\w.-]{0,127}` - - // digestPat matches well-formed digests, including algorithm (e.g. "sha256:"). - // - // TODO(thaJeztah): this should follow the same rules as https://pkg.go.dev/github.com/opencontainers/go-digest@v1.0.0#DigestRegexp - // so that go-digest defines the canonical format. Note that the go-digest is - // more relaxed: - // - it allows multiple algorithms (e.g. "sha256+b64:") to allow - // future expansion of supported algorithms. - // - it allows the "" value to use urlsafe base64 encoding as defined - // in [rfc4648, section 5]. - // - // [rfc4648, section 5]: https://www.rfc-editor.org/rfc/rfc4648#section-5. - digestPat = `[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*[:][[:xdigit:]]{32,}` - - // identifier is the format for a content addressable identifier using sha256. - // These identifiers are like digests without the algorithm, since sha256 is used. - identifier = `([a-f0-9]{64})` - - // ipv6address are enclosed between square brackets and may be represented - // in many ways, see rfc5952. Only IPv6 in compressed or uncompressed format - // are allowed, IPv6 zone identifiers (rfc6874) or Special addresses such as - // IPv4-Mapped are deliberately excluded. - ipv6address = `\[(?:[a-fA-F0-9:]+)\]` -) - -var ( - // domainName defines the structure of potential domain components - // that may be part of image names. This is purposely a subset of what is - // allowed by DNS to ensure backwards compatibility with Docker image - // names. This includes IPv4 addresses on decimal format. - domainName = domainNameComponent + anyTimes(`\.`+domainNameComponent) - - // host defines the structure of potential domains based on the URI - // Host subcomponent on rfc3986. It may be a subset of DNS domain name, - // or an IPv4 address in decimal format, or an IPv6 address between square - // brackets (excluding zone identifiers as defined by rfc6874 or special - // addresses such as IPv4-Mapped). - host = `(?:` + domainName + `|` + ipv6address + `)` - - // allowed by the URI Host subcomponent on rfc3986 to ensure backwards - // compatibility with Docker image names. - domainAndPort = host + optionalPort - - // anchoredTagRegexp matches valid tag names, anchored at the start and - // end of the matched string. - anchoredTagRegexp = regexp.MustCompile(anchored(tag)) - - // anchoredDigestRegexp matches valid digests, anchored at the start and - // end of the matched string. - anchoredDigestRegexp = regexp.MustCompile(anchored(digestPat)) - - // pathComponent restricts path-components to start with an alphanumeric - // character, with following parts able to be separated by a separator - // (one period, one or two underscore and multiple dashes). - pathComponent = alphanumeric + anyTimes(separator+alphanumeric) - - // remoteName matches the remote-name of a repository. It consists of one - // or more forward slash (/) delimited path-components: - // - // pathComponent[[/pathComponent] ...] // e.g., "library/ubuntu" - remoteName = pathComponent + anyTimes(`/`+pathComponent) - namePat = optional(domainAndPort+`/`) + remoteName - - // anchoredNameRegexp is used to parse a name value, capturing the - // domain and trailing components. - anchoredNameRegexp = regexp.MustCompile(anchored(optional(capture(domainAndPort), `/`), capture(remoteName))) - - referencePat = anchored(capture(namePat), optional(`:`, capture(tag)), optional(`@`, capture(digestPat))) - - // anchoredIdentifierRegexp is used to check or match an - // identifier value, anchored at start and end of string. - anchoredIdentifierRegexp = regexp.MustCompile(anchored(identifier)) -) - -// optional wraps the expression in a non-capturing group and makes the -// production optional. -func optional(res ...string) string { - return `(?:` + strings.Join(res, "") + `)?` -} - -// anyTimes wraps the expression in a non-capturing group that can occur -// any number of times. -func anyTimes(res ...string) string { - return `(?:` + strings.Join(res, "") + `)*` -} - -// capture wraps the expression in a capturing group. -func capture(res ...string) string { - return `(` + strings.Join(res, "") + `)` -} - -// anchored anchors the regular expression by adding start and end delimiters. -func anchored(res ...string) string { - return `^` + strings.Join(res, "") + `$` -} diff --git a/vendor/github.com/distribution/reference/sort.go b/vendor/github.com/distribution/reference/sort.go deleted file mode 100644 index 416c37b07..000000000 --- a/vendor/github.com/distribution/reference/sort.go +++ /dev/null @@ -1,75 +0,0 @@ -/* - Copyright The containerd 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 reference - -import ( - "sort" -) - -// Sort sorts string references preferring higher information references. -// -// The precedence is as follows: -// -// 1. [Named] + [Tagged] + [Digested] (e.g., "docker.io/library/busybox:latest@sha256:") -// 2. [Named] + [Tagged] (e.g., "docker.io/library/busybox:latest") -// 3. [Named] + [Digested] (e.g., "docker.io/library/busybo@sha256:") -// 4. [Named] (e.g., "docker.io/library/busybox") -// 5. [Digested] (e.g., "docker.io@sha256:") -// 6. Parse error -func Sort(references []string) []string { - var prefs []Reference - var bad []string - - for _, ref := range references { - pref, err := ParseAnyReference(ref) - if err != nil { - bad = append(bad, ref) - } else { - prefs = append(prefs, pref) - } - } - sort.Slice(prefs, func(a, b int) bool { - ar := refRank(prefs[a]) - br := refRank(prefs[b]) - if ar == br { - return prefs[a].String() < prefs[b].String() - } - return ar < br - }) - sort.Strings(bad) - var refs []string - for _, pref := range prefs { - refs = append(refs, pref.String()) - } - return append(refs, bad...) -} - -func refRank(ref Reference) uint8 { - if _, ok := ref.(Named); ok { - if _, ok = ref.(Tagged); ok { - if _, ok = ref.(Digested); ok { - return 1 - } - return 2 - } - if _, ok = ref.(Digested); ok { - return 3 - } - return 4 - } - return 5 -} diff --git a/vendor/github.com/docker/buildx/AUTHORS b/vendor/github.com/docker/buildx/AUTHORS deleted file mode 100644 index abf95bf70..000000000 --- a/vendor/github.com/docker/buildx/AUTHORS +++ /dev/null @@ -1,45 +0,0 @@ -# This file lists all individuals having contributed content to the repository. -# For how it is generated, see hack/dockerfiles/authors.Dockerfile. - -Akihiro Suda -Alex Couture-Beil -Andrew Haines -Andy MacKinlay -Anthony Poschen -Artur Klauser -Batuhan Apaydın -Bin Du -Brandon Philips -Brian Goff -CrazyMax -dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> -Devin Bayer -Djordje Lukic -Dmytro Makovey -Donghui Wang <977675308@qq.com> -faust -Felipe Santos -Fernando Miguel -gfrancesco -gracenoah -Hollow Man -Ilya Dmitrichenko -Jack Laxson -Jean-Yves Gastaud -khs1994 -Kotaro Adachi -l00397676 -Michal Augustyn -Patrick Van Stee -Saul Shanabrook -Sebastiaan van Stijn -SHIMA Tatsuya -Silvin Lubecki -Solomon Hykes -Sune Keller -Tibor Vass -Tõnis Tiigi -Ulysses Souza -Wang Jinglei -Xiang Dai <764524258@qq.com> -zelahi diff --git a/vendor/github.com/docker/buildx/LICENSE b/vendor/github.com/docker/buildx/LICENSE deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/docker/buildx/LICENSE +++ /dev/null @@ -1,202 +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/docker/buildx/builder/builder.go b/vendor/github.com/docker/buildx/builder/builder.go deleted file mode 100644 index 8353c84c2..000000000 --- a/vendor/github.com/docker/buildx/builder/builder.go +++ /dev/null @@ -1,292 +0,0 @@ -package builder - -import ( - "context" - "os" - "sort" - "sync" - - "github.com/docker/buildx/driver" - "github.com/docker/buildx/store" - "github.com/docker/buildx/store/storeutil" - "github.com/docker/buildx/util/dockerutil" - "github.com/docker/buildx/util/imagetools" - "github.com/docker/buildx/util/progress" - "github.com/docker/cli/cli/command" - "github.com/pkg/errors" - "golang.org/x/sync/errgroup" -) - -// Builder represents an active builder object -type Builder struct { - *store.NodeGroup - driverFactory driverFactory - nodes []Node - opts builderOpts - err error -} - -type builderOpts struct { - dockerCli command.Cli - name string - txn *store.Txn - contextPathHash string - validate bool -} - -// Option provides a variadic option for configuring the builder. -type Option func(b *Builder) - -// WithName sets builder name. -func WithName(name string) Option { - return func(b *Builder) { - b.opts.name = name - } -} - -// WithStore sets a store instance used at init. -func WithStore(txn *store.Txn) Option { - return func(b *Builder) { - b.opts.txn = txn - } -} - -// WithContextPathHash is used for determining pods in k8s driver instance. -func WithContextPathHash(contextPathHash string) Option { - return func(b *Builder) { - b.opts.contextPathHash = contextPathHash - } -} - -// WithSkippedValidation skips builder context validation. -func WithSkippedValidation() Option { - return func(b *Builder) { - b.opts.validate = false - } -} - -// New initializes a new builder client -func New(dockerCli command.Cli, opts ...Option) (_ *Builder, err error) { - b := &Builder{ - opts: builderOpts{ - dockerCli: dockerCli, - validate: true, - }, - } - for _, opt := range opts { - opt(b) - } - - if b.opts.txn == nil { - // if store instance is nil we create a short-lived one using the - // default store and ensure we release it on completion - var release func() - b.opts.txn, release, err = storeutil.GetStore(dockerCli) - if err != nil { - return nil, err - } - defer release() - } - - if b.opts.name != "" { - if b.NodeGroup, err = storeutil.GetNodeGroup(b.opts.txn, dockerCli, b.opts.name); err != nil { - return nil, err - } - } else { - if b.NodeGroup, err = storeutil.GetCurrentInstance(b.opts.txn, dockerCli); err != nil { - return nil, err - } - } - if b.opts.validate { - if err = b.Validate(); err != nil { - return nil, err - } - } - - return b, nil -} - -// Validate validates builder context -func (b *Builder) Validate() error { - if b.NodeGroup != nil && b.NodeGroup.DockerContext { - list, err := b.opts.dockerCli.ContextStore().List() - if err != nil { - return err - } - currentContext := b.opts.dockerCli.CurrentContext() - for _, l := range list { - if l.Name == b.Name && l.Name != currentContext { - return errors.Errorf("use `docker --context=%s buildx` to switch to context %q", l.Name, l.Name) - } - } - } - return nil -} - -// ContextName returns builder context name if available. -func (b *Builder) ContextName() string { - ctxbuilders, err := b.opts.dockerCli.ContextStore().List() - if err != nil { - return "" - } - for _, cb := range ctxbuilders { - if b.NodeGroup.Driver == "docker" && len(b.NodeGroup.Nodes) == 1 && b.NodeGroup.Nodes[0].Endpoint == cb.Name { - return cb.Name - } - } - return "" -} - -// ImageOpt returns registry auth configuration -func (b *Builder) ImageOpt() (imagetools.Opt, error) { - return storeutil.GetImageConfig(b.opts.dockerCli, b.NodeGroup) -} - -// Boot bootstrap a builder -func (b *Builder) Boot(ctx context.Context) (bool, error) { - toBoot := make([]int, 0, len(b.nodes)) - for idx, d := range b.nodes { - if d.Err != nil || d.Driver == nil || d.DriverInfo == nil { - continue - } - if d.DriverInfo.Status != driver.Running { - toBoot = append(toBoot, idx) - } - } - if len(toBoot) == 0 { - return false, nil - } - - printer, err := progress.NewPrinter(context.TODO(), os.Stderr, os.Stderr, progress.PrinterModeAuto) - if err != nil { - return false, err - } - - baseCtx := ctx - eg, _ := errgroup.WithContext(ctx) - for _, idx := range toBoot { - func(idx int) { - eg.Go(func() error { - pw := progress.WithPrefix(printer, b.NodeGroup.Nodes[idx].Name, len(toBoot) > 1) - _, err := driver.Boot(ctx, baseCtx, b.nodes[idx].Driver, pw) - if err != nil { - b.nodes[idx].Err = err - } - return nil - }) - }(idx) - } - - err = eg.Wait() - err1 := printer.Wait() - if err == nil { - err = err1 - } - - return true, err -} - -// Inactive checks if all nodes are inactive for this builder. -func (b *Builder) Inactive() bool { - for _, d := range b.nodes { - if d.DriverInfo != nil && d.DriverInfo.Status == driver.Running { - return false - } - } - return true -} - -// Err returns error if any. -func (b *Builder) Err() error { - return b.err -} - -type driverFactory struct { - driver.Factory - once sync.Once -} - -// Factory returns the driver factory. -func (b *Builder) Factory(ctx context.Context) (_ driver.Factory, err error) { - b.driverFactory.once.Do(func() { - if b.Driver != "" { - b.driverFactory.Factory, err = driver.GetFactory(b.Driver, true) - if err != nil { - return - } - } else { - // empty driver means nodegroup was implicitly created as a default - // driver for a docker context and allows falling back to a - // docker-container driver for older daemon that doesn't support - // buildkit (< 18.06). - ep := b.NodeGroup.Nodes[0].Endpoint - var dockerapi *dockerutil.ClientAPI - dockerapi, err = dockerutil.NewClientAPI(b.opts.dockerCli, b.NodeGroup.Nodes[0].Endpoint) - if err != nil { - return - } - // check if endpoint is healthy is needed to determine the driver type. - // if this fails then can't continue with driver selection. - if _, err = dockerapi.Ping(ctx); err != nil { - return - } - b.driverFactory.Factory, err = driver.GetDefaultFactory(ctx, ep, dockerapi, false) - if err != nil { - return - } - b.Driver = b.driverFactory.Factory.Name() - } - }) - return b.driverFactory.Factory, err -} - -// GetBuilders returns all builders -func GetBuilders(dockerCli command.Cli, txn *store.Txn) ([]*Builder, error) { - storeng, err := txn.List() - if err != nil { - return nil, err - } - - builders := make([]*Builder, len(storeng)) - seen := make(map[string]struct{}) - for i, ng := range storeng { - b, err := New(dockerCli, - WithName(ng.Name), - WithStore(txn), - WithSkippedValidation(), - ) - if err != nil { - return nil, err - } - builders[i] = b - seen[b.NodeGroup.Name] = struct{}{} - } - - contexts, err := dockerCli.ContextStore().List() - if err != nil { - return nil, err - } - sort.Slice(contexts, func(i, j int) bool { - return contexts[i].Name < contexts[j].Name - }) - - for _, c := range contexts { - // if a context has the same name as an instance from the store, do not - // add it to the builders list. An instance from the store takes - // precedence over context builders. - if _, ok := seen[c.Name]; ok { - continue - } - b, err := New(dockerCli, - WithName(c.Name), - WithStore(txn), - WithSkippedValidation(), - ) - if err != nil { - return nil, err - } - builders = append(builders, b) - } - - return builders, nil -} diff --git a/vendor/github.com/docker/buildx/builder/node.go b/vendor/github.com/docker/buildx/builder/node.go deleted file mode 100644 index a80562404..000000000 --- a/vendor/github.com/docker/buildx/builder/node.go +++ /dev/null @@ -1,211 +0,0 @@ -package builder - -import ( - "context" - - "github.com/docker/buildx/driver" - ctxkube "github.com/docker/buildx/driver/kubernetes/context" - "github.com/docker/buildx/store" - "github.com/docker/buildx/store/storeutil" - "github.com/docker/buildx/util/dockerutil" - "github.com/docker/buildx/util/imagetools" - "github.com/docker/buildx/util/platformutil" - "github.com/moby/buildkit/client" - "github.com/moby/buildkit/util/grpcerrors" - ocispecs "github.com/opencontainers/image-spec/specs-go/v1" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" - "golang.org/x/sync/errgroup" - "google.golang.org/grpc/codes" -) - -type Node struct { - store.Node - Builder string - Driver *driver.DriverHandle - DriverInfo *driver.Info - Platforms []ocispecs.Platform - GCPolicy []client.PruneInfo - Labels map[string]string - ImageOpt imagetools.Opt - ProxyConfig map[string]string - Version string - Err error -} - -// Nodes returns nodes for this builder. -func (b *Builder) Nodes() []Node { - return b.nodes -} - -// LoadNodes loads and returns nodes for this builder. -// TODO: this should be a method on a Node object and lazy load data for each driver. -func (b *Builder) LoadNodes(ctx context.Context, withData bool) (_ []Node, err error) { - eg, _ := errgroup.WithContext(ctx) - b.nodes = make([]Node, len(b.NodeGroup.Nodes)) - - defer func() { - if b.err == nil && err != nil { - b.err = err - } - }() - - factory, err := b.Factory(ctx) - if err != nil { - return nil, err - } - - imageopt, err := b.ImageOpt() - if err != nil { - return nil, err - } - - for i, n := range b.NodeGroup.Nodes { - func(i int, n store.Node) { - eg.Go(func() error { - node := Node{ - Node: n, - ProxyConfig: storeutil.GetProxyConfig(b.opts.dockerCli), - Platforms: n.Platforms, - Builder: b.Name, - } - defer func() { - b.nodes[i] = node - }() - - dockerapi, err := dockerutil.NewClientAPI(b.opts.dockerCli, n.Endpoint) - if err != nil { - node.Err = err - return nil - } - - contextStore := b.opts.dockerCli.ContextStore() - - var kcc driver.KubeClientConfig - kcc, err = ctxkube.ConfigFromEndpoint(n.Endpoint, contextStore) - if err != nil { - // err is returned if n.Endpoint is non-context name like "unix:///var/run/docker.sock". - // try again with name="default". - // FIXME(@AkihiroSuda): n should retain real context name. - kcc, err = ctxkube.ConfigFromEndpoint("default", contextStore) - if err != nil { - logrus.Error(err) - } - } - - tryToUseKubeConfigInCluster := false - if kcc == nil { - tryToUseKubeConfigInCluster = true - } else { - if _, err := kcc.ClientConfig(); err != nil { - tryToUseKubeConfigInCluster = true - } - } - if tryToUseKubeConfigInCluster { - kccInCluster := driver.KubeClientConfigInCluster{} - if _, err := kccInCluster.ClientConfig(); err == nil { - logrus.Debug("using kube config in cluster") - kcc = kccInCluster - } - } - - d, err := driver.GetDriver(ctx, "buildx_buildkit_"+n.Name, factory, n.Endpoint, dockerapi, imageopt.Auth, kcc, n.Flags, n.Files, n.DriverOpts, n.Platforms, b.opts.contextPathHash) - if err != nil { - node.Err = err - return nil - } - node.Driver = d - node.ImageOpt = imageopt - - if withData { - if err := node.loadData(ctx); err != nil { - node.Err = err - } - } - return nil - }) - }(i, n) - } - - if err := eg.Wait(); err != nil { - return nil, err - } - - // TODO: This should be done in the routine loading driver data - if withData { - kubernetesDriverCount := 0 - for _, d := range b.nodes { - if d.DriverInfo != nil && len(d.DriverInfo.DynamicNodes) > 0 { - kubernetesDriverCount++ - } - } - - isAllKubernetesDrivers := len(b.nodes) == kubernetesDriverCount - if isAllKubernetesDrivers { - var nodes []Node - var dynamicNodes []store.Node - for _, di := range b.nodes { - // dynamic nodes are used in Kubernetes driver. - // Kubernetes' pods are dynamically mapped to BuildKit Nodes. - if di.DriverInfo != nil && len(di.DriverInfo.DynamicNodes) > 0 { - for i := 0; i < len(di.DriverInfo.DynamicNodes); i++ { - diClone := di - if pl := di.DriverInfo.DynamicNodes[i].Platforms; len(pl) > 0 { - diClone.Platforms = pl - } - nodes = append(nodes, di) - } - dynamicNodes = append(dynamicNodes, di.DriverInfo.DynamicNodes...) - } - } - - // not append (remove the static nodes in the store) - b.NodeGroup.Nodes = dynamicNodes - b.nodes = nodes - b.NodeGroup.Dynamic = true - } - } - - return b.nodes, nil -} - -func (n *Node) loadData(ctx context.Context) error { - if n.Driver == nil { - return nil - } - info, err := n.Driver.Info(ctx) - if err != nil { - return err - } - n.DriverInfo = info - if n.DriverInfo.Status == driver.Running { - driverClient, err := n.Driver.Client(ctx) - if err != nil { - return err - } - workers, err := driverClient.ListWorkers(ctx) - if err != nil { - return errors.Wrap(err, "listing workers") - } - for idx, w := range workers { - n.Platforms = append(n.Platforms, w.Platforms...) - if idx == 0 { - n.GCPolicy = w.GCPolicy - n.Labels = w.Labels - } - } - n.Platforms = platformutil.Dedupe(n.Platforms) - inf, err := driverClient.Info(ctx) - if err != nil { - if st, ok := grpcerrors.AsGRPCStatus(err); ok && st.Code() == codes.Unimplemented { - n.Version, err = n.Driver.Version(ctx) - if err != nil { - return errors.Wrap(err, "getting version") - } - } - } else { - n.Version = inf.BuildkitVersion.Version - } - } - return nil -} diff --git a/vendor/github.com/docker/buildx/controller/pb/attest.go b/vendor/github.com/docker/buildx/controller/pb/attest.go deleted file mode 100644 index 06a7c945c..000000000 --- a/vendor/github.com/docker/buildx/controller/pb/attest.go +++ /dev/null @@ -1,20 +0,0 @@ -package pb - -func CreateAttestations(attests []*Attest) map[string]*string { - result := map[string]*string{} - for _, attest := range attests { - // ignore duplicates - if _, ok := result[attest.Type]; ok { - continue - } - - if attest.Disabled { - result[attest.Type] = nil - continue - } - - attrs := attest.Attrs - result[attest.Type] = &attrs - } - return result -} diff --git a/vendor/github.com/docker/buildx/controller/pb/cache.go b/vendor/github.com/docker/buildx/controller/pb/cache.go deleted file mode 100644 index 4b7c2b754..000000000 --- a/vendor/github.com/docker/buildx/controller/pb/cache.go +++ /dev/null @@ -1,21 +0,0 @@ -package pb - -import "github.com/moby/buildkit/client" - -func CreateCaches(entries []*CacheOptionsEntry) []client.CacheOptionsEntry { - var outs []client.CacheOptionsEntry - if len(entries) == 0 { - return nil - } - for _, entry := range entries { - out := client.CacheOptionsEntry{ - Type: entry.Type, - Attrs: map[string]string{}, - } - for k, v := range entry.Attrs { - out.Attrs[k] = v - } - outs = append(outs, out) - } - return outs -} diff --git a/vendor/github.com/docker/buildx/controller/pb/controller.pb.go b/vendor/github.com/docker/buildx/controller/pb/controller.pb.go deleted file mode 100644 index 03194937a..000000000 --- a/vendor/github.com/docker/buildx/controller/pb/controller.pb.go +++ /dev/null @@ -1,2666 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: controller.proto - -package pb - -import ( - context "context" - fmt "fmt" - proto "github.com/gogo/protobuf/proto" - control "github.com/moby/buildkit/api/services/control" - pb "github.com/moby/buildkit/sourcepolicy/pb" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - 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.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type ListProcessesRequest struct { - Ref string `protobuf:"bytes,1,opt,name=Ref,proto3" json:"Ref,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListProcessesRequest) Reset() { *m = ListProcessesRequest{} } -func (m *ListProcessesRequest) String() string { return proto.CompactTextString(m) } -func (*ListProcessesRequest) ProtoMessage() {} -func (*ListProcessesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{0} -} -func (m *ListProcessesRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListProcessesRequest.Unmarshal(m, b) -} -func (m *ListProcessesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListProcessesRequest.Marshal(b, m, deterministic) -} -func (m *ListProcessesRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListProcessesRequest.Merge(m, src) -} -func (m *ListProcessesRequest) XXX_Size() int { - return xxx_messageInfo_ListProcessesRequest.Size(m) -} -func (m *ListProcessesRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ListProcessesRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ListProcessesRequest proto.InternalMessageInfo - -func (m *ListProcessesRequest) GetRef() string { - if m != nil { - return m.Ref - } - return "" -} - -type ListProcessesResponse struct { - Infos []*ProcessInfo `protobuf:"bytes,1,rep,name=Infos,proto3" json:"Infos,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListProcessesResponse) Reset() { *m = ListProcessesResponse{} } -func (m *ListProcessesResponse) String() string { return proto.CompactTextString(m) } -func (*ListProcessesResponse) ProtoMessage() {} -func (*ListProcessesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{1} -} -func (m *ListProcessesResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListProcessesResponse.Unmarshal(m, b) -} -func (m *ListProcessesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListProcessesResponse.Marshal(b, m, deterministic) -} -func (m *ListProcessesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListProcessesResponse.Merge(m, src) -} -func (m *ListProcessesResponse) XXX_Size() int { - return xxx_messageInfo_ListProcessesResponse.Size(m) -} -func (m *ListProcessesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ListProcessesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ListProcessesResponse proto.InternalMessageInfo - -func (m *ListProcessesResponse) GetInfos() []*ProcessInfo { - if m != nil { - return m.Infos - } - return nil -} - -type ProcessInfo struct { - ProcessID string `protobuf:"bytes,1,opt,name=ProcessID,proto3" json:"ProcessID,omitempty"` - InvokeConfig *InvokeConfig `protobuf:"bytes,2,opt,name=InvokeConfig,proto3" json:"InvokeConfig,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ProcessInfo) Reset() { *m = ProcessInfo{} } -func (m *ProcessInfo) String() string { return proto.CompactTextString(m) } -func (*ProcessInfo) ProtoMessage() {} -func (*ProcessInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{2} -} -func (m *ProcessInfo) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ProcessInfo.Unmarshal(m, b) -} -func (m *ProcessInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ProcessInfo.Marshal(b, m, deterministic) -} -func (m *ProcessInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_ProcessInfo.Merge(m, src) -} -func (m *ProcessInfo) XXX_Size() int { - return xxx_messageInfo_ProcessInfo.Size(m) -} -func (m *ProcessInfo) XXX_DiscardUnknown() { - xxx_messageInfo_ProcessInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_ProcessInfo proto.InternalMessageInfo - -func (m *ProcessInfo) GetProcessID() string { - if m != nil { - return m.ProcessID - } - return "" -} - -func (m *ProcessInfo) GetInvokeConfig() *InvokeConfig { - if m != nil { - return m.InvokeConfig - } - return nil -} - -type DisconnectProcessRequest struct { - Ref string `protobuf:"bytes,1,opt,name=Ref,proto3" json:"Ref,omitempty"` - ProcessID string `protobuf:"bytes,2,opt,name=ProcessID,proto3" json:"ProcessID,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DisconnectProcessRequest) Reset() { *m = DisconnectProcessRequest{} } -func (m *DisconnectProcessRequest) String() string { return proto.CompactTextString(m) } -func (*DisconnectProcessRequest) ProtoMessage() {} -func (*DisconnectProcessRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{3} -} -func (m *DisconnectProcessRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DisconnectProcessRequest.Unmarshal(m, b) -} -func (m *DisconnectProcessRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DisconnectProcessRequest.Marshal(b, m, deterministic) -} -func (m *DisconnectProcessRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_DisconnectProcessRequest.Merge(m, src) -} -func (m *DisconnectProcessRequest) XXX_Size() int { - return xxx_messageInfo_DisconnectProcessRequest.Size(m) -} -func (m *DisconnectProcessRequest) XXX_DiscardUnknown() { - xxx_messageInfo_DisconnectProcessRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_DisconnectProcessRequest proto.InternalMessageInfo - -func (m *DisconnectProcessRequest) GetRef() string { - if m != nil { - return m.Ref - } - return "" -} - -func (m *DisconnectProcessRequest) GetProcessID() string { - if m != nil { - return m.ProcessID - } - return "" -} - -type DisconnectProcessResponse struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DisconnectProcessResponse) Reset() { *m = DisconnectProcessResponse{} } -func (m *DisconnectProcessResponse) String() string { return proto.CompactTextString(m) } -func (*DisconnectProcessResponse) ProtoMessage() {} -func (*DisconnectProcessResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{4} -} -func (m *DisconnectProcessResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DisconnectProcessResponse.Unmarshal(m, b) -} -func (m *DisconnectProcessResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DisconnectProcessResponse.Marshal(b, m, deterministic) -} -func (m *DisconnectProcessResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_DisconnectProcessResponse.Merge(m, src) -} -func (m *DisconnectProcessResponse) XXX_Size() int { - return xxx_messageInfo_DisconnectProcessResponse.Size(m) -} -func (m *DisconnectProcessResponse) XXX_DiscardUnknown() { - xxx_messageInfo_DisconnectProcessResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_DisconnectProcessResponse proto.InternalMessageInfo - -type BuildRequest struct { - Ref string `protobuf:"bytes,1,opt,name=Ref,proto3" json:"Ref,omitempty"` - Options *BuildOptions `protobuf:"bytes,2,opt,name=Options,proto3" json:"Options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *BuildRequest) Reset() { *m = BuildRequest{} } -func (m *BuildRequest) String() string { return proto.CompactTextString(m) } -func (*BuildRequest) ProtoMessage() {} -func (*BuildRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{5} -} -func (m *BuildRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_BuildRequest.Unmarshal(m, b) -} -func (m *BuildRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_BuildRequest.Marshal(b, m, deterministic) -} -func (m *BuildRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_BuildRequest.Merge(m, src) -} -func (m *BuildRequest) XXX_Size() int { - return xxx_messageInfo_BuildRequest.Size(m) -} -func (m *BuildRequest) XXX_DiscardUnknown() { - xxx_messageInfo_BuildRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_BuildRequest proto.InternalMessageInfo - -func (m *BuildRequest) GetRef() string { - if m != nil { - return m.Ref - } - return "" -} - -func (m *BuildRequest) GetOptions() *BuildOptions { - if m != nil { - return m.Options - } - return nil -} - -type BuildOptions struct { - ContextPath string `protobuf:"bytes,1,opt,name=ContextPath,proto3" json:"ContextPath,omitempty"` - DockerfileName string `protobuf:"bytes,2,opt,name=DockerfileName,proto3" json:"DockerfileName,omitempty"` - PrintFunc *PrintFunc `protobuf:"bytes,3,opt,name=PrintFunc,proto3" json:"PrintFunc,omitempty"` - NamedContexts map[string]string `protobuf:"bytes,4,rep,name=NamedContexts,proto3" json:"NamedContexts,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - Allow []string `protobuf:"bytes,5,rep,name=Allow,proto3" json:"Allow,omitempty"` - Attests []*Attest `protobuf:"bytes,6,rep,name=Attests,proto3" json:"Attests,omitempty"` - BuildArgs map[string]string `protobuf:"bytes,7,rep,name=BuildArgs,proto3" json:"BuildArgs,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - CacheFrom []*CacheOptionsEntry `protobuf:"bytes,8,rep,name=CacheFrom,proto3" json:"CacheFrom,omitempty"` - CacheTo []*CacheOptionsEntry `protobuf:"bytes,9,rep,name=CacheTo,proto3" json:"CacheTo,omitempty"` - CgroupParent string `protobuf:"bytes,10,opt,name=CgroupParent,proto3" json:"CgroupParent,omitempty"` - Exports []*ExportEntry `protobuf:"bytes,11,rep,name=Exports,proto3" json:"Exports,omitempty"` - ExtraHosts []string `protobuf:"bytes,12,rep,name=ExtraHosts,proto3" json:"ExtraHosts,omitempty"` - Labels map[string]string `protobuf:"bytes,13,rep,name=Labels,proto3" json:"Labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - NetworkMode string `protobuf:"bytes,14,opt,name=NetworkMode,proto3" json:"NetworkMode,omitempty"` - NoCacheFilter []string `protobuf:"bytes,15,rep,name=NoCacheFilter,proto3" json:"NoCacheFilter,omitempty"` - Platforms []string `protobuf:"bytes,16,rep,name=Platforms,proto3" json:"Platforms,omitempty"` - Secrets []*Secret `protobuf:"bytes,17,rep,name=Secrets,proto3" json:"Secrets,omitempty"` - ShmSize int64 `protobuf:"varint,18,opt,name=ShmSize,proto3" json:"ShmSize,omitempty"` - SSH []*SSH `protobuf:"bytes,19,rep,name=SSH,proto3" json:"SSH,omitempty"` - Tags []string `protobuf:"bytes,20,rep,name=Tags,proto3" json:"Tags,omitempty"` - Target string `protobuf:"bytes,21,opt,name=Target,proto3" json:"Target,omitempty"` - Ulimits *UlimitOpt `protobuf:"bytes,22,opt,name=Ulimits,proto3" json:"Ulimits,omitempty"` - Builder string `protobuf:"bytes,23,opt,name=Builder,proto3" json:"Builder,omitempty"` - NoCache bool `protobuf:"varint,24,opt,name=NoCache,proto3" json:"NoCache,omitempty"` - Pull bool `protobuf:"varint,25,opt,name=Pull,proto3" json:"Pull,omitempty"` - ExportPush bool `protobuf:"varint,26,opt,name=ExportPush,proto3" json:"ExportPush,omitempty"` - ExportLoad bool `protobuf:"varint,27,opt,name=ExportLoad,proto3" json:"ExportLoad,omitempty"` - SourcePolicy *pb.Policy `protobuf:"bytes,28,opt,name=SourcePolicy,proto3" json:"SourcePolicy,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *BuildOptions) Reset() { *m = BuildOptions{} } -func (m *BuildOptions) String() string { return proto.CompactTextString(m) } -func (*BuildOptions) ProtoMessage() {} -func (*BuildOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{6} -} -func (m *BuildOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_BuildOptions.Unmarshal(m, b) -} -func (m *BuildOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_BuildOptions.Marshal(b, m, deterministic) -} -func (m *BuildOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_BuildOptions.Merge(m, src) -} -func (m *BuildOptions) XXX_Size() int { - return xxx_messageInfo_BuildOptions.Size(m) -} -func (m *BuildOptions) XXX_DiscardUnknown() { - xxx_messageInfo_BuildOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_BuildOptions proto.InternalMessageInfo - -func (m *BuildOptions) GetContextPath() string { - if m != nil { - return m.ContextPath - } - return "" -} - -func (m *BuildOptions) GetDockerfileName() string { - if m != nil { - return m.DockerfileName - } - return "" -} - -func (m *BuildOptions) GetPrintFunc() *PrintFunc { - if m != nil { - return m.PrintFunc - } - return nil -} - -func (m *BuildOptions) GetNamedContexts() map[string]string { - if m != nil { - return m.NamedContexts - } - return nil -} - -func (m *BuildOptions) GetAllow() []string { - if m != nil { - return m.Allow - } - return nil -} - -func (m *BuildOptions) GetAttests() []*Attest { - if m != nil { - return m.Attests - } - return nil -} - -func (m *BuildOptions) GetBuildArgs() map[string]string { - if m != nil { - return m.BuildArgs - } - return nil -} - -func (m *BuildOptions) GetCacheFrom() []*CacheOptionsEntry { - if m != nil { - return m.CacheFrom - } - return nil -} - -func (m *BuildOptions) GetCacheTo() []*CacheOptionsEntry { - if m != nil { - return m.CacheTo - } - return nil -} - -func (m *BuildOptions) GetCgroupParent() string { - if m != nil { - return m.CgroupParent - } - return "" -} - -func (m *BuildOptions) GetExports() []*ExportEntry { - if m != nil { - return m.Exports - } - return nil -} - -func (m *BuildOptions) GetExtraHosts() []string { - if m != nil { - return m.ExtraHosts - } - return nil -} - -func (m *BuildOptions) GetLabels() map[string]string { - if m != nil { - return m.Labels - } - return nil -} - -func (m *BuildOptions) GetNetworkMode() string { - if m != nil { - return m.NetworkMode - } - return "" -} - -func (m *BuildOptions) GetNoCacheFilter() []string { - if m != nil { - return m.NoCacheFilter - } - return nil -} - -func (m *BuildOptions) GetPlatforms() []string { - if m != nil { - return m.Platforms - } - return nil -} - -func (m *BuildOptions) GetSecrets() []*Secret { - if m != nil { - return m.Secrets - } - return nil -} - -func (m *BuildOptions) GetShmSize() int64 { - if m != nil { - return m.ShmSize - } - return 0 -} - -func (m *BuildOptions) GetSSH() []*SSH { - if m != nil { - return m.SSH - } - return nil -} - -func (m *BuildOptions) GetTags() []string { - if m != nil { - return m.Tags - } - return nil -} - -func (m *BuildOptions) GetTarget() string { - if m != nil { - return m.Target - } - return "" -} - -func (m *BuildOptions) GetUlimits() *UlimitOpt { - if m != nil { - return m.Ulimits - } - return nil -} - -func (m *BuildOptions) GetBuilder() string { - if m != nil { - return m.Builder - } - return "" -} - -func (m *BuildOptions) GetNoCache() bool { - if m != nil { - return m.NoCache - } - return false -} - -func (m *BuildOptions) GetPull() bool { - if m != nil { - return m.Pull - } - return false -} - -func (m *BuildOptions) GetExportPush() bool { - if m != nil { - return m.ExportPush - } - return false -} - -func (m *BuildOptions) GetExportLoad() bool { - if m != nil { - return m.ExportLoad - } - return false -} - -func (m *BuildOptions) GetSourcePolicy() *pb.Policy { - if m != nil { - return m.SourcePolicy - } - return nil -} - -type ExportEntry struct { - Type string `protobuf:"bytes,1,opt,name=Type,proto3" json:"Type,omitempty"` - Attrs map[string]string `protobuf:"bytes,2,rep,name=Attrs,proto3" json:"Attrs,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - Destination string `protobuf:"bytes,3,opt,name=Destination,proto3" json:"Destination,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ExportEntry) Reset() { *m = ExportEntry{} } -func (m *ExportEntry) String() string { return proto.CompactTextString(m) } -func (*ExportEntry) ProtoMessage() {} -func (*ExportEntry) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{7} -} -func (m *ExportEntry) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ExportEntry.Unmarshal(m, b) -} -func (m *ExportEntry) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ExportEntry.Marshal(b, m, deterministic) -} -func (m *ExportEntry) XXX_Merge(src proto.Message) { - xxx_messageInfo_ExportEntry.Merge(m, src) -} -func (m *ExportEntry) XXX_Size() int { - return xxx_messageInfo_ExportEntry.Size(m) -} -func (m *ExportEntry) XXX_DiscardUnknown() { - xxx_messageInfo_ExportEntry.DiscardUnknown(m) -} - -var xxx_messageInfo_ExportEntry proto.InternalMessageInfo - -func (m *ExportEntry) GetType() string { - if m != nil { - return m.Type - } - return "" -} - -func (m *ExportEntry) GetAttrs() map[string]string { - if m != nil { - return m.Attrs - } - return nil -} - -func (m *ExportEntry) GetDestination() string { - if m != nil { - return m.Destination - } - return "" -} - -type CacheOptionsEntry struct { - Type string `protobuf:"bytes,1,opt,name=Type,proto3" json:"Type,omitempty"` - Attrs map[string]string `protobuf:"bytes,2,rep,name=Attrs,proto3" json:"Attrs,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CacheOptionsEntry) Reset() { *m = CacheOptionsEntry{} } -func (m *CacheOptionsEntry) String() string { return proto.CompactTextString(m) } -func (*CacheOptionsEntry) ProtoMessage() {} -func (*CacheOptionsEntry) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{8} -} -func (m *CacheOptionsEntry) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_CacheOptionsEntry.Unmarshal(m, b) -} -func (m *CacheOptionsEntry) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CacheOptionsEntry.Marshal(b, m, deterministic) -} -func (m *CacheOptionsEntry) XXX_Merge(src proto.Message) { - xxx_messageInfo_CacheOptionsEntry.Merge(m, src) -} -func (m *CacheOptionsEntry) XXX_Size() int { - return xxx_messageInfo_CacheOptionsEntry.Size(m) -} -func (m *CacheOptionsEntry) XXX_DiscardUnknown() { - xxx_messageInfo_CacheOptionsEntry.DiscardUnknown(m) -} - -var xxx_messageInfo_CacheOptionsEntry proto.InternalMessageInfo - -func (m *CacheOptionsEntry) GetType() string { - if m != nil { - return m.Type - } - return "" -} - -func (m *CacheOptionsEntry) GetAttrs() map[string]string { - if m != nil { - return m.Attrs - } - return nil -} - -type Attest struct { - Type string `protobuf:"bytes,1,opt,name=Type,proto3" json:"Type,omitempty"` - Disabled bool `protobuf:"varint,2,opt,name=Disabled,proto3" json:"Disabled,omitempty"` - Attrs string `protobuf:"bytes,3,opt,name=Attrs,proto3" json:"Attrs,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Attest) Reset() { *m = Attest{} } -func (m *Attest) String() string { return proto.CompactTextString(m) } -func (*Attest) ProtoMessage() {} -func (*Attest) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{9} -} -func (m *Attest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Attest.Unmarshal(m, b) -} -func (m *Attest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Attest.Marshal(b, m, deterministic) -} -func (m *Attest) XXX_Merge(src proto.Message) { - xxx_messageInfo_Attest.Merge(m, src) -} -func (m *Attest) XXX_Size() int { - return xxx_messageInfo_Attest.Size(m) -} -func (m *Attest) XXX_DiscardUnknown() { - xxx_messageInfo_Attest.DiscardUnknown(m) -} - -var xxx_messageInfo_Attest proto.InternalMessageInfo - -func (m *Attest) GetType() string { - if m != nil { - return m.Type - } - return "" -} - -func (m *Attest) GetDisabled() bool { - if m != nil { - return m.Disabled - } - return false -} - -func (m *Attest) GetAttrs() string { - if m != nil { - return m.Attrs - } - return "" -} - -type SSH struct { - ID string `protobuf:"bytes,1,opt,name=ID,proto3" json:"ID,omitempty"` - Paths []string `protobuf:"bytes,2,rep,name=Paths,proto3" json:"Paths,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SSH) Reset() { *m = SSH{} } -func (m *SSH) String() string { return proto.CompactTextString(m) } -func (*SSH) ProtoMessage() {} -func (*SSH) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{10} -} -func (m *SSH) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SSH.Unmarshal(m, b) -} -func (m *SSH) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SSH.Marshal(b, m, deterministic) -} -func (m *SSH) XXX_Merge(src proto.Message) { - xxx_messageInfo_SSH.Merge(m, src) -} -func (m *SSH) XXX_Size() int { - return xxx_messageInfo_SSH.Size(m) -} -func (m *SSH) XXX_DiscardUnknown() { - xxx_messageInfo_SSH.DiscardUnknown(m) -} - -var xxx_messageInfo_SSH proto.InternalMessageInfo - -func (m *SSH) GetID() string { - if m != nil { - return m.ID - } - return "" -} - -func (m *SSH) GetPaths() []string { - if m != nil { - return m.Paths - } - return nil -} - -type Secret struct { - ID string `protobuf:"bytes,1,opt,name=ID,proto3" json:"ID,omitempty"` - FilePath string `protobuf:"bytes,2,opt,name=FilePath,proto3" json:"FilePath,omitempty"` - Env string `protobuf:"bytes,3,opt,name=Env,proto3" json:"Env,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Secret) Reset() { *m = Secret{} } -func (m *Secret) String() string { return proto.CompactTextString(m) } -func (*Secret) ProtoMessage() {} -func (*Secret) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{11} -} -func (m *Secret) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Secret.Unmarshal(m, b) -} -func (m *Secret) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Secret.Marshal(b, m, deterministic) -} -func (m *Secret) XXX_Merge(src proto.Message) { - xxx_messageInfo_Secret.Merge(m, src) -} -func (m *Secret) XXX_Size() int { - return xxx_messageInfo_Secret.Size(m) -} -func (m *Secret) XXX_DiscardUnknown() { - xxx_messageInfo_Secret.DiscardUnknown(m) -} - -var xxx_messageInfo_Secret proto.InternalMessageInfo - -func (m *Secret) GetID() string { - if m != nil { - return m.ID - } - return "" -} - -func (m *Secret) GetFilePath() string { - if m != nil { - return m.FilePath - } - return "" -} - -func (m *Secret) GetEnv() string { - if m != nil { - return m.Env - } - return "" -} - -type PrintFunc struct { - Name string `protobuf:"bytes,1,opt,name=Name,proto3" json:"Name,omitempty"` - Format string `protobuf:"bytes,2,opt,name=Format,proto3" json:"Format,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PrintFunc) Reset() { *m = PrintFunc{} } -func (m *PrintFunc) String() string { return proto.CompactTextString(m) } -func (*PrintFunc) ProtoMessage() {} -func (*PrintFunc) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{12} -} -func (m *PrintFunc) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PrintFunc.Unmarshal(m, b) -} -func (m *PrintFunc) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PrintFunc.Marshal(b, m, deterministic) -} -func (m *PrintFunc) XXX_Merge(src proto.Message) { - xxx_messageInfo_PrintFunc.Merge(m, src) -} -func (m *PrintFunc) XXX_Size() int { - return xxx_messageInfo_PrintFunc.Size(m) -} -func (m *PrintFunc) XXX_DiscardUnknown() { - xxx_messageInfo_PrintFunc.DiscardUnknown(m) -} - -var xxx_messageInfo_PrintFunc proto.InternalMessageInfo - -func (m *PrintFunc) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *PrintFunc) GetFormat() string { - if m != nil { - return m.Format - } - return "" -} - -type InspectRequest struct { - Ref string `protobuf:"bytes,1,opt,name=Ref,proto3" json:"Ref,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *InspectRequest) Reset() { *m = InspectRequest{} } -func (m *InspectRequest) String() string { return proto.CompactTextString(m) } -func (*InspectRequest) ProtoMessage() {} -func (*InspectRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{13} -} -func (m *InspectRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_InspectRequest.Unmarshal(m, b) -} -func (m *InspectRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_InspectRequest.Marshal(b, m, deterministic) -} -func (m *InspectRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_InspectRequest.Merge(m, src) -} -func (m *InspectRequest) XXX_Size() int { - return xxx_messageInfo_InspectRequest.Size(m) -} -func (m *InspectRequest) XXX_DiscardUnknown() { - xxx_messageInfo_InspectRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_InspectRequest proto.InternalMessageInfo - -func (m *InspectRequest) GetRef() string { - if m != nil { - return m.Ref - } - return "" -} - -type InspectResponse struct { - Options *BuildOptions `protobuf:"bytes,1,opt,name=Options,proto3" json:"Options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *InspectResponse) Reset() { *m = InspectResponse{} } -func (m *InspectResponse) String() string { return proto.CompactTextString(m) } -func (*InspectResponse) ProtoMessage() {} -func (*InspectResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{14} -} -func (m *InspectResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_InspectResponse.Unmarshal(m, b) -} -func (m *InspectResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_InspectResponse.Marshal(b, m, deterministic) -} -func (m *InspectResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_InspectResponse.Merge(m, src) -} -func (m *InspectResponse) XXX_Size() int { - return xxx_messageInfo_InspectResponse.Size(m) -} -func (m *InspectResponse) XXX_DiscardUnknown() { - xxx_messageInfo_InspectResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_InspectResponse proto.InternalMessageInfo - -func (m *InspectResponse) GetOptions() *BuildOptions { - if m != nil { - return m.Options - } - return nil -} - -type UlimitOpt struct { - Values map[string]*Ulimit `protobuf:"bytes,1,rep,name=values,proto3" json:"values,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UlimitOpt) Reset() { *m = UlimitOpt{} } -func (m *UlimitOpt) String() string { return proto.CompactTextString(m) } -func (*UlimitOpt) ProtoMessage() {} -func (*UlimitOpt) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{15} -} -func (m *UlimitOpt) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UlimitOpt.Unmarshal(m, b) -} -func (m *UlimitOpt) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UlimitOpt.Marshal(b, m, deterministic) -} -func (m *UlimitOpt) XXX_Merge(src proto.Message) { - xxx_messageInfo_UlimitOpt.Merge(m, src) -} -func (m *UlimitOpt) XXX_Size() int { - return xxx_messageInfo_UlimitOpt.Size(m) -} -func (m *UlimitOpt) XXX_DiscardUnknown() { - xxx_messageInfo_UlimitOpt.DiscardUnknown(m) -} - -var xxx_messageInfo_UlimitOpt proto.InternalMessageInfo - -func (m *UlimitOpt) GetValues() map[string]*Ulimit { - if m != nil { - return m.Values - } - return nil -} - -type Ulimit struct { - Name string `protobuf:"bytes,1,opt,name=Name,proto3" json:"Name,omitempty"` - Hard int64 `protobuf:"varint,2,opt,name=Hard,proto3" json:"Hard,omitempty"` - Soft int64 `protobuf:"varint,3,opt,name=Soft,proto3" json:"Soft,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Ulimit) Reset() { *m = Ulimit{} } -func (m *Ulimit) String() string { return proto.CompactTextString(m) } -func (*Ulimit) ProtoMessage() {} -func (*Ulimit) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{16} -} -func (m *Ulimit) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Ulimit.Unmarshal(m, b) -} -func (m *Ulimit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Ulimit.Marshal(b, m, deterministic) -} -func (m *Ulimit) XXX_Merge(src proto.Message) { - xxx_messageInfo_Ulimit.Merge(m, src) -} -func (m *Ulimit) XXX_Size() int { - return xxx_messageInfo_Ulimit.Size(m) -} -func (m *Ulimit) XXX_DiscardUnknown() { - xxx_messageInfo_Ulimit.DiscardUnknown(m) -} - -var xxx_messageInfo_Ulimit proto.InternalMessageInfo - -func (m *Ulimit) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Ulimit) GetHard() int64 { - if m != nil { - return m.Hard - } - return 0 -} - -func (m *Ulimit) GetSoft() int64 { - if m != nil { - return m.Soft - } - return 0 -} - -type BuildResponse struct { - ExporterResponse map[string]string `protobuf:"bytes,1,rep,name=ExporterResponse,proto3" json:"ExporterResponse,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *BuildResponse) Reset() { *m = BuildResponse{} } -func (m *BuildResponse) String() string { return proto.CompactTextString(m) } -func (*BuildResponse) ProtoMessage() {} -func (*BuildResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{17} -} -func (m *BuildResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_BuildResponse.Unmarshal(m, b) -} -func (m *BuildResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_BuildResponse.Marshal(b, m, deterministic) -} -func (m *BuildResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_BuildResponse.Merge(m, src) -} -func (m *BuildResponse) XXX_Size() int { - return xxx_messageInfo_BuildResponse.Size(m) -} -func (m *BuildResponse) XXX_DiscardUnknown() { - xxx_messageInfo_BuildResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_BuildResponse proto.InternalMessageInfo - -func (m *BuildResponse) GetExporterResponse() map[string]string { - if m != nil { - return m.ExporterResponse - } - return nil -} - -type DisconnectRequest struct { - Ref string `protobuf:"bytes,1,opt,name=Ref,proto3" json:"Ref,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DisconnectRequest) Reset() { *m = DisconnectRequest{} } -func (m *DisconnectRequest) String() string { return proto.CompactTextString(m) } -func (*DisconnectRequest) ProtoMessage() {} -func (*DisconnectRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{18} -} -func (m *DisconnectRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DisconnectRequest.Unmarshal(m, b) -} -func (m *DisconnectRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DisconnectRequest.Marshal(b, m, deterministic) -} -func (m *DisconnectRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_DisconnectRequest.Merge(m, src) -} -func (m *DisconnectRequest) XXX_Size() int { - return xxx_messageInfo_DisconnectRequest.Size(m) -} -func (m *DisconnectRequest) XXX_DiscardUnknown() { - xxx_messageInfo_DisconnectRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_DisconnectRequest proto.InternalMessageInfo - -func (m *DisconnectRequest) GetRef() string { - if m != nil { - return m.Ref - } - return "" -} - -type DisconnectResponse struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DisconnectResponse) Reset() { *m = DisconnectResponse{} } -func (m *DisconnectResponse) String() string { return proto.CompactTextString(m) } -func (*DisconnectResponse) ProtoMessage() {} -func (*DisconnectResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{19} -} -func (m *DisconnectResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DisconnectResponse.Unmarshal(m, b) -} -func (m *DisconnectResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DisconnectResponse.Marshal(b, m, deterministic) -} -func (m *DisconnectResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_DisconnectResponse.Merge(m, src) -} -func (m *DisconnectResponse) XXX_Size() int { - return xxx_messageInfo_DisconnectResponse.Size(m) -} -func (m *DisconnectResponse) XXX_DiscardUnknown() { - xxx_messageInfo_DisconnectResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_DisconnectResponse proto.InternalMessageInfo - -type ListRequest struct { - Ref string `protobuf:"bytes,1,opt,name=Ref,proto3" json:"Ref,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListRequest) Reset() { *m = ListRequest{} } -func (m *ListRequest) String() string { return proto.CompactTextString(m) } -func (*ListRequest) ProtoMessage() {} -func (*ListRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{20} -} -func (m *ListRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListRequest.Unmarshal(m, b) -} -func (m *ListRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListRequest.Marshal(b, m, deterministic) -} -func (m *ListRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListRequest.Merge(m, src) -} -func (m *ListRequest) XXX_Size() int { - return xxx_messageInfo_ListRequest.Size(m) -} -func (m *ListRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ListRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ListRequest proto.InternalMessageInfo - -func (m *ListRequest) GetRef() string { - if m != nil { - return m.Ref - } - return "" -} - -type ListResponse struct { - Keys []string `protobuf:"bytes,1,rep,name=keys,proto3" json:"keys,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListResponse) Reset() { *m = ListResponse{} } -func (m *ListResponse) String() string { return proto.CompactTextString(m) } -func (*ListResponse) ProtoMessage() {} -func (*ListResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{21} -} -func (m *ListResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListResponse.Unmarshal(m, b) -} -func (m *ListResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListResponse.Marshal(b, m, deterministic) -} -func (m *ListResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListResponse.Merge(m, src) -} -func (m *ListResponse) XXX_Size() int { - return xxx_messageInfo_ListResponse.Size(m) -} -func (m *ListResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ListResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ListResponse proto.InternalMessageInfo - -func (m *ListResponse) GetKeys() []string { - if m != nil { - return m.Keys - } - return nil -} - -type InputMessage struct { - // Types that are valid to be assigned to Input: - // *InputMessage_Init - // *InputMessage_Data - Input isInputMessage_Input `protobuf_oneof:"Input"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *InputMessage) Reset() { *m = InputMessage{} } -func (m *InputMessage) String() string { return proto.CompactTextString(m) } -func (*InputMessage) ProtoMessage() {} -func (*InputMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{22} -} -func (m *InputMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_InputMessage.Unmarshal(m, b) -} -func (m *InputMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_InputMessage.Marshal(b, m, deterministic) -} -func (m *InputMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_InputMessage.Merge(m, src) -} -func (m *InputMessage) XXX_Size() int { - return xxx_messageInfo_InputMessage.Size(m) -} -func (m *InputMessage) XXX_DiscardUnknown() { - xxx_messageInfo_InputMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_InputMessage proto.InternalMessageInfo - -type isInputMessage_Input interface { - isInputMessage_Input() -} - -type InputMessage_Init struct { - Init *InputInitMessage `protobuf:"bytes,1,opt,name=Init,proto3,oneof" json:"Init,omitempty"` -} -type InputMessage_Data struct { - Data *DataMessage `protobuf:"bytes,2,opt,name=Data,proto3,oneof" json:"Data,omitempty"` -} - -func (*InputMessage_Init) isInputMessage_Input() {} -func (*InputMessage_Data) isInputMessage_Input() {} - -func (m *InputMessage) GetInput() isInputMessage_Input { - if m != nil { - return m.Input - } - return nil -} - -func (m *InputMessage) GetInit() *InputInitMessage { - if x, ok := m.GetInput().(*InputMessage_Init); ok { - return x.Init - } - return nil -} - -func (m *InputMessage) GetData() *DataMessage { - if x, ok := m.GetInput().(*InputMessage_Data); ok { - return x.Data - } - return nil -} - -// XXX_OneofWrappers is for the internal use of the proto package. -func (*InputMessage) XXX_OneofWrappers() []interface{} { - return []interface{}{ - (*InputMessage_Init)(nil), - (*InputMessage_Data)(nil), - } -} - -type InputInitMessage struct { - Ref string `protobuf:"bytes,1,opt,name=Ref,proto3" json:"Ref,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *InputInitMessage) Reset() { *m = InputInitMessage{} } -func (m *InputInitMessage) String() string { return proto.CompactTextString(m) } -func (*InputInitMessage) ProtoMessage() {} -func (*InputInitMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{23} -} -func (m *InputInitMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_InputInitMessage.Unmarshal(m, b) -} -func (m *InputInitMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_InputInitMessage.Marshal(b, m, deterministic) -} -func (m *InputInitMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_InputInitMessage.Merge(m, src) -} -func (m *InputInitMessage) XXX_Size() int { - return xxx_messageInfo_InputInitMessage.Size(m) -} -func (m *InputInitMessage) XXX_DiscardUnknown() { - xxx_messageInfo_InputInitMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_InputInitMessage proto.InternalMessageInfo - -func (m *InputInitMessage) GetRef() string { - if m != nil { - return m.Ref - } - return "" -} - -type DataMessage struct { - EOF bool `protobuf:"varint,1,opt,name=EOF,proto3" json:"EOF,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 *DataMessage) Reset() { *m = DataMessage{} } -func (m *DataMessage) String() string { return proto.CompactTextString(m) } -func (*DataMessage) ProtoMessage() {} -func (*DataMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{24} -} -func (m *DataMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DataMessage.Unmarshal(m, b) -} -func (m *DataMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DataMessage.Marshal(b, m, deterministic) -} -func (m *DataMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_DataMessage.Merge(m, src) -} -func (m *DataMessage) XXX_Size() int { - return xxx_messageInfo_DataMessage.Size(m) -} -func (m *DataMessage) XXX_DiscardUnknown() { - xxx_messageInfo_DataMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_DataMessage proto.InternalMessageInfo - -func (m *DataMessage) GetEOF() bool { - if m != nil { - return m.EOF - } - return false -} - -func (m *DataMessage) GetData() []byte { - if m != nil { - return m.Data - } - return nil -} - -type InputResponse struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *InputResponse) Reset() { *m = InputResponse{} } -func (m *InputResponse) String() string { return proto.CompactTextString(m) } -func (*InputResponse) ProtoMessage() {} -func (*InputResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{25} -} -func (m *InputResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_InputResponse.Unmarshal(m, b) -} -func (m *InputResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_InputResponse.Marshal(b, m, deterministic) -} -func (m *InputResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_InputResponse.Merge(m, src) -} -func (m *InputResponse) XXX_Size() int { - return xxx_messageInfo_InputResponse.Size(m) -} -func (m *InputResponse) XXX_DiscardUnknown() { - xxx_messageInfo_InputResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_InputResponse proto.InternalMessageInfo - -type Message struct { - // Types that are valid to be assigned to Input: - // *Message_Init - // *Message_File - // *Message_Resize - // *Message_Signal - Input isMessage_Input `protobuf_oneof:"Input"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -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_ed7f10298fa1d90f, []int{26} -} -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 (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) -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type isMessage_Input interface { - isMessage_Input() -} - -type Message_Init struct { - Init *InitMessage `protobuf:"bytes,1,opt,name=Init,proto3,oneof" json:"Init,omitempty"` -} -type Message_File struct { - File *FdMessage `protobuf:"bytes,2,opt,name=File,proto3,oneof" json:"File,omitempty"` -} -type Message_Resize struct { - Resize *ResizeMessage `protobuf:"bytes,3,opt,name=Resize,proto3,oneof" json:"Resize,omitempty"` -} -type Message_Signal struct { - Signal *SignalMessage `protobuf:"bytes,4,opt,name=Signal,proto3,oneof" json:"Signal,omitempty"` -} - -func (*Message_Init) isMessage_Input() {} -func (*Message_File) isMessage_Input() {} -func (*Message_Resize) isMessage_Input() {} -func (*Message_Signal) isMessage_Input() {} - -func (m *Message) GetInput() isMessage_Input { - if m != nil { - return m.Input - } - return nil -} - -func (m *Message) GetInit() *InitMessage { - if x, ok := m.GetInput().(*Message_Init); ok { - return x.Init - } - return nil -} - -func (m *Message) GetFile() *FdMessage { - if x, ok := m.GetInput().(*Message_File); ok { - return x.File - } - return nil -} - -func (m *Message) GetResize() *ResizeMessage { - if x, ok := m.GetInput().(*Message_Resize); ok { - return x.Resize - } - return nil -} - -func (m *Message) GetSignal() *SignalMessage { - if x, ok := m.GetInput().(*Message_Signal); ok { - return x.Signal - } - return nil -} - -// XXX_OneofWrappers is for the internal use of the proto package. -func (*Message) XXX_OneofWrappers() []interface{} { - return []interface{}{ - (*Message_Init)(nil), - (*Message_File)(nil), - (*Message_Resize)(nil), - (*Message_Signal)(nil), - } -} - -type InitMessage struct { - Ref string `protobuf:"bytes,1,opt,name=Ref,proto3" json:"Ref,omitempty"` - // If ProcessID already exists in the server, it tries to connect to it - // instead of invoking the new one. In this case, InvokeConfig will be ignored. - ProcessID string `protobuf:"bytes,2,opt,name=ProcessID,proto3" json:"ProcessID,omitempty"` - InvokeConfig *InvokeConfig `protobuf:"bytes,3,opt,name=InvokeConfig,proto3" json:"InvokeConfig,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *InitMessage) Reset() { *m = InitMessage{} } -func (m *InitMessage) String() string { return proto.CompactTextString(m) } -func (*InitMessage) ProtoMessage() {} -func (*InitMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{27} -} -func (m *InitMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_InitMessage.Unmarshal(m, b) -} -func (m *InitMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_InitMessage.Marshal(b, m, deterministic) -} -func (m *InitMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_InitMessage.Merge(m, src) -} -func (m *InitMessage) XXX_Size() int { - return xxx_messageInfo_InitMessage.Size(m) -} -func (m *InitMessage) XXX_DiscardUnknown() { - xxx_messageInfo_InitMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_InitMessage proto.InternalMessageInfo - -func (m *InitMessage) GetRef() string { - if m != nil { - return m.Ref - } - return "" -} - -func (m *InitMessage) GetProcessID() string { - if m != nil { - return m.ProcessID - } - return "" -} - -func (m *InitMessage) GetInvokeConfig() *InvokeConfig { - if m != nil { - return m.InvokeConfig - } - return nil -} - -type InvokeConfig struct { - Entrypoint []string `protobuf:"bytes,1,rep,name=Entrypoint,proto3" json:"Entrypoint,omitempty"` - Cmd []string `protobuf:"bytes,2,rep,name=Cmd,proto3" json:"Cmd,omitempty"` - Env []string `protobuf:"bytes,3,rep,name=Env,proto3" json:"Env,omitempty"` - User string `protobuf:"bytes,4,opt,name=User,proto3" json:"User,omitempty"` - NoUser bool `protobuf:"varint,5,opt,name=NoUser,proto3" json:"NoUser,omitempty"` - Cwd string `protobuf:"bytes,6,opt,name=Cwd,proto3" json:"Cwd,omitempty"` - NoCwd bool `protobuf:"varint,7,opt,name=NoCwd,proto3" json:"NoCwd,omitempty"` - Tty bool `protobuf:"varint,8,opt,name=Tty,proto3" json:"Tty,omitempty"` - Rollback bool `protobuf:"varint,9,opt,name=Rollback,proto3" json:"Rollback,omitempty"` - Initial bool `protobuf:"varint,10,opt,name=Initial,proto3" json:"Initial,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *InvokeConfig) Reset() { *m = InvokeConfig{} } -func (m *InvokeConfig) String() string { return proto.CompactTextString(m) } -func (*InvokeConfig) ProtoMessage() {} -func (*InvokeConfig) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{28} -} -func (m *InvokeConfig) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_InvokeConfig.Unmarshal(m, b) -} -func (m *InvokeConfig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_InvokeConfig.Marshal(b, m, deterministic) -} -func (m *InvokeConfig) XXX_Merge(src proto.Message) { - xxx_messageInfo_InvokeConfig.Merge(m, src) -} -func (m *InvokeConfig) XXX_Size() int { - return xxx_messageInfo_InvokeConfig.Size(m) -} -func (m *InvokeConfig) XXX_DiscardUnknown() { - xxx_messageInfo_InvokeConfig.DiscardUnknown(m) -} - -var xxx_messageInfo_InvokeConfig proto.InternalMessageInfo - -func (m *InvokeConfig) GetEntrypoint() []string { - if m != nil { - return m.Entrypoint - } - return nil -} - -func (m *InvokeConfig) GetCmd() []string { - if m != nil { - return m.Cmd - } - return nil -} - -func (m *InvokeConfig) GetEnv() []string { - if m != nil { - return m.Env - } - return nil -} - -func (m *InvokeConfig) GetUser() string { - if m != nil { - return m.User - } - return "" -} - -func (m *InvokeConfig) GetNoUser() bool { - if m != nil { - return m.NoUser - } - return false -} - -func (m *InvokeConfig) GetCwd() string { - if m != nil { - return m.Cwd - } - return "" -} - -func (m *InvokeConfig) GetNoCwd() bool { - if m != nil { - return m.NoCwd - } - return false -} - -func (m *InvokeConfig) GetTty() bool { - if m != nil { - return m.Tty - } - return false -} - -func (m *InvokeConfig) GetRollback() bool { - if m != nil { - return m.Rollback - } - return false -} - -func (m *InvokeConfig) GetInitial() bool { - if m != nil { - return m.Initial - } - return false -} - -type FdMessage struct { - Fd uint32 `protobuf:"varint,1,opt,name=Fd,proto3" json:"Fd,omitempty"` - EOF bool `protobuf:"varint,2,opt,name=EOF,proto3" json:"EOF,omitempty"` - Data []byte `protobuf:"bytes,3,opt,name=Data,proto3" json:"Data,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FdMessage) Reset() { *m = FdMessage{} } -func (m *FdMessage) String() string { return proto.CompactTextString(m) } -func (*FdMessage) ProtoMessage() {} -func (*FdMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{29} -} -func (m *FdMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FdMessage.Unmarshal(m, b) -} -func (m *FdMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FdMessage.Marshal(b, m, deterministic) -} -func (m *FdMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_FdMessage.Merge(m, src) -} -func (m *FdMessage) XXX_Size() int { - return xxx_messageInfo_FdMessage.Size(m) -} -func (m *FdMessage) XXX_DiscardUnknown() { - xxx_messageInfo_FdMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_FdMessage proto.InternalMessageInfo - -func (m *FdMessage) GetFd() uint32 { - if m != nil { - return m.Fd - } - return 0 -} - -func (m *FdMessage) GetEOF() bool { - if m != nil { - return m.EOF - } - return false -} - -func (m *FdMessage) GetData() []byte { - if m != nil { - return m.Data - } - return nil -} - -type ResizeMessage struct { - Rows uint32 `protobuf:"varint,1,opt,name=Rows,proto3" json:"Rows,omitempty"` - Cols uint32 `protobuf:"varint,2,opt,name=Cols,proto3" json:"Cols,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ResizeMessage) Reset() { *m = ResizeMessage{} } -func (m *ResizeMessage) String() string { return proto.CompactTextString(m) } -func (*ResizeMessage) ProtoMessage() {} -func (*ResizeMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{30} -} -func (m *ResizeMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ResizeMessage.Unmarshal(m, b) -} -func (m *ResizeMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ResizeMessage.Marshal(b, m, deterministic) -} -func (m *ResizeMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_ResizeMessage.Merge(m, src) -} -func (m *ResizeMessage) XXX_Size() int { - return xxx_messageInfo_ResizeMessage.Size(m) -} -func (m *ResizeMessage) XXX_DiscardUnknown() { - xxx_messageInfo_ResizeMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_ResizeMessage proto.InternalMessageInfo - -func (m *ResizeMessage) GetRows() uint32 { - if m != nil { - return m.Rows - } - return 0 -} - -func (m *ResizeMessage) GetCols() uint32 { - if m != nil { - return m.Cols - } - return 0 -} - -type SignalMessage struct { - // we only send name (ie HUP, INT) because the int values - // are platform dependent. - 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 *SignalMessage) Reset() { *m = SignalMessage{} } -func (m *SignalMessage) String() string { return proto.CompactTextString(m) } -func (*SignalMessage) ProtoMessage() {} -func (*SignalMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{31} -} -func (m *SignalMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SignalMessage.Unmarshal(m, b) -} -func (m *SignalMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SignalMessage.Marshal(b, m, deterministic) -} -func (m *SignalMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_SignalMessage.Merge(m, src) -} -func (m *SignalMessage) XXX_Size() int { - return xxx_messageInfo_SignalMessage.Size(m) -} -func (m *SignalMessage) XXX_DiscardUnknown() { - xxx_messageInfo_SignalMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_SignalMessage proto.InternalMessageInfo - -func (m *SignalMessage) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -type StatusRequest struct { - Ref string `protobuf:"bytes,1,opt,name=Ref,proto3" json:"Ref,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StatusRequest) Reset() { *m = StatusRequest{} } -func (m *StatusRequest) String() string { return proto.CompactTextString(m) } -func (*StatusRequest) ProtoMessage() {} -func (*StatusRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{32} -} -func (m *StatusRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StatusRequest.Unmarshal(m, b) -} -func (m *StatusRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StatusRequest.Marshal(b, m, deterministic) -} -func (m *StatusRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_StatusRequest.Merge(m, src) -} -func (m *StatusRequest) XXX_Size() int { - return xxx_messageInfo_StatusRequest.Size(m) -} -func (m *StatusRequest) XXX_DiscardUnknown() { - xxx_messageInfo_StatusRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_StatusRequest proto.InternalMessageInfo - -func (m *StatusRequest) GetRef() string { - if m != nil { - return m.Ref - } - return "" -} - -type StatusResponse struct { - Vertexes []*control.Vertex `protobuf:"bytes,1,rep,name=vertexes,proto3" json:"vertexes,omitempty"` - Statuses []*control.VertexStatus `protobuf:"bytes,2,rep,name=statuses,proto3" json:"statuses,omitempty"` - Logs []*control.VertexLog `protobuf:"bytes,3,rep,name=logs,proto3" json:"logs,omitempty"` - Warnings []*control.VertexWarning `protobuf:"bytes,4,rep,name=warnings,proto3" json:"warnings,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StatusResponse) Reset() { *m = StatusResponse{} } -func (m *StatusResponse) String() string { return proto.CompactTextString(m) } -func (*StatusResponse) ProtoMessage() {} -func (*StatusResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{33} -} -func (m *StatusResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StatusResponse.Unmarshal(m, b) -} -func (m *StatusResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StatusResponse.Marshal(b, m, deterministic) -} -func (m *StatusResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_StatusResponse.Merge(m, src) -} -func (m *StatusResponse) XXX_Size() int { - return xxx_messageInfo_StatusResponse.Size(m) -} -func (m *StatusResponse) XXX_DiscardUnknown() { - xxx_messageInfo_StatusResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_StatusResponse proto.InternalMessageInfo - -func (m *StatusResponse) GetVertexes() []*control.Vertex { - if m != nil { - return m.Vertexes - } - return nil -} - -func (m *StatusResponse) GetStatuses() []*control.VertexStatus { - if m != nil { - return m.Statuses - } - return nil -} - -func (m *StatusResponse) GetLogs() []*control.VertexLog { - if m != nil { - return m.Logs - } - return nil -} - -func (m *StatusResponse) GetWarnings() []*control.VertexWarning { - if m != nil { - return m.Warnings - } - return nil -} - -type InfoRequest struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *InfoRequest) Reset() { *m = InfoRequest{} } -func (m *InfoRequest) String() string { return proto.CompactTextString(m) } -func (*InfoRequest) ProtoMessage() {} -func (*InfoRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{34} -} -func (m *InfoRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_InfoRequest.Unmarshal(m, b) -} -func (m *InfoRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_InfoRequest.Marshal(b, m, deterministic) -} -func (m *InfoRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_InfoRequest.Merge(m, src) -} -func (m *InfoRequest) XXX_Size() int { - return xxx_messageInfo_InfoRequest.Size(m) -} -func (m *InfoRequest) XXX_DiscardUnknown() { - xxx_messageInfo_InfoRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_InfoRequest proto.InternalMessageInfo - -type InfoResponse struct { - BuildxVersion *BuildxVersion `protobuf:"bytes,1,opt,name=buildxVersion,proto3" json:"buildxVersion,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *InfoResponse) Reset() { *m = InfoResponse{} } -func (m *InfoResponse) String() string { return proto.CompactTextString(m) } -func (*InfoResponse) ProtoMessage() {} -func (*InfoResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{35} -} -func (m *InfoResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_InfoResponse.Unmarshal(m, b) -} -func (m *InfoResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_InfoResponse.Marshal(b, m, deterministic) -} -func (m *InfoResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_InfoResponse.Merge(m, src) -} -func (m *InfoResponse) XXX_Size() int { - return xxx_messageInfo_InfoResponse.Size(m) -} -func (m *InfoResponse) XXX_DiscardUnknown() { - xxx_messageInfo_InfoResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_InfoResponse proto.InternalMessageInfo - -func (m *InfoResponse) GetBuildxVersion() *BuildxVersion { - if m != nil { - return m.BuildxVersion - } - return nil -} - -type BuildxVersion struct { - Package string `protobuf:"bytes,1,opt,name=package,proto3" json:"package,omitempty"` - Version string `protobuf:"bytes,2,opt,name=version,proto3" json:"version,omitempty"` - Revision string `protobuf:"bytes,3,opt,name=revision,proto3" json:"revision,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *BuildxVersion) Reset() { *m = BuildxVersion{} } -func (m *BuildxVersion) String() string { return proto.CompactTextString(m) } -func (*BuildxVersion) ProtoMessage() {} -func (*BuildxVersion) Descriptor() ([]byte, []int) { - return fileDescriptor_ed7f10298fa1d90f, []int{36} -} -func (m *BuildxVersion) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_BuildxVersion.Unmarshal(m, b) -} -func (m *BuildxVersion) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_BuildxVersion.Marshal(b, m, deterministic) -} -func (m *BuildxVersion) XXX_Merge(src proto.Message) { - xxx_messageInfo_BuildxVersion.Merge(m, src) -} -func (m *BuildxVersion) XXX_Size() int { - return xxx_messageInfo_BuildxVersion.Size(m) -} -func (m *BuildxVersion) XXX_DiscardUnknown() { - xxx_messageInfo_BuildxVersion.DiscardUnknown(m) -} - -var xxx_messageInfo_BuildxVersion proto.InternalMessageInfo - -func (m *BuildxVersion) GetPackage() string { - if m != nil { - return m.Package - } - return "" -} - -func (m *BuildxVersion) GetVersion() string { - if m != nil { - return m.Version - } - return "" -} - -func (m *BuildxVersion) GetRevision() string { - if m != nil { - return m.Revision - } - return "" -} - -func init() { - proto.RegisterType((*ListProcessesRequest)(nil), "buildx.controller.v1.ListProcessesRequest") - proto.RegisterType((*ListProcessesResponse)(nil), "buildx.controller.v1.ListProcessesResponse") - proto.RegisterType((*ProcessInfo)(nil), "buildx.controller.v1.ProcessInfo") - proto.RegisterType((*DisconnectProcessRequest)(nil), "buildx.controller.v1.DisconnectProcessRequest") - proto.RegisterType((*DisconnectProcessResponse)(nil), "buildx.controller.v1.DisconnectProcessResponse") - proto.RegisterType((*BuildRequest)(nil), "buildx.controller.v1.BuildRequest") - proto.RegisterType((*BuildOptions)(nil), "buildx.controller.v1.BuildOptions") - proto.RegisterMapType((map[string]string)(nil), "buildx.controller.v1.BuildOptions.BuildArgsEntry") - proto.RegisterMapType((map[string]string)(nil), "buildx.controller.v1.BuildOptions.LabelsEntry") - proto.RegisterMapType((map[string]string)(nil), "buildx.controller.v1.BuildOptions.NamedContextsEntry") - proto.RegisterType((*ExportEntry)(nil), "buildx.controller.v1.ExportEntry") - proto.RegisterMapType((map[string]string)(nil), "buildx.controller.v1.ExportEntry.AttrsEntry") - proto.RegisterType((*CacheOptionsEntry)(nil), "buildx.controller.v1.CacheOptionsEntry") - proto.RegisterMapType((map[string]string)(nil), "buildx.controller.v1.CacheOptionsEntry.AttrsEntry") - proto.RegisterType((*Attest)(nil), "buildx.controller.v1.Attest") - proto.RegisterType((*SSH)(nil), "buildx.controller.v1.SSH") - proto.RegisterType((*Secret)(nil), "buildx.controller.v1.Secret") - proto.RegisterType((*PrintFunc)(nil), "buildx.controller.v1.PrintFunc") - proto.RegisterType((*InspectRequest)(nil), "buildx.controller.v1.InspectRequest") - proto.RegisterType((*InspectResponse)(nil), "buildx.controller.v1.InspectResponse") - proto.RegisterType((*UlimitOpt)(nil), "buildx.controller.v1.UlimitOpt") - proto.RegisterMapType((map[string]*Ulimit)(nil), "buildx.controller.v1.UlimitOpt.ValuesEntry") - proto.RegisterType((*Ulimit)(nil), "buildx.controller.v1.Ulimit") - proto.RegisterType((*BuildResponse)(nil), "buildx.controller.v1.BuildResponse") - proto.RegisterMapType((map[string]string)(nil), "buildx.controller.v1.BuildResponse.ExporterResponseEntry") - proto.RegisterType((*DisconnectRequest)(nil), "buildx.controller.v1.DisconnectRequest") - proto.RegisterType((*DisconnectResponse)(nil), "buildx.controller.v1.DisconnectResponse") - proto.RegisterType((*ListRequest)(nil), "buildx.controller.v1.ListRequest") - proto.RegisterType((*ListResponse)(nil), "buildx.controller.v1.ListResponse") - proto.RegisterType((*InputMessage)(nil), "buildx.controller.v1.InputMessage") - proto.RegisterType((*InputInitMessage)(nil), "buildx.controller.v1.InputInitMessage") - proto.RegisterType((*DataMessage)(nil), "buildx.controller.v1.DataMessage") - proto.RegisterType((*InputResponse)(nil), "buildx.controller.v1.InputResponse") - proto.RegisterType((*Message)(nil), "buildx.controller.v1.Message") - proto.RegisterType((*InitMessage)(nil), "buildx.controller.v1.InitMessage") - proto.RegisterType((*InvokeConfig)(nil), "buildx.controller.v1.InvokeConfig") - proto.RegisterType((*FdMessage)(nil), "buildx.controller.v1.FdMessage") - proto.RegisterType((*ResizeMessage)(nil), "buildx.controller.v1.ResizeMessage") - proto.RegisterType((*SignalMessage)(nil), "buildx.controller.v1.SignalMessage") - proto.RegisterType((*StatusRequest)(nil), "buildx.controller.v1.StatusRequest") - proto.RegisterType((*StatusResponse)(nil), "buildx.controller.v1.StatusResponse") - proto.RegisterType((*InfoRequest)(nil), "buildx.controller.v1.InfoRequest") - proto.RegisterType((*InfoResponse)(nil), "buildx.controller.v1.InfoResponse") - proto.RegisterType((*BuildxVersion)(nil), "buildx.controller.v1.BuildxVersion") -} - -func init() { proto.RegisterFile("controller.proto", fileDescriptor_ed7f10298fa1d90f) } - -var fileDescriptor_ed7f10298fa1d90f = []byte{ - // 1881 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x58, 0x5f, 0x6f, 0xdb, 0xc8, - 0x11, 0x2f, 0x25, 0x59, 0x7f, 0x46, 0x96, 0xe3, 0x6c, 0x9d, 0x74, 0xc3, 0xa4, 0x17, 0x87, 0x49, - 0xae, 0x42, 0x53, 0x48, 0x77, 0xbe, 0xa6, 0xbe, 0x5c, 0xee, 0x80, 0xda, 0xb2, 0x05, 0xfb, 0x90, - 0xd8, 0xc6, 0xca, 0xc9, 0xa1, 0x2d, 0xd0, 0x80, 0x92, 0xd6, 0x32, 0x21, 0x8a, 0xab, 0x72, 0x57, - 0xb6, 0xd5, 0xa7, 0xbe, 0xf4, 0xad, 0xe8, 0xf7, 0x28, 0xfa, 0x11, 0xfa, 0xd2, 0x7e, 0xa1, 0xa2, - 0x1f, 0xa1, 0xd8, 0x3f, 0xa4, 0x48, 0x4b, 0x94, 0xed, 0xf6, 0x49, 0x3b, 0xc3, 0xdf, 0x6f, 0x76, - 0x67, 0x38, 0x3b, 0x33, 0x14, 0xac, 0xf7, 0x58, 0x20, 0x42, 0xe6, 0xfb, 0x34, 0x6c, 0x8c, 0x43, - 0x26, 0x18, 0xda, 0xe8, 0x4e, 0x3c, 0xbf, 0x7f, 0xd5, 0x48, 0x3c, 0xb8, 0xf8, 0xd2, 0x7e, 0x3b, - 0xf0, 0xc4, 0xf9, 0xa4, 0xdb, 0xe8, 0xb1, 0x51, 0x73, 0xc4, 0xba, 0xd3, 0xa6, 0x42, 0x0d, 0x3d, - 0xd1, 0x74, 0xc7, 0x5e, 0x93, 0xd3, 0xf0, 0xc2, 0xeb, 0x51, 0xde, 0x34, 0xa4, 0xe8, 0x57, 0x9b, - 0xb4, 0x5f, 0x67, 0x92, 0x39, 0x9b, 0x84, 0x3d, 0x3a, 0x66, 0xbe, 0xd7, 0x9b, 0x36, 0xc7, 0xdd, - 0xa6, 0x5e, 0x69, 0x9a, 0x53, 0x87, 0x8d, 0x77, 0x1e, 0x17, 0x27, 0x21, 0xeb, 0x51, 0xce, 0x29, - 0x27, 0xf4, 0x0f, 0x13, 0xca, 0x05, 0x5a, 0x87, 0x3c, 0xa1, 0x67, 0xd8, 0xda, 0xb4, 0xea, 0x15, - 0x22, 0x97, 0xce, 0x09, 0x3c, 0xb8, 0x86, 0xe4, 0x63, 0x16, 0x70, 0x8a, 0xb6, 0x61, 0xe5, 0x30, - 0x38, 0x63, 0x1c, 0x5b, 0x9b, 0xf9, 0x7a, 0x75, 0xeb, 0x59, 0x63, 0x91, 0x73, 0x0d, 0xc3, 0x93, - 0x48, 0xa2, 0xf1, 0x0e, 0x87, 0x6a, 0x42, 0x8b, 0x9e, 0x40, 0x25, 0x12, 0xf7, 0xcc, 0xc6, 0x33, - 0x05, 0x6a, 0xc3, 0xea, 0x61, 0x70, 0xc1, 0x86, 0xb4, 0xc5, 0x82, 0x33, 0x6f, 0x80, 0x73, 0x9b, - 0x56, 0xbd, 0xba, 0xe5, 0x2c, 0xde, 0x2c, 0x89, 0x24, 0x29, 0x9e, 0xf3, 0x3d, 0xe0, 0x3d, 0x8f, - 0xf7, 0x58, 0x10, 0xd0, 0x5e, 0xe4, 0x4c, 0xa6, 0xd3, 0xe9, 0x33, 0xe5, 0xae, 0x9d, 0xc9, 0x79, - 0x0c, 0x8f, 0x16, 0xd8, 0xd2, 0x61, 0x71, 0x7e, 0x0f, 0xab, 0xbb, 0xf2, 0x6c, 0xd9, 0xc6, 0xbf, - 0x85, 0xd2, 0xf1, 0x58, 0x78, 0x2c, 0xe0, 0xcb, 0xbd, 0x51, 0x66, 0x0c, 0x92, 0x44, 0x14, 0xe7, - 0x9f, 0x55, 0xb3, 0x81, 0x51, 0xa0, 0x4d, 0xa8, 0xb6, 0x58, 0x20, 0xe8, 0x95, 0x38, 0x71, 0xc5, - 0xb9, 0xd9, 0x28, 0xa9, 0x42, 0x9f, 0xc3, 0xda, 0x1e, 0xeb, 0x0d, 0x69, 0x78, 0xe6, 0xf9, 0xf4, - 0xc8, 0x1d, 0x51, 0xe3, 0xd2, 0x35, 0x2d, 0xfa, 0x4e, 0x7a, 0xed, 0x05, 0xa2, 0x3d, 0x09, 0x7a, - 0x38, 0xaf, 0x8e, 0xf6, 0x34, 0xeb, 0xad, 0x1a, 0x18, 0x99, 0x31, 0xd0, 0xef, 0xa0, 0x26, 0xcd, - 0xf4, 0xcd, 0xd6, 0x1c, 0x17, 0x54, 0x62, 0xbc, 0xbe, 0xd9, 0xbb, 0x46, 0x8a, 0xb7, 0x1f, 0x88, - 0x70, 0x4a, 0xd2, 0xb6, 0xd0, 0x06, 0xac, 0xec, 0xf8, 0x3e, 0xbb, 0xc4, 0x2b, 0x9b, 0xf9, 0x7a, - 0x85, 0x68, 0x01, 0xfd, 0x0a, 0x4a, 0x3b, 0x42, 0x50, 0x2e, 0x38, 0x2e, 0xaa, 0xcd, 0x9e, 0x2c, - 0xde, 0x4c, 0x83, 0x48, 0x04, 0x46, 0xc7, 0x50, 0x51, 0xfb, 0xef, 0x84, 0x03, 0x8e, 0x4b, 0x8a, - 0xf9, 0xe5, 0x2d, 0x8e, 0x19, 0x73, 0xf4, 0x11, 0x67, 0x36, 0xd0, 0x3e, 0x54, 0x5a, 0x6e, 0xef, - 0x9c, 0xb6, 0x43, 0x36, 0xc2, 0x65, 0x65, 0xf0, 0x67, 0x8b, 0x0d, 0x2a, 0x98, 0x31, 0x68, 0xcc, - 0xc4, 0x4c, 0xb4, 0x03, 0x25, 0x25, 0x9c, 0x32, 0x5c, 0xb9, 0x9b, 0x91, 0x88, 0x87, 0x1c, 0x58, - 0x6d, 0x0d, 0x42, 0x36, 0x19, 0x9f, 0xb8, 0x21, 0x0d, 0x04, 0x06, 0xf5, 0xaa, 0x53, 0x3a, 0xf4, - 0x16, 0x4a, 0xfb, 0x57, 0x63, 0x16, 0x0a, 0x8e, 0xab, 0xcb, 0x2e, 0xaf, 0x06, 0x99, 0x0d, 0x0c, - 0x03, 0x7d, 0x06, 0xb0, 0x7f, 0x25, 0x42, 0xf7, 0x80, 0xc9, 0xb0, 0xaf, 0xaa, 0xd7, 0x91, 0xd0, - 0xa0, 0x36, 0x14, 0xdf, 0xb9, 0x5d, 0xea, 0x73, 0x5c, 0x53, 0xb6, 0x1b, 0xb7, 0x08, 0xac, 0x26, - 0xe8, 0x8d, 0x0c, 0x5b, 0xe6, 0xf5, 0x11, 0x15, 0x97, 0x2c, 0x1c, 0xbe, 0x67, 0x7d, 0x8a, 0xd7, - 0x74, 0x5e, 0x27, 0x54, 0xe8, 0x05, 0xd4, 0x8e, 0x98, 0x0e, 0x9e, 0xe7, 0x0b, 0x1a, 0xe2, 0x7b, - 0xea, 0x30, 0x69, 0xa5, 0xba, 0xcb, 0xbe, 0x2b, 0xce, 0x58, 0x38, 0xe2, 0x78, 0x5d, 0x21, 0x66, - 0x0a, 0x99, 0x41, 0x1d, 0xda, 0x0b, 0xa9, 0xe0, 0xf8, 0xfe, 0xb2, 0x0c, 0xd2, 0x20, 0x12, 0x81, - 0x11, 0x86, 0x52, 0xe7, 0x7c, 0xd4, 0xf1, 0xfe, 0x48, 0x31, 0xda, 0xb4, 0xea, 0x79, 0x12, 0x89, - 0xe8, 0x15, 0xe4, 0x3b, 0x9d, 0x03, 0xfc, 0x63, 0x65, 0xed, 0x51, 0x86, 0xb5, 0xce, 0x01, 0x91, - 0x28, 0x84, 0xa0, 0x70, 0xea, 0x0e, 0x38, 0xde, 0x50, 0xe7, 0x52, 0x6b, 0xf4, 0x10, 0x8a, 0xa7, - 0x6e, 0x38, 0xa0, 0x02, 0x3f, 0x50, 0x3e, 0x1b, 0x09, 0xbd, 0x81, 0xd2, 0x07, 0xdf, 0x1b, 0x79, - 0x82, 0xe3, 0x87, 0xcb, 0x2e, 0xa7, 0x06, 0x1d, 0x8f, 0x05, 0x89, 0xf0, 0xf2, 0xb4, 0x2a, 0xde, - 0x34, 0xc4, 0x3f, 0x51, 0x36, 0x23, 0x51, 0x3e, 0x31, 0xe1, 0xc2, 0x78, 0xd3, 0xaa, 0x97, 0x49, - 0x24, 0xca, 0xa3, 0x9d, 0x4c, 0x7c, 0x1f, 0x3f, 0x52, 0x6a, 0xb5, 0xd6, 0xef, 0x5e, 0xa6, 0xc1, - 0xc9, 0x84, 0x9f, 0x63, 0x5b, 0x3d, 0x49, 0x68, 0x66, 0xcf, 0xdf, 0x31, 0xb7, 0x8f, 0x1f, 0x27, - 0x9f, 0x4b, 0x0d, 0x3a, 0x84, 0xd5, 0x8e, 0x6a, 0x4b, 0x27, 0xaa, 0x19, 0xe1, 0x27, 0xca, 0x8f, - 0x97, 0x0d, 0xd9, 0xb9, 0x1a, 0x51, 0xe7, 0x92, 0x3e, 0x24, 0x9b, 0x57, 0x43, 0x83, 0x49, 0x8a, - 0x6a, 0xff, 0x1a, 0xd0, 0x7c, 0xd5, 0x90, 0xd5, 0x76, 0x48, 0xa7, 0x51, 0xb5, 0x1d, 0xd2, 0xa9, - 0x2c, 0x1c, 0x17, 0xae, 0x3f, 0x89, 0x6a, 0x9e, 0x16, 0xbe, 0xc9, 0x7d, 0x6d, 0xd9, 0xdf, 0xc2, - 0x5a, 0xfa, 0x42, 0xdf, 0x89, 0xfd, 0x06, 0xaa, 0x89, 0xac, 0xbd, 0x0b, 0xd5, 0xf9, 0x97, 0x05, - 0xd5, 0xc4, 0xd5, 0x52, 0x49, 0x30, 0x1d, 0x53, 0x43, 0x56, 0x6b, 0xb4, 0x0b, 0x2b, 0x3b, 0x42, - 0x84, 0xb2, 0x45, 0xc8, 0x3c, 0xfa, 0xc5, 0x8d, 0x17, 0xb4, 0xa1, 0xe0, 0xfa, 0x0a, 0x69, 0xaa, - 0xbc, 0x41, 0x7b, 0x94, 0x0b, 0x2f, 0x70, 0xe5, 0x2d, 0x53, 0x15, 0xbd, 0x42, 0x92, 0x2a, 0xfb, - 0x6b, 0x80, 0x19, 0xed, 0x4e, 0x3e, 0xfc, 0xdd, 0x82, 0xfb, 0x73, 0x55, 0x68, 0xa1, 0x27, 0x07, - 0x69, 0x4f, 0xb6, 0x6e, 0x59, 0xd1, 0xe6, 0xfd, 0xf9, 0x3f, 0x4e, 0x7b, 0x04, 0x45, 0x5d, 0xfa, - 0x17, 0x9e, 0xd0, 0x86, 0xf2, 0x9e, 0xc7, 0xdd, 0xae, 0x4f, 0xfb, 0x8a, 0x5a, 0x26, 0xb1, 0xac, - 0xfa, 0x8e, 0x3a, 0xbd, 0x8e, 0x9e, 0x16, 0x1c, 0x7d, 0xc7, 0xd1, 0x1a, 0xe4, 0xe2, 0x99, 0x25, - 0x77, 0xb8, 0x27, 0xc1, 0xb2, 0xe1, 0x6a, 0x57, 0x2b, 0x44, 0x0b, 0x4e, 0x1b, 0x8a, 0xba, 0x6a, - 0xcc, 0xe1, 0x6d, 0x28, 0xb7, 0x3d, 0x9f, 0xaa, 0xbe, 0xad, 0xcf, 0x1c, 0xcb, 0xd2, 0xbd, 0xfd, - 0xe0, 0xc2, 0x6c, 0x2b, 0x97, 0xce, 0x76, 0xa2, 0x3d, 0x4b, 0x3f, 0x54, 0x27, 0x37, 0x7e, 0xa8, - 0xfe, 0xfd, 0x10, 0x8a, 0x6d, 0x16, 0x8e, 0x5c, 0x61, 0x8c, 0x19, 0xc9, 0x71, 0x60, 0xed, 0x30, - 0xe0, 0x63, 0xda, 0x13, 0xd9, 0x63, 0xde, 0x31, 0xdc, 0x8b, 0x31, 0x66, 0xc0, 0x4b, 0xcc, 0x29, - 0xd6, 0xdd, 0xe7, 0x94, 0xbf, 0x59, 0x50, 0x89, 0x2b, 0x11, 0x6a, 0x41, 0x51, 0xbd, 0x8d, 0x68, - 0x5a, 0x7c, 0x75, 0x43, 0xe9, 0x6a, 0x7c, 0x54, 0x68, 0xd3, 0x11, 0x34, 0xd5, 0xfe, 0x01, 0xaa, - 0x09, 0xf5, 0x82, 0x04, 0xd8, 0x4a, 0x26, 0x40, 0x66, 0x29, 0xd7, 0x9b, 0x24, 0xd3, 0x63, 0x0f, - 0x8a, 0x5a, 0xb9, 0x30, 0xac, 0x08, 0x0a, 0x07, 0x6e, 0xa8, 0x53, 0x23, 0x4f, 0xd4, 0x5a, 0xea, - 0x3a, 0xec, 0x4c, 0xa8, 0xd7, 0x93, 0x27, 0x6a, 0xed, 0xfc, 0xc3, 0x82, 0x9a, 0x19, 0xfd, 0x4c, - 0x04, 0x29, 0xac, 0xeb, 0x1b, 0x4a, 0xc3, 0x48, 0x67, 0xfc, 0x7f, 0xb3, 0x24, 0x94, 0x11, 0xb4, - 0x71, 0x9d, 0xab, 0xa3, 0x31, 0x67, 0xd2, 0x6e, 0xc1, 0x83, 0x85, 0xd0, 0x3b, 0x5d, 0x91, 0x97, - 0x70, 0x7f, 0x36, 0xd4, 0x66, 0xe7, 0xc9, 0x06, 0xa0, 0x24, 0xcc, 0x0c, 0xbd, 0x4f, 0xa1, 0x2a, - 0x3f, 0x12, 0xb2, 0x69, 0x0e, 0xac, 0x6a, 0x80, 0x89, 0x0c, 0x82, 0xc2, 0x90, 0x4e, 0x75, 0x36, - 0x54, 0x88, 0x5a, 0x3b, 0x7f, 0xb5, 0xe4, 0xac, 0x3f, 0x9e, 0x88, 0xf7, 0x94, 0x73, 0x77, 0x20, - 0x13, 0xb0, 0x70, 0x18, 0x78, 0xc2, 0x64, 0xdf, 0xe7, 0x59, 0x33, 0xff, 0x78, 0x22, 0x24, 0xcc, - 0xb0, 0x0e, 0x7e, 0x44, 0x14, 0x0b, 0x6d, 0x43, 0x61, 0xcf, 0x15, 0xae, 0xc9, 0x85, 0x8c, 0x09, - 0x47, 0x22, 0x12, 0x44, 0x29, 0xee, 0x96, 0xe4, 0x87, 0xcd, 0x78, 0x22, 0x9c, 0x17, 0xb0, 0x7e, - 0xdd, 0xfa, 0x02, 0xd7, 0xbe, 0x82, 0x6a, 0xc2, 0x8a, 0xba, 0xb7, 0xc7, 0x6d, 0x05, 0x28, 0x13, - 0xb9, 0x94, 0xbe, 0xc6, 0x07, 0x59, 0xd5, 0x7b, 0x38, 0xf7, 0xa0, 0xa6, 0x4c, 0xc7, 0x11, 0xfc, - 0x53, 0x0e, 0x4a, 0x91, 0x89, 0xed, 0x94, 0xdf, 0xcf, 0xb2, 0xfc, 0x9e, 0x77, 0xf9, 0x35, 0x14, - 0x64, 0xfd, 0x30, 0x2e, 0x67, 0x8c, 0x07, 0xed, 0x7e, 0x82, 0x26, 0xe1, 0xe8, 0x3b, 0x28, 0x12, - 0xca, 0xe5, 0x28, 0xa3, 0x87, 0xfe, 0xe7, 0x8b, 0x89, 0x1a, 0x33, 0x23, 0x1b, 0x92, 0xa4, 0x77, - 0xbc, 0x41, 0xe0, 0xfa, 0xb8, 0xb0, 0x8c, 0xae, 0x31, 0x09, 0xba, 0x56, 0xcc, 0xc2, 0xfd, 0x67, - 0x0b, 0xaa, 0x4b, 0x43, 0xbd, 0xfc, 0xb3, 0x6c, 0xee, 0x53, 0x31, 0xff, 0x3f, 0x7e, 0x2a, 0xfe, - 0xdb, 0x4a, 0x1b, 0x52, 0x53, 0x8d, 0xbc, 0x4f, 0x63, 0xe6, 0x05, 0xc2, 0xa4, 0x6c, 0x42, 0x23, - 0x0f, 0xda, 0x1a, 0xf5, 0x4d, 0xd1, 0x97, 0xcb, 0x59, 0xf1, 0xce, 0x9b, 0xe2, 0x2d, 0x93, 0xe0, - 0x03, 0xa7, 0xa1, 0x0a, 0x51, 0x85, 0xa8, 0xb5, 0xac, 0xd7, 0x47, 0x4c, 0x69, 0x57, 0x54, 0xb6, - 0x18, 0x49, 0xd9, 0xbb, 0xec, 0xe3, 0xa2, 0x76, 0xbc, 0x75, 0xa9, 0xba, 0xd0, 0x11, 0x93, 0xba, - 0x92, 0x02, 0x6a, 0x41, 0xe2, 0x4e, 0xc5, 0x14, 0x97, 0x75, 0xaa, 0x9d, 0x8a, 0xa9, 0x6c, 0x28, - 0x84, 0xf9, 0x7e, 0xd7, 0xed, 0x0d, 0x71, 0x45, 0x77, 0xb2, 0x48, 0x96, 0x93, 0x9e, 0x8c, 0xae, - 0xe7, 0xfa, 0xea, 0x9b, 0xa0, 0x4c, 0x22, 0xd1, 0xd9, 0x81, 0x4a, 0x9c, 0x14, 0xb2, 0x47, 0xb5, - 0xfb, 0x2a, 0xe8, 0x35, 0x92, 0x6b, 0xf7, 0xa3, 0x7c, 0xce, 0xcd, 0xe7, 0x73, 0x3e, 0x91, 0xcf, - 0xdb, 0x50, 0x4b, 0xa5, 0x87, 0x04, 0x11, 0x76, 0xc9, 0x8d, 0x21, 0xb5, 0x96, 0xba, 0x16, 0xf3, - 0xf5, 0x57, 0x6f, 0x8d, 0xa8, 0xb5, 0xf3, 0x1c, 0x6a, 0xa9, 0xc4, 0x58, 0x54, 0x81, 0x9d, 0x67, - 0x50, 0xeb, 0x08, 0x57, 0x4c, 0x96, 0xfc, 0x4d, 0xf1, 0x1f, 0x0b, 0xd6, 0x22, 0x8c, 0xa9, 0x31, - 0xbf, 0x84, 0xf2, 0x05, 0x0d, 0x05, 0xbd, 0x8a, 0xbb, 0x0e, 0x9e, 0x1f, 0x34, 0x3f, 0x2a, 0x04, - 0x89, 0x91, 0xe8, 0x1b, 0x28, 0x73, 0x65, 0x87, 0x46, 0x13, 0xcb, 0x67, 0x59, 0x2c, 0xb3, 0x5f, - 0x8c, 0x47, 0x4d, 0x28, 0xf8, 0x6c, 0xc0, 0xd5, 0x7b, 0xaf, 0x6e, 0x3d, 0xce, 0xe2, 0xbd, 0x63, - 0x03, 0xa2, 0x80, 0xe8, 0x2d, 0x94, 0x2f, 0xdd, 0x30, 0xf0, 0x82, 0x41, 0xf4, 0xb5, 0xfc, 0x34, - 0x8b, 0xf4, 0x83, 0xc6, 0x91, 0x98, 0xe0, 0xd4, 0xe4, 0x75, 0x39, 0x63, 0x26, 0x26, 0xce, 0x6f, - 0x64, 0xd6, 0x4a, 0xd1, 0xb8, 0x7f, 0x08, 0x35, 0x9d, 0xf9, 0x1f, 0x69, 0xc8, 0xe5, 0xfc, 0x67, - 0x2d, 0xbb, 0x9d, 0xbb, 0x49, 0x28, 0x49, 0x33, 0x9d, 0x4f, 0xa6, 0xb1, 0x45, 0x0a, 0x99, 0x4b, - 0x63, 0xb7, 0x37, 0x74, 0x07, 0xd1, 0x7b, 0x8a, 0x44, 0xf9, 0xe4, 0xc2, 0xec, 0xa7, 0x2f, 0x68, - 0x24, 0xca, 0xdc, 0x0c, 0xe9, 0x85, 0xc7, 0x67, 0xa3, 0x68, 0x2c, 0x6f, 0xfd, 0xa5, 0x04, 0xd0, - 0x8a, 0xcf, 0x83, 0x4e, 0x60, 0x45, 0xed, 0x87, 0x9c, 0xa5, 0x6d, 0x52, 0xf9, 0x6d, 0x3f, 0xbf, - 0x45, 0x2b, 0x45, 0x1f, 0x65, 0xf2, 0xab, 0xf1, 0x06, 0xbd, 0xc8, 0x2a, 0x08, 0xc9, 0x09, 0xc9, - 0x7e, 0x79, 0x03, 0xca, 0xd8, 0xfd, 0x00, 0x45, 0x9d, 0x05, 0x28, 0xab, 0xea, 0x25, 0xf3, 0xd6, - 0x7e, 0xb1, 0x1c, 0xa4, 0x8d, 0x7e, 0x61, 0x21, 0x62, 0x6a, 0x22, 0x72, 0x96, 0x34, 0x3d, 0x73, - 0x63, 0xb2, 0x02, 0x90, 0xea, 0x2f, 0x75, 0x0b, 0x7d, 0x0f, 0x45, 0x5d, 0xd5, 0xd0, 0x4f, 0x17, - 0x13, 0x22, 0x7b, 0xcb, 0x1f, 0xd7, 0xad, 0x2f, 0x2c, 0xf4, 0x1e, 0x0a, 0xb2, 0x9d, 0xa3, 0x8c, - 0xde, 0x94, 0x98, 0x05, 0x6c, 0x67, 0x19, 0xc4, 0x44, 0xf1, 0x13, 0xc0, 0x6c, 0xa8, 0x40, 0x19, - 0xff, 0x79, 0xcc, 0x4d, 0x27, 0x76, 0xfd, 0x66, 0xa0, 0xd9, 0xe0, 0xbd, 0xec, 0xa8, 0x67, 0x0c, - 0x65, 0xf6, 0xd2, 0xf8, 0x1a, 0xd9, 0xce, 0x32, 0x88, 0x31, 0x77, 0x0e, 0xb5, 0xd4, 0x7f, 0xa2, - 0xe8, 0xe7, 0xd9, 0x4e, 0x5e, 0xff, 0x8b, 0xd5, 0x7e, 0x75, 0x2b, 0xac, 0xd9, 0x49, 0x24, 0xa7, - 0x32, 0xf3, 0x18, 0x35, 0x6e, 0xf2, 0x3b, 0xfd, 0xff, 0xa6, 0xdd, 0xbc, 0x35, 0x5e, 0xef, 0xba, - 0x5b, 0xf8, 0x6d, 0x6e, 0xdc, 0xed, 0x16, 0xd5, 0x5f, 0xc5, 0x5f, 0xfd, 0x37, 0x00, 0x00, 0xff, - 0xff, 0xc1, 0x4b, 0x2d, 0x65, 0xc8, 0x16, 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 - -// ControllerClient is the client API for Controller service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type ControllerClient interface { - Build(ctx context.Context, in *BuildRequest, opts ...grpc.CallOption) (*BuildResponse, error) - Inspect(ctx context.Context, in *InspectRequest, opts ...grpc.CallOption) (*InspectResponse, error) - Status(ctx context.Context, in *StatusRequest, opts ...grpc.CallOption) (Controller_StatusClient, error) - Input(ctx context.Context, opts ...grpc.CallOption) (Controller_InputClient, error) - Invoke(ctx context.Context, opts ...grpc.CallOption) (Controller_InvokeClient, error) - List(ctx context.Context, in *ListRequest, opts ...grpc.CallOption) (*ListResponse, error) - Disconnect(ctx context.Context, in *DisconnectRequest, opts ...grpc.CallOption) (*DisconnectResponse, error) - Info(ctx context.Context, in *InfoRequest, opts ...grpc.CallOption) (*InfoResponse, error) - ListProcesses(ctx context.Context, in *ListProcessesRequest, opts ...grpc.CallOption) (*ListProcessesResponse, error) - DisconnectProcess(ctx context.Context, in *DisconnectProcessRequest, opts ...grpc.CallOption) (*DisconnectProcessResponse, error) -} - -type controllerClient struct { - cc *grpc.ClientConn -} - -func NewControllerClient(cc *grpc.ClientConn) ControllerClient { - return &controllerClient{cc} -} - -func (c *controllerClient) Build(ctx context.Context, in *BuildRequest, opts ...grpc.CallOption) (*BuildResponse, error) { - out := new(BuildResponse) - err := c.cc.Invoke(ctx, "/buildx.controller.v1.Controller/Build", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *controllerClient) Inspect(ctx context.Context, in *InspectRequest, opts ...grpc.CallOption) (*InspectResponse, error) { - out := new(InspectResponse) - err := c.cc.Invoke(ctx, "/buildx.controller.v1.Controller/Inspect", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *controllerClient) Status(ctx context.Context, in *StatusRequest, opts ...grpc.CallOption) (Controller_StatusClient, error) { - stream, err := c.cc.NewStream(ctx, &_Controller_serviceDesc.Streams[0], "/buildx.controller.v1.Controller/Status", opts...) - if err != nil { - return nil, err - } - x := &controllerStatusClient{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 Controller_StatusClient interface { - Recv() (*StatusResponse, error) - grpc.ClientStream -} - -type controllerStatusClient struct { - grpc.ClientStream -} - -func (x *controllerStatusClient) Recv() (*StatusResponse, error) { - m := new(StatusResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *controllerClient) Input(ctx context.Context, opts ...grpc.CallOption) (Controller_InputClient, error) { - stream, err := c.cc.NewStream(ctx, &_Controller_serviceDesc.Streams[1], "/buildx.controller.v1.Controller/Input", opts...) - if err != nil { - return nil, err - } - x := &controllerInputClient{stream} - return x, nil -} - -type Controller_InputClient interface { - Send(*InputMessage) error - CloseAndRecv() (*InputResponse, error) - grpc.ClientStream -} - -type controllerInputClient struct { - grpc.ClientStream -} - -func (x *controllerInputClient) Send(m *InputMessage) error { - return x.ClientStream.SendMsg(m) -} - -func (x *controllerInputClient) CloseAndRecv() (*InputResponse, error) { - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - m := new(InputResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *controllerClient) Invoke(ctx context.Context, opts ...grpc.CallOption) (Controller_InvokeClient, error) { - stream, err := c.cc.NewStream(ctx, &_Controller_serviceDesc.Streams[2], "/buildx.controller.v1.Controller/Invoke", opts...) - if err != nil { - return nil, err - } - x := &controllerInvokeClient{stream} - return x, nil -} - -type Controller_InvokeClient interface { - Send(*Message) error - Recv() (*Message, error) - grpc.ClientStream -} - -type controllerInvokeClient struct { - grpc.ClientStream -} - -func (x *controllerInvokeClient) Send(m *Message) error { - return x.ClientStream.SendMsg(m) -} - -func (x *controllerInvokeClient) Recv() (*Message, error) { - m := new(Message) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *controllerClient) List(ctx context.Context, in *ListRequest, opts ...grpc.CallOption) (*ListResponse, error) { - out := new(ListResponse) - err := c.cc.Invoke(ctx, "/buildx.controller.v1.Controller/List", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *controllerClient) Disconnect(ctx context.Context, in *DisconnectRequest, opts ...grpc.CallOption) (*DisconnectResponse, error) { - out := new(DisconnectResponse) - err := c.cc.Invoke(ctx, "/buildx.controller.v1.Controller/Disconnect", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *controllerClient) Info(ctx context.Context, in *InfoRequest, opts ...grpc.CallOption) (*InfoResponse, error) { - out := new(InfoResponse) - err := c.cc.Invoke(ctx, "/buildx.controller.v1.Controller/Info", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *controllerClient) ListProcesses(ctx context.Context, in *ListProcessesRequest, opts ...grpc.CallOption) (*ListProcessesResponse, error) { - out := new(ListProcessesResponse) - err := c.cc.Invoke(ctx, "/buildx.controller.v1.Controller/ListProcesses", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *controllerClient) DisconnectProcess(ctx context.Context, in *DisconnectProcessRequest, opts ...grpc.CallOption) (*DisconnectProcessResponse, error) { - out := new(DisconnectProcessResponse) - err := c.cc.Invoke(ctx, "/buildx.controller.v1.Controller/DisconnectProcess", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// ControllerServer is the server API for Controller service. -type ControllerServer interface { - Build(context.Context, *BuildRequest) (*BuildResponse, error) - Inspect(context.Context, *InspectRequest) (*InspectResponse, error) - Status(*StatusRequest, Controller_StatusServer) error - Input(Controller_InputServer) error - Invoke(Controller_InvokeServer) error - List(context.Context, *ListRequest) (*ListResponse, error) - Disconnect(context.Context, *DisconnectRequest) (*DisconnectResponse, error) - Info(context.Context, *InfoRequest) (*InfoResponse, error) - ListProcesses(context.Context, *ListProcessesRequest) (*ListProcessesResponse, error) - DisconnectProcess(context.Context, *DisconnectProcessRequest) (*DisconnectProcessResponse, error) -} - -// UnimplementedControllerServer can be embedded to have forward compatible implementations. -type UnimplementedControllerServer struct { -} - -func (*UnimplementedControllerServer) Build(ctx context.Context, req *BuildRequest) (*BuildResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Build not implemented") -} -func (*UnimplementedControllerServer) Inspect(ctx context.Context, req *InspectRequest) (*InspectResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Inspect not implemented") -} -func (*UnimplementedControllerServer) Status(req *StatusRequest, srv Controller_StatusServer) error { - return status.Errorf(codes.Unimplemented, "method Status not implemented") -} -func (*UnimplementedControllerServer) Input(srv Controller_InputServer) error { - return status.Errorf(codes.Unimplemented, "method Input not implemented") -} -func (*UnimplementedControllerServer) Invoke(srv Controller_InvokeServer) error { - return status.Errorf(codes.Unimplemented, "method Invoke not implemented") -} -func (*UnimplementedControllerServer) List(ctx context.Context, req *ListRequest) (*ListResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method List not implemented") -} -func (*UnimplementedControllerServer) Disconnect(ctx context.Context, req *DisconnectRequest) (*DisconnectResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Disconnect not implemented") -} -func (*UnimplementedControllerServer) Info(ctx context.Context, req *InfoRequest) (*InfoResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Info not implemented") -} -func (*UnimplementedControllerServer) ListProcesses(ctx context.Context, req *ListProcessesRequest) (*ListProcessesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ListProcesses not implemented") -} -func (*UnimplementedControllerServer) DisconnectProcess(ctx context.Context, req *DisconnectProcessRequest) (*DisconnectProcessResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method DisconnectProcess not implemented") -} - -func RegisterControllerServer(s *grpc.Server, srv ControllerServer) { - s.RegisterService(&_Controller_serviceDesc, srv) -} - -func _Controller_Build_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(BuildRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ControllerServer).Build(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/buildx.controller.v1.Controller/Build", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ControllerServer).Build(ctx, req.(*BuildRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Controller_Inspect_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(InspectRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ControllerServer).Inspect(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/buildx.controller.v1.Controller/Inspect", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ControllerServer).Inspect(ctx, req.(*InspectRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Controller_Status_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(StatusRequest) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(ControllerServer).Status(m, &controllerStatusServer{stream}) -} - -type Controller_StatusServer interface { - Send(*StatusResponse) error - grpc.ServerStream -} - -type controllerStatusServer struct { - grpc.ServerStream -} - -func (x *controllerStatusServer) Send(m *StatusResponse) error { - return x.ServerStream.SendMsg(m) -} - -func _Controller_Input_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(ControllerServer).Input(&controllerInputServer{stream}) -} - -type Controller_InputServer interface { - SendAndClose(*InputResponse) error - Recv() (*InputMessage, error) - grpc.ServerStream -} - -type controllerInputServer struct { - grpc.ServerStream -} - -func (x *controllerInputServer) SendAndClose(m *InputResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *controllerInputServer) Recv() (*InputMessage, error) { - m := new(InputMessage) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func _Controller_Invoke_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(ControllerServer).Invoke(&controllerInvokeServer{stream}) -} - -type Controller_InvokeServer interface { - Send(*Message) error - Recv() (*Message, error) - grpc.ServerStream -} - -type controllerInvokeServer struct { - grpc.ServerStream -} - -func (x *controllerInvokeServer) Send(m *Message) error { - return x.ServerStream.SendMsg(m) -} - -func (x *controllerInvokeServer) Recv() (*Message, error) { - m := new(Message) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func _Controller_List_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ListRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ControllerServer).List(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/buildx.controller.v1.Controller/List", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ControllerServer).List(ctx, req.(*ListRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Controller_Disconnect_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(DisconnectRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ControllerServer).Disconnect(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/buildx.controller.v1.Controller/Disconnect", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ControllerServer).Disconnect(ctx, req.(*DisconnectRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Controller_Info_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(InfoRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ControllerServer).Info(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/buildx.controller.v1.Controller/Info", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ControllerServer).Info(ctx, req.(*InfoRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Controller_ListProcesses_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ListProcessesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ControllerServer).ListProcesses(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/buildx.controller.v1.Controller/ListProcesses", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ControllerServer).ListProcesses(ctx, req.(*ListProcessesRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Controller_DisconnectProcess_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(DisconnectProcessRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ControllerServer).DisconnectProcess(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/buildx.controller.v1.Controller/DisconnectProcess", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ControllerServer).DisconnectProcess(ctx, req.(*DisconnectProcessRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Controller_serviceDesc = grpc.ServiceDesc{ - ServiceName: "buildx.controller.v1.Controller", - HandlerType: (*ControllerServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Build", - Handler: _Controller_Build_Handler, - }, - { - MethodName: "Inspect", - Handler: _Controller_Inspect_Handler, - }, - { - MethodName: "List", - Handler: _Controller_List_Handler, - }, - { - MethodName: "Disconnect", - Handler: _Controller_Disconnect_Handler, - }, - { - MethodName: "Info", - Handler: _Controller_Info_Handler, - }, - { - MethodName: "ListProcesses", - Handler: _Controller_ListProcesses_Handler, - }, - { - MethodName: "DisconnectProcess", - Handler: _Controller_DisconnectProcess_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "Status", - Handler: _Controller_Status_Handler, - ServerStreams: true, - }, - { - StreamName: "Input", - Handler: _Controller_Input_Handler, - ClientStreams: true, - }, - { - StreamName: "Invoke", - Handler: _Controller_Invoke_Handler, - ServerStreams: true, - ClientStreams: true, - }, - }, - Metadata: "controller.proto", -} diff --git a/vendor/github.com/docker/buildx/controller/pb/controller.proto b/vendor/github.com/docker/buildx/controller/pb/controller.proto deleted file mode 100644 index 2300b7edb..000000000 --- a/vendor/github.com/docker/buildx/controller/pb/controller.proto +++ /dev/null @@ -1,244 +0,0 @@ -syntax = "proto3"; - -package buildx.controller.v1; - -import "github.com/moby/buildkit/api/services/control/control.proto"; -import "github.com/moby/buildkit/sourcepolicy/pb/policy.proto"; - -option go_package = "pb"; - -service Controller { - rpc Build(BuildRequest) returns (BuildResponse); - rpc Inspect(InspectRequest) returns (InspectResponse); - rpc Status(StatusRequest) returns (stream StatusResponse); - rpc Input(stream InputMessage) returns (InputResponse); - rpc Invoke(stream Message) returns (stream Message); - rpc List(ListRequest) returns (ListResponse); - rpc Disconnect(DisconnectRequest) returns (DisconnectResponse); - rpc Info(InfoRequest) returns (InfoResponse); - rpc ListProcesses(ListProcessesRequest) returns (ListProcessesResponse); - rpc DisconnectProcess(DisconnectProcessRequest) returns (DisconnectProcessResponse); -} - -message ListProcessesRequest { - string Ref = 1; -} - -message ListProcessesResponse { - repeated ProcessInfo Infos = 1; -} - -message ProcessInfo { - string ProcessID = 1; - InvokeConfig InvokeConfig = 2; -} - -message DisconnectProcessRequest { - string Ref = 1; - string ProcessID = 2; -} - -message DisconnectProcessResponse { -} - -message BuildRequest { - string Ref = 1; - BuildOptions Options = 2; -} - -message BuildOptions { - string ContextPath = 1; - string DockerfileName = 2; - PrintFunc PrintFunc = 3; - map NamedContexts = 4; - - repeated string Allow = 5; - repeated Attest Attests = 6; - map BuildArgs = 7; - repeated CacheOptionsEntry CacheFrom = 8; - repeated CacheOptionsEntry CacheTo = 9; - string CgroupParent = 10; - repeated ExportEntry Exports = 11; - repeated string ExtraHosts = 12; - map Labels = 13; - string NetworkMode = 14; - repeated string NoCacheFilter = 15; - repeated string Platforms = 16; - repeated Secret Secrets = 17; - int64 ShmSize = 18; - repeated SSH SSH = 19; - repeated string Tags = 20; - string Target = 21; - UlimitOpt Ulimits = 22; - - string Builder = 23; - bool NoCache = 24; - bool Pull = 25; - bool ExportPush = 26; - bool ExportLoad = 27; - moby.buildkit.v1.sourcepolicy.Policy SourcePolicy = 28; -} - -message ExportEntry { - string Type = 1; - map Attrs = 2; - string Destination = 3; -} - -message CacheOptionsEntry { - string Type = 1; - map Attrs = 2; -} - -message Attest { - string Type = 1; - bool Disabled = 2; - string Attrs = 3; -} - -message SSH { - string ID = 1; - repeated string Paths = 2; -} - -message Secret { - string ID = 1; - string FilePath = 2; - string Env = 3; -} - -message PrintFunc { - string Name = 1; - string Format = 2; -} - -message InspectRequest { - string Ref = 1; -} - -message InspectResponse { - BuildOptions Options = 1; -} - -message UlimitOpt { - map values = 1; -} - -message Ulimit { - string Name = 1; - int64 Hard = 2; - int64 Soft = 3; -} - -message BuildResponse { - map ExporterResponse = 1; -} - -message DisconnectRequest { - string Ref = 1; -} - -message DisconnectResponse {} - -message ListRequest { - string Ref = 1; -} - -message ListResponse { - repeated string keys = 1; -} - -message InputMessage { - oneof Input { - InputInitMessage Init = 1; - DataMessage Data = 2; - } -} - -message InputInitMessage { - string Ref = 1; -} - -message DataMessage { - bool EOF = 1; // true if eof was reached - bytes Data = 2; // should be chunked smaller than 4MB: - // https://pkg.go.dev/google.golang.org/grpc#MaxRecvMsgSize -} - -message InputResponse {} - -message Message { - oneof Input { - InitMessage Init = 1; - // FdMessage used from client to server for input (stdin) and - // from server to client for output (stdout, stderr) - FdMessage File = 2; - // ResizeMessage used from client to server for terminal resize events - ResizeMessage Resize = 3; - // SignalMessage is used from client to server to send signal events - SignalMessage Signal = 4; - } -} - -message InitMessage { - string Ref = 1; - - // If ProcessID already exists in the server, it tries to connect to it - // instead of invoking the new one. In this case, InvokeConfig will be ignored. - string ProcessID = 2; - InvokeConfig InvokeConfig = 3; -} - -message InvokeConfig { - repeated string Entrypoint = 1; - repeated string Cmd = 2; - repeated string Env = 3; - string User = 4; - bool NoUser = 5; // Do not set user but use the image's default - string Cwd = 6; - bool NoCwd = 7; // Do not set cwd but use the image's default - bool Tty = 8; - bool Rollback = 9; // Kill all process in the container and recreate it. - bool Initial = 10; // Run container from the initial state of that stage (supported only on the failed step) -} - -message FdMessage { - uint32 Fd = 1; // what fd the data was from - bool EOF = 2; // true if eof was reached - bytes Data = 3; // should be chunked smaller than 4MB: - // https://pkg.go.dev/google.golang.org/grpc#MaxRecvMsgSize -} - -message ResizeMessage { - uint32 Rows = 1; - uint32 Cols = 2; -} - -message SignalMessage { - // we only send name (ie HUP, INT) because the int values - // are platform dependent. - string Name = 1; -} - -message StatusRequest { - string Ref = 1; -} - -message StatusResponse { - repeated moby.buildkit.v1.Vertex vertexes = 1; - repeated moby.buildkit.v1.VertexStatus statuses = 2; - repeated moby.buildkit.v1.VertexLog logs = 3; - repeated moby.buildkit.v1.VertexWarning warnings = 4; -} - -message InfoRequest {} - -message InfoResponse { - BuildxVersion buildxVersion = 1; -} - -message BuildxVersion { - string package = 1; - string version = 2; - string revision = 3; -} diff --git a/vendor/github.com/docker/buildx/controller/pb/export.go b/vendor/github.com/docker/buildx/controller/pb/export.go deleted file mode 100644 index 93392a432..000000000 --- a/vendor/github.com/docker/buildx/controller/pb/export.go +++ /dev/null @@ -1,100 +0,0 @@ -package pb - -import ( - "io" - "os" - "strconv" - - "github.com/containerd/console" - "github.com/moby/buildkit/client" - "github.com/pkg/errors" -) - -func CreateExports(entries []*ExportEntry) ([]client.ExportEntry, error) { - var outs []client.ExportEntry - if len(entries) == 0 { - return nil, nil - } - for _, entry := range entries { - if entry.Type == "" { - return nil, errors.Errorf("type is required for output") - } - - out := client.ExportEntry{ - Type: entry.Type, - Attrs: map[string]string{}, - } - for k, v := range entry.Attrs { - out.Attrs[k] = v - } - - supportFile := false - supportDir := false - switch out.Type { - case client.ExporterLocal: - supportDir = true - case client.ExporterTar: - supportFile = true - case client.ExporterOCI, client.ExporterDocker: - tar, err := strconv.ParseBool(out.Attrs["tar"]) - if err != nil { - tar = true - } - supportFile = tar - supportDir = !tar - case "registry": - out.Type = client.ExporterImage - } - - if supportDir { - if entry.Destination == "" { - return nil, errors.Errorf("dest is required for %s exporter", out.Type) - } - if entry.Destination == "-" { - return nil, errors.Errorf("dest cannot be stdout for %s exporter", out.Type) - } - - fi, err := os.Stat(entry.Destination) - if err != nil && !os.IsNotExist(err) { - return nil, errors.Wrapf(err, "invalid destination directory: %s", entry.Destination) - } - if err == nil && !fi.IsDir() { - return nil, errors.Errorf("destination directory %s is a file", entry.Destination) - } - out.OutputDir = entry.Destination - } - if supportFile { - if entry.Destination == "" && out.Type != client.ExporterDocker { - entry.Destination = "-" - } - if entry.Destination == "-" { - if _, err := console.ConsoleFromFile(os.Stdout); err == nil { - return nil, errors.Errorf("dest file is required for %s exporter. refusing to write to console", out.Type) - } - out.Output = wrapWriteCloser(os.Stdout) - } else if entry.Destination != "" { - fi, err := os.Stat(entry.Destination) - if err != nil && !os.IsNotExist(err) { - return nil, errors.Wrapf(err, "invalid destination file: %s", entry.Destination) - } - if err == nil && fi.IsDir() { - return nil, errors.Errorf("destination file %s is a directory", entry.Destination) - } - f, err := os.Create(entry.Destination) - if err != nil { - return nil, errors.Errorf("failed to open %s", err) - } - out.Output = wrapWriteCloser(f) - } - } - - outs = append(outs, out) - } - return outs, nil -} - -func wrapWriteCloser(wc io.WriteCloser) func(map[string]string) (io.WriteCloser, error) { - return func(map[string]string) (io.WriteCloser, error) { - return wc, nil - } -} diff --git a/vendor/github.com/docker/buildx/controller/pb/generate.go b/vendor/github.com/docker/buildx/controller/pb/generate.go deleted file mode 100644 index b997566e2..000000000 --- a/vendor/github.com/docker/buildx/controller/pb/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package pb - -//go:generate protoc -I=. -I=../../vendor/ --gogo_out=plugins=grpc:. controller.proto diff --git a/vendor/github.com/docker/buildx/controller/pb/path.go b/vendor/github.com/docker/buildx/controller/pb/path.go deleted file mode 100644 index b2bbe0c71..000000000 --- a/vendor/github.com/docker/buildx/controller/pb/path.go +++ /dev/null @@ -1,175 +0,0 @@ -package pb - -import ( - "path/filepath" - "strings" - - "github.com/docker/docker/builder/remotecontext/urlutil" - "github.com/moby/buildkit/util/gitutil" -) - -// ResolveOptionPaths resolves all paths contained in BuildOptions -// and replaces them to absolute paths. -func ResolveOptionPaths(options *BuildOptions) (_ *BuildOptions, err error) { - localContext := false - if options.ContextPath != "" && options.ContextPath != "-" { - if !isRemoteURL(options.ContextPath) { - localContext = true - options.ContextPath, err = filepath.Abs(options.ContextPath) - if err != nil { - return nil, err - } - } - } - if options.DockerfileName != "" && options.DockerfileName != "-" { - if localContext && !urlutil.IsURL(options.DockerfileName) { - options.DockerfileName, err = filepath.Abs(options.DockerfileName) - if err != nil { - return nil, err - } - } - } - - var contexts map[string]string - for k, v := range options.NamedContexts { - if isRemoteURL(v) || strings.HasPrefix(v, "docker-image://") { - // url prefix, this is a remote path - } else if strings.HasPrefix(v, "oci-layout://") { - // oci layout prefix, this is a local path - p := strings.TrimPrefix(v, "oci-layout://") - p, err = filepath.Abs(p) - if err != nil { - return nil, err - } - v = "oci-layout://" + p - } else { - // no prefix, assume local path - v, err = filepath.Abs(v) - if err != nil { - return nil, err - } - } - - if contexts == nil { - contexts = make(map[string]string) - } - contexts[k] = v - } - options.NamedContexts = contexts - - var cacheFrom []*CacheOptionsEntry - for _, co := range options.CacheFrom { - switch co.Type { - case "local": - var attrs map[string]string - for k, v := range co.Attrs { - if attrs == nil { - attrs = make(map[string]string) - } - switch k { - case "src": - p := v - if p != "" { - p, err = filepath.Abs(p) - if err != nil { - return nil, err - } - } - attrs[k] = p - default: - attrs[k] = v - } - } - co.Attrs = attrs - cacheFrom = append(cacheFrom, co) - default: - cacheFrom = append(cacheFrom, co) - } - } - options.CacheFrom = cacheFrom - - var cacheTo []*CacheOptionsEntry - for _, co := range options.CacheTo { - switch co.Type { - case "local": - var attrs map[string]string - for k, v := range co.Attrs { - if attrs == nil { - attrs = make(map[string]string) - } - switch k { - case "dest": - p := v - if p != "" { - p, err = filepath.Abs(p) - if err != nil { - return nil, err - } - } - attrs[k] = p - default: - attrs[k] = v - } - } - co.Attrs = attrs - cacheTo = append(cacheTo, co) - default: - cacheTo = append(cacheTo, co) - } - } - options.CacheTo = cacheTo - var exports []*ExportEntry - for _, e := range options.Exports { - if e.Destination != "" && e.Destination != "-" { - e.Destination, err = filepath.Abs(e.Destination) - if err != nil { - return nil, err - } - } - exports = append(exports, e) - } - options.Exports = exports - - var secrets []*Secret - for _, s := range options.Secrets { - if s.FilePath != "" { - s.FilePath, err = filepath.Abs(s.FilePath) - if err != nil { - return nil, err - } - } - secrets = append(secrets, s) - } - options.Secrets = secrets - - var ssh []*SSH - for _, s := range options.SSH { - var ps []string - for _, pt := range s.Paths { - p := pt - if p != "" { - p, err = filepath.Abs(p) - if err != nil { - return nil, err - } - } - ps = append(ps, p) - - } - s.Paths = ps - ssh = append(ssh, s) - } - options.SSH = ssh - - return options, nil -} - -func isRemoteURL(c string) bool { - if urlutil.IsURL(c) { - return true - } - if _, err := gitutil.ParseGitRef(c); err == nil { - return true - } - return false -} diff --git a/vendor/github.com/docker/buildx/controller/pb/progress.go b/vendor/github.com/docker/buildx/controller/pb/progress.go deleted file mode 100644 index f2041236e..000000000 --- a/vendor/github.com/docker/buildx/controller/pb/progress.go +++ /dev/null @@ -1,126 +0,0 @@ -package pb - -import ( - "github.com/docker/buildx/util/progress" - control "github.com/moby/buildkit/api/services/control" - "github.com/moby/buildkit/client" - "github.com/opencontainers/go-digest" -) - -type writer struct { - ch chan<- *StatusResponse -} - -func NewProgressWriter(ch chan<- *StatusResponse) progress.Writer { - return &writer{ch: ch} -} - -func (w *writer) Write(status *client.SolveStatus) { - w.ch <- ToControlStatus(status) -} - -func (w *writer) WriteBuildRef(target string, ref string) { - return -} - -func (w *writer) ValidateLogSource(digest.Digest, interface{}) bool { - return true -} - -func (w *writer) ClearLogSource(interface{}) {} - -func ToControlStatus(s *client.SolveStatus) *StatusResponse { - resp := StatusResponse{} - for _, v := range s.Vertexes { - resp.Vertexes = append(resp.Vertexes, &control.Vertex{ - Digest: v.Digest, - Inputs: v.Inputs, - Name: v.Name, - Started: v.Started, - Completed: v.Completed, - Error: v.Error, - Cached: v.Cached, - ProgressGroup: v.ProgressGroup, - }) - } - for _, v := range s.Statuses { - resp.Statuses = append(resp.Statuses, &control.VertexStatus{ - ID: v.ID, - Vertex: v.Vertex, - Name: v.Name, - Total: v.Total, - Current: v.Current, - Timestamp: v.Timestamp, - Started: v.Started, - Completed: v.Completed, - }) - } - for _, v := range s.Logs { - resp.Logs = append(resp.Logs, &control.VertexLog{ - Vertex: v.Vertex, - Stream: int64(v.Stream), - Msg: v.Data, - Timestamp: v.Timestamp, - }) - } - for _, v := range s.Warnings { - resp.Warnings = append(resp.Warnings, &control.VertexWarning{ - Vertex: v.Vertex, - Level: int64(v.Level), - Short: v.Short, - Detail: v.Detail, - Url: v.URL, - Info: v.SourceInfo, - Ranges: v.Range, - }) - } - return &resp -} - -func FromControlStatus(resp *StatusResponse) *client.SolveStatus { - s := client.SolveStatus{} - for _, v := range resp.Vertexes { - s.Vertexes = append(s.Vertexes, &client.Vertex{ - Digest: v.Digest, - Inputs: v.Inputs, - Name: v.Name, - Started: v.Started, - Completed: v.Completed, - Error: v.Error, - Cached: v.Cached, - ProgressGroup: v.ProgressGroup, - }) - } - for _, v := range resp.Statuses { - s.Statuses = append(s.Statuses, &client.VertexStatus{ - ID: v.ID, - Vertex: v.Vertex, - Name: v.Name, - Total: v.Total, - Current: v.Current, - Timestamp: v.Timestamp, - Started: v.Started, - Completed: v.Completed, - }) - } - for _, v := range resp.Logs { - s.Logs = append(s.Logs, &client.VertexLog{ - Vertex: v.Vertex, - Stream: int(v.Stream), - Data: v.Msg, - Timestamp: v.Timestamp, - }) - } - for _, v := range resp.Warnings { - s.Warnings = append(s.Warnings, &client.VertexWarning{ - Vertex: v.Vertex, - Level: int(v.Level), - Short: v.Short, - Detail: v.Detail, - URL: v.Url, - SourceInfo: v.Info, - Range: v.Ranges, - }) - } - return &s -} diff --git a/vendor/github.com/docker/buildx/controller/pb/secrets.go b/vendor/github.com/docker/buildx/controller/pb/secrets.go deleted file mode 100644 index c85b55d16..000000000 --- a/vendor/github.com/docker/buildx/controller/pb/secrets.go +++ /dev/null @@ -1,22 +0,0 @@ -package pb - -import ( - "github.com/moby/buildkit/session" - "github.com/moby/buildkit/session/secrets/secretsprovider" -) - -func CreateSecrets(secrets []*Secret) (session.Attachable, error) { - fs := make([]secretsprovider.Source, 0, len(secrets)) - for _, secret := range secrets { - fs = append(fs, secretsprovider.Source{ - ID: secret.ID, - FilePath: secret.FilePath, - Env: secret.Env, - }) - } - store, err := secretsprovider.NewStore(fs) - if err != nil { - return nil, err - } - return secretsprovider.NewSecretProvider(store), nil -} diff --git a/vendor/github.com/docker/buildx/controller/pb/ssh.go b/vendor/github.com/docker/buildx/controller/pb/ssh.go deleted file mode 100644 index 3d026ebb9..000000000 --- a/vendor/github.com/docker/buildx/controller/pb/ssh.go +++ /dev/null @@ -1,18 +0,0 @@ -package pb - -import ( - "github.com/moby/buildkit/session" - "github.com/moby/buildkit/session/sshforward/sshprovider" -) - -func CreateSSH(ssh []*SSH) (session.Attachable, error) { - configs := make([]sshprovider.AgentConfig, 0, len(ssh)) - for _, ssh := range ssh { - cfg := sshprovider.AgentConfig{ - ID: ssh.ID, - Paths: append([]string{}, ssh.Paths...), - } - configs = append(configs, cfg) - } - return sshprovider.NewSSHAgentProvider(configs) -} diff --git a/vendor/github.com/docker/buildx/driver/bkimage/bkimage.go b/vendor/github.com/docker/buildx/driver/bkimage/bkimage.go deleted file mode 100644 index f2443e7c1..000000000 --- a/vendor/github.com/docker/buildx/driver/bkimage/bkimage.go +++ /dev/null @@ -1,7 +0,0 @@ -package bkimage - -const ( - DefaultImage = "moby/buildkit:buildx-stable-1" // TODO: make this verified - QemuImage = "tonistiigi/binfmt:latest" // TODO: make this verified - DefaultRootlessImage = DefaultImage + "-rootless" -) diff --git a/vendor/github.com/docker/buildx/driver/docker-container/driver.go b/vendor/github.com/docker/buildx/driver/docker-container/driver.go deleted file mode 100644 index e06380bf1..000000000 --- a/vendor/github.com/docker/buildx/driver/docker-container/driver.go +++ /dev/null @@ -1,453 +0,0 @@ -package docker - -import ( - "bytes" - "context" - "io" - "net" - "os" - "path" - "path/filepath" - "strings" - "sync/atomic" - "time" - - "github.com/docker/buildx/driver" - "github.com/docker/buildx/driver/bkimage" - "github.com/docker/buildx/util/confutil" - "github.com/docker/buildx/util/imagetools" - "github.com/docker/buildx/util/progress" - dockertypes "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/mount" - "github.com/docker/docker/api/types/network" - dockerclient "github.com/docker/docker/client" - dockerarchive "github.com/docker/docker/pkg/archive" - "github.com/docker/docker/pkg/idtools" - "github.com/docker/docker/pkg/stdcopy" - "github.com/moby/buildkit/client" - "github.com/moby/buildkit/util/tracing/detect" - "github.com/pkg/errors" -) - -const ( - volumeStateSuffix = "_state" -) - -type Driver struct { - driver.InitConfig - factory driver.Factory - netMode string - image string - cgroupParent string - env []string -} - -func (d *Driver) IsMobyDriver() bool { - return false -} - -func (d *Driver) Config() driver.InitConfig { - return d.InitConfig -} - -func (d *Driver) Bootstrap(ctx context.Context, l progress.Logger) error { - return progress.Wrap("[internal] booting buildkit", l, func(sub progress.SubLogger) error { - _, err := d.DockerAPI.ContainerInspect(ctx, d.Name) - if err != nil { - if dockerclient.IsErrNotFound(err) { - return d.create(ctx, sub) - } - return err - } - return sub.Wrap("starting container "+d.Name, func() error { - if err := d.start(ctx, sub); err != nil { - return err - } - if err := d.wait(ctx, sub); err != nil { - return err - } - return nil - }) - }) -} - -func (d *Driver) create(ctx context.Context, l progress.SubLogger) error { - imageName := bkimage.DefaultImage - if d.image != "" { - imageName = d.image - } - - if err := l.Wrap("pulling image "+imageName, func() error { - ra, err := imagetools.RegistryAuthForRef(imageName, d.Auth) - if err != nil { - return err - } - rc, err := d.DockerAPI.ImageCreate(ctx, imageName, dockertypes.ImageCreateOptions{ - RegistryAuth: ra, - }) - if err != nil { - return err - } - _, err = io.Copy(io.Discard, rc) - return err - }); err != nil { - // image pulling failed, check if it exists in local image store. - // if not, return pulling error. otherwise log it. - _, _, errInspect := d.DockerAPI.ImageInspectWithRaw(ctx, imageName) - if errInspect != nil { - return err - } - l.Wrap("pulling failed, using local image "+imageName, func() error { return nil }) - } - - cfg := &container.Config{ - Image: imageName, - Env: d.env, - } - if d.InitConfig.BuildkitFlags != nil { - cfg.Cmd = d.InitConfig.BuildkitFlags - } - - useInit := true // let it cleanup exited processes created by BuildKit's container API - if err := l.Wrap("creating container "+d.Name, func() error { - hc := &container.HostConfig{ - Privileged: true, - Mounts: []mount.Mount{ - { - Type: mount.TypeVolume, - Source: d.Name + volumeStateSuffix, - Target: confutil.DefaultBuildKitStateDir, - }, - }, - Init: &useInit, - } - if d.netMode != "" { - hc.NetworkMode = container.NetworkMode(d.netMode) - } - if info, err := d.DockerAPI.Info(ctx); err == nil { - if info.CgroupDriver == "cgroupfs" { - // Place all buildkit containers inside this cgroup by default so limits can be attached - // to all build activity on the host. - hc.CgroupParent = "/docker/buildx" - if d.cgroupParent != "" { - hc.CgroupParent = d.cgroupParent - } - } - - secOpts, err := dockertypes.DecodeSecurityOptions(info.SecurityOptions) - if err != nil { - return err - } - for _, f := range secOpts { - if f.Name == "userns" { - hc.UsernsMode = "host" - break - } - } - - } - _, err := d.DockerAPI.ContainerCreate(ctx, cfg, hc, &network.NetworkingConfig{}, nil, d.Name) - if err != nil { - return err - } - if err := d.copyToContainer(ctx, d.InitConfig.Files); err != nil { - return err - } - if err := d.start(ctx, l); err != nil { - return err - } - if err := d.wait(ctx, l); err != nil { - return err - } - return nil - }); err != nil { - return err - } - return nil -} - -func (d *Driver) wait(ctx context.Context, l progress.SubLogger) error { - try := 1 - for { - bufStdout := &bytes.Buffer{} - bufStderr := &bytes.Buffer{} - if err := d.run(ctx, []string{"buildctl", "debug", "workers"}, bufStdout, bufStderr); err != nil { - if try > 15 { - if err != nil { - d.copyLogs(context.TODO(), l) - if bufStdout.Len() != 0 { - l.Log(1, bufStdout.Bytes()) - } - if bufStderr.Len() != 0 { - l.Log(2, bufStderr.Bytes()) - } - } - return err - } - select { - case <-ctx.Done(): - return ctx.Err() - case <-time.After(time.Duration(try*120) * time.Millisecond): - try++ - continue - } - } - return nil - } -} - -func (d *Driver) copyLogs(ctx context.Context, l progress.SubLogger) error { - rc, err := d.DockerAPI.ContainerLogs(ctx, d.Name, dockertypes.ContainerLogsOptions{ - ShowStdout: true, ShowStderr: true, - }) - if err != nil { - return err - } - stdout := &logWriter{logger: l, stream: 1} - stderr := &logWriter{logger: l, stream: 2} - if _, err := stdcopy.StdCopy(stdout, stderr, rc); err != nil { - return err - } - return rc.Close() -} - -func (d *Driver) copyToContainer(ctx context.Context, files map[string][]byte) error { - srcPath, err := writeConfigFiles(files) - if err != nil { - return err - } - if srcPath != "" { - defer os.RemoveAll(srcPath) - } - srcArchive, err := dockerarchive.TarWithOptions(srcPath, &dockerarchive.TarOptions{ - ChownOpts: &idtools.Identity{UID: 0, GID: 0}, - }) - if err != nil { - return err - } - defer srcArchive.Close() - return d.DockerAPI.CopyToContainer(ctx, d.Name, "/", srcArchive, dockertypes.CopyToContainerOptions{}) -} - -func (d *Driver) exec(ctx context.Context, cmd []string) (string, net.Conn, error) { - execConfig := dockertypes.ExecConfig{ - Cmd: cmd, - AttachStdin: true, - AttachStdout: true, - AttachStderr: true, - } - response, err := d.DockerAPI.ContainerExecCreate(ctx, d.Name, execConfig) - if err != nil { - return "", nil, err - } - - execID := response.ID - if execID == "" { - return "", nil, errors.New("exec ID empty") - } - - resp, err := d.DockerAPI.ContainerExecAttach(ctx, execID, dockertypes.ExecStartCheck{}) - if err != nil { - return "", nil, err - } - return execID, resp.Conn, nil -} - -func (d *Driver) run(ctx context.Context, cmd []string, stdout, stderr io.Writer) (err error) { - id, conn, err := d.exec(ctx, cmd) - if err != nil { - return err - } - if _, err := stdcopy.StdCopy(stdout, stderr, conn); err != nil { - return err - } - conn.Close() - resp, err := d.DockerAPI.ContainerExecInspect(ctx, id) - if err != nil { - return err - } - if resp.ExitCode != 0 { - return errors.Errorf("exit code %d", resp.ExitCode) - } - return nil -} - -func (d *Driver) start(ctx context.Context, l progress.SubLogger) error { - return d.DockerAPI.ContainerStart(ctx, d.Name, dockertypes.ContainerStartOptions{}) -} - -func (d *Driver) Info(ctx context.Context) (*driver.Info, error) { - ctn, err := d.DockerAPI.ContainerInspect(ctx, d.Name) - if err != nil { - if dockerclient.IsErrNotFound(err) { - return &driver.Info{ - Status: driver.Inactive, - }, nil - } - return nil, err - } - - if ctn.State.Running { - return &driver.Info{ - Status: driver.Running, - }, nil - } - - return &driver.Info{ - Status: driver.Stopped, - }, nil -} - -func (d *Driver) Version(ctx context.Context) (string, error) { - bufStdout := &bytes.Buffer{} - bufStderr := &bytes.Buffer{} - if err := d.run(ctx, []string{"buildkitd", "--version"}, bufStdout, bufStderr); err != nil { - if bufStderr.Len() > 0 { - return "", errors.Wrap(err, bufStderr.String()) - } - return "", err - } - version := strings.Fields(bufStdout.String()) - if len(version) != 4 { - return "", errors.Errorf("unexpected version format: %s", bufStdout.String()) - } - return version[2], nil -} - -func (d *Driver) Stop(ctx context.Context, force bool) error { - info, err := d.Info(ctx) - if err != nil { - return err - } - if info.Status == driver.Running { - return d.DockerAPI.ContainerStop(ctx, d.Name, container.StopOptions{}) - } - return nil -} - -func (d *Driver) Rm(ctx context.Context, force, rmVolume, rmDaemon bool) error { - info, err := d.Info(ctx) - if err != nil { - return err - } - if info.Status != driver.Inactive { - container, err := d.DockerAPI.ContainerInspect(ctx, d.Name) - if err != nil { - return err - } - if rmDaemon { - if err := d.DockerAPI.ContainerRemove(ctx, d.Name, dockertypes.ContainerRemoveOptions{ - RemoveVolumes: true, - Force: force, - }); err != nil { - return err - } - for _, v := range container.Mounts { - if v.Name != d.Name+volumeStateSuffix { - continue - } - if rmVolume { - return d.DockerAPI.VolumeRemove(ctx, d.Name+volumeStateSuffix, false) - } - } - } - } - return nil -} - -func (d *Driver) Client(ctx context.Context) (*client.Client, error) { - _, conn, err := d.exec(ctx, []string{"buildctl", "dial-stdio"}) - if err != nil { - return nil, err - } - - conn = demuxConn(conn) - - exp, err := detect.Exporter() - if err != nil { - return nil, err - } - - var opts []client.ClientOpt - var counter int64 - opts = append(opts, client.WithContextDialer(func(context.Context, string) (net.Conn, error) { - if atomic.AddInt64(&counter, 1) > 1 { - return nil, net.ErrClosed - } - return conn, nil - })) - if td, ok := exp.(client.TracerDelegate); ok { - opts = append(opts, client.WithTracerDelegate(td)) - } - return client.New(ctx, "", opts...) -} - -func (d *Driver) Factory() driver.Factory { - return d.factory -} - -func (d *Driver) Features(ctx context.Context) map[driver.Feature]bool { - return map[driver.Feature]bool{ - driver.OCIExporter: true, - driver.DockerExporter: true, - driver.CacheExport: true, - driver.MultiPlatform: true, - } -} - -func demuxConn(c net.Conn) net.Conn { - pr, pw := io.Pipe() - // TODO: rewrite parser with Reader() to avoid goroutine switch - go func() { - _, err := stdcopy.StdCopy(pw, os.Stderr, c) - pw.CloseWithError(err) - }() - return &demux{ - Conn: c, - Reader: pr, - } -} - -type demux struct { - net.Conn - io.Reader -} - -func (d *demux) Read(dt []byte) (int, error) { - return d.Reader.Read(dt) -} - -type logWriter struct { - logger progress.SubLogger - stream int -} - -func (l *logWriter) Write(dt []byte) (int, error) { - l.logger.Log(l.stream, dt) - return len(dt), nil -} - -func writeConfigFiles(m map[string][]byte) (_ string, err error) { - // Temp dir that will be copied to the container - tmpDir, err := os.MkdirTemp("", "buildkitd-config") - if err != nil { - return "", err - } - defer func() { - if err != nil { - os.RemoveAll(tmpDir) - } - }() - for f, dt := range m { - f = path.Join(confutil.DefaultBuildKitConfigDir, f) - p := filepath.Join(tmpDir, f) - if err := os.MkdirAll(filepath.Dir(p), 0700); err != nil { - return "", err - } - if err := os.WriteFile(p, dt, 0600); err != nil { - return "", err - } - } - return tmpDir, nil -} diff --git a/vendor/github.com/docker/buildx/driver/docker-container/factory.go b/vendor/github.com/docker/buildx/driver/docker-container/factory.go deleted file mode 100644 index 118d9c5a3..000000000 --- a/vendor/github.com/docker/buildx/driver/docker-container/factory.go +++ /dev/null @@ -1,70 +0,0 @@ -package docker - -import ( - "context" - "fmt" - "strings" - - "github.com/docker/buildx/driver" - dockerclient "github.com/docker/docker/client" - "github.com/pkg/errors" -) - -const prioritySupported = 30 -const priorityUnsupported = 70 - -func init() { - driver.Register(&factory{}) -} - -type factory struct { -} - -func (*factory) Name() string { - return "docker-container" -} - -func (*factory) Usage() string { - return "docker-container" -} - -func (*factory) Priority(ctx context.Context, endpoint string, api dockerclient.APIClient) int { - if api == nil { - return priorityUnsupported - } - return prioritySupported -} - -func (f *factory) New(ctx context.Context, cfg driver.InitConfig) (driver.Driver, error) { - if cfg.DockerAPI == nil { - return nil, errors.Errorf("%s driver requires docker API access", f.Name()) - } - d := &Driver{factory: f, InitConfig: cfg} - for k, v := range cfg.DriverOpts { - switch { - case k == "network": - d.netMode = v - if v == "host" { - d.InitConfig.BuildkitFlags = append(d.InitConfig.BuildkitFlags, "--allow-insecure-entitlement=network.host") - } - case k == "image": - d.image = v - case k == "cgroup-parent": - d.cgroupParent = v - case strings.HasPrefix(k, "env."): - envName := strings.TrimPrefix(k, "env.") - if envName == "" { - return nil, errors.Errorf("invalid env option %q, expecting env.FOO=bar", k) - } - d.env = append(d.env, fmt.Sprintf("%s=%s", envName, v)) - default: - return nil, errors.Errorf("invalid driver option %s for docker-container driver", k) - } - } - - return d, nil -} - -func (f *factory) AllowsInstances() bool { - return true -} diff --git a/vendor/github.com/docker/buildx/driver/docker/driver.go b/vendor/github.com/docker/buildx/driver/docker/driver.go deleted file mode 100644 index 64c0dd25b..000000000 --- a/vendor/github.com/docker/buildx/driver/docker/driver.go +++ /dev/null @@ -1,91 +0,0 @@ -package docker - -import ( - "context" - "net" - "strings" - - "github.com/docker/buildx/driver" - "github.com/docker/buildx/util/progress" - "github.com/moby/buildkit/client" - "github.com/pkg/errors" -) - -type Driver struct { - factory driver.Factory - driver.InitConfig -} - -func (d *Driver) Bootstrap(ctx context.Context, l progress.Logger) error { - return nil -} - -func (d *Driver) Info(ctx context.Context) (*driver.Info, error) { - _, err := d.DockerAPI.ServerVersion(ctx) - if err != nil { - return nil, errors.Wrapf(driver.ErrNotConnecting, err.Error()) - } - return &driver.Info{ - Status: driver.Running, - }, nil -} - -func (d *Driver) Version(ctx context.Context) (string, error) { - v, err := d.DockerAPI.ServerVersion(ctx) - if err != nil { - return "", errors.Wrapf(driver.ErrNotConnecting, err.Error()) - } - if bkversion, _ := resolveBuildKitVersion(v.Version); bkversion != "" { - return bkversion, nil - } - // https://github.com/moby/moby/blob/efc7a2abc3ab6dfa7d8d5d8c1c3b99138989b0f1/builder/builder-next/worker/worker.go#L176 - return strings.TrimSuffix(v.Version, "-moby"), nil -} - -func (d *Driver) Stop(ctx context.Context, force bool) error { - return nil -} - -func (d *Driver) Rm(ctx context.Context, force, rmVolume, rmDaemon bool) error { - return nil -} - -func (d *Driver) Client(ctx context.Context) (*client.Client, error) { - return client.New(ctx, "", client.WithContextDialer(func(context.Context, string) (net.Conn, error) { - return d.DockerAPI.DialHijack(ctx, "/grpc", "h2c", nil) - }), client.WithSessionDialer(func(ctx context.Context, proto string, meta map[string][]string) (net.Conn, error) { - return d.DockerAPI.DialHijack(ctx, "/session", proto, meta) - })) -} - -func (d *Driver) Features(ctx context.Context) map[driver.Feature]bool { - var useContainerdSnapshotter bool - c, err := d.Client(ctx) - if err == nil { - workers, _ := c.ListWorkers(ctx) - for _, w := range workers { - if _, ok := w.Labels["org.mobyproject.buildkit.worker.snapshotter"]; ok { - useContainerdSnapshotter = true - } - } - c.Close() - } - return map[driver.Feature]bool{ - driver.OCIExporter: useContainerdSnapshotter, - driver.DockerExporter: useContainerdSnapshotter, - driver.CacheExport: useContainerdSnapshotter, - driver.MultiPlatform: useContainerdSnapshotter, - } -} - -func (d *Driver) Factory() driver.Factory { - return d.factory -} - -func (d *Driver) IsMobyDriver() bool { - return true -} - -func (d *Driver) Config() driver.InitConfig { - return d.InitConfig -} diff --git a/vendor/github.com/docker/buildx/driver/docker/factory.go b/vendor/github.com/docker/buildx/driver/docker/factory.go deleted file mode 100644 index 8f2e37bce..000000000 --- a/vendor/github.com/docker/buildx/driver/docker/factory.go +++ /dev/null @@ -1,56 +0,0 @@ -package docker - -import ( - "context" - - "github.com/docker/buildx/driver" - dockerclient "github.com/docker/docker/client" - "github.com/pkg/errors" -) - -const prioritySupported = 10 -const priorityUnsupported = 99 - -func init() { - driver.Register(&factory{}) -} - -type factory struct { -} - -func (*factory) Name() string { - return "docker" -} - -func (*factory) Usage() string { - return "docker" -} - -func (*factory) Priority(ctx context.Context, endpoint string, api dockerclient.APIClient) int { - if api == nil { - return priorityUnsupported - } - - c, err := api.DialHijack(ctx, "/grpc", "h2c", nil) - if err != nil { - return priorityUnsupported - } - c.Close() - - return prioritySupported -} - -func (f *factory) New(ctx context.Context, cfg driver.InitConfig) (driver.Driver, error) { - if cfg.DockerAPI == nil { - return nil, errors.Errorf("docker driver requires docker API access") - } - if len(cfg.Files) > 0 { - return nil, errors.Errorf("setting config file is not supported for docker driver, use dockerd configuration file") - } - - return &Driver{factory: f, InitConfig: cfg}, nil -} - -func (f *factory) AllowsInstances() bool { - return false -} diff --git a/vendor/github.com/docker/buildx/driver/docker/version.go b/vendor/github.com/docker/buildx/driver/docker/version.go deleted file mode 100644 index 2de359de7..000000000 --- a/vendor/github.com/docker/buildx/driver/docker/version.go +++ /dev/null @@ -1,190 +0,0 @@ -package docker - -import ( - "github.com/Masterminds/semver/v3" -) - -type mobyBuildkitVersion struct { - MobyVersionConstraint string - BuildkitVersion string -} - -// https://gist.github.com/crazy-max/780cb6878c37cb79ec3f7699706cf83f -// constraint syntax: https://github.com/Masterminds/semver#checking-version-constraints -var mobyBuildkitVersions = []mobyBuildkitVersion{ - { - MobyVersionConstraint: ">= 18.06.0-0, < 18.06.1-0", - BuildkitVersion: "v0.0.0+9acf51e", - }, - { - MobyVersionConstraint: ">= 18.06.1-0, < 18.09.0-0", - BuildkitVersion: "v0.0.0+98f1604", - }, - { - MobyVersionConstraint: ">= 18.09.0-0, < 18.09.1-0", - BuildkitVersion: "v0.0.0+c7bb575", - }, - { - MobyVersionConstraint: "~18.09.1-0", - BuildkitVersion: "v0.3.3", - }, - { - MobyVersionConstraint: "> 18.09.1-0, < 18.09.6-0", - BuildkitVersion: "v0.3.3+d9f7592", - }, - { - MobyVersionConstraint: ">= 18.09.6-0, < 18.09.7-0", - BuildkitVersion: "v0.4.0+ed4da8b", - }, - { - MobyVersionConstraint: ">= 18.09.7-0, < 19.03.0-0", - BuildkitVersion: "v0.4.0+05766c5", - }, - { - MobyVersionConstraint: "<= 19.03.0-beta2", - BuildkitVersion: "v0.4.0+b302896", - }, - { - MobyVersionConstraint: "<= 19.03.0-beta3", - BuildkitVersion: "v0.4.0+8818c67", - }, - { - MobyVersionConstraint: "<= 19.03.0-beta5", - BuildkitVersion: "v0.5.1+f238f1e", - }, - { - MobyVersionConstraint: "< 19.03.2-0", - BuildkitVersion: "v0.5.1+1f89ec1", - }, - { - MobyVersionConstraint: "<= 19.03.2-beta1", - BuildkitVersion: "v0.6.1", - }, - { - MobyVersionConstraint: ">= 19.03.2-0, < 19.03.3-0", - BuildkitVersion: "v0.6.1+588c73e", - }, - { - MobyVersionConstraint: ">= 19.03.3-0, < 19.03.5-beta2", - BuildkitVersion: "v0.6.2", - }, - { - MobyVersionConstraint: "<= 19.03.5-rc1", - BuildkitVersion: "v0.6.2+ff93519", - }, - { - MobyVersionConstraint: "<= 19.03.5", - BuildkitVersion: "v0.6.3+928f3b4", - }, - { - MobyVersionConstraint: "<= 19.03.6-rc1", - BuildkitVersion: "v0.6.3+926935b", - }, - { - MobyVersionConstraint: ">= 19.03.6-rc2, < 19.03.7-0", - BuildkitVersion: "v0.6.3+57e8ad5", - }, - { - MobyVersionConstraint: ">= 19.03.7-0, < 19.03.9-0", - BuildkitVersion: "v0.6.4", - }, - { - MobyVersionConstraint: ">= 19.03.9-0, < 19.03.13-0", - BuildkitVersion: "v0.6.4+a7d7b7f", - }, - { - MobyVersionConstraint: "<= 19.03.13-beta2", - BuildkitVersion: "v0.6.4+da1f4bf", - }, - { - MobyVersionConstraint: "<= 19.03.14", - BuildkitVersion: "v0.6.4+df89d4d", - }, - { - MobyVersionConstraint: "< 20.10.0", - BuildkitVersion: "v0.6.4+396bfe2", - }, - { - MobyVersionConstraint: "20.10.0-0 - 20.10.2-0", - BuildkitVersion: "v0.8.1", - }, - { - MobyVersionConstraint: ">= 20.10.3-0, < 20.10.4-0", - BuildkitVersion: "v0.8.1+68bb095", - }, - { - MobyVersionConstraint: "20.10.4-0 - 20.10.6", - BuildkitVersion: "v0.8.2", - }, - { - MobyVersionConstraint: "20.10.7-0 - 20.10.10-0", - BuildkitVersion: "v0.8.2+244e8cde", - }, - { - MobyVersionConstraint: "20.10.11-0 - 20.10.18-0", - BuildkitVersion: "v0.8.2+bc07b2b8", - }, - { - MobyVersionConstraint: ">= 20.10.19-0, < 20.10.20-0", - BuildkitVersion: "v0.8.2+3a1eeca5", - }, - { - MobyVersionConstraint: ">= 20.10.20-0, < 20.10.21-0", - BuildkitVersion: "v0.8.2+c0149372", - }, - { - MobyVersionConstraint: ">= 20.10.21-0, <= 20.10.23", - BuildkitVersion: "v0.8.2+eeb7b65", - }, - { - MobyVersionConstraint: "~20.10-0", - BuildkitVersion: "v0.8+unknown", - }, - { - MobyVersionConstraint: "~22.06-0", - BuildkitVersion: "v0.10.3", - }, - { - MobyVersionConstraint: ">= 23.0.0-0, < 23.0.1-0", - BuildkitVersion: "v0.10.6", - }, - { - MobyVersionConstraint: "23.0.1", - BuildkitVersion: "v0.10.6+4f0ee09", - }, - { - MobyVersionConstraint: ">= 23.0.2-0, < 23.0.4-0", - BuildkitVersion: "v0.10.6+70f2ad5", - }, - { - MobyVersionConstraint: ">= 23.0.4-0, < 23.0.7-0", - BuildkitVersion: "v0.10.6+d52b2d5", - }, - { - MobyVersionConstraint: "~23-0", - BuildkitVersion: "v0.10+unknown", - }, -} - -func resolveBuildKitVersion(ver string) (string, error) { - mobyVersion, err := semver.NewVersion(ver) - if err != nil { - return "", err - } - for _, m := range mobyBuildkitVersions { - c, err := semver.NewConstraint(m.MobyVersionConstraint) - if err != nil { - return "", err - } - //if _, errs := c.Validate(mobyVersion); len(errs) > 0 { - // for _, err := range errs { - // fmt.Printf("%s: %v\n", m.MobyVersionConstraint, err) - // } - //} - if !c.Check(mobyVersion) { - continue - } - return m.BuildkitVersion, nil - } - return "", nil -} diff --git a/vendor/github.com/docker/buildx/driver/driver.go b/vendor/github.com/docker/buildx/driver/driver.go deleted file mode 100644 index 8642a543c..000000000 --- a/vendor/github.com/docker/buildx/driver/driver.go +++ /dev/null @@ -1,112 +0,0 @@ -package driver - -import ( - "context" - "io" - - "github.com/docker/buildx/store" - "github.com/docker/buildx/util/progress" - clitypes "github.com/docker/cli/cli/config/types" - controlapi "github.com/moby/buildkit/api/services/control" - "github.com/moby/buildkit/client" - "github.com/pkg/errors" -) - -var ErrNotRunning = errors.Errorf("driver not running") -var ErrNotConnecting = errors.Errorf("driver not connecting") - -type Status int - -const ( - Inactive Status = iota - Starting - Running - Stopping - Stopped -) - -func (s Status) String() string { - switch s { - case Inactive: - return "inactive" - case Starting: - return "starting" - case Running: - return "running" - case Stopping: - return "stopping" - case Stopped: - return "stopped" - } - return "unknown" -} - -type Info struct { - Status Status - // DynamicNodes must be empty if the actual nodes are statically listed in the store - DynamicNodes []store.Node -} - -type Auth interface { - GetAuthConfig(registryHostname string) (clitypes.AuthConfig, error) -} - -type Driver interface { - Factory() Factory - Bootstrap(context.Context, progress.Logger) error - Info(context.Context) (*Info, error) - Version(context.Context) (string, error) - Stop(ctx context.Context, force bool) error - Rm(ctx context.Context, force, rmVolume, rmDaemon bool) error - Client(ctx context.Context) (*client.Client, error) - Features(ctx context.Context) map[Feature]bool - IsMobyDriver() bool - Config() InitConfig -} - -func Boot(ctx, clientContext context.Context, d *DriverHandle, pw progress.Writer) (*client.Client, error) { - try := 0 - for { - info, err := d.Info(ctx) - if err != nil { - return nil, err - } - try++ - if info.Status != Running { - if try > 2 { - return nil, errors.Errorf("failed to bootstrap %T driver in attempts", d) - } - if err := d.Bootstrap(ctx, pw.Write); err != nil { - return nil, err - } - } - - c, err := d.Client(clientContext) - if err != nil { - if errors.Cause(err) == ErrNotRunning && try <= 2 { - continue - } - return nil, err - } - return c, nil - } -} - -func historyAPISupported(ctx context.Context, c *client.Client) bool { - cl, err := c.ControlClient().ListenBuildHistory(ctx, &controlapi.BuildHistoryRequest{ - ActiveOnly: true, - Ref: "buildx-test-history-api-feature", // dummy ref to check if the server supports the API - EarlyExit: true, - }) - if err != nil { - return false - } - for { - _, err := cl.Recv() - if errors.Is(err, io.EOF) { - return true - } else if err != nil { - return false - } - } -} diff --git a/vendor/github.com/docker/buildx/driver/features.go b/vendor/github.com/docker/buildx/driver/features.go deleted file mode 100644 index e48d73094..000000000 --- a/vendor/github.com/docker/buildx/driver/features.go +++ /dev/null @@ -1,9 +0,0 @@ -package driver - -type Feature string - -const OCIExporter Feature = "OCI exporter" -const DockerExporter Feature = "Docker exporter" - -const CacheExport Feature = "Cache export" -const MultiPlatform Feature = "Multiple platforms" diff --git a/vendor/github.com/docker/buildx/driver/kubernetes/context/constants.go b/vendor/github.com/docker/buildx/driver/kubernetes/context/constants.go deleted file mode 100644 index f3856da15..000000000 --- a/vendor/github.com/docker/buildx/driver/kubernetes/context/constants.go +++ /dev/null @@ -1,6 +0,0 @@ -package context - -const ( - // KubernetesEndpoint is the kubernetes endpoint name in a stored context - KubernetesEndpoint = "kubernetes" -) diff --git a/vendor/github.com/docker/buildx/driver/kubernetes/context/load.go b/vendor/github.com/docker/buildx/driver/kubernetes/context/load.go deleted file mode 100644 index d6a23d853..000000000 --- a/vendor/github.com/docker/buildx/driver/kubernetes/context/load.go +++ /dev/null @@ -1,178 +0,0 @@ -package context - -import ( - "net/url" - "os" - "path/filepath" - "strings" - - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/context" - "github.com/docker/cli/cli/context/store" - "github.com/docker/docker/pkg/homedir" - "k8s.io/client-go/tools/clientcmd" - clientcmdapi "k8s.io/client-go/tools/clientcmd/api" -) - -// EndpointMeta is a typed wrapper around a context-store generic endpoint describing -// a Kubernetes endpoint, without TLS data -type EndpointMeta struct { - context.EndpointMetaBase - DefaultNamespace string `json:",omitempty"` - ProxyURL string `json:",omitempty"` - AuthProvider *clientcmdapi.AuthProviderConfig `json:",omitempty"` - Exec *clientcmdapi.ExecConfig `json:",omitempty"` - UsernamePassword *UsernamePassword `json:"usernamePassword,omitempty"` -} - -// UsernamePassword contains username/password auth info -type UsernamePassword struct { - Username string `json:"username,omitempty"` - Password string `json:"password,omitempty"` -} - -var _ command.EndpointDefaultResolver = &EndpointMeta{} - -// Endpoint is a typed wrapper around a context-store generic endpoint describing -// a Kubernetes endpoint, with TLS data -type Endpoint struct { - EndpointMeta - TLSData *context.TLSData -} - -func init() { - command.RegisterDefaultStoreEndpoints( - store.EndpointTypeGetter(KubernetesEndpoint, func() interface{} { return &EndpointMeta{} }), - ) -} - -// WithTLSData loads TLS materials for the endpoint -func (c *EndpointMeta) WithTLSData(s store.Reader, contextName string) (Endpoint, error) { - tlsData, err := context.LoadTLSData(s, contextName, KubernetesEndpoint) - if err != nil { - return Endpoint{}, err - } - return Endpoint{ - EndpointMeta: *c, - TLSData: tlsData, - }, nil -} - -// KubernetesConfig creates the kubernetes client config from the endpoint -func (c *Endpoint) KubernetesConfig() clientcmd.ClientConfig { - cfg := clientcmdapi.NewConfig() - cluster := clientcmdapi.NewCluster() - cluster.Server = c.Host - if c.ProxyURL != "" { - cluster.ProxyURL = c.ProxyURL - } - cluster.InsecureSkipTLSVerify = c.SkipTLSVerify - authInfo := clientcmdapi.NewAuthInfo() - if c.TLSData != nil { - cluster.CertificateAuthorityData = c.TLSData.CA - authInfo.ClientCertificateData = c.TLSData.Cert - authInfo.ClientKeyData = c.TLSData.Key - } - if c.UsernamePassword != nil { - authInfo.Username = c.UsernamePassword.Username - authInfo.Password = c.UsernamePassword.Password - } - authInfo.AuthProvider = c.AuthProvider - authInfo.Exec = c.Exec - cfg.Clusters["cluster"] = cluster - cfg.AuthInfos["authInfo"] = authInfo - ctx := clientcmdapi.NewContext() - ctx.AuthInfo = "authInfo" - ctx.Cluster = "cluster" - ctx.Namespace = c.DefaultNamespace - cfg.Contexts["context"] = ctx - cfg.CurrentContext = "context" - return clientcmd.NewDefaultClientConfig(*cfg, &clientcmd.ConfigOverrides{}) -} - -// ResolveDefault returns endpoint metadata for the default Kubernetes -// endpoint, which is derived from the env-based kubeconfig. -func (c *EndpointMeta) ResolveDefault() (interface{}, *store.EndpointTLSData, error) { - kubeconfig := os.Getenv("KUBECONFIG") - if kubeconfig == "" { - kubeconfig = filepath.Join(homedir.Get(), ".kube/config") - } - kubeEP, err := FromKubeConfig(kubeconfig, "", "") - if err != nil { - // We deliberately quash the error here, returning nil - // for the first argument is sufficient to indicate we weren't able to - // provide a default - return nil, nil, nil - } - var tls *store.EndpointTLSData - if kubeEP.TLSData != nil { - tls = kubeEP.TLSData.ToStoreTLSData() - } - return kubeEP.EndpointMeta, tls, nil -} - -// EndpointFromContext extracts kubernetes endpoint info from current context -func EndpointFromContext(metadata store.Metadata) *EndpointMeta { - ep, ok := metadata.Endpoints[KubernetesEndpoint] - if !ok { - return nil - } - typed, ok := ep.(EndpointMeta) - if !ok { - return nil - } - return &typed -} - -// ConfigFromContext resolves a kubernetes client config for the specified context. -// If kubeconfigOverride is specified, use this config file instead of the context defaults.ConfigFromContext -// if command.ContextDockerHost is specified as the context name, fallsback to the default user's kubeconfig file -func ConfigFromContext(name string, s store.Reader) (clientcmd.ClientConfig, error) { - ctxMeta, err := s.GetMetadata(name) - if err != nil { - return nil, err - } - epMeta := EndpointFromContext(ctxMeta) - if epMeta != nil { - ep, err := epMeta.WithTLSData(s, name) - if err != nil { - return nil, err - } - return ep.KubernetesConfig(), nil - } - // context has no kubernetes endpoint - return NewKubernetesConfig(""), nil -} - -// NewKubernetesConfig resolves the path to the desired Kubernetes configuration -// file based on the KUBECONFIG environment variable and command line flags. -func NewKubernetesConfig(configPath string) clientcmd.ClientConfig { - kubeConfig := configPath - if kubeConfig == "" { - if config := os.Getenv("KUBECONFIG"); config != "" { - kubeConfig = config - } else { - kubeConfig = filepath.Join(homedir.Get(), ".kube/config") - } - } - return clientcmd.NewNonInteractiveDeferredLoadingClientConfig( - &clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeConfig}, - &clientcmd.ConfigOverrides{}) -} - -// ConfigFromEndpoint loads kubernetes config from endpoint -func ConfigFromEndpoint(endpointName string, s store.Reader) (clientcmd.ClientConfig, error) { - if strings.HasPrefix(endpointName, "kubernetes://") { - u, _ := url.Parse(endpointName) - if kubeconfig := u.Query().Get("kubeconfig"); kubeconfig != "" { - _ = os.Setenv(clientcmd.RecommendedConfigPathEnvVar, kubeconfig) - } - rules := clientcmd.NewDefaultClientConfigLoadingRules() - apiConfig, err := rules.Load() - if err != nil { - return nil, err - } - return clientcmd.NewDefaultClientConfig(*apiConfig, &clientcmd.ConfigOverrides{}), nil - } - return ConfigFromContext(endpointName, s) -} diff --git a/vendor/github.com/docker/buildx/driver/kubernetes/context/save.go b/vendor/github.com/docker/buildx/driver/kubernetes/context/save.go deleted file mode 100644 index 7eb346bd9..000000000 --- a/vendor/github.com/docker/buildx/driver/kubernetes/context/save.go +++ /dev/null @@ -1,81 +0,0 @@ -package context - -import ( - "os" - - "github.com/docker/cli/cli/context" - "k8s.io/client-go/tools/clientcmd" - clientcmdapi "k8s.io/client-go/tools/clientcmd/api" -) - -// FromKubeConfig creates a Kubernetes endpoint from a Kubeconfig file -func FromKubeConfig(kubeconfig, kubeContext, namespaceOverride string) (Endpoint, error) { - cfg := clientcmd.NewNonInteractiveDeferredLoadingClientConfig( - &clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfig}, - &clientcmd.ConfigOverrides{CurrentContext: kubeContext, Context: clientcmdapi.Context{Namespace: namespaceOverride}}) - ns, _, err := cfg.Namespace() - if err != nil { - return Endpoint{}, err - } - clientcfg, err := cfg.ClientConfig() - if err != nil { - return Endpoint{}, err - } - - var proxyURLString string - if clientcfg.Proxy != nil { - proxyURL, err := clientcfg.Proxy(nil) - if err != nil { - return Endpoint{}, err - } - - proxyURLString = proxyURL.String() - } - - var ca, key, cert []byte - if ca, err = readFileOrDefault(clientcfg.CAFile, clientcfg.CAData); err != nil { - return Endpoint{}, err - } - if key, err = readFileOrDefault(clientcfg.KeyFile, clientcfg.KeyData); err != nil { - return Endpoint{}, err - } - if cert, err = readFileOrDefault(clientcfg.CertFile, clientcfg.CertData); err != nil { - return Endpoint{}, err - } - var tlsData *context.TLSData - if ca != nil || cert != nil || key != nil { - tlsData = &context.TLSData{ - CA: ca, - Cert: cert, - Key: key, - } - } - var usernamePassword *UsernamePassword - if clientcfg.Username != "" || clientcfg.Password != "" { - usernamePassword = &UsernamePassword{ - Username: clientcfg.Username, - Password: clientcfg.Password, - } - } - return Endpoint{ - EndpointMeta: EndpointMeta{ - EndpointMetaBase: context.EndpointMetaBase{ - Host: clientcfg.Host, - SkipTLSVerify: clientcfg.Insecure, - }, - DefaultNamespace: ns, - ProxyURL: proxyURLString, - AuthProvider: clientcfg.AuthProvider, - Exec: clientcfg.ExecProvider, - UsernamePassword: usernamePassword, - }, - TLSData: tlsData, - }, nil -} - -func readFileOrDefault(path string, defaultValue []byte) ([]byte, error) { - if path != "" { - return os.ReadFile(path) - } - return defaultValue, nil -} diff --git a/vendor/github.com/docker/buildx/driver/kubernetes/driver.go b/vendor/github.com/docker/buildx/driver/kubernetes/driver.go deleted file mode 100644 index 55c7853da..000000000 --- a/vendor/github.com/docker/buildx/driver/kubernetes/driver.go +++ /dev/null @@ -1,238 +0,0 @@ -package kubernetes - -import ( - "context" - "fmt" - "net" - "strings" - "time" - - "github.com/docker/buildx/driver" - "github.com/docker/buildx/driver/kubernetes/execconn" - "github.com/docker/buildx/driver/kubernetes/manifest" - "github.com/docker/buildx/driver/kubernetes/podchooser" - "github.com/docker/buildx/store" - "github.com/docker/buildx/util/platformutil" - "github.com/docker/buildx/util/progress" - "github.com/moby/buildkit/client" - "github.com/moby/buildkit/util/tracing/detect" - "github.com/pkg/errors" - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/kubernetes" - clientappsv1 "k8s.io/client-go/kubernetes/typed/apps/v1" - clientcorev1 "k8s.io/client-go/kubernetes/typed/core/v1" -) - -const ( - DriverName = "kubernetes" -) - -const ( - // valid values for driver-opt loadbalance - LoadbalanceRandom = "random" - LoadbalanceSticky = "sticky" -) - -type Driver struct { - driver.InitConfig - factory driver.Factory - minReplicas int - deployment *appsv1.Deployment - configMaps []*corev1.ConfigMap - clientset *kubernetes.Clientset - deploymentClient clientappsv1.DeploymentInterface - podClient clientcorev1.PodInterface - configMapClient clientcorev1.ConfigMapInterface - podChooser podchooser.PodChooser -} - -func (d *Driver) IsMobyDriver() bool { - return false -} - -func (d *Driver) Config() driver.InitConfig { - return d.InitConfig -} - -func (d *Driver) Bootstrap(ctx context.Context, l progress.Logger) error { - return progress.Wrap("[internal] booting buildkit", l, func(sub progress.SubLogger) error { - _, err := d.deploymentClient.Get(ctx, d.deployment.Name, metav1.GetOptions{}) - if err != nil { - if !apierrors.IsNotFound(err) { - return errors.Wrapf(err, "error for bootstrap %q", d.deployment.Name) - } - - for _, cfg := range d.configMaps { - // create ConfigMap first if exists - _, err = d.configMapClient.Create(ctx, cfg, metav1.CreateOptions{}) - if err != nil { - if !apierrors.IsAlreadyExists(err) { - return errors.Wrapf(err, "error while calling configMapClient.Create for %q", cfg.Name) - } - _, err = d.configMapClient.Update(ctx, cfg, metav1.UpdateOptions{}) - if err != nil { - return errors.Wrapf(err, "error while calling configMapClient.Update for %q", cfg.Name) - } - } - } - - _, err = d.deploymentClient.Create(ctx, d.deployment, metav1.CreateOptions{}) - if err != nil { - return errors.Wrapf(err, "error while calling deploymentClient.Create for %q", d.deployment.Name) - } - } - return sub.Wrap( - fmt.Sprintf("waiting for %d pods to be ready", d.minReplicas), - func() error { - if err := d.wait(ctx); err != nil { - return err - } - return nil - }) - }) -} - -func (d *Driver) wait(ctx context.Context) error { - // TODO: use watch API - var ( - err error - depl *appsv1.Deployment - ) - for try := 0; try < 100; try++ { - depl, err = d.deploymentClient.Get(ctx, d.deployment.Name, metav1.GetOptions{}) - if err == nil { - if depl.Status.ReadyReplicas >= int32(d.minReplicas) { - return nil - } - err = errors.Errorf("expected %d replicas to be ready, got %d", - d.minReplicas, depl.Status.ReadyReplicas) - } - select { - case <-ctx.Done(): - return ctx.Err() - case <-time.After(time.Duration(100+try*20) * time.Millisecond): - } - } - return err -} - -func (d *Driver) Info(ctx context.Context) (*driver.Info, error) { - depl, err := d.deploymentClient.Get(ctx, d.deployment.Name, metav1.GetOptions{}) - if err != nil { - // TODO: return err if err != ErrNotFound - return &driver.Info{ - Status: driver.Inactive, - }, nil - } - if depl.Status.ReadyReplicas <= 0 { - return &driver.Info{ - Status: driver.Stopped, - }, nil - } - pods, err := podchooser.ListRunningPods(ctx, d.podClient, depl) - if err != nil { - return nil, err - } - var dynNodes []store.Node - for _, p := range pods { - node := store.Node{ - Name: p.Name, - // Other fields are unset (TODO: detect real platforms) - } - - if p.Annotations != nil { - if p, ok := p.Annotations[manifest.AnnotationPlatform]; ok { - ps, err := platformutil.Parse(strings.Split(p, ",")) - if err == nil { - node.Platforms = ps - } - } - } - - dynNodes = append(dynNodes, node) - } - return &driver.Info{ - Status: driver.Running, - DynamicNodes: dynNodes, - }, nil -} - -func (d *Driver) Version(ctx context.Context) (string, error) { - return "", nil -} - -func (d *Driver) Stop(ctx context.Context, force bool) error { - // future version may scale the replicas to zero here - return nil -} - -func (d *Driver) Rm(ctx context.Context, force, rmVolume, rmDaemon bool) error { - if !rmDaemon { - return nil - } - - if err := d.deploymentClient.Delete(ctx, d.deployment.Name, metav1.DeleteOptions{}); err != nil { - if !apierrors.IsNotFound(err) { - return errors.Wrapf(err, "error while calling deploymentClient.Delete for %q", d.deployment.Name) - } - } - for _, cfg := range d.configMaps { - if err := d.configMapClient.Delete(ctx, cfg.Name, metav1.DeleteOptions{}); err != nil { - if !apierrors.IsNotFound(err) { - return errors.Wrapf(err, "error while calling configMapClient.Delete for %q", cfg.Name) - } - } - } - return nil -} - -func (d *Driver) Client(ctx context.Context) (*client.Client, error) { - restClient := d.clientset.CoreV1().RESTClient() - restClientConfig, err := d.KubeClientConfig.ClientConfig() - if err != nil { - return nil, err - } - pod, err := d.podChooser.ChoosePod(ctx) - if err != nil { - return nil, err - } - if len(pod.Spec.Containers) == 0 { - return nil, errors.Errorf("pod %s does not have any container", pod.Name) - } - containerName := pod.Spec.Containers[0].Name - cmd := []string{"buildctl", "dial-stdio"} - conn, err := execconn.ExecConn(ctx, restClient, restClientConfig, pod.Namespace, pod.Name, containerName, cmd) - if err != nil { - return nil, err - } - - exp, err := detect.Exporter() - if err != nil { - return nil, err - } - - var opts []client.ClientOpt - opts = append(opts, client.WithContextDialer(func(context.Context, string) (net.Conn, error) { - return conn, nil - })) - if td, ok := exp.(client.TracerDelegate); ok { - opts = append(opts, client.WithTracerDelegate(td)) - } - return client.New(ctx, "", opts...) -} - -func (d *Driver) Factory() driver.Factory { - return d.factory -} - -func (d *Driver) Features(ctx context.Context) map[driver.Feature]bool { - return map[driver.Feature]bool{ - driver.OCIExporter: true, - driver.DockerExporter: d.DockerAPI != nil, - driver.CacheExport: true, - driver.MultiPlatform: true, // Untested (needs multiple Driver instances) - } -} diff --git a/vendor/github.com/docker/buildx/driver/kubernetes/execconn/execconn.go b/vendor/github.com/docker/buildx/driver/kubernetes/execconn/execconn.go deleted file mode 100644 index 36c3eefa2..000000000 --- a/vendor/github.com/docker/buildx/driver/kubernetes/execconn/execconn.go +++ /dev/null @@ -1,136 +0,0 @@ -package execconn - -import ( - "context" - "io" - "net" - "os" - "sync" - "time" - - "github.com/sirupsen/logrus" - corev1 "k8s.io/api/core/v1" - "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/remotecommand" -) - -func ExecConn(ctx context.Context, restClient rest.Interface, restConfig *rest.Config, namespace, pod, container string, cmd []string) (net.Conn, error) { - req := restClient. - Post(). - Namespace(namespace). - Resource("pods"). - Name(pod). - SubResource("exec"). - VersionedParams(&corev1.PodExecOptions{ - Container: container, - Command: cmd, - Stdin: true, - Stdout: true, - Stderr: true, - TTY: false, - }, scheme.ParameterCodec) - exec, err := remotecommand.NewSPDYExecutor(restConfig, "POST", req.URL()) - if err != nil { - return nil, err - } - stdinR, stdinW := io.Pipe() - stdoutR, stdoutW := io.Pipe() - kc := &kubeConn{ - stdin: stdinW, - stdout: stdoutR, - localAddr: dummyAddr{network: "dummy", s: "dummy-0"}, - remoteAddr: dummyAddr{network: "dummy", s: "dummy-1"}, - } - go func() { - serr := exec.StreamWithContext(ctx, remotecommand.StreamOptions{ - Stdin: stdinR, - Stdout: stdoutW, - Stderr: os.Stderr, - Tty: false, - }) - if serr != nil && serr != context.Canceled { - logrus.Error(serr) - } - }() - return kc, nil -} - -type kubeConn struct { - stdin io.WriteCloser - stdout io.ReadCloser - stdioClosedMu sync.Mutex // for stdinClosed and stdoutClosed - stdinClosed bool - stdoutClosed bool - localAddr net.Addr - remoteAddr net.Addr -} - -func (c *kubeConn) Write(p []byte) (int, error) { - return c.stdin.Write(p) -} - -func (c *kubeConn) Read(p []byte) (int, error) { - return c.stdout.Read(p) -} - -func (c *kubeConn) CloseWrite() error { - err := c.stdin.Close() - c.stdioClosedMu.Lock() - c.stdinClosed = true - c.stdioClosedMu.Unlock() - return err -} -func (c *kubeConn) CloseRead() error { - err := c.stdout.Close() - c.stdioClosedMu.Lock() - c.stdoutClosed = true - c.stdioClosedMu.Unlock() - return err -} - -func (c *kubeConn) Close() error { - var err error - c.stdioClosedMu.Lock() - stdinClosed := c.stdinClosed - c.stdioClosedMu.Unlock() - if !stdinClosed { - err = c.CloseWrite() - } - c.stdioClosedMu.Lock() - stdoutClosed := c.stdoutClosed - c.stdioClosedMu.Unlock() - if !stdoutClosed { - err = c.CloseRead() - } - return err -} - -func (c *kubeConn) LocalAddr() net.Addr { - return c.localAddr -} -func (c *kubeConn) RemoteAddr() net.Addr { - return c.remoteAddr -} -func (c *kubeConn) SetDeadline(t time.Time) error { - return nil -} -func (c *kubeConn) SetReadDeadline(t time.Time) error { - return nil -} -func (c *kubeConn) SetWriteDeadline(t time.Time) error { - return nil -} - -type dummyAddr struct { - network string - s string -} - -func (d dummyAddr) Network() string { - return d.network -} - -func (d dummyAddr) String() string { - return d.s -} diff --git a/vendor/github.com/docker/buildx/driver/kubernetes/factory.go b/vendor/github.com/docker/buildx/driver/kubernetes/factory.go deleted file mode 100644 index 7b71d9b37..000000000 --- a/vendor/github.com/docker/buildx/driver/kubernetes/factory.go +++ /dev/null @@ -1,235 +0,0 @@ -package kubernetes - -import ( - "context" - "strconv" - "strings" - - corev1 "k8s.io/api/core/v1" - - "github.com/docker/buildx/driver" - "github.com/docker/buildx/driver/bkimage" - "github.com/docker/buildx/driver/kubernetes/manifest" - "github.com/docker/buildx/driver/kubernetes/podchooser" - dockerclient "github.com/docker/docker/client" - "github.com/pkg/errors" - "k8s.io/client-go/kubernetes" -) - -const prioritySupported = 40 -const priorityUnsupported = 80 - -func init() { - driver.Register(&factory{}) -} - -type factory struct { -} - -func (*factory) Name() string { - return DriverName -} - -func (*factory) Usage() string { - return DriverName -} - -func (*factory) Priority(ctx context.Context, endpoint string, api dockerclient.APIClient) int { - if api == nil { - return priorityUnsupported - } - return prioritySupported -} - -func (f *factory) New(ctx context.Context, cfg driver.InitConfig) (driver.Driver, error) { - if cfg.KubeClientConfig == nil { - return nil, errors.Errorf("%s driver requires kubernetes API access", DriverName) - } - deploymentName, err := buildxNameToDeploymentName(cfg.Name) - if err != nil { - return nil, err - } - namespace, _, err := cfg.KubeClientConfig.Namespace() - if err != nil { - return nil, errors.Wrap(err, "cannot determine Kubernetes namespace, specify manually") - } - restClientConfig, err := cfg.KubeClientConfig.ClientConfig() - if err != nil { - return nil, err - } - clientset, err := kubernetes.NewForConfig(restClientConfig) - if err != nil { - return nil, err - } - - d := &Driver{ - factory: f, - InitConfig: cfg, - clientset: clientset, - } - - deploymentOpt, loadbalance, namespace, err := f.processDriverOpts(deploymentName, namespace, cfg) - if nil != err { - return nil, err - } - - d.deployment, d.configMaps, err = manifest.NewDeployment(deploymentOpt) - if err != nil { - return nil, err - } - - d.minReplicas = deploymentOpt.Replicas - - d.deploymentClient = clientset.AppsV1().Deployments(namespace) - d.podClient = clientset.CoreV1().Pods(namespace) - d.configMapClient = clientset.CoreV1().ConfigMaps(namespace) - - switch loadbalance { - case LoadbalanceSticky: - d.podChooser = &podchooser.StickyPodChooser{ - Key: cfg.ContextPathHash, - PodClient: d.podClient, - Deployment: d.deployment, - } - case LoadbalanceRandom: - d.podChooser = &podchooser.RandomPodChooser{ - PodClient: d.podClient, - Deployment: d.deployment, - } - } - return d, nil -} - -func (f *factory) processDriverOpts(deploymentName string, namespace string, cfg driver.InitConfig) (*manifest.DeploymentOpt, string, string, error) { - deploymentOpt := &manifest.DeploymentOpt{ - Name: deploymentName, - Image: bkimage.DefaultImage, - Replicas: 1, - BuildkitFlags: cfg.BuildkitFlags, - Rootless: false, - Platforms: cfg.Platforms, - ConfigFiles: cfg.Files, - } - - deploymentOpt.Qemu.Image = bkimage.QemuImage - - loadbalance := LoadbalanceSticky - var err error - - for k, v := range cfg.DriverOpts { - switch k { - case "image": - if v != "" { - deploymentOpt.Image = v - } - case "namespace": - namespace = v - case "replicas": - deploymentOpt.Replicas, err = strconv.Atoi(v) - if err != nil { - return nil, "", "", err - } - case "requests.cpu": - deploymentOpt.RequestsCPU = v - case "requests.memory": - deploymentOpt.RequestsMemory = v - case "limits.cpu": - deploymentOpt.LimitsCPU = v - case "limits.memory": - deploymentOpt.LimitsMemory = v - case "rootless": - deploymentOpt.Rootless, err = strconv.ParseBool(v) - if err != nil { - return nil, "", "", err - } - if _, isImage := cfg.DriverOpts["image"]; !isImage { - deploymentOpt.Image = bkimage.DefaultRootlessImage - } - case "serviceaccount": - deploymentOpt.ServiceAccountName = v - case "nodeselector": - kvs := strings.Split(strings.Trim(v, `"`), ",") - s := map[string]string{} - for i := range kvs { - kv := strings.Split(kvs[i], "=") - if len(kv) == 2 { - s[kv[0]] = kv[1] - } - } - deploymentOpt.NodeSelector = s - case "tolerations": - ts := strings.Split(v, ";") - deploymentOpt.Tolerations = []corev1.Toleration{} - for i := range ts { - kvs := strings.Split(ts[i], ",") - - t := corev1.Toleration{} - - for j := range kvs { - kv := strings.Split(kvs[j], "=") - if len(kv) == 2 { - switch kv[0] { - case "key": - t.Key = kv[1] - case "operator": - t.Operator = corev1.TolerationOperator(kv[1]) - case "value": - t.Value = kv[1] - case "effect": - t.Effect = corev1.TaintEffect(kv[1]) - case "tolerationSeconds": - c, err := strconv.Atoi(kv[1]) - if nil != err { - return nil, "", "", err - } - c64 := int64(c) - t.TolerationSeconds = &c64 - default: - return nil, "", "", errors.Errorf("invalid tolaration %q", v) - } - } - } - - deploymentOpt.Tolerations = append(deploymentOpt.Tolerations, t) - } - case "loadbalance": - switch v { - case LoadbalanceSticky: - case LoadbalanceRandom: - default: - return nil, "", "", errors.Errorf("invalid loadbalance %q", v) - } - loadbalance = v - case "qemu.install": - deploymentOpt.Qemu.Install, err = strconv.ParseBool(v) - if err != nil { - return nil, "", "", err - } - case "qemu.image": - if v != "" { - deploymentOpt.Qemu.Image = v - } - default: - return nil, "", "", errors.Errorf("invalid driver option %s for driver %s", k, DriverName) - } - } - - return deploymentOpt, loadbalance, namespace, nil -} - -func (f *factory) AllowsInstances() bool { - return true -} - -// buildxNameToDeploymentName converts buildx name to Kubernetes Deployment name. -// -// eg. "buildx_buildkit_loving_mendeleev0" -> "loving-mendeleev0" -func buildxNameToDeploymentName(bx string) (string, error) { - // TODO: commands.util.go should not pass "buildx_buildkit_" prefix to drivers - if !strings.HasPrefix(bx, "buildx_buildkit_") { - return "", errors.Errorf("expected a string with \"buildx_buildkit_\", got %q", bx) - } - s := strings.TrimPrefix(bx, "buildx_buildkit_") - s = strings.ReplaceAll(s, "_", "-") - return s, nil -} diff --git a/vendor/github.com/docker/buildx/driver/kubernetes/manifest/manifest.go b/vendor/github.com/docker/buildx/driver/kubernetes/manifest/manifest.go deleted file mode 100644 index 5f5467c8f..000000000 --- a/vendor/github.com/docker/buildx/driver/kubernetes/manifest/manifest.go +++ /dev/null @@ -1,269 +0,0 @@ -package manifest - -import ( - "fmt" - "path" - "strings" - - "github.com/docker/buildx/util/platformutil" - v1 "github.com/opencontainers/image-spec/specs-go/v1" - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/resource" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -type DeploymentOpt struct { - Namespace string - Name string - Image string - Replicas int - ServiceAccountName string - - // Qemu - Qemu struct { - // when true, will install binfmt - Install bool - Image string - } - - BuildkitFlags []string - // files mounted at /etc/buildkitd - ConfigFiles map[string][]byte - - Rootless bool - NodeSelector map[string]string - Tolerations []corev1.Toleration - RequestsCPU string - RequestsMemory string - LimitsCPU string - LimitsMemory string - Platforms []v1.Platform -} - -const ( - containerName = "buildkitd" - AnnotationPlatform = "buildx.docker.com/platform" -) - -func NewDeployment(opt *DeploymentOpt) (d *appsv1.Deployment, c []*corev1.ConfigMap, err error) { - labels := map[string]string{ - "app": opt.Name, - } - annotations := map[string]string{} - replicas := int32(opt.Replicas) - privileged := true - args := opt.BuildkitFlags - - if len(opt.Platforms) > 0 { - annotations[AnnotationPlatform] = strings.Join(platformutil.Format(opt.Platforms), ",") - } - - d = &appsv1.Deployment{ - TypeMeta: metav1.TypeMeta{ - APIVersion: appsv1.SchemeGroupVersion.String(), - Kind: "Deployment", - }, - ObjectMeta: metav1.ObjectMeta{ - Namespace: opt.Namespace, - Name: opt.Name, - Labels: labels, - Annotations: annotations, - }, - Spec: appsv1.DeploymentSpec{ - Replicas: &replicas, - Selector: &metav1.LabelSelector{ - MatchLabels: labels, - }, - Template: corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: labels, - Annotations: annotations, - }, - Spec: corev1.PodSpec{ - ServiceAccountName: opt.ServiceAccountName, - Containers: []corev1.Container{ - { - Name: containerName, - Image: opt.Image, - Args: args, - SecurityContext: &corev1.SecurityContext{ - Privileged: &privileged, - }, - ReadinessProbe: &corev1.Probe{ - ProbeHandler: corev1.ProbeHandler{ - Exec: &corev1.ExecAction{ - Command: []string{"buildctl", "debug", "workers"}, - }, - }, - }, - Resources: corev1.ResourceRequirements{ - Requests: corev1.ResourceList{}, - Limits: corev1.ResourceList{}, - }, - }, - }, - }, - }, - }, - } - for _, cfg := range splitConfigFiles(opt.ConfigFiles) { - cc := &corev1.ConfigMap{ - TypeMeta: metav1.TypeMeta{ - APIVersion: corev1.SchemeGroupVersion.String(), - Kind: "ConfigMap", - }, - ObjectMeta: metav1.ObjectMeta{ - Namespace: opt.Namespace, - Name: opt.Name + "-" + cfg.name, - Annotations: annotations, - }, - Data: cfg.files, - } - - d.Spec.Template.Spec.Containers[0].VolumeMounts = []corev1.VolumeMount{{ - Name: cfg.name, - MountPath: path.Join("/etc/buildkit", cfg.path), - }} - - d.Spec.Template.Spec.Volumes = []corev1.Volume{{ - Name: "config", - VolumeSource: corev1.VolumeSource{ - ConfigMap: &corev1.ConfigMapVolumeSource{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: cc.Name, - }, - }, - }, - }} - c = append(c, cc) - } - - if opt.Qemu.Install { - d.Spec.Template.Spec.InitContainers = []corev1.Container{ - { - Name: "qemu", - Image: opt.Qemu.Image, - Args: []string{"--install", "all"}, - SecurityContext: &corev1.SecurityContext{ - Privileged: &privileged, - }, - }, - } - } - - if opt.Rootless { - if err := toRootless(d); err != nil { - return nil, nil, err - } - } - - if len(opt.NodeSelector) > 0 { - d.Spec.Template.Spec.NodeSelector = opt.NodeSelector - } - - if len(opt.Tolerations) > 0 { - d.Spec.Template.Spec.Tolerations = opt.Tolerations - } - - if opt.RequestsCPU != "" { - reqCPU, err := resource.ParseQuantity(opt.RequestsCPU) - if err != nil { - return nil, nil, err - } - d.Spec.Template.Spec.Containers[0].Resources.Requests[corev1.ResourceCPU] = reqCPU - } - - if opt.RequestsMemory != "" { - reqMemory, err := resource.ParseQuantity(opt.RequestsMemory) - if err != nil { - return nil, nil, err - } - d.Spec.Template.Spec.Containers[0].Resources.Requests[corev1.ResourceMemory] = reqMemory - } - - if opt.LimitsCPU != "" { - limCPU, err := resource.ParseQuantity(opt.LimitsCPU) - if err != nil { - return nil, nil, err - } - d.Spec.Template.Spec.Containers[0].Resources.Limits[corev1.ResourceCPU] = limCPU - } - - if opt.LimitsMemory != "" { - limMemory, err := resource.ParseQuantity(opt.LimitsMemory) - if err != nil { - return nil, nil, err - } - d.Spec.Template.Spec.Containers[0].Resources.Limits[corev1.ResourceMemory] = limMemory - } - - return -} - -func toRootless(d *appsv1.Deployment) error { - d.Spec.Template.Spec.Containers[0].Args = append( - d.Spec.Template.Spec.Containers[0].Args, - "--oci-worker-no-process-sandbox", - ) - d.Spec.Template.Spec.Containers[0].SecurityContext = &corev1.SecurityContext{ - SeccompProfile: &corev1.SeccompProfile{ - Type: corev1.SeccompProfileTypeUnconfined, - }, - } - if d.Spec.Template.ObjectMeta.Annotations == nil { - d.Spec.Template.ObjectMeta.Annotations = make(map[string]string, 1) - } - d.Spec.Template.ObjectMeta.Annotations["container.apparmor.security.beta.kubernetes.io/"+containerName] = "unconfined" - - // Dockerfile has `VOLUME /home/user/.local/share/buildkit` by default too, - // but the default VOLUME does not work with rootless on Google's Container-Optimized OS - // as it is mounted with `nosuid,nodev`. - // https://github.com/moby/buildkit/issues/879#issuecomment-1240347038 - // https://github.com/moby/buildkit/pull/3097 - const emptyDirVolName = "buildkitd" - d.Spec.Template.Spec.Containers[0].VolumeMounts = append(d.Spec.Template.Spec.Containers[0].VolumeMounts, corev1.VolumeMount{ - Name: emptyDirVolName, - MountPath: "/home/user/.local/share/buildkit", - }) - d.Spec.Template.Spec.Volumes = append(d.Spec.Template.Spec.Volumes, corev1.Volume{ - Name: emptyDirVolName, - VolumeSource: corev1.VolumeSource{ - EmptyDir: &corev1.EmptyDirVolumeSource{}, - }, - }) - - return nil -} - -type config struct { - name string - path string - files map[string]string -} - -func splitConfigFiles(m map[string][]byte) []config { - var c []config - idx := map[string]int{} - nameIdx := 0 - for k, v := range m { - dir := path.Dir(k) - i, ok := idx[dir] - if !ok { - idx[dir] = len(c) - i = len(c) - name := "config" - if dir != "." { - nameIdx++ - name = fmt.Sprintf("%s-%d", name, nameIdx) - } - c = append(c, config{ - path: dir, - name: name, - files: map[string]string{}, - }) - } - c[i].files[path.Base(k)] = string(v) - } - return c -} diff --git a/vendor/github.com/docker/buildx/driver/kubernetes/podchooser/podchooser.go b/vendor/github.com/docker/buildx/driver/kubernetes/podchooser/podchooser.go deleted file mode 100644 index 06a294417..000000000 --- a/vendor/github.com/docker/buildx/driver/kubernetes/podchooser/podchooser.go +++ /dev/null @@ -1,101 +0,0 @@ -package podchooser - -import ( - "context" - "math/rand" - "sort" - "time" - - "github.com/pkg/errors" - "github.com/serialx/hashring" - "github.com/sirupsen/logrus" - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - clientcorev1 "k8s.io/client-go/kubernetes/typed/core/v1" -) - -type PodChooser interface { - ChoosePod(ctx context.Context) (*corev1.Pod, error) -} - -type RandomPodChooser struct { - RandSource rand.Source - PodClient clientcorev1.PodInterface - Deployment *appsv1.Deployment -} - -func (pc *RandomPodChooser) ChoosePod(ctx context.Context) (*corev1.Pod, error) { - pods, err := ListRunningPods(ctx, pc.PodClient, pc.Deployment) - if err != nil { - return nil, err - } - if len(pods) == 0 { - return nil, errors.New("no running buildkit pods found") - } - randSource := pc.RandSource - if randSource == nil { - randSource = rand.NewSource(time.Now().Unix()) - } - rnd := rand.New(randSource) //nolint:gosec // no strong seeding required - n := rnd.Int() % len(pods) - logrus.Debugf("RandomPodChooser.ChoosePod(): len(pods)=%d, n=%d", len(pods), n) - return pods[n], nil -} - -type StickyPodChooser struct { - Key string - PodClient clientcorev1.PodInterface - Deployment *appsv1.Deployment -} - -func (pc *StickyPodChooser) ChoosePod(ctx context.Context) (*corev1.Pod, error) { - pods, err := ListRunningPods(ctx, pc.PodClient, pc.Deployment) - if err != nil { - return nil, err - } - var podNames []string - podMap := make(map[string]*corev1.Pod, len(pods)) - for _, pod := range pods { - podNames = append(podNames, pod.Name) - podMap[pod.Name] = pod - } - ring := hashring.New(podNames) - chosen, ok := ring.GetNode(pc.Key) - if !ok { - // NOTREACHED - logrus.Errorf("no pod found for key %q", pc.Key) - rpc := &RandomPodChooser{ - PodClient: pc.PodClient, - Deployment: pc.Deployment, - } - return rpc.ChoosePod(ctx) - } - return podMap[chosen], nil -} - -func ListRunningPods(ctx context.Context, client clientcorev1.PodInterface, depl *appsv1.Deployment) ([]*corev1.Pod, error) { - selector, err := metav1.LabelSelectorAsSelector(depl.Spec.Selector) - if err != nil { - return nil, err - } - listOpts := metav1.ListOptions{ - LabelSelector: selector.String(), - } - podList, err := client.List(ctx, listOpts) - if err != nil { - return nil, err - } - var runningPods []*corev1.Pod - for i := range podList.Items { - pod := &podList.Items[i] - if pod.Status.Phase == corev1.PodRunning { - logrus.Debugf("pod runnning: %q", pod.Name) - runningPods = append(runningPods, pod) - } - } - sort.Slice(runningPods, func(i, j int) bool { - return runningPods[i].Name < runningPods[j].Name - }) - return runningPods, nil -} diff --git a/vendor/github.com/docker/buildx/driver/manager.go b/vendor/github.com/docker/buildx/driver/manager.go deleted file mode 100644 index b4ec318f3..000000000 --- a/vendor/github.com/docker/buildx/driver/manager.go +++ /dev/null @@ -1,216 +0,0 @@ -package driver - -import ( - "context" - "net" - "os" - "sort" - "strings" - "sync" - - dockerclient "github.com/docker/docker/client" - "github.com/moby/buildkit/client" - specs "github.com/opencontainers/image-spec/specs-go/v1" - "github.com/pkg/errors" - "k8s.io/client-go/rest" -) - -type Factory interface { - Name() string - Usage() string - Priority(ctx context.Context, endpoint string, api dockerclient.APIClient) int - New(ctx context.Context, cfg InitConfig) (Driver, error) - AllowsInstances() bool -} - -type BuildkitConfig struct { - // Entitlements []string - // Rootless bool -} - -type KubeClientConfig interface { - ClientConfig() (*rest.Config, error) - Namespace() (string, bool, error) -} - -type KubeClientConfigInCluster struct{} - -func (k KubeClientConfigInCluster) ClientConfig() (*rest.Config, error) { - return rest.InClusterConfig() -} - -func (k KubeClientConfigInCluster) Namespace() (string, bool, error) { - namespace, err := os.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace") - if err != nil { - return "", false, err - } - return strings.TrimSpace(string(namespace)), true, nil -} - -type InitConfig struct { - // This object needs updates to be generic for different drivers - Name string - EndpointAddr string - DockerAPI dockerclient.APIClient - KubeClientConfig KubeClientConfig - BuildkitFlags []string - Files map[string][]byte - DriverOpts map[string]string - Auth Auth - Platforms []specs.Platform - // ContextPathHash can be used for determining pods in the driver instance - ContextPathHash string -} - -var drivers map[string]Factory - -func Register(f Factory) { - if drivers == nil { - drivers = map[string]Factory{} - } - drivers[f.Name()] = f -} - -func GetDefaultFactory(ctx context.Context, ep string, c dockerclient.APIClient, instanceRequired bool) (Factory, error) { - if len(drivers) == 0 { - return nil, errors.Errorf("no drivers available") - } - type p struct { - f Factory - priority int - } - dd := make([]p, 0, len(drivers)) - for _, f := range drivers { - if instanceRequired && !f.AllowsInstances() { - continue - } - dd = append(dd, p{f: f, priority: f.Priority(ctx, ep, c)}) - } - sort.Slice(dd, func(i, j int) bool { - return dd[i].priority < dd[j].priority - }) - return dd[0].f, nil -} - -func GetFactory(name string, instanceRequired bool) (Factory, error) { - for _, f := range drivers { - if f.Name() == name { - if instanceRequired && !f.AllowsInstances() { - return nil, errors.Errorf("additional instances of driver %q cannot be created", name) - } - return f, nil - } - } - return nil, errors.Errorf("failed to find driver %q", name) -} - -func GetDriver(ctx context.Context, name string, f Factory, endpointAddr string, api dockerclient.APIClient, auth Auth, kcc KubeClientConfig, flags []string, files map[string][]byte, do map[string]string, platforms []specs.Platform, contextPathHash string) (*DriverHandle, error) { - ic := InitConfig{ - EndpointAddr: endpointAddr, - DockerAPI: api, - KubeClientConfig: kcc, - Name: name, - BuildkitFlags: flags, - DriverOpts: do, - Auth: auth, - Platforms: platforms, - ContextPathHash: contextPathHash, - Files: files, - } - if f == nil { - var err error - f, err = GetDefaultFactory(ctx, endpointAddr, api, false) - if err != nil { - return nil, err - } - } - d, err := f.New(ctx, ic) - if err != nil { - return nil, err - } - return &DriverHandle{Driver: d}, nil -} - -func GetFactories(instanceRequired bool) []Factory { - ds := make([]Factory, 0, len(drivers)) - for _, d := range drivers { - if instanceRequired && !d.AllowsInstances() { - continue - } - ds = append(ds, d) - } - sort.Slice(ds, func(i, j int) bool { - return ds[i].Name() < ds[j].Name() - }) - return ds -} - -type DriverHandle struct { - Driver - client *client.Client - err error - once sync.Once - featuresOnce sync.Once - features map[Feature]bool - historyAPISupportedOnce sync.Once - historyAPISupported bool - hostGatewayIPOnce sync.Once - hostGatewayIP net.IP - hostGatewayIPErr error -} - -func (d *DriverHandle) Client(ctx context.Context) (*client.Client, error) { - d.once.Do(func() { - d.client, d.err = d.Driver.Client(ctx) - }) - return d.client, d.err -} - -func (d *DriverHandle) Features(ctx context.Context) map[Feature]bool { - d.featuresOnce.Do(func() { - d.features = d.Driver.Features(ctx) - }) - return d.features -} - -func (d *DriverHandle) HistoryAPISupported(ctx context.Context) bool { - d.historyAPISupportedOnce.Do(func() { - if c, err := d.Client(ctx); err == nil { - d.historyAPISupported = historyAPISupported(ctx, c) - } - }) - return d.historyAPISupported -} - -func (d *DriverHandle) HostGatewayIP(ctx context.Context) (net.IP, error) { - d.hostGatewayIPOnce.Do(func() { - if !d.Driver.IsMobyDriver() { - d.hostGatewayIPErr = errors.New("host-gateway is only supported with the docker driver") - return - } - c, err := d.Client(ctx) - if err != nil { - d.hostGatewayIPErr = err - return - } - workers, err := c.ListWorkers(ctx) - if err != nil { - d.hostGatewayIPErr = errors.Wrap(err, "listing workers") - return - } - for _, w := range workers { - // should match github.com/docker/docker/builder/builder-next/worker/label.HostGatewayIP const - if v, ok := w.Labels["org.mobyproject.buildkit.worker.moby.host-gateway-ip"]; ok && v != "" { - ip := net.ParseIP(v) - if ip == nil { - d.hostGatewayIPErr = errors.Errorf("failed to parse host-gateway IP: %s", v) - return - } - d.hostGatewayIP = ip - return - } - } - d.hostGatewayIPErr = errors.New("host-gateway IP not found") - }) - return d.hostGatewayIP, d.hostGatewayIPErr -} diff --git a/vendor/github.com/docker/buildx/driver/remote/driver.go b/vendor/github.com/docker/buildx/driver/remote/driver.go deleted file mode 100644 index fa5cfcc5a..000000000 --- a/vendor/github.com/docker/buildx/driver/remote/driver.go +++ /dev/null @@ -1,109 +0,0 @@ -package remote - -import ( - "context" - "time" - - "github.com/docker/buildx/driver" - "github.com/docker/buildx/util/progress" - "github.com/moby/buildkit/client" -) - -type Driver struct { - factory driver.Factory - driver.InitConfig - *tlsOpts -} - -type tlsOpts struct { - serverName string - caCert string - cert string - key string -} - -func (d *Driver) Bootstrap(ctx context.Context, l progress.Logger) error { - for i := 0; ; i++ { - info, err := d.Info(ctx) - if err != nil { - return err - } - if info.Status != driver.Inactive { - return nil - } - - select { - case <-ctx.Done(): - return ctx.Err() - default: - if i > 10 { - i = 10 - } - time.Sleep(time.Duration(i) * time.Second) - } - } -} - -func (d *Driver) Info(ctx context.Context) (*driver.Info, error) { - c, err := d.Client(ctx) - if err != nil { - return &driver.Info{ - Status: driver.Inactive, - }, nil - } - - if _, err := c.ListWorkers(ctx); err != nil { - return &driver.Info{ - Status: driver.Inactive, - }, nil - } - - return &driver.Info{ - Status: driver.Running, - }, nil -} - -func (d *Driver) Version(ctx context.Context) (string, error) { - return "", nil -} - -func (d *Driver) Stop(ctx context.Context, force bool) error { - return nil -} - -func (d *Driver) Rm(ctx context.Context, force, rmVolume, rmDaemon bool) error { - return nil -} - -func (d *Driver) Client(ctx context.Context) (*client.Client, error) { - opts := []client.ClientOpt{} - if d.tlsOpts != nil { - opts = append(opts, []client.ClientOpt{ - client.WithServerConfig(d.tlsOpts.serverName, d.tlsOpts.caCert), - client.WithCredentials(d.tlsOpts.cert, d.tlsOpts.key), - }...) - } - - return client.New(ctx, d.InitConfig.EndpointAddr, opts...) -} - -func (d *Driver) Features(ctx context.Context) map[driver.Feature]bool { - return map[driver.Feature]bool{ - driver.OCIExporter: true, - driver.DockerExporter: true, - driver.CacheExport: true, - driver.MultiPlatform: true, - } -} - -func (d *Driver) Factory() driver.Factory { - return d.factory -} - -func (d *Driver) IsMobyDriver() bool { - return false -} - -func (d *Driver) Config() driver.InitConfig { - return d.InitConfig -} diff --git a/vendor/github.com/docker/buildx/driver/remote/factory.go b/vendor/github.com/docker/buildx/driver/remote/factory.go deleted file mode 100644 index 374d97d5b..000000000 --- a/vendor/github.com/docker/buildx/driver/remote/factory.go +++ /dev/null @@ -1,118 +0,0 @@ -package remote - -import ( - "context" - "net/url" - "path/filepath" - "strings" - - // import connhelpers for special url schemes - _ "github.com/moby/buildkit/client/connhelper/dockercontainer" - _ "github.com/moby/buildkit/client/connhelper/kubepod" - _ "github.com/moby/buildkit/client/connhelper/ssh" - - "github.com/docker/buildx/driver" - util "github.com/docker/buildx/driver/remote/util" - dockerclient "github.com/docker/docker/client" - "github.com/pkg/errors" -) - -const prioritySupported = 20 -const priorityUnsupported = 90 - -func init() { - driver.Register(&factory{}) -} - -type factory struct { -} - -func (*factory) Name() string { - return "remote" -} - -func (*factory) Usage() string { - return "remote" -} - -func (*factory) Priority(ctx context.Context, endpoint string, api dockerclient.APIClient) int { - if util.IsValidEndpoint(endpoint) != nil { - return priorityUnsupported - } - return prioritySupported -} - -func (f *factory) New(ctx context.Context, cfg driver.InitConfig) (driver.Driver, error) { - if len(cfg.Files) > 0 { - return nil, errors.Errorf("setting config file is not supported for remote driver") - } - if len(cfg.BuildkitFlags) > 0 { - return nil, errors.Errorf("setting buildkit flags is not supported for remote driver") - } - - d := &Driver{ - factory: f, - InitConfig: cfg, - } - - tls := &tlsOpts{} - tlsEnabled := false - for k, v := range cfg.DriverOpts { - switch k { - case "servername": - tls.serverName = v - tlsEnabled = true - case "cacert": - if !filepath.IsAbs(v) { - return nil, errors.Errorf("non-absolute path '%s' provided for %s", v, k) - } - tls.caCert = v - tlsEnabled = true - case "cert": - if !filepath.IsAbs(v) { - return nil, errors.Errorf("non-absolute path '%s' provided for %s", v, k) - } - tls.cert = v - tlsEnabled = true - case "key": - if !filepath.IsAbs(v) { - return nil, errors.Errorf("non-absolute path '%s' provided for %s", v, k) - } - tls.key = v - tlsEnabled = true - default: - return nil, errors.Errorf("invalid driver option %s for remote driver", k) - } - } - - if tlsEnabled { - if tls.serverName == "" { - // guess servername as hostname of target address - uri, err := url.Parse(cfg.EndpointAddr) - if err != nil { - return nil, err - } - tls.serverName = uri.Hostname() - } - missing := []string{} - if tls.caCert == "" { - missing = append(missing, "cacert") - } - if tls.cert != "" && tls.key == "" { - missing = append(missing, "key") - } - if tls.key != "" && tls.cert == "" { - missing = append(missing, "cert") - } - if len(missing) > 0 { - return nil, errors.Errorf("tls enabled, but missing keys %s", strings.Join(missing, ", ")) - } - d.tlsOpts = tls - } - - return d, nil -} - -func (f *factory) AllowsInstances() bool { - return true -} diff --git a/vendor/github.com/docker/buildx/driver/remote/util/endpoint.go b/vendor/github.com/docker/buildx/driver/remote/util/endpoint.go deleted file mode 100644 index 3b535f525..000000000 --- a/vendor/github.com/docker/buildx/driver/remote/util/endpoint.go +++ /dev/null @@ -1,26 +0,0 @@ -package remote - -import ( - "net/url" - - "github.com/pkg/errors" -) - -var schemes = map[string]struct{}{ - "tcp": {}, - "unix": {}, - "ssh": {}, - "docker-container": {}, - "kube-pod": {}, -} - -func IsValidEndpoint(ep string) error { - endpoint, err := url.Parse(ep) - if err != nil { - return errors.Wrapf(err, "failed to parse endpoint %s", ep) - } - if _, ok := schemes[endpoint.Scheme]; !ok { - return errors.Errorf("unrecognized url scheme %s", endpoint.Scheme) - } - return nil -} diff --git a/vendor/github.com/docker/buildx/localstate/localstate.go b/vendor/github.com/docker/buildx/localstate/localstate.go deleted file mode 100644 index 49b7a0b66..000000000 --- a/vendor/github.com/docker/buildx/localstate/localstate.go +++ /dev/null @@ -1,93 +0,0 @@ -package localstate - -import ( - "encoding/json" - "os" - "path/filepath" - - "github.com/docker/docker/pkg/ioutils" - "github.com/pkg/errors" -) - -const refsDir = "refs" - -type State struct { - LocalPath string - DockerfilePath string -} - -type LocalState struct { - root string -} - -func New(root string) (*LocalState, error) { - if root == "" { - return nil, errors.Errorf("root dir empty") - } - if err := os.MkdirAll(filepath.Join(root, refsDir), 0700); err != nil { - return nil, err - } - return &LocalState{ - root: root, - }, nil -} - -func (ls *LocalState) ReadRef(builderName, nodeName, id string) (*State, error) { - if err := ls.validate(builderName, nodeName, id); err != nil { - return nil, err - } - dt, err := os.ReadFile(filepath.Join(ls.root, refsDir, builderName, nodeName, id)) - if err != nil { - return nil, err - } - var st State - if err := json.Unmarshal(dt, &st); err != nil { - return nil, err - } - return &st, nil -} - -func (ls *LocalState) SaveRef(builderName, nodeName, id string, st State) error { - if err := ls.validate(builderName, nodeName, id); err != nil { - return err - } - refDir := filepath.Join(ls.root, refsDir, builderName, nodeName) - if err := os.MkdirAll(refDir, 0700); err != nil { - return err - } - dt, err := json.Marshal(st) - if err != nil { - return err - } - return ioutils.AtomicWriteFile(filepath.Join(refDir, id), dt, 0600) -} - -func (ls *LocalState) RemoveBuilder(builderName string) error { - if builderName == "" { - return errors.Errorf("builder name empty") - } - return os.RemoveAll(filepath.Join(ls.root, refsDir, builderName)) -} - -func (ls *LocalState) RemoveBuilderNode(builderName string, nodeName string) error { - if builderName == "" { - return errors.Errorf("builder name empty") - } - if nodeName == "" { - return errors.Errorf("node name empty") - } - return os.RemoveAll(filepath.Join(ls.root, refsDir, builderName, nodeName)) -} - -func (ls *LocalState) validate(builderName, nodeName, id string) error { - if builderName == "" { - return errors.Errorf("builder name empty") - } - if nodeName == "" { - return errors.Errorf("node name empty") - } - if id == "" { - return errors.Errorf("ref ID empty") - } - return nil -} diff --git a/vendor/github.com/docker/buildx/store/nodegroup.go b/vendor/github.com/docker/buildx/store/nodegroup.go deleted file mode 100644 index 823470dd4..000000000 --- a/vendor/github.com/docker/buildx/store/nodegroup.go +++ /dev/null @@ -1,230 +0,0 @@ -package store - -import ( - "fmt" - "time" - - "github.com/containerd/containerd/platforms" - "github.com/docker/buildx/util/confutil" - "github.com/docker/buildx/util/platformutil" - specs "github.com/opencontainers/image-spec/specs-go/v1" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" -) - -type NodeGroup struct { - Name string - Driver string - Nodes []Node - Dynamic bool - - // skip the following fields from being saved in the store - DockerContext bool `json:"-"` - LastActivity time.Time `json:"-"` -} - -type Node struct { - Name string - Endpoint string - Platforms []specs.Platform - Flags []string - DriverOpts map[string]string - - Files map[string][]byte -} - -func (ng *NodeGroup) Leave(name string) error { - if ng.Dynamic { - return errors.New("dynamic node group does not support Leave") - } - i := ng.findNode(name) - if i == -1 { - return errors.Errorf("node %q not found for %s", name, ng.Name) - } - if len(ng.Nodes) == 1 { - return errors.Errorf("can not leave last node, do you want to rm instance instead?") - } - ng.Nodes = append(ng.Nodes[:i], ng.Nodes[i+1:]...) - return nil -} - -func (ng *NodeGroup) Update(name, endpoint string, platforms []string, endpointsSet bool, actionAppend bool, flags []string, configFile string, do map[string]string) error { - if ng.Dynamic { - return errors.New("dynamic node group does not support Update") - } - i := ng.findNode(name) - if i == -1 && !actionAppend { - if len(ng.Nodes) > 0 { - return errors.Errorf("node %s not found, did you mean to append?", name) - } - ng.Nodes = nil - } - - pp, err := platformutil.Parse(platforms) - if err != nil { - return err - } - - var files map[string][]byte - if configFile != "" { - files, err = confutil.LoadConfigFiles(configFile) - if err != nil { - return err - } - } - - if i != -1 { - n := ng.Nodes[i] - needsRestart := false - if endpointsSet { - n.Endpoint = endpoint - needsRestart = true - } - if len(platforms) > 0 { - n.Platforms = pp - } - if flags != nil { - n.Flags = flags - needsRestart = true - } - if do != nil { - n.DriverOpts = do - needsRestart = true - } - if configFile != "" { - for k, v := range files { - n.Files[k] = v - } - needsRestart = true - } - if needsRestart { - logrus.Warn("new settings may not be used until builder is restarted") - } - - ng.Nodes[i] = n - if err := ng.validateDuplicates(endpoint, i); err != nil { - return err - } - return nil - } - - if name == "" { - name = ng.nextNodeName() - } - - name, err = ValidateName(name) - if err != nil { - return err - } - - n := Node{ - Name: name, - Endpoint: endpoint, - Platforms: pp, - Flags: flags, - DriverOpts: do, - Files: files, - } - - ng.Nodes = append(ng.Nodes, n) - - if err := ng.validateDuplicates(endpoint, len(ng.Nodes)-1); err != nil { - return err - } - return nil -} - -func (ng *NodeGroup) Copy() *NodeGroup { - nodes := make([]Node, len(ng.Nodes)) - for i, node := range ng.Nodes { - nodes[i] = *node.Copy() - } - return &NodeGroup{ - Name: ng.Name, - Driver: ng.Driver, - Nodes: nodes, - Dynamic: ng.Dynamic, - } -} - -func (n *Node) Copy() *Node { - platforms := []specs.Platform{} - copy(platforms, n.Platforms) - flags := []string{} - copy(flags, n.Flags) - driverOpts := map[string]string{} - for k, v := range n.DriverOpts { - driverOpts[k] = v - } - files := map[string][]byte{} - for k, v := range n.Files { - vv := []byte{} - copy(vv, v) - files[k] = vv - } - return &Node{ - Name: n.Name, - Endpoint: n.Endpoint, - Platforms: platforms, - Flags: flags, - DriverOpts: driverOpts, - Files: files, - } -} - -func (ng *NodeGroup) validateDuplicates(ep string, idx int) error { - i := 0 - for _, n := range ng.Nodes { - if n.Endpoint == ep { - i++ - } - } - if i > 1 { - return errors.Errorf("invalid duplicate endpoint %s", ep) - } - - m := map[string]struct{}{} - for _, p := range ng.Nodes[idx].Platforms { - m[platforms.Format(p)] = struct{}{} - } - - for i := range ng.Nodes { - if i == idx { - continue - } - ng.Nodes[i].Platforms = filterPlatforms(ng.Nodes[i].Platforms, m) - } - - return nil -} - -func (ng *NodeGroup) findNode(name string) int { - for i, n := range ng.Nodes { - if n.Name == name { - return i - } - } - return -1 -} - -func (ng *NodeGroup) nextNodeName() string { - i := 0 - for { - name := fmt.Sprintf("%s%d", ng.Name, i) - if ii := ng.findNode(name); ii != -1 { - i++ - continue - } - return name - } -} - -func filterPlatforms(in []specs.Platform, m map[string]struct{}) []specs.Platform { - out := make([]specs.Platform, 0, len(in)) - for _, p := range in { - if _, ok := m[platforms.Format(p)]; !ok { - out = append(out, p) - } - } - return out -} diff --git a/vendor/github.com/docker/buildx/store/store.go b/vendor/github.com/docker/buildx/store/store.go deleted file mode 100644 index 2d4b0b12e..000000000 --- a/vendor/github.com/docker/buildx/store/store.go +++ /dev/null @@ -1,253 +0,0 @@ -package store - -import ( - "encoding/json" - "os" - "path/filepath" - "sort" - "time" - - "github.com/docker/buildx/localstate" - "github.com/docker/docker/pkg/ioutils" - "github.com/gofrs/flock" - "github.com/opencontainers/go-digest" - "github.com/pkg/errors" -) - -const ( - instanceDir = "instances" - defaultsDir = "defaults" - activityDir = "activity" -) - -func New(root string) (*Store, error) { - if err := os.MkdirAll(filepath.Join(root, instanceDir), 0700); err != nil { - return nil, err - } - if err := os.MkdirAll(filepath.Join(root, defaultsDir), 0700); err != nil { - return nil, err - } - if err := os.MkdirAll(filepath.Join(root, activityDir), 0700); err != nil { - return nil, err - } - return &Store{root: root}, nil -} - -type Store struct { - root string -} - -func (s *Store) Txn() (*Txn, func(), error) { - l := flock.New(filepath.Join(s.root, ".lock")) - if err := l.Lock(); err != nil { - return nil, nil, err - } - return &Txn{ - s: s, - }, func() { - l.Close() - }, nil -} - -type Txn struct { - s *Store -} - -func (t *Txn) List() ([]*NodeGroup, error) { - pp := filepath.Join(t.s.root, instanceDir) - fis, err := os.ReadDir(pp) - if err != nil { - return nil, err - } - ngs := make([]*NodeGroup, 0, len(fis)) - for _, fi := range fis { - ng, err := t.NodeGroupByName(fi.Name()) - if err != nil { - if os.IsNotExist(errors.Cause(err)) { - os.RemoveAll(filepath.Join(pp, fi.Name())) - continue - } - return nil, err - } - ngs = append(ngs, ng) - } - - sort.Slice(ngs, func(i, j int) bool { - return ngs[i].Name < ngs[j].Name - }) - - return ngs, nil -} - -func (t *Txn) NodeGroupByName(name string) (*NodeGroup, error) { - name, err := ValidateName(name) - if err != nil { - return nil, err - } - dt, err := os.ReadFile(filepath.Join(t.s.root, instanceDir, name)) - if err != nil { - return nil, err - } - var ng NodeGroup - if err := json.Unmarshal(dt, &ng); err != nil { - return nil, err - } - if ng.LastActivity, err = t.GetLastActivity(&ng); err != nil { - return nil, err - } - return &ng, nil -} - -func (t *Txn) Save(ng *NodeGroup) error { - name, err := ValidateName(ng.Name) - if err != nil { - return err - } - if err := t.UpdateLastActivity(ng); err != nil { - return err - } - dt, err := json.Marshal(ng) - if err != nil { - return err - } - return ioutils.AtomicWriteFile(filepath.Join(t.s.root, instanceDir, name), dt, 0600) -} - -func (t *Txn) Remove(name string) error { - name, err := ValidateName(name) - if err != nil { - return err - } - if err := t.RemoveLastActivity(name); err != nil { - return err - } - ls, err := localstate.New(t.s.root) - if err != nil { - return err - } - if err := ls.RemoveBuilder(name); err != nil { - return err - } - return os.RemoveAll(filepath.Join(t.s.root, instanceDir, name)) -} - -func (t *Txn) SetCurrent(key, name string, global, def bool) error { - c := current{ - Key: key, - Name: name, - Global: global, - } - dt, err := json.Marshal(c) - if err != nil { - return err - } - if err := ioutils.AtomicWriteFile(filepath.Join(t.s.root, "current"), dt, 0600); err != nil { - return err - } - - h := toHash(key) - - if def { - if err := ioutils.AtomicWriteFile(filepath.Join(t.s.root, defaultsDir, h), []byte(name), 0600); err != nil { - return err - } - } else { - os.RemoveAll(filepath.Join(t.s.root, defaultsDir, h)) // ignore error - } - return nil -} - -func (t *Txn) UpdateLastActivity(ng *NodeGroup) error { - return ioutils.AtomicWriteFile(filepath.Join(t.s.root, activityDir, ng.Name), []byte(time.Now().UTC().Format(time.RFC3339)), 0600) -} - -func (t *Txn) GetLastActivity(ng *NodeGroup) (la time.Time, _ error) { - dt, err := os.ReadFile(filepath.Join(t.s.root, activityDir, ng.Name)) - if err != nil { - if os.IsNotExist(errors.Cause(err)) { - return la, nil - } - return la, err - } - return time.Parse(time.RFC3339, string(dt)) -} - -func (t *Txn) RemoveLastActivity(name string) error { - name, err := ValidateName(name) - if err != nil { - return err - } - return os.RemoveAll(filepath.Join(t.s.root, activityDir, name)) -} - -func (t *Txn) reset(key string) error { - dt, err := json.Marshal(current{Key: key}) - if err != nil { - return err - } - if err := ioutils.AtomicWriteFile(filepath.Join(t.s.root, "current"), dt, 0600); err != nil { - return err - } - return nil -} - -func (t *Txn) Current(key string) (*NodeGroup, error) { - dt, err := os.ReadFile(filepath.Join(t.s.root, "current")) - if err != nil { - if !os.IsNotExist(err) { - return nil, err - } - } - if err == nil { - var c current - if err := json.Unmarshal(dt, &c); err != nil { - return nil, err - } - if c.Name != "" { - if c.Global { - ng, err := t.NodeGroupByName(c.Name) - if err == nil { - return ng, nil - } - } - - if c.Key == key { - ng, err := t.NodeGroupByName(c.Name) - if err == nil { - return ng, nil - } - return nil, nil - } - } - } - - h := toHash(key) - - dt, err = os.ReadFile(filepath.Join(t.s.root, defaultsDir, h)) - if err != nil { - if os.IsNotExist(err) { - t.reset(key) - return nil, nil - } - return nil, err - } - - ng, err := t.NodeGroupByName(string(dt)) - if err != nil { - t.reset(key) - } - if err := t.SetCurrent(key, string(dt), false, true); err != nil { - return nil, err - } - return ng, nil -} - -type current struct { - Key string - Name string - Global bool -} - -func toHash(in string) string { - return digest.FromBytes([]byte(in)).Hex()[:20] -} diff --git a/vendor/github.com/docker/buildx/store/storeutil/storeutil.go b/vendor/github.com/docker/buildx/store/storeutil/storeutil.go deleted file mode 100644 index 41e7c264a..000000000 --- a/vendor/github.com/docker/buildx/store/storeutil/storeutil.go +++ /dev/null @@ -1,161 +0,0 @@ -package storeutil - -import ( - "bytes" - "os" - "strings" - - "github.com/docker/buildx/store" - "github.com/docker/buildx/util/confutil" - "github.com/docker/buildx/util/dockerutil" - "github.com/docker/buildx/util/imagetools" - "github.com/docker/buildx/util/resolver" - "github.com/docker/cli/cli/command" - buildkitdconfig "github.com/moby/buildkit/cmd/buildkitd/config" - "github.com/pkg/errors" -) - -// GetStore returns current builder instance store -func GetStore(dockerCli command.Cli) (*store.Txn, func(), error) { - s, err := store.New(confutil.ConfigDir(dockerCli)) - if err != nil { - return nil, nil, err - } - return s.Txn() -} - -func GetProxyConfig(dockerCli command.Cli) map[string]string { - cfg := dockerCli.ConfigFile() - host := dockerCli.Client().DaemonHost() - - proxy, ok := cfg.Proxies[host] - if !ok { - proxy = cfg.Proxies["default"] - } - - m := map[string]string{} - - if v := proxy.HTTPProxy; v != "" { - m["HTTP_PROXY"] = v - } - if v := proxy.HTTPSProxy; v != "" { - m["HTTPS_PROXY"] = v - } - if v := proxy.NoProxy; v != "" { - m["NO_PROXY"] = v - } - if v := proxy.FTPProxy; v != "" { - m["FTP_PROXY"] = v - } - return m -} - -// GetCurrentInstance finds the current builder instance -func GetCurrentInstance(txn *store.Txn, dockerCli command.Cli) (*store.NodeGroup, error) { - ep, err := dockerutil.GetCurrentEndpoint(dockerCli) - if err != nil { - return nil, err - } - ng, err := txn.Current(ep) - if err != nil { - return nil, err - } - if ng == nil { - ng, err = GetNodeGroup(txn, dockerCli, dockerCli.CurrentContext()) - if err != nil { - return nil, err - } - } - - return ng, nil -} - -// GetNodeGroup returns nodegroup based on the name -func GetNodeGroup(txn *store.Txn, dockerCli command.Cli, name string) (*store.NodeGroup, error) { - ng, err := txn.NodeGroupByName(name) - if err != nil { - if !os.IsNotExist(errors.Cause(err)) && !store.IsErrInvalidName(err) { - return nil, err - } - } - if ng != nil { - return ng, nil - } - - list, err := dockerCli.ContextStore().List() - if err != nil { - return nil, err - } - for _, l := range list { - if l.Name == name { - ng = &store.NodeGroup{ - Name: name, - Nodes: []store.Node{ - { - Name: name, - Endpoint: name, - }, - }, - DockerContext: true, - } - if ng.LastActivity, err = txn.GetLastActivity(ng); err != nil { - return nil, err - } - return ng, nil - } - } - - return nil, errors.Errorf("no builder %q found", name) -} - -func GetImageConfig(dockerCli command.Cli, ng *store.NodeGroup) (opt imagetools.Opt, err error) { - opt.Auth = dockerCli.ConfigFile() - - if ng == nil || len(ng.Nodes) == 0 { - return opt, nil - } - - files := ng.Nodes[0].Files - - dt, ok := files["buildkitd.toml"] - if !ok { - return opt, nil - } - - config, err := buildkitdconfig.Load(bytes.NewReader(dt)) - if err != nil { - return opt, err - } - - regconfig := make(map[string]resolver.RegistryConfig) - - for k, v := range config.Registries { - rc := resolver.RegistryConfig{ - Mirrors: v.Mirrors, - PlainHTTP: v.PlainHTTP, - Insecure: v.Insecure, - } - for _, ca := range v.RootCAs { - dt, ok := files[strings.TrimPrefix(ca, confutil.DefaultBuildKitConfigDir+"/")] - if ok { - rc.RootCAs = append(rc.RootCAs, dt) - } - } - - for _, kp := range v.KeyPairs { - key, keyok := files[strings.TrimPrefix(kp.Key, confutil.DefaultBuildKitConfigDir+"/")] - cert, certok := files[strings.TrimPrefix(kp.Certificate, confutil.DefaultBuildKitConfigDir+"/")] - if keyok && certok { - rc.KeyPairs = append(rc.KeyPairs, resolver.TLSKeyPair{ - Key: key, - Certificate: cert, - }) - } - } - regconfig[k] = rc - } - - opt.RegistryConfig = regconfig - - return opt, nil -} diff --git a/vendor/github.com/docker/buildx/store/util.go b/vendor/github.com/docker/buildx/store/util.go deleted file mode 100644 index 269ca4a03..000000000 --- a/vendor/github.com/docker/buildx/store/util.go +++ /dev/null @@ -1,54 +0,0 @@ -package store - -import ( - "os" - "regexp" - "strings" - - "github.com/docker/docker/pkg/namesgenerator" - "github.com/pkg/errors" -) - -var namePattern = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9\.\-_]*$`) - -type errInvalidName struct { - error -} - -func (e *errInvalidName) Error() string { - return e.error.Error() -} - -func (e *errInvalidName) Unwrap() error { - return e.error -} - -func IsErrInvalidName(err error) bool { - _, ok := err.(*errInvalidName) - return ok -} - -func ValidateName(s string) (string, error) { - if !namePattern.MatchString(s) { - return "", &errInvalidName{ - errors.Errorf("invalid name %s, name needs to start with a letter and may not contain symbols, except ._-", s), - } - } - return strings.ToLower(s), nil -} - -func GenerateName(txn *Txn) (string, error) { - var name string - for i := 0; i < 6; i++ { - name = namesgenerator.GetRandomName(i) - if _, err := txn.NodeGroupByName(name); err != nil { - if !os.IsNotExist(errors.Cause(err)) { - return "", err - } - } else { - continue - } - return name, nil - } - return "", errors.Errorf("failed to generate random name") -} diff --git a/vendor/github.com/docker/buildx/util/buildflags/attests.go b/vendor/github.com/docker/buildx/util/buildflags/attests.go deleted file mode 100644 index 71150d272..000000000 --- a/vendor/github.com/docker/buildx/util/buildflags/attests.go +++ /dev/null @@ -1,80 +0,0 @@ -package buildflags - -import ( - "encoding/csv" - "fmt" - "strconv" - "strings" - - controllerapi "github.com/docker/buildx/controller/pb" - "github.com/pkg/errors" -) - -func CanonicalizeAttest(attestType string, in string) string { - if in == "" { - return "" - } - if b, err := strconv.ParseBool(in); err == nil { - return fmt.Sprintf("type=%s,disabled=%t", attestType, !b) - } - return fmt.Sprintf("type=%s,%s", attestType, in) -} - -func ParseAttests(in []string) ([]*controllerapi.Attest, error) { - out := []*controllerapi.Attest{} - found := map[string]struct{}{} - for _, in := range in { - in := in - attest, err := ParseAttest(in) - if err != nil { - return nil, err - } - - if _, ok := found[attest.Type]; ok { - return nil, errors.Errorf("duplicate attestation field %s", attest.Type) - } - found[attest.Type] = struct{}{} - - out = append(out, attest) - } - return out, nil -} - -func ParseAttest(in string) (*controllerapi.Attest, error) { - if in == "" { - return nil, nil - } - - csvReader := csv.NewReader(strings.NewReader(in)) - fields, err := csvReader.Read() - if err != nil { - return nil, err - } - - attest := controllerapi.Attest{ - Attrs: in, - } - for _, field := range fields { - key, value, ok := strings.Cut(field, "=") - if !ok { - return nil, errors.Errorf("invalid value %s", field) - } - key = strings.TrimSpace(strings.ToLower(key)) - - switch key { - case "type": - attest.Type = value - case "disabled": - disabled, err := strconv.ParseBool(value) - if err != nil { - return nil, errors.Wrapf(err, "invalid value %s", field) - } - attest.Disabled = disabled - } - } - if attest.Type == "" { - return nil, errors.Errorf("attestation type not specified") - } - - return &attest, nil -} diff --git a/vendor/github.com/docker/buildx/util/buildflags/cache.go b/vendor/github.com/docker/buildx/util/buildflags/cache.go deleted file mode 100644 index 866ed0ffd..000000000 --- a/vendor/github.com/docker/buildx/util/buildflags/cache.go +++ /dev/null @@ -1,115 +0,0 @@ -package buildflags - -import ( - "context" - "encoding/csv" - "os" - "strings" - - awsconfig "github.com/aws/aws-sdk-go-v2/config" - controllerapi "github.com/docker/buildx/controller/pb" - "github.com/pkg/errors" -) - -func ParseCacheEntry(in []string) ([]*controllerapi.CacheOptionsEntry, error) { - outs := make([]*controllerapi.CacheOptionsEntry, 0, len(in)) - for _, in := range in { - csvReader := csv.NewReader(strings.NewReader(in)) - fields, err := csvReader.Read() - if err != nil { - return nil, err - } - if isRefOnlyFormat(fields) { - for _, field := range fields { - outs = append(outs, &controllerapi.CacheOptionsEntry{ - Type: "registry", - Attrs: map[string]string{"ref": field}, - }) - } - continue - } - - out := controllerapi.CacheOptionsEntry{ - Attrs: map[string]string{}, - } - for _, field := range fields { - parts := strings.SplitN(field, "=", 2) - if len(parts) != 2 { - return nil, errors.Errorf("invalid value %s", field) - } - key := strings.ToLower(parts[0]) - value := parts[1] - switch key { - case "type": - out.Type = value - default: - out.Attrs[key] = value - } - } - if out.Type == "" { - return nil, errors.Errorf("type required form> %q", in) - } - if !addGithubToken(&out) { - continue - } - addAwsCredentials(&out) - outs = append(outs, &out) - } - return outs, nil -} - -func isRefOnlyFormat(in []string) bool { - for _, v := range in { - if strings.Contains(v, "=") { - return false - } - } - return true -} - -func addGithubToken(ci *controllerapi.CacheOptionsEntry) bool { - if ci.Type != "gha" { - return true - } - if _, ok := ci.Attrs["token"]; !ok { - if v, ok := os.LookupEnv("ACTIONS_RUNTIME_TOKEN"); ok { - ci.Attrs["token"] = v - } - } - if _, ok := ci.Attrs["url"]; !ok { - if v, ok := os.LookupEnv("ACTIONS_CACHE_URL"); ok { - ci.Attrs["url"] = v - } - } - return ci.Attrs["token"] != "" && ci.Attrs["url"] != "" -} - -func addAwsCredentials(ci *controllerapi.CacheOptionsEntry) { - if ci.Type != "s3" { - return - } - _, okAccessKeyID := ci.Attrs["access_key_id"] - _, okSecretAccessKey := ci.Attrs["secret_access_key"] - // If the user provides access_key_id, secret_access_key, do not override the session token. - if okAccessKeyID && okSecretAccessKey { - return - } - ctx := context.TODO() - awsConfig, err := awsconfig.LoadDefaultConfig(ctx) - if err != nil { - return - } - credentials, err := awsConfig.Credentials.Retrieve(ctx) - if err != nil { - return - } - if !okAccessKeyID && credentials.AccessKeyID != "" { - ci.Attrs["access_key_id"] = credentials.AccessKeyID - } - if !okSecretAccessKey && credentials.SecretAccessKey != "" { - ci.Attrs["secret_access_key"] = credentials.SecretAccessKey - } - if _, ok := ci.Attrs["session_token"]; !ok && credentials.SessionToken != "" { - ci.Attrs["session_token"] = credentials.SessionToken - } -} diff --git a/vendor/github.com/docker/buildx/util/buildflags/context.go b/vendor/github.com/docker/buildx/util/buildflags/context.go deleted file mode 100644 index e67fb97ce..000000000 --- a/vendor/github.com/docker/buildx/util/buildflags/context.go +++ /dev/null @@ -1,28 +0,0 @@ -package buildflags - -import ( - "strings" - - "github.com/docker/distribution/reference" - "github.com/pkg/errors" -) - -func ParseContextNames(values []string) (map[string]string, error) { - if len(values) == 0 { - return nil, nil - } - result := make(map[string]string, len(values)) - for _, value := range values { - kv := strings.SplitN(value, "=", 2) - if len(kv) != 2 { - return nil, errors.Errorf("invalid context value: %s, expected key=value", value) - } - named, err := reference.ParseNormalizedNamed(kv[0]) - if err != nil { - return nil, errors.Wrapf(err, "invalid context name %s", kv[0]) - } - name := strings.TrimSuffix(reference.FamiliarString(named), ":latest") - result[name] = kv[1] - } - return result, nil -} diff --git a/vendor/github.com/docker/buildx/util/buildflags/entitlements.go b/vendor/github.com/docker/buildx/util/buildflags/entitlements.go deleted file mode 100644 index a393e9a57..000000000 --- a/vendor/github.com/docker/buildx/util/buildflags/entitlements.go +++ /dev/null @@ -1,21 +0,0 @@ -package buildflags - -import ( - "github.com/moby/buildkit/util/entitlements" - "github.com/pkg/errors" -) - -func ParseEntitlements(in []string) ([]entitlements.Entitlement, error) { - out := make([]entitlements.Entitlement, 0, len(in)) - for _, v := range in { - switch v { - case "security.insecure": - out = append(out, entitlements.EntitlementSecurityInsecure) - case "network.host": - out = append(out, entitlements.EntitlementNetworkHost) - default: - return nil, errors.Errorf("invalid entitlement: %v", v) - } - } - return out, nil -} diff --git a/vendor/github.com/docker/buildx/util/buildflags/export.go b/vendor/github.com/docker/buildx/util/buildflags/export.go deleted file mode 100644 index 8f1b73cf7..000000000 --- a/vendor/github.com/docker/buildx/util/buildflags/export.go +++ /dev/null @@ -1,76 +0,0 @@ -package buildflags - -import ( - "encoding/csv" - "strings" - - controllerapi "github.com/docker/buildx/controller/pb" - "github.com/moby/buildkit/client" - "github.com/pkg/errors" -) - -func ParseExports(inp []string) ([]*controllerapi.ExportEntry, error) { - var outs []*controllerapi.ExportEntry - if len(inp) == 0 { - return nil, nil - } - for _, s := range inp { - csvReader := csv.NewReader(strings.NewReader(s)) - fields, err := csvReader.Read() - if err != nil { - return nil, err - } - - out := controllerapi.ExportEntry{ - Attrs: map[string]string{}, - } - if len(fields) == 1 && fields[0] == s && !strings.HasPrefix(s, "type=") { - if s != "-" { - outs = append(outs, &controllerapi.ExportEntry{ - Type: client.ExporterLocal, - Destination: s, - }) - continue - } - out = controllerapi.ExportEntry{ - Type: client.ExporterTar, - Destination: s, - } - } - - if out.Type == "" { - for _, field := range fields { - parts := strings.SplitN(field, "=", 2) - if len(parts) != 2 { - return nil, errors.Errorf("invalid value %s", field) - } - key := strings.TrimSpace(strings.ToLower(parts[0])) - value := parts[1] - switch key { - case "type": - out.Type = value - default: - out.Attrs[key] = value - } - } - } - if out.Type == "" { - return nil, errors.Errorf("type is required for output") - } - - if out.Type == "registry" { - out.Type = client.ExporterImage - if _, ok := out.Attrs["push"]; !ok { - out.Attrs["push"] = "true" - } - } - - if dest, ok := out.Attrs["dest"]; ok { - out.Destination = dest - delete(out.Attrs, "dest") - } - - outs = append(outs, &out) - } - return outs, nil -} diff --git a/vendor/github.com/docker/buildx/util/buildflags/printfunc.go b/vendor/github.com/docker/buildx/util/buildflags/printfunc.go deleted file mode 100644 index 68f10ef2d..000000000 --- a/vendor/github.com/docker/buildx/util/buildflags/printfunc.go +++ /dev/null @@ -1,37 +0,0 @@ -package buildflags - -import ( - "encoding/csv" - "strings" - - controllerapi "github.com/docker/buildx/controller/pb" - "github.com/pkg/errors" -) - -func ParsePrintFunc(str string) (*controllerapi.PrintFunc, error) { - if str == "" { - return nil, nil - } - csvReader := csv.NewReader(strings.NewReader(str)) - fields, err := csvReader.Read() - if err != nil { - return nil, err - } - f := &controllerapi.PrintFunc{} - for _, field := range fields { - parts := strings.SplitN(field, "=", 2) - if len(parts) == 2 { - if parts[0] == "format" { - f.Format = parts[1] - } else { - return nil, errors.Errorf("invalid print field: %s", field) - } - } else { - if f.Name != "" { - return nil, errors.Errorf("invalid print value: %s", str) - } - f.Name = field - } - } - return f, nil -} diff --git a/vendor/github.com/docker/buildx/util/buildflags/secrets.go b/vendor/github.com/docker/buildx/util/buildflags/secrets.go deleted file mode 100644 index 251120850..000000000 --- a/vendor/github.com/docker/buildx/util/buildflags/secrets.go +++ /dev/null @@ -1,63 +0,0 @@ -package buildflags - -import ( - "encoding/csv" - "strings" - - controllerapi "github.com/docker/buildx/controller/pb" - "github.com/pkg/errors" -) - -func ParseSecretSpecs(sl []string) ([]*controllerapi.Secret, error) { - fs := make([]*controllerapi.Secret, 0, len(sl)) - for _, v := range sl { - s, err := parseSecret(v) - if err != nil { - return nil, err - } - fs = append(fs, s) - } - return fs, nil -} - -func parseSecret(value string) (*controllerapi.Secret, error) { - csvReader := csv.NewReader(strings.NewReader(value)) - fields, err := csvReader.Read() - if err != nil { - return nil, errors.Wrap(err, "failed to parse csv secret") - } - - fs := controllerapi.Secret{} - - var typ string - for _, field := range fields { - parts := strings.SplitN(field, "=", 2) - key := strings.ToLower(parts[0]) - - if len(parts) != 2 { - return nil, errors.Errorf("invalid field '%s' must be a key=value pair", field) - } - - value := parts[1] - switch key { - case "type": - if value != "file" && value != "env" { - return nil, errors.Errorf("unsupported secret type %q", value) - } - typ = value - case "id": - fs.ID = value - case "source", "src": - fs.FilePath = value - case "env": - fs.Env = value - default: - return nil, errors.Errorf("unexpected key '%s' in '%s'", key, field) - } - } - if typ == "env" && fs.Env == "" { - fs.Env = fs.FilePath - fs.FilePath = "" - } - return &fs, nil -} diff --git a/vendor/github.com/docker/buildx/util/buildflags/ssh.go b/vendor/github.com/docker/buildx/util/buildflags/ssh.go deleted file mode 100644 index 255f11177..000000000 --- a/vendor/github.com/docker/buildx/util/buildflags/ssh.go +++ /dev/null @@ -1,33 +0,0 @@ -package buildflags - -import ( - "strings" - - controllerapi "github.com/docker/buildx/controller/pb" - "github.com/moby/buildkit/util/gitutil" -) - -func ParseSSHSpecs(sl []string) ([]*controllerapi.SSH, error) { - var outs []*controllerapi.SSH - if len(sl) == 0 { - return nil, nil - } - - for _, s := range sl { - parts := strings.SplitN(s, "=", 2) - out := controllerapi.SSH{ - ID: parts[0], - } - if len(parts) > 1 { - out.Paths = strings.Split(parts[1], ",") - } - outs = append(outs, &out) - } - return outs, nil -} - -// IsGitSSH returns true if the given repo URL is accessed over ssh -func IsGitSSH(url string) bool { - _, gitProtocol := gitutil.ParseProtocol(url) - return gitProtocol == gitutil.SSHProtocol -} diff --git a/vendor/github.com/docker/buildx/util/confutil/config.go b/vendor/github.com/docker/buildx/util/confutil/config.go deleted file mode 100644 index e789fccaa..000000000 --- a/vendor/github.com/docker/buildx/util/confutil/config.go +++ /dev/null @@ -1,52 +0,0 @@ -package confutil - -import ( - "os" - "path" - "path/filepath" - - "github.com/docker/cli/cli/command" - "github.com/pelletier/go-toml" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" -) - -// ConfigDir will look for correct configuration store path; -// if `$BUILDX_CONFIG` is set - use it, otherwise use parent directory -// of Docker config file (i.e. `${DOCKER_CONFIG}/buildx`) -func ConfigDir(dockerCli command.Cli) string { - if buildxConfig := os.Getenv("BUILDX_CONFIG"); buildxConfig != "" { - logrus.Debugf("using config store %q based in \"$BUILDX_CONFIG\" environment variable", buildxConfig) - return buildxConfig - } - - buildxConfig := filepath.Join(filepath.Dir(dockerCli.ConfigFile().Filename), "buildx") - logrus.Debugf("using default config store %q", buildxConfig) - return buildxConfig -} - -// DefaultConfigFile returns the default BuildKit configuration file path -func DefaultConfigFile(dockerCli command.Cli) (string, bool) { - f := path.Join(ConfigDir(dockerCli), "buildkitd.default.toml") - if _, err := os.Stat(f); err == nil { - return f, true - } - return "", false -} - -// loadConfigTree loads BuildKit config toml tree -func loadConfigTree(fp string) (*toml.Tree, error) { - f, err := os.Open(fp) - if err != nil { - if errors.Is(err, os.ErrNotExist) { - return nil, nil - } - return nil, errors.Wrapf(err, "failed to load config from %s", fp) - } - defer f.Close() - t, err := toml.LoadReader(f) - if err != nil { - return t, errors.Wrap(err, "failed to parse config") - } - return t, nil -} diff --git a/vendor/github.com/docker/buildx/util/confutil/container.go b/vendor/github.com/docker/buildx/util/confutil/container.go deleted file mode 100644 index 609217f9b..000000000 --- a/vendor/github.com/docker/buildx/util/confutil/container.go +++ /dev/null @@ -1,135 +0,0 @@ -package confutil - -import ( - "bytes" - "io" - "os" - "path" - "regexp" - - "github.com/pelletier/go-toml" - "github.com/pkg/errors" -) - -const ( - // DefaultBuildKitStateDir and DefaultBuildKitConfigDir are the location - // where buildkitd inside the container stores its state. Some drivers - // create a Linux container, so this should match the location for Linux, - // as defined in: https://github.com/moby/buildkit/blob/v0.9.0/util/appdefaults/appdefaults_unix.go#L11-L15 - DefaultBuildKitStateDir = "/var/lib/buildkit" - DefaultBuildKitConfigDir = "/etc/buildkit" -) - -var reInvalidCertsDir = regexp.MustCompile(`[^a-zA-Z0-9.-]+`) - -// LoadConfigFiles creates a temp directory with BuildKit config and -// registry certificates ready to be copied to a container. -func LoadConfigFiles(bkconfig string) (map[string][]byte, error) { - if _, err := os.Stat(bkconfig); errors.Is(err, os.ErrNotExist) { - return nil, errors.Wrapf(err, "buildkit configuration file not found: %s", bkconfig) - } else if err != nil { - return nil, errors.Wrapf(err, "invalid buildkit configuration file: %s", bkconfig) - } - - // Load config tree - btoml, err := loadConfigTree(bkconfig) - if err != nil { - return nil, err - } - - m := make(map[string][]byte) - - // Iterate through registry config to copy certs and update - // BuildKit config with the underlying certs' path in the container. - // - // The following BuildKit config: - // - // [registry."myregistry.io"] - // ca=["/etc/config/myca.pem"] - // [[registry."myregistry.io".keypair]] - // key="/etc/config/key.pem" - // cert="/etc/config/cert.pem" - // - // will be translated in the container as: - // - // [registry."myregistry.io"] - // ca=["/etc/buildkit/certs/myregistry.io/myca.pem"] - // [[registry."myregistry.io".keypair]] - // key="/etc/buildkit/certs/myregistry.io/key.pem" - // cert="/etc/buildkit/certs/myregistry.io/cert.pem" - if btoml.Has("registry") { - for regName := range btoml.GetArray("registry").(*toml.Tree).Values() { - regConf := btoml.GetPath([]string{"registry", regName}).(*toml.Tree) - if regConf == nil { - continue - } - pfx := path.Join("certs", reInvalidCertsDir.ReplaceAllString(regName, "_")) - if regConf.Has("ca") { - regCAs := regConf.GetArray("ca").([]string) - if len(regCAs) > 0 { - var cas []string - for _, ca := range regCAs { - fp := path.Join(pfx, path.Base(ca)) - cas = append(cas, path.Join(DefaultBuildKitConfigDir, fp)) - - dt, err := readFile(ca) - if err != nil { - return nil, errors.Wrapf(err, "failed to read CA file: %s", ca) - } - m[fp] = dt - } - regConf.Set("ca", cas) - } - } - if regConf.Has("keypair") { - regKeyPairs := regConf.GetArray("keypair").([]*toml.Tree) - if len(regKeyPairs) == 0 { - continue - } - for _, kp := range regKeyPairs { - if kp == nil { - continue - } - key := kp.Get("key").(string) - if len(key) > 0 { - fp := path.Join(pfx, path.Base(key)) - kp.Set("key", path.Join(DefaultBuildKitConfigDir, fp)) - dt, err := readFile(key) - if err != nil { - return nil, errors.Wrapf(err, "failed to read key file: %s", key) - } - m[fp] = dt - } - cert := kp.Get("cert").(string) - if len(cert) > 0 { - fp := path.Join(pfx, path.Base(cert)) - kp.Set("cert", path.Join(DefaultBuildKitConfigDir, fp)) - dt, err := readFile(cert) - if err != nil { - return nil, errors.Wrapf(err, "failed to read cert file: %s", cert) - } - m[fp] = dt - } - } - } - } - } - - b := bytes.NewBuffer(nil) - _, err = btoml.WriteTo(b) - if err != nil { - return nil, err - } - m["buildkitd.toml"] = b.Bytes() - - return m, nil -} - -func readFile(fp string) ([]byte, error) { - sf, err := os.Open(fp) - if err != nil { - return nil, err - } - defer sf.Close() - return io.ReadAll(io.LimitReader(sf, 1024*1024)) -} diff --git a/vendor/github.com/docker/buildx/util/desktop/desktop.go b/vendor/github.com/docker/buildx/util/desktop/desktop.go deleted file mode 100644 index 7fa4ee6d8..000000000 --- a/vendor/github.com/docker/buildx/util/desktop/desktop.go +++ /dev/null @@ -1,86 +0,0 @@ -package desktop - -import ( - "bytes" - "fmt" - "io" - "os" - "path/filepath" - "sync" - - "github.com/containerd/console" -) - -var ( - bbEnabledOnce sync.Once - bbEnabled bool -) - -func BuildBackendEnabled() bool { - bbEnabledOnce.Do(func() { - home, err := os.UserHomeDir() - if err != nil { - return - } - _, err = os.Stat(filepath.Join(home, ".docker", "desktop-build", ".lastaccess")) - bbEnabled = err == nil - }) - return bbEnabled -} - -func BuildDetailsOutput(refs map[string]string, term bool) string { - if len(refs) == 0 { - return "" - } - refURL := func(ref string) string { - return fmt.Sprintf("docker-desktop://dashboard/build/%s", ref) - } - var out bytes.Buffer - out.WriteString("View build details: ") - multiTargets := len(refs) > 1 - for target, ref := range refs { - if multiTargets { - out.WriteString(fmt.Sprintf("\n %s: ", target)) - } - if term { - out.WriteString(hyperlink(refURL(ref))) - } else { - out.WriteString(refURL(ref)) - } - } - return out.String() -} - -func PrintBuildDetails(w io.Writer, refs map[string]string, term bool) { - if out := BuildDetailsOutput(refs, term); out != "" { - fmt.Fprintf(w, "\n%s\n", out) - } -} - -func hyperlink(url string) string { - // create an escape sequence using the OSC 8 format: https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda - return fmt.Sprintf("\033]8;;%s\033\\%s\033]8;;\033\\", url, url) -} - -type ErrorWithBuildRef struct { - Ref string - Err error - Msg string -} - -func (e *ErrorWithBuildRef) Error() string { - return e.Err.Error() -} - -func (e *ErrorWithBuildRef) Unwrap() error { - return e.Err -} - -func (e *ErrorWithBuildRef) Print(w io.Writer) error { - var term bool - if _, err := console.ConsoleFromFile(os.Stderr); err == nil { - term = true - } - fmt.Fprintf(w, "\n%s\n", BuildDetailsOutput(map[string]string{"default": e.Ref}, term)) - return nil -} diff --git a/vendor/github.com/docker/buildx/util/dockerutil/api.go b/vendor/github.com/docker/buildx/util/dockerutil/api.go deleted file mode 100644 index 5fd9b6521..000000000 --- a/vendor/github.com/docker/buildx/util/dockerutil/api.go +++ /dev/null @@ -1,45 +0,0 @@ -package dockerutil - -import ( - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/context/docker" - "github.com/docker/docker/client" -) - -// ClientAPI represents an active docker API object. -type ClientAPI struct { - client.APIClient -} - -func NewClientAPI(cli command.Cli, ep string) (*ClientAPI, error) { - ca := &ClientAPI{} - - var dep docker.Endpoint - dem, err := GetDockerEndpoint(cli, ep) - if err != nil { - return nil, err - } else if dem != nil { - dep, err = docker.WithTLSData(cli.ContextStore(), ep, *dem) - if err != nil { - return nil, err - } - } else { - dep = docker.Endpoint{ - EndpointMeta: docker.EndpointMeta{ - Host: ep, - }, - } - } - - clientOpts, err := dep.ClientOpts() - if err != nil { - return nil, err - } - - ca.APIClient, err = client.NewClientWithOpts(clientOpts...) - if err != nil { - return nil, err - } - - return ca, nil -} diff --git a/vendor/github.com/docker/buildx/util/dockerutil/client.go b/vendor/github.com/docker/buildx/util/dockerutil/client.go deleted file mode 100644 index 5a1ff36f1..000000000 --- a/vendor/github.com/docker/buildx/util/dockerutil/client.go +++ /dev/null @@ -1,119 +0,0 @@ -package dockerutil - -import ( - "context" - "io" - "sync" - - "github.com/docker/buildx/util/progress" - "github.com/docker/cli/cli/command" - "github.com/docker/docker/client" -) - -// Client represents an active docker object. -type Client struct { - cli command.Cli - - featuresOnce sync.Once - featuresCache map[Feature]bool -} - -// NewClient initializes a new docker client. -func NewClient(cli command.Cli) *Client { - return &Client{cli: cli} -} - -// API returns a new docker API client. -func (c *Client) API(name string) (client.APIClient, error) { - if name == "" { - name = c.cli.CurrentContext() - } - return NewClientAPI(c.cli, name) -} - -// LoadImage imports an image to docker. -func (c *Client) LoadImage(ctx context.Context, name string, status progress.Writer) (io.WriteCloser, func(), error) { - dapi, err := c.API(name) - if err != nil { - return nil, nil, err - } - - pr, pw := io.Pipe() - done := make(chan struct{}) - - ctx, cancel := context.WithCancel(ctx) - var w *waitingWriter - w = &waitingWriter{ - PipeWriter: pw, - f: func() { - resp, err := dapi.ImageLoad(ctx, pr, false) - defer close(done) - if err != nil { - pr.CloseWithError(err) - w.mu.Lock() - w.err = err - w.mu.Unlock() - return - } - prog := progress.WithPrefix(status, "", false) - progress.FromReader(prog, "importing to docker", resp.Body) - }, - done: done, - cancel: cancel, - } - return w, func() { - pr.Close() - }, nil -} - -func (c *Client) Features(ctx context.Context, name string) map[Feature]bool { - c.featuresOnce.Do(func() { - c.featuresCache = c.features(ctx, name) - }) - return c.featuresCache -} - -func (c *Client) features(ctx context.Context, name string) map[Feature]bool { - features := make(map[Feature]bool) - if dapi, err := c.API(name); err == nil { - if info, err := dapi.Info(ctx); err == nil { - for _, v := range info.DriverStatus { - switch v[0] { - case "driver-type": - if v[1] == "io.containerd.snapshotter.v1" { - features[OCIImporter] = true - } - } - } - } - } - return features -} - -type waitingWriter struct { - *io.PipeWriter - f func() - once sync.Once - mu sync.Mutex - err error - done chan struct{} - cancel func() -} - -func (w *waitingWriter) Write(dt []byte) (int, error) { - w.once.Do(func() { - go w.f() - }) - return w.PipeWriter.Write(dt) -} - -func (w *waitingWriter) Close() error { - err := w.PipeWriter.Close() - <-w.done - if err == nil { - w.mu.Lock() - defer w.mu.Unlock() - return w.err - } - return err -} diff --git a/vendor/github.com/docker/buildx/util/dockerutil/context.go b/vendor/github.com/docker/buildx/util/dockerutil/context.go deleted file mode 100644 index e4e0c697a..000000000 --- a/vendor/github.com/docker/buildx/util/dockerutil/context.go +++ /dev/null @@ -1,40 +0,0 @@ -package dockerutil - -import ( - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/context/docker" - "github.com/pkg/errors" -) - -// GetDockerEndpoint returns docker endpoint meta for given context -func GetDockerEndpoint(dockerCli command.Cli, name string) (*docker.EndpointMeta, error) { - list, err := dockerCli.ContextStore().List() - if err != nil { - return nil, err - } - for _, l := range list { - if l.Name == name { - epm, err := docker.EndpointFromContext(l) - if err != nil { - return nil, err - } - return &epm, nil - } - } - return nil, nil -} - -// GetCurrentEndpoint returns the current default endpoint value -func GetCurrentEndpoint(dockerCli command.Cli) (string, error) { - name := dockerCli.CurrentContext() - if name != "default" { - return name, nil - } - dem, err := GetDockerEndpoint(dockerCli, name) - if err != nil { - return "", errors.Errorf("docker endpoint for %q not found", name) - } else if dem != nil { - return dem.Host, nil - } - return "", nil -} diff --git a/vendor/github.com/docker/buildx/util/dockerutil/features.go b/vendor/github.com/docker/buildx/util/dockerutil/features.go deleted file mode 100644 index 5d621b0b0..000000000 --- a/vendor/github.com/docker/buildx/util/dockerutil/features.go +++ /dev/null @@ -1,5 +0,0 @@ -package dockerutil - -type Feature string - -const OCIImporter Feature = "OCI importer" diff --git a/vendor/github.com/docker/buildx/util/gitutil/gitpath_unix.go b/vendor/github.com/docker/buildx/util/gitutil/gitpath_unix.go deleted file mode 100644 index 898cb654d..000000000 --- a/vendor/github.com/docker/buildx/util/gitutil/gitpath_unix.go +++ /dev/null @@ -1,42 +0,0 @@ -//go:build !windows -// +build !windows - -package gitutil - -import ( - "os" - "os/exec" - "path/filepath" - - "github.com/moby/sys/mountinfo" -) - -func gitPath(wd string) (string, error) { - // On WSL2 we need to check if the current working directory is mounted on - // a Windows drive and if so, we need to use the Windows git executable. - if os.Getenv("WSL_DISTRO_NAME") != "" && wd != "" { - // ensure any symlinks are resolved - wdPath, err := filepath.EvalSymlinks(wd) - if err != nil { - return "", err - } - mi, err := mountinfo.GetMounts(mountinfo.ParentsFilter(wdPath)) - if err != nil { - return "", err - } - // find the longest mount point - var idx, maxlen int - for i := range mi { - if len(mi[i].Mountpoint) > maxlen { - maxlen = len(mi[i].Mountpoint) - idx = i - } - } - if mi[idx].FSType == "9p" { - if p, err := exec.LookPath("git.exe"); err == nil { - return p, nil - } - } - } - return exec.LookPath("git") -} diff --git a/vendor/github.com/docker/buildx/util/gitutil/gitpath_windows.go b/vendor/github.com/docker/buildx/util/gitutil/gitpath_windows.go deleted file mode 100644 index a1a915384..000000000 --- a/vendor/github.com/docker/buildx/util/gitutil/gitpath_windows.go +++ /dev/null @@ -1,9 +0,0 @@ -package gitutil - -import ( - "os/exec" -) - -func gitPath(wd string) (string, error) { - return exec.LookPath("git.exe") -} diff --git a/vendor/github.com/docker/buildx/util/gitutil/gitutil.go b/vendor/github.com/docker/buildx/util/gitutil/gitutil.go deleted file mode 100644 index 8ab76ab20..000000000 --- a/vendor/github.com/docker/buildx/util/gitutil/gitutil.go +++ /dev/null @@ -1,172 +0,0 @@ -package gitutil - -import ( - "bytes" - "context" - "net/url" - "os" - "os/exec" - "path/filepath" - "strings" - - "github.com/pkg/errors" -) - -// Git represents an active git object -type Git struct { - ctx context.Context - wd string - gitpath string -} - -// Option provides a variadic option for configuring the git client. -type Option func(b *Git) - -// WithContext sets context. -func WithContext(ctx context.Context) Option { - return func(b *Git) { - b.ctx = ctx - } -} - -// WithWorkingDir sets working directory. -func WithWorkingDir(wd string) Option { - return func(b *Git) { - b.wd = wd - } -} - -// New initializes a new git client -func New(opts ...Option) (*Git, error) { - var err error - c := &Git{ - ctx: context.Background(), - } - - for _, opt := range opts { - opt(c) - } - - c.gitpath, err = gitPath(c.wd) - if err != nil { - return nil, errors.New("git not found in PATH") - } - - return c, nil -} - -func (c *Git) IsInsideWorkTree() bool { - out, err := c.clean(c.run("rev-parse", "--is-inside-work-tree")) - return out == "true" && err == nil -} - -func (c *Git) IsDirty() bool { - out, err := c.run("status", "--porcelain", "--ignored") - return strings.TrimSpace(out) != "" || err != nil -} - -func (c *Git) RootDir() (string, error) { - return c.clean(c.run("rev-parse", "--show-toplevel")) -} - -func (c *Git) GitDir() (string, error) { - dir, err := c.RootDir() - if err != nil { - return "", err - } - return filepath.Join(dir, ".git"), nil -} - -func (c *Git) RemoteURL() (string, error) { - // Try to get the remote URL from the origin remote first - if ru, err := c.clean(c.run("remote", "get-url", "origin")); err == nil && ru != "" { - return stripCredentials(ru), nil - } - // If that fails, try to get the remote URL from the upstream remote - if ru, err := c.clean(c.run("remote", "get-url", "upstream")); err == nil && ru != "" { - return stripCredentials(ru), nil - } - return "", errors.New("no remote URL found for either origin or upstream") -} - -func (c *Git) FullCommit() (string, error) { - return c.clean(c.run("show", "--format=%H", "HEAD", "--quiet", "--")) -} - -func (c *Git) ShortCommit() (string, error) { - return c.clean(c.run("show", "--format=%h", "HEAD", "--quiet", "--")) -} - -func (c *Git) Tag() (string, error) { - var tag string - var err error - for _, fn := range []func() (string, error){ - func() (string, error) { - return c.clean(c.run("tag", "--points-at", "HEAD", "--sort", "-version:creatordate")) - }, - func() (string, error) { - return c.clean(c.run("describe", "--tags", "--abbrev=0")) - }, - } { - tag, err = fn() - if tag != "" || err != nil { - return tag, err - } - } - return tag, err -} - -func (c *Git) run(args ...string) (string, error) { - var extraArgs = []string{ - "-c", "log.showSignature=false", - } - - args = append(extraArgs, args...) - cmd := exec.CommandContext(c.ctx, c.gitpath, args...) - if c.wd != "" { - cmd.Dir = c.wd - } - - // Override the locale to ensure consistent output - cmd.Env = append(os.Environ(), "LC_ALL=C") - - stdout := bytes.Buffer{} - stderr := bytes.Buffer{} - cmd.Stdout = &stdout - cmd.Stderr = &stderr - - if err := cmd.Run(); err != nil { - return "", errors.New(stderr.String()) - } - return stdout.String(), nil -} - -func (c *Git) clean(out string, err error) (string, error) { - out = strings.ReplaceAll(strings.Split(out, "\n")[0], "'", "") - if err != nil { - err = errors.New(strings.TrimSuffix(err.Error(), "\n")) - } - return out, err -} - -func IsUnknownRevision(err error) bool { - if err == nil { - return false - } - // https://github.com/git/git/blob/a6a323b31e2bcbac2518bddec71ea7ad558870eb/setup.c#L204 - errMsg := strings.ToLower(err.Error()) - return strings.Contains(errMsg, "unknown revision or path not in the working tree") || strings.Contains(errMsg, "bad revision") -} - -// stripCredentials takes a URL and strips username and password from it. -// e.g. "https://user:password@host.tld/path.git" will be changed to -// "https://host.tld/path.git". -// TODO: remove this function once fix from BuildKit is vendored here -func stripCredentials(s string) string { - ru, err := url.Parse(s) - if err != nil { - return s // string is not a URL, just return it - } - ru.User = nil - return ru.String() -} diff --git a/vendor/github.com/docker/buildx/util/gitutil/testutil.go b/vendor/github.com/docker/buildx/util/gitutil/testutil.go deleted file mode 100644 index ea9dd058e..000000000 --- a/vendor/github.com/docker/buildx/util/gitutil/testutil.go +++ /dev/null @@ -1,85 +0,0 @@ -package gitutil - -import ( - "os" - "strings" - "testing" - - "github.com/stretchr/testify/require" -) - -func GitInit(c *Git, tb testing.TB) { - tb.Helper() - out, err := fakeGit(c, "init") - require.NoError(tb, err) - require.Contains(tb, out, "Initialized empty Git repository") - require.NoError(tb, err) - GitCheckoutBranch(c, tb, "main") - _, _ = fakeGit(c, "branch", "-D", "master") -} - -func GitCommit(c *Git, tb testing.TB, msg string) { - tb.Helper() - out, err := fakeGit(c, "commit", "--allow-empty", "-m", msg) - require.NoError(tb, err) - require.Contains(tb, out, "main", msg) -} - -func GitTag(c *Git, tb testing.TB, tag string) { - tb.Helper() - out, err := fakeGit(c, "tag", tag) - require.NoError(tb, err) - require.Empty(tb, out) -} - -func GitCheckoutBranch(c *Git, tb testing.TB, name string) { - tb.Helper() - out, err := fakeGit(c, "checkout", "-b", name) - require.NoError(tb, err) - require.Empty(tb, out) -} - -func GitAdd(c *Git, tb testing.TB, files ...string) { - tb.Helper() - args := append([]string{"add"}, files...) - _, err := fakeGit(c, args...) - require.NoError(tb, err) -} - -func GitSetRemote(c *Git, tb testing.TB, name string, url string) { - tb.Helper() - _, err := fakeGit(c, "remote", "add", name, url) - require.NoError(tb, err) -} - -func Mktmp(tb testing.TB) string { - tb.Helper() - folder := tb.TempDir() - current, err := os.Getwd() - require.NoError(tb, err) - require.NoError(tb, os.Chdir(folder)) - tb.Cleanup(func() { - require.NoError(tb, os.Chdir(current)) - }) - return folder -} - -func fakeGit(c *Git, args ...string) (string, error) { - allArgs := []string{ - "-c", "user.name=buildx", - "-c", "user.email=buildx@docker.com", - "-c", "commit.gpgSign=false", - "-c", "tag.gpgSign=false", - "-c", "log.showSignature=false", - } - allArgs = append(allArgs, args...) - return c.clean(c.run(allArgs...)) -} - -func IsAmbiguousArgument(err error) bool { - if err == nil { - return false - } - errMsg := strings.ToLower(err.Error()) - return strings.Contains(errMsg, "use '--' to separate paths from revisions") -} diff --git a/vendor/github.com/docker/buildx/util/gitutil/testutilserve.go b/vendor/github.com/docker/buildx/util/gitutil/testutilserve.go deleted file mode 100644 index 631ed6935..000000000 --- a/vendor/github.com/docker/buildx/util/gitutil/testutilserve.go +++ /dev/null @@ -1,62 +0,0 @@ -package gitutil - -import ( - "context" - "fmt" - "net" - "net/http" - "testing" - - "github.com/stretchr/testify/require" -) - -func GitServeHTTP(c *Git, t testing.TB) (url string) { - t.Helper() - gitUpdateServerInfo(c, t) - ctx, cancel := context.WithCancel(context.TODO()) - - ready := make(chan struct{}) - done := make(chan struct{}) - - name := "test.git" - dir, err := c.GitDir() - if err != nil { - cancel() - } - - var addr string - go func() { - mux := http.NewServeMux() - prefix := fmt.Sprintf("/%s/", name) - mux.Handle(prefix, http.StripPrefix(prefix, http.FileServer(http.Dir(dir)))) - l, err := net.Listen("tcp", "localhost:0") - if err != nil { - panic(err) - } - - addr = l.Addr().String() - - close(ready) - - s := http.Server{Handler: mux} //nolint:gosec // potential attacks are not relevant for tests - go s.Serve(l) - <-ctx.Done() - s.Shutdown(context.TODO()) - l.Close() - - close(done) - }() - <-ready - - t.Cleanup(func() { - cancel() - <-done - }) - return fmt.Sprintf("http://%s/%s", addr, name) -} - -func gitUpdateServerInfo(c *Git, tb testing.TB) { - tb.Helper() - _, err := fakeGit(c, "update-server-info") - require.NoError(tb, err) -} diff --git a/vendor/github.com/docker/buildx/util/imagetools/create.go b/vendor/github.com/docker/buildx/util/imagetools/create.go deleted file mode 100644 index 3b1057bc4..000000000 --- a/vendor/github.com/docker/buildx/util/imagetools/create.go +++ /dev/null @@ -1,268 +0,0 @@ -package imagetools - -import ( - "bytes" - "context" - "encoding/json" - "net/url" - "strings" - - "github.com/containerd/containerd/content" - "github.com/containerd/containerd/errdefs" - "github.com/containerd/containerd/images" - "github.com/containerd/containerd/platforms" - "github.com/containerd/containerd/remotes" - "github.com/docker/distribution/reference" - "github.com/moby/buildkit/util/contentutil" - "github.com/opencontainers/go-digest" - "github.com/opencontainers/image-spec/specs-go" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" - "github.com/pkg/errors" - "golang.org/x/sync/errgroup" -) - -type Source struct { - Desc ocispec.Descriptor - Ref reference.Named -} - -func (r *Resolver) Combine(ctx context.Context, srcs []*Source) ([]byte, ocispec.Descriptor, error) { - eg, ctx := errgroup.WithContext(ctx) - - dts := make([][]byte, len(srcs)) - for i := range dts { - func(i int) { - eg.Go(func() error { - dt, err := r.GetDescriptor(ctx, srcs[i].Ref.String(), srcs[i].Desc) - if err != nil { - return err - } - dts[i] = dt - - if srcs[i].Desc.MediaType == "" { - mt, err := detectMediaType(dt) - if err != nil { - return err - } - srcs[i].Desc.MediaType = mt - } - - mt := srcs[i].Desc.MediaType - - switch mt { - case images.MediaTypeDockerSchema2Manifest, ocispec.MediaTypeImageManifest: - p := srcs[i].Desc.Platform - if srcs[i].Desc.Platform == nil { - p = &ocispec.Platform{} - } - if p.OS == "" || p.Architecture == "" { - if err := r.loadPlatform(ctx, p, srcs[i].Ref.String(), dt); err != nil { - return err - } - } - srcs[i].Desc.Platform = p - case images.MediaTypeDockerSchema1Manifest: - return errors.Errorf("schema1 manifests are not allowed in manifest lists") - } - - return nil - }) - }(i) - } - - if err := eg.Wait(); err != nil { - return nil, ocispec.Descriptor{}, err - } - - // on single source, return original bytes - if len(srcs) == 1 { - if mt := srcs[0].Desc.MediaType; mt == images.MediaTypeDockerSchema2ManifestList || mt == ocispec.MediaTypeImageIndex { - return dts[0], srcs[0].Desc, nil - } - } - - m := map[digest.Digest]int{} - newDescs := make([]ocispec.Descriptor, 0, len(srcs)) - - addDesc := func(d ocispec.Descriptor) { - idx, ok := m[d.Digest] - if ok { - old := newDescs[idx] - if old.MediaType == "" { - old.MediaType = d.MediaType - } - if d.Platform != nil { - old.Platform = d.Platform - } - if old.Annotations == nil { - old.Annotations = map[string]string{} - } - for k, v := range d.Annotations { - old.Annotations[k] = v - } - newDescs[idx] = old - } else { - m[d.Digest] = len(newDescs) - newDescs = append(newDescs, d) - } - } - - for i, src := range srcs { - switch src.Desc.MediaType { - case images.MediaTypeDockerSchema2ManifestList, ocispec.MediaTypeImageIndex: - var mfst ocispec.Index - if err := json.Unmarshal(dts[i], &mfst); err != nil { - return nil, ocispec.Descriptor{}, errors.WithStack(err) - } - for _, d := range mfst.Manifests { - addDesc(d) - } - default: - addDesc(src.Desc) - } - } - - dockerMfsts := 0 - for _, desc := range newDescs { - if strings.HasPrefix(desc.MediaType, "application/vnd.docker.") { - dockerMfsts++ - } - } - - var mt string - if dockerMfsts == len(newDescs) { - // all manifests are Docker types, use Docker manifest list - mt = images.MediaTypeDockerSchema2ManifestList - } else { - // otherwise, use OCI index - mt = ocispec.MediaTypeImageIndex - } - - idxBytes, err := json.MarshalIndent(ocispec.Index{ - MediaType: mt, - Versioned: specs.Versioned{ - SchemaVersion: 2, - }, - Manifests: newDescs, - }, "", " ") - if err != nil { - return nil, ocispec.Descriptor{}, errors.Wrap(err, "failed to marshal index") - } - - return idxBytes, ocispec.Descriptor{ - MediaType: mt, - Size: int64(len(idxBytes)), - Digest: digest.FromBytes(idxBytes), - }, nil -} - -func (r *Resolver) Push(ctx context.Context, ref reference.Named, desc ocispec.Descriptor, dt []byte) error { - ctx = remotes.WithMediaTypeKeyPrefix(ctx, "application/vnd.in-toto+json", "intoto") - - ref = reference.TagNameOnly(ref) - p, err := r.resolver().Pusher(ctx, ref.String()) - if err != nil { - return err - } - cw, err := p.Push(ctx, desc) - if err != nil { - if errdefs.IsAlreadyExists(err) { - return nil - } - return err - } - - err = content.Copy(ctx, cw, bytes.NewReader(dt), desc.Size, desc.Digest) - if errdefs.IsAlreadyExists(err) { - return nil - } - return err -} - -func (r *Resolver) Copy(ctx context.Context, src *Source, dest reference.Named) error { - ctx = remotes.WithMediaTypeKeyPrefix(ctx, "application/vnd.in-toto+json", "intoto") - - dest = reference.TagNameOnly(dest) - p, err := r.resolver().Pusher(ctx, dest.String()) - if err != nil { - return err - } - - srcRef := reference.TagNameOnly(src.Ref) - f, err := r.resolver().Fetcher(ctx, srcRef.String()) - if err != nil { - return err - } - - refspec := reference.TrimNamed(src.Ref).String() - u, err := url.Parse("dummy://" + refspec) - if err != nil { - return err - } - source, repo := u.Hostname(), strings.TrimPrefix(u.Path, "/") - if src.Desc.Annotations == nil { - src.Desc.Annotations = make(map[string]string) - } - src.Desc.Annotations["containerd.io/distribution.source."+source] = repo - - err = contentutil.CopyChain(ctx, contentutil.FromPusher(p), contentutil.FromFetcher(f), src.Desc) - if err != nil { - return err - } - return nil -} - -func (r *Resolver) loadPlatform(ctx context.Context, p2 *ocispec.Platform, in string, dt []byte) error { - var manifest ocispec.Manifest - if err := json.Unmarshal(dt, &manifest); err != nil { - return errors.WithStack(err) - } - - dt, err := r.GetDescriptor(ctx, in, manifest.Config) - if err != nil { - return err - } - - var p ocispec.Platform - if err := json.Unmarshal(dt, &p); err != nil { - return errors.WithStack(err) - } - - p = platforms.Normalize(p) - - if p2.Architecture == "" { - p2.Architecture = p.Architecture - if p2.Variant == "" { - p2.Variant = p.Variant - } - } - if p2.OS == "" { - p2.OS = p.OS - } - - return nil -} - -func detectMediaType(dt []byte) (string, error) { - var mfst struct { - MediaType string `json:"mediaType"` - Config json.RawMessage `json:"config"` - FSLayers []string `json:"fsLayers"` - } - - if err := json.Unmarshal(dt, &mfst); err != nil { - return "", errors.WithStack(err) - } - - if mfst.MediaType != "" { - return mfst.MediaType, nil - } - if mfst.Config != nil { - return images.MediaTypeDockerSchema2Manifest, nil - } - if len(mfst.FSLayers) > 0 { - return images.MediaTypeDockerSchema1Manifest, nil - } - - return images.MediaTypeDockerSchema2ManifestList, nil -} diff --git a/vendor/github.com/docker/buildx/util/imagetools/inspect.go b/vendor/github.com/docker/buildx/util/imagetools/inspect.go deleted file mode 100644 index 78cd76021..000000000 --- a/vendor/github.com/docker/buildx/util/imagetools/inspect.go +++ /dev/null @@ -1,162 +0,0 @@ -package imagetools - -import ( - "bytes" - "context" - "encoding/base64" - "encoding/json" - "io" - "net/http" - - "github.com/containerd/containerd/log" - "github.com/containerd/containerd/remotes" - "github.com/containerd/containerd/remotes/docker" - "github.com/docker/buildx/util/resolver" - clitypes "github.com/docker/cli/cli/config/types" - "github.com/docker/distribution/reference" - "github.com/moby/buildkit/util/contentutil" - "github.com/moby/buildkit/util/tracing" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" - "github.com/sirupsen/logrus" -) - -type Auth interface { - GetAuthConfig(registryHostname string) (clitypes.AuthConfig, error) -} - -type Opt struct { - Auth Auth - RegistryConfig map[string]resolver.RegistryConfig -} - -type Resolver struct { - auth docker.Authorizer - hosts docker.RegistryHosts - buffer contentutil.Buffer -} - -func New(opt Opt) *Resolver { - return &Resolver{ - auth: docker.NewDockerAuthorizer(docker.WithAuthCreds(toCredentialsFunc(opt.Auth)), docker.WithAuthClient(http.DefaultClient)), - hosts: resolver.NewRegistryConfig(opt.RegistryConfig), - buffer: contentutil.NewBuffer(), - } -} - -func (r *Resolver) resolver() remotes.Resolver { - return docker.NewResolver(docker.ResolverOptions{ - Hosts: func(domain string) ([]docker.RegistryHost, error) { - res, err := r.hosts(domain) - if err != nil { - return nil, err - } - for i := range res { - res[i].Authorizer = r.auth - res[i].Client = tracing.DefaultClient - } - return res, nil - }, - }) -} - -func (r *Resolver) Resolve(ctx context.Context, in string) (string, ocispec.Descriptor, error) { - // discard containerd logger to avoid printing unnecessary info during image reference resolution. - // https://github.com/containerd/containerd/blob/1a88cf5242445657258e0c744def5017d7cfb492/remotes/docker/resolver.go#L288 - logger := logrus.New() - logger.Out = io.Discard - ctx = log.WithLogger(ctx, logrus.NewEntry(logger)) - - ref, err := parseRef(in) - if err != nil { - return "", ocispec.Descriptor{}, err - } - - in, desc, err := r.resolver().Resolve(ctx, ref.String()) - if err != nil { - return "", ocispec.Descriptor{}, err - } - - return in, desc, nil -} - -func (r *Resolver) Get(ctx context.Context, in string) ([]byte, ocispec.Descriptor, error) { - in, desc, err := r.Resolve(ctx, in) - if err != nil { - return nil, ocispec.Descriptor{}, err - } - - dt, err := r.GetDescriptor(ctx, in, desc) - if err != nil { - return nil, ocispec.Descriptor{}, err - } - return dt, desc, nil -} - -func (r *Resolver) GetDescriptor(ctx context.Context, in string, desc ocispec.Descriptor) ([]byte, error) { - fetcher, err := r.resolver().Fetcher(ctx, in) - if err != nil { - return nil, err - } - - rc, err := fetcher.Fetch(ctx, desc) - if err != nil { - return nil, err - } - - buf := &bytes.Buffer{} - _, err = io.Copy(buf, rc) - rc.Close() - if err != nil { - return nil, err - } - - return buf.Bytes(), nil -} - -func parseRef(s string) (reference.Named, error) { - ref, err := reference.ParseNormalizedNamed(s) - if err != nil { - return nil, err - } - ref = reference.TagNameOnly(ref) - return ref, nil -} - -func toCredentialsFunc(a Auth) func(string) (string, string, error) { - return func(host string) (string, string, error) { - if host == "registry-1.docker.io" { - host = "https://index.docker.io/v1/" - } - ac, err := a.GetAuthConfig(host) - if err != nil { - return "", "", err - } - if ac.IdentityToken != "" { - return "", ac.IdentityToken, nil - } - return ac.Username, ac.Password, nil - } -} - -func RegistryAuthForRef(ref string, a Auth) (string, error) { - if a == nil { - return "", nil - } - r, err := parseRef(ref) - if err != nil { - return "", err - } - host := reference.Domain(r) - if host == "docker.io" { - host = "https://index.docker.io/v1/" - } - ac, err := a.GetAuthConfig(host) - if err != nil { - return "", err - } - buf, err := json.Marshal(ac) - if err != nil { - return "", err - } - return base64.URLEncoding.EncodeToString(buf), nil -} diff --git a/vendor/github.com/docker/buildx/util/imagetools/loader.go b/vendor/github.com/docker/buildx/util/imagetools/loader.go deleted file mode 100644 index a16515667..000000000 --- a/vendor/github.com/docker/buildx/util/imagetools/loader.go +++ /dev/null @@ -1,417 +0,0 @@ -package imagetools - -// TODO: replace with go-imageinspect library when public - -import ( - "context" - "encoding/json" - "sort" - "strings" - "sync" - - "github.com/containerd/containerd/content" - "github.com/containerd/containerd/images" - "github.com/containerd/containerd/platforms" - "github.com/containerd/containerd/remotes" - "github.com/docker/distribution/reference" - "github.com/moby/buildkit/util/contentutil" - "github.com/opencontainers/go-digest" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" - "github.com/pkg/errors" - "golang.org/x/sync/errgroup" -) - -var ( - annotationReferences = []string{ - "com.docker.reference.digest", - "vnd.docker.reference.digest", // TODO: deprecate/remove after migration to new annotation - } -) - -type contentCache interface { - content.Provider - content.Ingester -} - -type loader struct { - resolver remotes.Resolver - cache contentCache -} - -type manifest struct { - desc ocispec.Descriptor - manifest ocispec.Manifest -} - -type index struct { - desc ocispec.Descriptor - index ocispec.Index -} - -type asset struct { - config *ocispec.Image - sbom *sbomStub - provenance *provenanceStub - - deferredSbom func() (*sbomStub, error) - deferredProvenance func() (*provenanceStub, error) -} - -type result struct { - mu sync.Mutex - indexes map[digest.Digest]index - manifests map[digest.Digest]manifest - images map[string]digest.Digest - refs map[digest.Digest][]digest.Digest - - platforms []string - assets map[string]asset -} - -func newLoader(resolver remotes.Resolver) *loader { - return &loader{ - resolver: resolver, - cache: contentutil.NewBuffer(), - } -} - -func (l *loader) Load(ctx context.Context, ref string) (*result, error) { - named, err := parseRef(ref) - if err != nil { - return nil, err - } - - _, desc, err := l.resolver.Resolve(ctx, named.String()) - if err != nil { - return nil, err - } - - canonical, err := reference.WithDigest(named, desc.Digest) - if err != nil { - return nil, err - } - - fetcher, err := l.resolver.Fetcher(ctx, canonical.String()) - if err != nil { - return nil, err - } - - r := &result{ - indexes: make(map[digest.Digest]index), - manifests: make(map[digest.Digest]manifest), - images: make(map[string]digest.Digest), - refs: make(map[digest.Digest][]digest.Digest), - assets: make(map[string]asset), - } - - if err := l.fetch(ctx, fetcher, desc, r); err != nil { - return nil, err - } - - for platform, dgst := range r.images { - r.platforms = append(r.platforms, platform) - - mfst, ok := r.manifests[dgst] - if !ok { - return nil, errors.Errorf("image %s not found", platform) - } - - var a asset - annotations := make(map[string]string, len(mfst.manifest.Annotations)+len(mfst.desc.Annotations)) - for k, v := range mfst.desc.Annotations { - annotations[k] = v - } - for k, v := range mfst.manifest.Annotations { - annotations[k] = v - } - - if err := l.scanConfig(ctx, fetcher, mfst.manifest.Config, &a); err != nil { - return nil, err - } - - refs, ok := r.refs[dgst] - if ok { - if err := l.scanSBOM(ctx, fetcher, r, refs, &a); err != nil { - return nil, err - } - } - - if err := l.scanProvenance(ctx, fetcher, r, refs, &a); err != nil { - return nil, err - } - - r.assets[platform] = a - } - - sort.Strings(r.platforms) - return r, nil -} - -func (l *loader) fetch(ctx context.Context, fetcher remotes.Fetcher, desc ocispec.Descriptor, r *result) error { - _, err := remotes.FetchHandler(l.cache, fetcher)(ctx, desc) - if err != nil { - return err - } - - switch desc.MediaType { - case images.MediaTypeDockerSchema2Manifest, ocispec.MediaTypeImageManifest: - var mfst ocispec.Manifest - dt, err := content.ReadBlob(ctx, l.cache, desc) - if err != nil { - return err - } - if err := json.Unmarshal(dt, &mfst); err != nil { - return err - } - r.mu.Lock() - r.manifests[desc.Digest] = manifest{ - desc: desc, - manifest: mfst, - } - r.mu.Unlock() - - found := false - for _, annotationReference := range annotationReferences { - ref, ok := desc.Annotations[annotationReference] - if !ok { - continue - } - - refdgst, err := digest.Parse(ref) - if err != nil { - return err - } - r.mu.Lock() - r.refs[refdgst] = append(r.refs[refdgst], desc.Digest) - r.mu.Unlock() - found = true - break - } - if !found { - p := desc.Platform - if p == nil { - p, err = l.readPlatformFromConfig(ctx, fetcher, mfst.Config) - if err != nil { - return err - } - } - r.mu.Lock() - r.images[platforms.Format(platforms.Normalize(*p))] = desc.Digest - r.mu.Unlock() - } - case images.MediaTypeDockerSchema2ManifestList, ocispec.MediaTypeImageIndex: - var idx ocispec.Index - dt, err := content.ReadBlob(ctx, l.cache, desc) - if err != nil { - return err - } - - if err := json.Unmarshal(dt, &idx); err != nil { - return err - } - - r.mu.Lock() - r.indexes[desc.Digest] = index{ - desc: desc, - index: idx, - } - r.mu.Unlock() - - eg, ctx := errgroup.WithContext(ctx) - for _, d := range idx.Manifests { - d := d - eg.Go(func() error { - return l.fetch(ctx, fetcher, d, r) - }) - } - - if err := eg.Wait(); err != nil { - return err - } - default: - } - return nil -} - -func (l *loader) readPlatformFromConfig(ctx context.Context, fetcher remotes.Fetcher, desc ocispec.Descriptor) (*ocispec.Platform, error) { - _, err := remotes.FetchHandler(l.cache, fetcher)(ctx, desc) - if err != nil { - return nil, err - } - - dt, err := content.ReadBlob(ctx, l.cache, desc) - if err != nil { - return nil, err - } - - var config ocispec.Image - if err := json.Unmarshal(dt, &config); err != nil { - return nil, err - } - - return &ocispec.Platform{ - OS: config.OS, - Architecture: config.Architecture, - Variant: config.Variant, - }, nil -} - -func (l *loader) scanConfig(ctx context.Context, fetcher remotes.Fetcher, desc ocispec.Descriptor, as *asset) error { - _, err := remotes.FetchHandler(l.cache, fetcher)(ctx, desc) - if err != nil { - return err - } - dt, err := content.ReadBlob(ctx, l.cache, desc) - if err != nil { - return err - } - return json.Unmarshal(dt, &as.config) -} - -type sbomStub struct { - SPDX interface{} `json:",omitempty"` - AdditionalSPDXs []interface{} `json:",omitempty"` -} - -func (l *loader) scanSBOM(ctx context.Context, fetcher remotes.Fetcher, r *result, refs []digest.Digest, as *asset) error { - ctx = remotes.WithMediaTypeKeyPrefix(ctx, "application/vnd.in-toto+json", "intoto") - as.deferredSbom = func() (*sbomStub, error) { - var sbom *sbomStub - for _, dgst := range refs { - mfst, ok := r.manifests[dgst] - if !ok { - return nil, errors.Errorf("referenced image %s not found", dgst) - } - for _, layer := range mfst.manifest.Layers { - if layer.MediaType == "application/vnd.in-toto+json" && layer.Annotations["in-toto.io/predicate-type"] == "https://spdx.dev/Document" { - _, err := remotes.FetchHandler(l.cache, fetcher)(ctx, layer) - if err != nil { - return nil, err - } - dt, err := content.ReadBlob(ctx, l.cache, layer) - if err != nil { - return nil, err - } - var spdx struct { - Predicate interface{} `json:"predicate"` - } - if err := json.Unmarshal(dt, &spdx); err != nil { - return nil, err - } - - if sbom == nil { - sbom = &sbomStub{} - sbom.SPDX = spdx.Predicate - } else { - sbom.AdditionalSPDXs = append(sbom.AdditionalSPDXs, spdx.Predicate) - } - } - } - } - return sbom, nil - } - return nil -} - -type provenanceStub struct { - SLSA interface{} `json:",omitempty"` -} - -func (l *loader) scanProvenance(ctx context.Context, fetcher remotes.Fetcher, r *result, refs []digest.Digest, as *asset) error { - ctx = remotes.WithMediaTypeKeyPrefix(ctx, "application/vnd.in-toto+json", "intoto") - as.deferredProvenance = func() (*provenanceStub, error) { - var provenance *provenanceStub - for _, dgst := range refs { - mfst, ok := r.manifests[dgst] - if !ok { - return nil, errors.Errorf("referenced image %s not found", dgst) - } - for _, layer := range mfst.manifest.Layers { - if layer.MediaType == "application/vnd.in-toto+json" && strings.HasPrefix(layer.Annotations["in-toto.io/predicate-type"], "https://slsa.dev/provenance/") { - _, err := remotes.FetchHandler(l.cache, fetcher)(ctx, layer) - if err != nil { - return nil, err - } - dt, err := content.ReadBlob(ctx, l.cache, layer) - if err != nil { - return nil, err - } - var slsa struct { - Predicate interface{} `json:"predicate"` - } - if err := json.Unmarshal(dt, &slsa); err != nil { - return nil, err - } - provenance = &provenanceStub{ - SLSA: slsa.Predicate, - } - break - } - } - } - return provenance, nil - } - return nil -} - -func (r *result) Configs() map[string]*ocispec.Image { - if len(r.assets) == 0 { - return nil - } - res := make(map[string]*ocispec.Image) - for p, a := range r.assets { - if a.config == nil { - continue - } - res[p] = a.config - } - return res -} - -func (r *result) Provenance() (map[string]provenanceStub, error) { - if len(r.assets) == 0 { - return nil, nil - } - res := make(map[string]provenanceStub) - for p, a := range r.assets { - if a.deferredProvenance == nil { - continue - } - if a.provenance == nil { - provenance, err := a.deferredProvenance() - if err != nil { - return nil, err - } - if provenance == nil { - continue - } - a.provenance = provenance - } - res[p] = *a.provenance - } - return res, nil -} - -func (r *result) SBOM() (map[string]sbomStub, error) { - if len(r.assets) == 0 { - return nil, nil - } - res := make(map[string]sbomStub) - for p, a := range r.assets { - if a.deferredSbom == nil { - continue - } - if a.sbom == nil { - sbom, err := a.deferredSbom() - if err != nil { - return nil, err - } - if sbom == nil { - continue - } - a.sbom = sbom - } - res[p] = *a.sbom - } - return res, nil -} diff --git a/vendor/github.com/docker/buildx/util/imagetools/printers.go b/vendor/github.com/docker/buildx/util/imagetools/printers.go deleted file mode 100644 index 78041cc72..000000000 --- a/vendor/github.com/docker/buildx/util/imagetools/printers.go +++ /dev/null @@ -1,251 +0,0 @@ -package imagetools - -import ( - "context" - "encoding/json" - "fmt" - "io" - "os" - "strings" - "text/tabwriter" - "text/template" - - "github.com/containerd/containerd/images" - "github.com/containerd/containerd/platforms" - "github.com/docker/distribution/reference" - "github.com/opencontainers/go-digest" - ocispecs "github.com/opencontainers/image-spec/specs-go/v1" -) - -const defaultPfx = " " - -type Printer struct { - ctx context.Context - resolver *Resolver - - name string - format string - - raw []byte - ref reference.Named - manifest ocispecs.Descriptor - index ocispecs.Index -} - -func NewPrinter(ctx context.Context, opt Opt, name string, format string) (*Printer, error) { - resolver := New(opt) - - ref, err := parseRef(name) - if err != nil { - return nil, err - } - - dt, mfst, err := resolver.Get(ctx, ref.String()) - if err != nil { - return nil, err - } - - var idx ocispecs.Index - if err = json.Unmarshal(dt, &idx); err != nil { - return nil, err - } - - return &Printer{ - ctx: ctx, - resolver: resolver, - name: name, - format: format, - raw: dt, - ref: ref, - manifest: mfst, - index: idx, - }, nil -} - -func (p *Printer) Print(raw bool, out io.Writer) error { - if raw { - _, err := fmt.Fprintf(out, "%s", p.raw) // avoid newline to keep digest - return err - } - - if p.format == "" { - w := tabwriter.NewWriter(out, 0, 0, 1, ' ', 0) - _, _ = fmt.Fprintf(w, "Name:\t%s\n", p.ref.String()) - _, _ = fmt.Fprintf(w, "MediaType:\t%s\n", p.manifest.MediaType) - _, _ = fmt.Fprintf(w, "Digest:\t%s\n", p.manifest.Digest) - _ = w.Flush() - switch p.manifest.MediaType { - case images.MediaTypeDockerSchema2ManifestList, ocispecs.MediaTypeImageIndex: - if err := p.printManifestList(out); err != nil { - return err - } - } - return nil - } - - res, err := newLoader(p.resolver.resolver()).Load(p.ctx, p.name) - if err != nil { - return err - } - - tpl, err := template.New("").Funcs(template.FuncMap{ - "json": func(v interface{}) string { - b, _ := json.MarshalIndent(v, "", " ") - return string(b) - }, - }).Parse(p.format) - if err != nil { - return err - } - - imageconfigs := res.Configs() - format := tpl.Root.String() - - var mfst interface{} - switch p.manifest.MediaType { - case images.MediaTypeDockerSchema2Manifest, ocispecs.MediaTypeImageManifest: - mfst = p.manifest - case images.MediaTypeDockerSchema2ManifestList, ocispecs.MediaTypeImageIndex: - mfst = struct { - SchemaVersion int `json:"schemaVersion"` - MediaType string `json:"mediaType,omitempty"` - Digest digest.Digest `json:"digest"` - Size int64 `json:"size"` - Manifests []ocispecs.Descriptor `json:"manifests"` - Annotations map[string]string `json:"annotations,omitempty"` - }{ - SchemaVersion: p.index.Versioned.SchemaVersion, - MediaType: p.index.MediaType, - Digest: p.manifest.Digest, - Size: p.manifest.Size, - Manifests: p.index.Manifests, - Annotations: p.index.Annotations, - } - } - - switch { - // TODO: print formatted config - case strings.HasPrefix(format, "{{.Manifest"): - w := tabwriter.NewWriter(out, 0, 0, 1, ' ', 0) - _, _ = fmt.Fprintf(w, "Name:\t%s\n", p.ref.String()) - switch { - case strings.HasPrefix(format, "{{.Manifest"): - _, _ = fmt.Fprintf(w, "MediaType:\t%s\n", p.manifest.MediaType) - _, _ = fmt.Fprintf(w, "Digest:\t%s\n", p.manifest.Digest) - _ = w.Flush() - switch p.manifest.MediaType { - case images.MediaTypeDockerSchema2ManifestList, ocispecs.MediaTypeImageIndex: - _ = p.printManifestList(out) - } - } - default: - if len(res.platforms) > 1 { - return tpl.Execute(out, tplInputs{ - Name: p.name, - Manifest: mfst, - Image: imageconfigs, - result: res, - }) - } - var ic *ocispecs.Image - for _, v := range imageconfigs { - ic = v - } - return tpl.Execute(out, tplInput{ - Name: p.name, - Manifest: mfst, - Image: ic, - result: res, - }) - } - - return nil -} - -func (p *Printer) printManifestList(out io.Writer) error { - w := tabwriter.NewWriter(out, 0, 0, 1, ' ', 0) - _, _ = fmt.Fprintf(w, "\t\n") - _, _ = fmt.Fprintf(w, "Manifests:\t\n") - _ = w.Flush() - - w = tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', 0) - for i, m := range p.index.Manifests { - if i != 0 { - _, _ = fmt.Fprintf(w, "\t\n") - } - cr, err := reference.WithDigest(p.ref, m.Digest) - if err != nil { - return err - } - _, _ = fmt.Fprintf(w, "%sName:\t%s\n", defaultPfx, cr.String()) - _, _ = fmt.Fprintf(w, "%sMediaType:\t%s\n", defaultPfx, m.MediaType) - if p := m.Platform; p != nil { - _, _ = fmt.Fprintf(w, "%sPlatform:\t%s\n", defaultPfx, platforms.Format(*p)) - if p.OSVersion != "" { - _, _ = fmt.Fprintf(w, "%sOSVersion:\t%s\n", defaultPfx, p.OSVersion) - } - if len(p.OSFeatures) > 0 { - _, _ = fmt.Fprintf(w, "%sOSFeatures:\t%s\n", defaultPfx, strings.Join(p.OSFeatures, ", ")) - } - if len(m.URLs) > 0 { - _, _ = fmt.Fprintf(w, "%sURLs:\t%s\n", defaultPfx, strings.Join(m.URLs, ", ")) - } - if len(m.Annotations) > 0 { - _, _ = fmt.Fprintf(w, "%sAnnotations:\t\n", defaultPfx) - _ = w.Flush() - w2 := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', 0) - for k, v := range m.Annotations { - _, _ = fmt.Fprintf(w2, "%s%s:\t%s\n", defaultPfx+defaultPfx, k, v) - } - _ = w2.Flush() - } - } - } - return w.Flush() -} - -type tplInput struct { - Name string `json:"name,omitempty"` - Manifest interface{} `json:"manifest,omitempty"` - Image *ocispecs.Image `json:"image,omitempty"` - - result *result -} - -func (inp tplInput) SBOM() (sbomStub, error) { - sbom, err := inp.result.SBOM() - if err != nil { - return sbomStub{}, nil - } - for _, v := range sbom { - return v, nil - } - return sbomStub{}, nil -} - -func (inp tplInput) Provenance() (provenanceStub, error) { - provenance, err := inp.result.Provenance() - if err != nil { - return provenanceStub{}, nil - } - for _, v := range provenance { - return v, nil - } - return provenanceStub{}, nil -} - -type tplInputs struct { - Name string `json:"name,omitempty"` - Manifest interface{} `json:"manifest,omitempty"` - Image map[string]*ocispecs.Image `json:"image,omitempty"` - - result *result -} - -func (inp tplInputs) SBOM() (map[string]sbomStub, error) { - return inp.result.SBOM() -} - -func (inp tplInputs) Provenance() (map[string]provenanceStub, error) { - return inp.result.Provenance() -} diff --git a/vendor/github.com/docker/buildx/util/logutil/filter.go b/vendor/github.com/docker/buildx/util/logutil/filter.go deleted file mode 100644 index 2746cfc8a..000000000 --- a/vendor/github.com/docker/buildx/util/logutil/filter.go +++ /dev/null @@ -1,38 +0,0 @@ -package logutil - -import ( - "io" - "strings" - - "github.com/sirupsen/logrus" -) - -func NewFilter(levels []logrus.Level, filters ...string) logrus.Hook { - dl := logrus.New() - dl.SetOutput(io.Discard) - return &logsFilter{ - levels: levels, - filters: filters, - discardLogger: dl, - } -} - -type logsFilter struct { - levels []logrus.Level - filters []string - discardLogger *logrus.Logger -} - -func (d *logsFilter) Levels() []logrus.Level { - return d.levels -} - -func (d *logsFilter) Fire(entry *logrus.Entry) error { - for _, f := range d.filters { - if strings.Contains(entry.Message, f) { - entry.Logger = d.discardLogger - return nil - } - } - return nil -} diff --git a/vendor/github.com/docker/buildx/util/logutil/format.go b/vendor/github.com/docker/buildx/util/logutil/format.go deleted file mode 100644 index b392e2a65..000000000 --- a/vendor/github.com/docker/buildx/util/logutil/format.go +++ /dev/null @@ -1,23 +0,0 @@ -package logutil - -import ( - "bytes" - "fmt" - "strings" - - "github.com/sirupsen/logrus" -) - -type Formatter struct { - logrus.TextFormatter -} - -func (f *Formatter) Format(entry *logrus.Entry) ([]byte, error) { - msg := bytes.NewBuffer(nil) - fmt.Fprintf(msg, "%s: %s", strings.ToUpper(entry.Level.String()), entry.Message) - if v, ok := entry.Data[logrus.ErrorKey]; ok { - fmt.Fprintf(msg, ": %v", v) - } - fmt.Fprintf(msg, "\n") - return msg.Bytes(), nil -} diff --git a/vendor/github.com/docker/buildx/util/logutil/pause.go b/vendor/github.com/docker/buildx/util/logutil/pause.go deleted file mode 100644 index 930dca21e..000000000 --- a/vendor/github.com/docker/buildx/util/logutil/pause.go +++ /dev/null @@ -1,52 +0,0 @@ -package logutil - -import ( - "bytes" - "io" - "sync" - - "github.com/sirupsen/logrus" -) - -func Pause(l *logrus.Logger) func() { - // initialize formatter with original terminal settings - l.Formatter.Format(logrus.NewEntry(l)) - - bw := newBufferedWriter(l.Out) - l.SetOutput(bw) - return func() { - bw.resume() - } -} - -type bufferedWriter struct { - mu sync.Mutex - buf *bytes.Buffer - w io.Writer -} - -func newBufferedWriter(w io.Writer) *bufferedWriter { - return &bufferedWriter{ - buf: bytes.NewBuffer(nil), - w: w, - } -} - -func (bw *bufferedWriter) Write(p []byte) (int, error) { - bw.mu.Lock() - defer bw.mu.Unlock() - if bw.buf == nil { - return bw.w.Write(p) - } - return bw.buf.Write(p) -} - -func (bw *bufferedWriter) resume() { - bw.mu.Lock() - defer bw.mu.Unlock() - if bw.buf == nil { - return - } - io.Copy(bw.w, bw.buf) - bw.buf = nil -} diff --git a/vendor/github.com/docker/buildx/util/platformutil/parse.go b/vendor/github.com/docker/buildx/util/platformutil/parse.go deleted file mode 100644 index c17a77cca..000000000 --- a/vendor/github.com/docker/buildx/util/platformutil/parse.go +++ /dev/null @@ -1,86 +0,0 @@ -package platformutil - -import ( - "strings" - - "github.com/containerd/containerd/platforms" - specs "github.com/opencontainers/image-spec/specs-go/v1" -) - -func Parse(platformsStr []string) ([]specs.Platform, error) { - if len(platformsStr) == 0 { - return nil, nil - } - out := make([]specs.Platform, 0, len(platformsStr)) - for _, s := range platformsStr { - parts := strings.Split(s, ",") - if len(parts) > 1 { - p, err := Parse(parts) - if err != nil { - return nil, err - } - out = append(out, p...) - continue - } - p, err := parse(s) - if err != nil { - return nil, err - } - out = append(out, platforms.Normalize(p)) - } - return out, nil -} - -func parse(in string) (specs.Platform, error) { - if strings.EqualFold(in, "local") { - return platforms.DefaultSpec(), nil - } - return platforms.Parse(in) -} - -func Dedupe(in []specs.Platform) []specs.Platform { - m := map[string]struct{}{} - out := make([]specs.Platform, 0, len(in)) - for _, p := range in { - p := platforms.Normalize(p) - key := platforms.Format(p) - if _, ok := m[key]; ok { - continue - } - m[key] = struct{}{} - out = append(out, p) - } - return out -} - -func FormatInGroups(gg ...[]specs.Platform) []string { - m := map[string]struct{}{} - out := make([]string, 0, len(gg)) - for i, g := range gg { - for _, p := range g { - p := platforms.Normalize(p) - key := platforms.Format(p) - if _, ok := m[key]; ok { - continue - } - m[key] = struct{}{} - v := platforms.Format(p) - if i == 0 { - v += "*" - } - out = append(out, v) - } - } - return out -} - -func Format(in []specs.Platform) []string { - if len(in) == 0 { - return nil - } - out := make([]string, 0, len(in)) - for _, p := range in { - out = append(out, platforms.Format(p)) - } - return out -} diff --git a/vendor/github.com/docker/buildx/util/progress/fromreader.go b/vendor/github.com/docker/buildx/util/progress/fromreader.go deleted file mode 100644 index dbff5afc8..000000000 --- a/vendor/github.com/docker/buildx/util/progress/fromreader.go +++ /dev/null @@ -1,37 +0,0 @@ -package progress - -import ( - "io" - "time" - - "github.com/moby/buildkit/client" - "github.com/moby/buildkit/identity" - "github.com/opencontainers/go-digest" -) - -func FromReader(w Writer, name string, rc io.ReadCloser) { - dgst := digest.FromBytes([]byte(identity.NewID())) - tm := time.Now() - - vtx := client.Vertex{ - Digest: dgst, - Name: name, - Started: &tm, - } - - w.Write(&client.SolveStatus{ - Vertexes: []*client.Vertex{&vtx}, - }) - - _, err := io.Copy(io.Discard, rc) - - tm2 := time.Now() - vtx2 := vtx - vtx2.Completed = &tm2 - if err != nil { - vtx2.Error = err.Error() - } - w.Write(&client.SolveStatus{ - Vertexes: []*client.Vertex{&vtx2}, - }) -} diff --git a/vendor/github.com/docker/buildx/util/progress/multiwriter.go b/vendor/github.com/docker/buildx/util/progress/multiwriter.go deleted file mode 100644 index a4f9b5037..000000000 --- a/vendor/github.com/docker/buildx/util/progress/multiwriter.go +++ /dev/null @@ -1,40 +0,0 @@ -package progress - -import ( - "strings" - - "github.com/moby/buildkit/client" -) - -func WithPrefix(w Writer, pfx string, force bool) Writer { - return &prefixed{ - Writer: w, - pfx: pfx, - force: force, - } -} - -type prefixed struct { - Writer - pfx string - force bool -} - -func (p *prefixed) Write(v *client.SolveStatus) { - if p.force { - for _, v := range v.Vertexes { - v.Name = addPrefix(p.pfx, v.Name) - if v.ProgressGroup != nil { - v.ProgressGroup.Name = addPrefix(p.pfx, v.ProgressGroup.Name) - } - } - } - p.Writer.Write(v) -} - -func addPrefix(pfx, name string) string { - if strings.HasPrefix(name, "[") { - return "[" + pfx + " " + name[1:] - } - return "[" + pfx + "] " + name -} diff --git a/vendor/github.com/docker/buildx/util/progress/printer.go b/vendor/github.com/docker/buildx/util/progress/printer.go deleted file mode 100644 index fdc74d917..000000000 --- a/vendor/github.com/docker/buildx/util/progress/printer.go +++ /dev/null @@ -1,188 +0,0 @@ -package progress - -import ( - "context" - "io" - "os" - "sync" - - "github.com/containerd/console" - "github.com/docker/buildx/util/logutil" - "github.com/moby/buildkit/client" - "github.com/moby/buildkit/util/progress/progressui" - "github.com/opencontainers/go-digest" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" -) - -const ( - PrinterModeAuto = "auto" - PrinterModeTty = "tty" - PrinterModePlain = "plain" - PrinterModeQuiet = "quiet" -) - -type Printer struct { - status chan *client.SolveStatus - - ready chan struct{} - done chan struct{} - paused chan struct{} - - err error - warnings []client.VertexWarning - logMu sync.Mutex - logSourceMap map[digest.Digest]interface{} - - // TODO: remove once we can use result context to pass build ref - // see https://github.com/docker/buildx/pull/1861 - buildRefsMu sync.Mutex - buildRefs map[string]string -} - -func (p *Printer) Wait() error { - close(p.status) - <-p.done - return p.err -} - -func (p *Printer) Pause() error { - p.paused = make(chan struct{}) - return p.Wait() -} - -func (p *Printer) Unpause() { - close(p.paused) - <-p.ready -} - -func (p *Printer) Write(s *client.SolveStatus) { - p.status <- s -} - -func (p *Printer) Warnings() []client.VertexWarning { - return p.warnings -} - -func (p *Printer) ValidateLogSource(dgst digest.Digest, v interface{}) bool { - p.logMu.Lock() - defer p.logMu.Unlock() - src, ok := p.logSourceMap[dgst] - if ok { - if src == v { - return true - } - } else { - p.logSourceMap[dgst] = v - return true - } - return false -} - -func (p *Printer) ClearLogSource(v interface{}) { - p.logMu.Lock() - defer p.logMu.Unlock() - for d := range p.logSourceMap { - if p.logSourceMap[d] == v { - delete(p.logSourceMap, d) - } - } -} - -func NewPrinter(ctx context.Context, w io.Writer, out console.File, mode string, opts ...PrinterOpt) (*Printer, error) { - opt := &printerOpts{} - for _, o := range opts { - o(opt) - } - - if v := os.Getenv("BUILDKIT_PROGRESS"); v != "" && mode == PrinterModeAuto { - mode = v - } - - var c console.Console - switch mode { - case PrinterModeQuiet: - w = io.Discard - case PrinterModeAuto, PrinterModeTty: - if cons, err := console.ConsoleFromFile(out); err == nil { - c = cons - } else { - if mode == PrinterModeTty { - return nil, errors.Wrap(err, "failed to get console") - } - } - } - - pw := &Printer{ - ready: make(chan struct{}), - } - go func() { - for { - pw.status = make(chan *client.SolveStatus) - pw.done = make(chan struct{}) - - pw.logMu.Lock() - pw.logSourceMap = map[digest.Digest]interface{}{} - pw.logMu.Unlock() - - resumeLogs := logutil.Pause(logrus.StandardLogger()) - close(pw.ready) - // not using shared context to not disrupt display but let is finish reporting errors - pw.warnings, pw.err = progressui.DisplaySolveStatus(ctx, c, w, pw.status, opt.displayOpts...) - resumeLogs() - close(pw.done) - - if opt.onclose != nil { - opt.onclose() - } - if pw.paused == nil { - break - } - - pw.ready = make(chan struct{}) - <-pw.paused - pw.paused = nil - } - }() - <-pw.ready - return pw, nil -} - -func (p *Printer) WriteBuildRef(target string, ref string) { - p.buildRefsMu.Lock() - defer p.buildRefsMu.Unlock() - if p.buildRefs == nil { - p.buildRefs = map[string]string{} - } - p.buildRefs[target] = ref -} - -func (p *Printer) BuildRefs() map[string]string { - return p.buildRefs -} - -type printerOpts struct { - displayOpts []progressui.DisplaySolveStatusOpt - - onclose func() -} - -type PrinterOpt func(b *printerOpts) - -func WithPhase(phase string) PrinterOpt { - return func(opt *printerOpts) { - opt.displayOpts = append(opt.displayOpts, progressui.WithPhase(phase)) - } -} - -func WithDesc(text string, console string) PrinterOpt { - return func(opt *printerOpts) { - opt.displayOpts = append(opt.displayOpts, progressui.WithDesc(text, console)) - } -} - -func WithOnClose(onclose func()) PrinterOpt { - return func(opt *printerOpts) { - opt.onclose = onclose - } -} diff --git a/vendor/github.com/docker/buildx/util/progress/progress.go b/vendor/github.com/docker/buildx/util/progress/progress.go deleted file mode 100644 index 8e616aa9a..000000000 --- a/vendor/github.com/docker/buildx/util/progress/progress.go +++ /dev/null @@ -1,98 +0,0 @@ -package progress - -import ( - "time" - - "github.com/moby/buildkit/client" - "github.com/moby/buildkit/identity" - "github.com/opencontainers/go-digest" -) - -type Logger func(*client.SolveStatus) - -type SubLogger interface { - Wrap(name string, fn func() error) error - Log(stream int, dt []byte) - SetStatus(*client.VertexStatus) -} - -func Wrap(name string, l Logger, fn func(SubLogger) error) (err error) { - dgst := digest.FromBytes([]byte(identity.NewID())) - tm := time.Now() - l(&client.SolveStatus{ - Vertexes: []*client.Vertex{{ - Digest: dgst, - Name: name, - Started: &tm, - }}, - }) - - defer func() { - tm2 := time.Now() - errMsg := "" - if err != nil { - errMsg = err.Error() - } - l(&client.SolveStatus{ - Vertexes: []*client.Vertex{{ - Digest: dgst, - Name: name, - Started: &tm, - Completed: &tm2, - Error: errMsg, - }}, - }) - }() - - return fn(&subLogger{dgst, l}) -} - -type subLogger struct { - dgst digest.Digest - logger Logger -} - -func (sl *subLogger) Wrap(name string, fn func() error) (err error) { - tm := time.Now() - sl.logger(&client.SolveStatus{ - Statuses: []*client.VertexStatus{{ - Vertex: sl.dgst, - ID: name, - Timestamp: time.Now(), - Started: &tm, - }}, - }) - - defer func() { - tm2 := time.Now() - sl.logger(&client.SolveStatus{ - Statuses: []*client.VertexStatus{{ - Vertex: sl.dgst, - ID: name, - Timestamp: time.Now(), - Started: &tm, - Completed: &tm2, - }}, - }) - }() - - return fn() -} - -func (sl *subLogger) Log(stream int, dt []byte) { - sl.logger(&client.SolveStatus{ - Logs: []*client.VertexLog{{ - Vertex: sl.dgst, - Stream: stream, - Data: dt, - Timestamp: time.Now(), - }}, - }) -} - -func (sl *subLogger) SetStatus(st *client.VertexStatus) { - st.Vertex = sl.dgst - sl.logger(&client.SolveStatus{ - Statuses: []*client.VertexStatus{st}, - }) -} diff --git a/vendor/github.com/docker/buildx/util/progress/reset.go b/vendor/github.com/docker/buildx/util/progress/reset.go deleted file mode 100644 index 2f2752152..000000000 --- a/vendor/github.com/docker/buildx/util/progress/reset.go +++ /dev/null @@ -1,60 +0,0 @@ -package progress - -import ( - "time" - - "github.com/moby/buildkit/client" -) - -func ResetTime(in Writer) Writer { - return &pw{Writer: in, status: make(chan *client.SolveStatus), tm: time.Now()} -} - -func (w *pw) Write(st *client.SolveStatus) { - if w.diff == nil { - for _, v := range st.Vertexes { - if v.Started != nil { - d := v.Started.Sub(w.tm) - w.diff = &d - } - } - } - if w.diff != nil { - for _, v := range st.Vertexes { - if v.Started != nil { - d := v.Started.Add(-*w.diff) - v.Started = &d - } - if v.Completed != nil { - d := v.Completed.Add(-*w.diff) - v.Completed = &d - } - } - for _, v := range st.Statuses { - if v.Started != nil { - d := v.Started.Add(-*w.diff) - v.Started = &d - } - if v.Completed != nil { - d := v.Completed.Add(-*w.diff) - v.Completed = &d - } - v.Timestamp = v.Timestamp.Add(-*w.diff) - } - for _, v := range st.Logs { - v.Timestamp = v.Timestamp.Add(-*w.diff) - } - } - w.Writer.Write(st) -} - -type pw struct { - Writer - tm time.Time - diff *time.Duration - status chan *client.SolveStatus -} - -func (w *pw) Status() chan *client.SolveStatus { - return w.status -} diff --git a/vendor/github.com/docker/buildx/util/progress/writer.go b/vendor/github.com/docker/buildx/util/progress/writer.go deleted file mode 100644 index 8e566f118..000000000 --- a/vendor/github.com/docker/buildx/util/progress/writer.go +++ /dev/null @@ -1,96 +0,0 @@ -package progress - -import ( - "time" - - "github.com/moby/buildkit/client" - "github.com/moby/buildkit/identity" - "github.com/opencontainers/go-digest" -) - -type Writer interface { - Write(*client.SolveStatus) - WriteBuildRef(string, string) - ValidateLogSource(digest.Digest, interface{}) bool - ClearLogSource(interface{}) -} - -func Write(w Writer, name string, f func() error) { - dgst := digest.FromBytes([]byte(identity.NewID())) - tm := time.Now() - - vtx := client.Vertex{ - Digest: dgst, - Name: name, - Started: &tm, - } - - w.Write(&client.SolveStatus{ - Vertexes: []*client.Vertex{&vtx}, - }) - - err := f() - - tm2 := time.Now() - vtx2 := vtx - vtx2.Completed = &tm2 - if err != nil { - vtx2.Error = err.Error() - } - w.Write(&client.SolveStatus{ - Vertexes: []*client.Vertex{&vtx2}, - }) -} - -func WriteBuildRef(w Writer, target string, ref string) { - w.WriteBuildRef(target, ref) -} - -func NewChannel(w Writer) (chan *client.SolveStatus, chan struct{}) { - ch := make(chan *client.SolveStatus) - done := make(chan struct{}) - go func() { - for { - v, ok := <-ch - if !ok { - close(done) - w.ClearLogSource(done) - return - } - - if len(v.Logs) > 0 { - logs := make([]*client.VertexLog, 0, len(v.Logs)) - for _, l := range v.Logs { - if w.ValidateLogSource(l.Vertex, done) { - logs = append(logs, l) - } - } - v.Logs = logs - } - - w.Write(v) - } - }() - return ch, done -} - -type tee struct { - Writer - ch chan *client.SolveStatus -} - -func (t *tee) Write(v *client.SolveStatus) { - v2 := *v - t.ch <- &v2 - t.Writer.Write(v) -} - -func Tee(w Writer, ch chan *client.SolveStatus) Writer { - if ch == nil { - return w - } - return &tee{ - Writer: w, - ch: ch, - } -} diff --git a/vendor/github.com/docker/buildx/util/resolver/resolver.go b/vendor/github.com/docker/buildx/util/resolver/resolver.go deleted file mode 100644 index 1f0c4ba0e..000000000 --- a/vendor/github.com/docker/buildx/util/resolver/resolver.go +++ /dev/null @@ -1,188 +0,0 @@ -package resolver - -import ( - "crypto/tls" - "crypto/x509" - "net" - "net/http" - "runtime" - "time" - - "github.com/containerd/containerd/remotes/docker" - "github.com/moby/buildkit/util/tracing" - "github.com/pkg/errors" -) - -// TODO: copied from buildkit/util/resolver. Update upstream so we can use the same code. - -type RegistryConfig struct { - Mirrors []string - PlainHTTP *bool - Insecure *bool - RootCAs [][]byte - KeyPairs []TLSKeyPair -} - -type TLSKeyPair struct { - Key []byte - Certificate []byte -} - -func fillInsecureOpts(host string, c RegistryConfig, h docker.RegistryHost) ([]docker.RegistryHost, error) { - var hosts []docker.RegistryHost - - tc, err := loadTLSConfig(c) - if err != nil { - return nil, err - } - var isHTTP bool - - if c.PlainHTTP != nil && *c.PlainHTTP { - isHTTP = true - } - if c.PlainHTTP == nil { - if ok, _ := docker.MatchLocalhost(host); ok { - isHTTP = true - } - } - - if isHTTP { - h2 := h - h2.Scheme = "http" - hosts = append(hosts, h2) - } - if c.Insecure != nil && *c.Insecure { - h2 := h - transport := newDefaultTransport() - transport.TLSClientConfig = tc - h2.Client = &http.Client{ - Transport: tracing.NewTransport(transport), - } - tc.InsecureSkipVerify = true - hosts = append(hosts, h2) - } - - if len(hosts) == 0 { - transport := newDefaultTransport() - transport.TLSClientConfig = tc - - h.Client = &http.Client{ - Transport: tracing.NewTransport(transport), - } - hosts = append(hosts, h) - } - - return hosts, nil -} - -func loadTLSConfig(c RegistryConfig) (*tls.Config, error) { - tc := &tls.Config{} - if len(c.RootCAs) > 0 { - systemPool, err := x509.SystemCertPool() - if err != nil { - if runtime.GOOS == "windows" { - systemPool = x509.NewCertPool() - } else { - return nil, errors.Wrapf(err, "unable to get system cert pool") - } - } - tc.RootCAs = systemPool - } - - for _, p := range c.RootCAs { - tc.RootCAs.AppendCertsFromPEM(p) - } - - for _, kp := range c.KeyPairs { - cert, err := tls.X509KeyPair(kp.Certificate, kp.Key) - if err != nil { - return nil, errors.Wrapf(err, "failed to load keypair for %s", kp.Certificate) - } - tc.Certificates = append(tc.Certificates, cert) - } - return tc, nil -} - -// NewRegistryConfig converts registry config to docker.RegistryHosts callback -func NewRegistryConfig(m map[string]RegistryConfig) docker.RegistryHosts { - return docker.Registries( - func(host string) ([]docker.RegistryHost, error) { - c, ok := m[host] - if !ok { - return nil, nil - } - - var out []docker.RegistryHost - - for _, mirror := range c.Mirrors { - h := docker.RegistryHost{ - Scheme: "https", - Client: newDefaultClient(), - Host: mirror, - Path: "/v2", - Capabilities: docker.HostCapabilityPull | docker.HostCapabilityResolve, - } - - hosts, err := fillInsecureOpts(mirror, m[mirror], h) - if err != nil { - return nil, err - } - - out = append(out, hosts...) - } - - if host == "docker.io" { - host = "registry-1.docker.io" - } - - h := docker.RegistryHost{ - Scheme: "https", - Client: newDefaultClient(), - Host: host, - Path: "/v2", - Capabilities: docker.HostCapabilityPush | docker.HostCapabilityPull | docker.HostCapabilityResolve, - } - - hosts, err := fillInsecureOpts(host, c, h) - if err != nil { - return nil, err - } - - out = append(out, hosts...) - return out, nil - }, - docker.ConfigureDefaultRegistries( - docker.WithClient(newDefaultClient()), - docker.WithPlainHTTP(docker.MatchLocalhost), - ), - ) -} - -func newDefaultClient() *http.Client { - return &http.Client{ - Transport: tracing.NewTransport(newDefaultTransport()), - } -} - -// newDefaultTransport is for pull or push client -// -// NOTE: For push, there must disable http2 for https because the flow control -// will limit data transfer. The net/http package doesn't provide http2 tunable -// settings which limits push performance. -// -// REF: https://github.com/golang/go/issues/14077 -func newDefaultTransport() *http.Transport { - return &http.Transport{ - Proxy: http.ProxyFromEnvironment, - DialContext: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 60 * time.Second, - }).DialContext, - MaxIdleConns: 30, - IdleConnTimeout: 120 * time.Second, - MaxIdleConnsPerHost: 4, - TLSHandshakeTimeout: 10 * time.Second, - ExpectContinueTimeout: 5 * time.Second, - TLSNextProto: make(map[string]func(authority string, c *tls.Conn) http.RoundTripper), - } -} diff --git a/vendor/github.com/docker/buildx/util/waitmap/waitmap.go b/vendor/github.com/docker/buildx/util/waitmap/waitmap.go deleted file mode 100644 index c34b8f0cb..000000000 --- a/vendor/github.com/docker/buildx/util/waitmap/waitmap.go +++ /dev/null @@ -1,74 +0,0 @@ -package waitmap - -import ( - "context" - "sync" -) - -type Map struct { - mu sync.RWMutex - m map[string]interface{} - ch map[string]chan struct{} -} - -func New() *Map { - return &Map{ - m: make(map[string]interface{}), - ch: make(map[string]chan struct{}), - } -} - -func (m *Map) Set(key string, value interface{}) { - m.mu.Lock() - defer m.mu.Unlock() - - m.m[key] = value - - if ch, ok := m.ch[key]; ok { - if ch != nil { - close(ch) - } - } - m.ch[key] = nil -} - -func (m *Map) Get(ctx context.Context, keys ...string) (map[string]interface{}, error) { - if len(keys) == 0 { - return map[string]interface{}{}, nil - } - - if len(keys) > 1 { - out := make(map[string]interface{}) - for _, key := range keys { - mm, err := m.Get(ctx, key) - if err != nil { - return nil, err - } - out[key] = mm[key] - } - return out, nil - } - - key := keys[0] - m.mu.Lock() - ch, ok := m.ch[key] - if !ok { - ch = make(chan struct{}) - m.ch[key] = ch - } - - if ch != nil { - m.mu.Unlock() - select { - case <-ctx.Done(): - return nil, ctx.Err() - case <-ch: - m.mu.Lock() - } - } - - res := m.m[key] - m.mu.Unlock() - - return map[string]interface{}{key: res}, nil -} diff --git a/vendor/github.com/docker/cli/AUTHORS b/vendor/github.com/docker/cli/AUTHORS deleted file mode 100644 index 483743c99..000000000 --- a/vendor/github.com/docker/cli/AUTHORS +++ /dev/null @@ -1,852 +0,0 @@ -# File @generated by scripts/docs/generate-authors.sh. DO NOT EDIT. -# This file lists all contributors to the repository. -# See scripts/docs/generate-authors.sh to make modifications. - -Aanand Prasad -Aaron L. Xu -Aaron Lehmann -Aaron.L.Xu -Abdur Rehman -Abhinandan Prativadi -Abin Shahab -Abreto FU -Ace Tang -Addam Hardy -Adolfo Ochagavía -Adrian Plata -Adrien Duermael -Adrien Folie -Ahmet Alp Balkan -Aidan Feldman -Aidan Hobson Sayers -AJ Bowen -Akhil Mohan -Akihiro Suda -Akim Demaille -Alan Thompson -Albert Callarisa -Alberto Roura -Albin Kerouanton -Aleksa Sarai -Aleksander Piotrowski -Alessandro Boch -Alex Couture-Beil -Alex Mavrogiannis -Alex Mayer -Alexander Boyd -Alexander Larsson -Alexander Morozov -Alexander Ryabov -Alexandre González -Alexey Igrychev -Alexis Couvreur -Alfred Landrum -Alicia Lauerman -Allen Sun -Alvin Deng -Amen Belayneh -Amey Shrivastava <72866602+AmeyShrivastava@users.noreply.github.com> -Amir Goldstein -Amit Krishnan -Amit Shukla -Amy Lindburg -Anca Iordache -Anda Xu -Andrea Luzzardi -Andreas Köhler -Andres G. Aragoneses -Andres Leon Rangel -Andrew France -Andrew Hsu -Andrew Macpherson -Andrew McDonnell -Andrew Po -Andrey Petrov -Andrii Berehuliak -André Martins -Andy Goldstein -Andy Rothfusz -Anil Madhavapeddy -Ankush Agarwal -Anne Henmi -Anton Polonskiy -Antonio Murdaca -Antonis Kalipetis -Anusha Ragunathan -Ao Li -Arash Deshmeh -Arko Dasgupta -Arnaud Porterie -Arnaud Rebillout -Arthur Peka -Ashwini Oruganti -Azat Khuyiyakhmetov -Bardia Keyoumarsi -Barnaby Gray -Bastiaan Bakker -BastianHofmann -Ben Bodenmiller -Ben Bonnefoy -Ben Creasy -Ben Firshman -Benjamin Boudreau -Benjamin Böhmke -Benjamin Nater -Benoit Sigoure -Bhumika Bayani -Bill Wang -Bin Liu -Bingshen Wang -Bishal Das -Boaz Shuster -Bogdan Anton -Boris Pruessmann -Brad Baker -Bradley Cicenas -Brandon Mitchell -Brandon Philips -Brent Salisbury -Bret Fisher -Brian (bex) Exelbierd -Brian Goff -Brian Wieder -Bruno Sousa -Bryan Bess -Bryan Boreham -Bryan Murphy -bryfry -Cameron Spear -Cao Weiwei -Carlo Mion -Carlos Alexandro Becker -Carlos de Paula -Ce Gao -Cedric Davies -Cezar Sa Espinola -Chad Faragher -Chao Wang -Charles Chan -Charles Law -Charles Smith -Charlie Drage -Charlotte Mach -ChaYoung You -Chee Hau Lim -Chen Chuanliang -Chen Hanxiao -Chen Mingjie -Chen Qiu -Chris Couzens -Chris Gavin -Chris Gibson -Chris McKinnel -Chris Snow -Chris Vermilion -Chris Weyl -Christian Persson -Christian Stefanescu -Christophe Robin -Christophe Vidal -Christopher Biscardi -Christopher Crone -Christopher Jones -Christopher Svensson -Christy Norman -Chun Chen -Clinton Kitson -Coenraad Loubser -Colin Hebert -Collin Guarino -Colm Hally -Comical Derskeal <27731088+derskeal@users.noreply.github.com> -Conner Crosby -Corey Farrell -Corey Quon -Cory Bennet -Craig Wilhite -Cristian Staretu -Daehyeok Mun -Dafydd Crosby -Daisuke Ito -dalanlan -Damien Nadé -Dan Cotora -Daniel Artine -Daniel Cassidy -Daniel Dao -Daniel Farrell -Daniel Gasienica -Daniel Goosen -Daniel Helfand -Daniel Hiltgen -Daniel J Walsh -Daniel Nephin -Daniel Norberg -Daniel Watkins -Daniel Zhang -Daniil Nikolenko -Danny Berger -Darren Shepherd -Darren Stahl -Dattatraya Kumbhar -Dave Goodchild -Dave Henderson -Dave Tucker -David Alvarez -David Beitey -David Calavera -David Cramer -David Dooling -David Gageot -David Karlsson -David Lechner -David Scott -David Sheets -David Williamson -David Xia -David Young -Deng Guangxing -Denis Defreyne -Denis Gladkikh -Denis Ollier -Dennis Docter -Derek McGowan -Des Preston -Deshi Xiao -Dharmit Shah -Dhawal Yogesh Bhanushali -Dieter Reuter -Dima Stopel -Dimitry Andric -Ding Fei -Diogo Monica -Djordje Lukic -Dmitriy Fishman -Dmitry Gusev -Dmitry Smirnov -Dmitry V. Krivenok -Dominik Braun -Don Kjer -Dong Chen -DongGeon Lee -Doug Davis -Drew Erny -Ed Costello -Elango Sivanandam -Eli Uriegas -Eli Uriegas -Elias Faxö -Elliot Luo <956941328@qq.com> -Eric Curtin -Eric Engestrom -Eric G. Noriega -Eric Rosenberg -Eric Sage -Eric-Olivier Lamey -Erica Windisch -Erik Hollensbe -Erik Humphrey -Erik St. Martin -Essam A. Hassan -Ethan Haynes -Euan Kemp -Eugene Yakubovich -Evan Allrich -Evan Hazlett -Evan Krall -Evelyn Xu -Everett Toews -Fabio Falci -Fabrizio Soppelsa -Felix Geyer -Felix Hupfeld -Felix Rabe -fezzik1620 -Filip Jareš -Flavio Crisciani -Florian Klein -Forest Johnson -Foysal Iqbal -François Scala -Fred Lifton -Frederic Hemberger -Frederick F. Kautz IV -Frederik Nordahl Jul Sabroe -Frieder Bluemle -Gabriel Gore -Gabriel Nicolas Avellaneda -Gaetan de Villele -Gang Qiao -Gary Schaetz -Genki Takiuchi -George MacRorie -George Xie -Gianluca Borello -Gildas Cuisinier -Gio d'Amelio -Gleb Stsenov -Goksu Toprak -Gou Rao -Govind Rai -Grant Reaber -Greg Pflaum -Gsealy -Guilhem Lettron -Guillaume J. Charmes -Guillaume Le Floch -Guillaume Tardif -gwx296173 -Günther Jungbluth -Hakan Özler -Hao Zhang <21521210@zju.edu.cn> -Harald Albers -Harold Cooper -Harry Zhang -He Simei -Hector S -Helen Xie -Henning Sprang -Henry N -Hernan Garcia -Hongbin Lu -Hu Keping -Huayi Zhang -Hugo Gabriel Eyherabide -huqun -Huu Nguyen -Hyzhou Zhy -Iain Samuel McLean Elder -Ian Campbell -Ian Philpot -Ignacio Capurro -Ilya Dmitrichenko -Ilya Khlopotov -Ilya Sotkov -Ioan Eugen Stan -Isabel Jimenez -Ivan Grcic -Ivan Grund -Ivan Markin -Jacob Atzen -Jacob Tomlinson -Jaivish Kothari -Jake Lambert -Jake Sanders -James Nesbitt -James Turnbull -Jamie Hannaford -Jan Koprowski -Jan Pazdziora -Jan-Jaap Driessen -Jana Radhakrishnan -Jared Hocutt -Jasmine Hegman -Jason Hall -Jason Heiss -Jason Plum -Jay Kamat -Jean Lecordier -Jean Rouge -Jean-Christophe Sirot -Jean-Pierre Huynh -Jeff Lindsay -Jeff Nickoloff -Jeff Silberman -Jennings Zhang -Jeremy Chambers -Jeremy Unruh -Jeremy Yallop -Jeroen Franse -Jesse Adametz -Jessica Frazelle -Jezeniel Zapanta -Jian Zhang -Jie Luo -Jilles Oldenbeuving -Jim Galasyn -Jim Lin -Jimmy Leger -Jimmy Song -jimmyxian -Jintao Zhang -Joao Fernandes -Joe Abbey -Joe Doliner -Joe Gordon -Joel Handwell -Joey Geiger -Joffrey F -Johan Euphrosine -Johannes 'fish' Ziemke -John Feminella -John Harris -John Howard -John Howard -John Laswell -John Maguire -John Mulhausen -John Starks -John Stephens -John Tims -John V. Martinez -John Willis -Jon Johnson -Jon Zeolla -Jonatas Baldin -Jonathan Boulle -Jonathan Lee -Jonathan Lomas -Jonathan McCrohan -Jonathan Warriss-Simmons -Jonh Wendell -Jordan Jennings -Jorge Vallecillo -Jose J. Escobar <53836904+jescobar-docker@users.noreply.github.com> -Joseph Kern -Josh Bodah -Josh Chorlton -Josh Hawn -Josh Horwitz -Josh Soref -Julien Barbier -Julien Kassar -Julien Maitrehenry -Justas Brazauskas -Justin Cormack -Justin Simonelis -Justyn Temme -Jyrki Puttonen -Jérémie Drouet -Jérôme Petazzoni -Jörg Thalheim -Kai Blin -Kai Qiang Wu (Kennan) -Kara Alexandra -Kareem Khazem -Karthik Nayak -Kat Samperi -Kathryn Spiers -Katie McLaughlin -Ke Xu -Kei Ohmura -Keith Hudgins -Kelton Bassingthwaite -Ken Cochrane -Ken ICHIKAWA -Kenfe-Mickaël Laventure -Kevin Alvarez -Kevin Burke -Kevin Feyrer -Kevin Kern -Kevin Kirsche -Kevin Meredith -Kevin Richardson -Kevin Woblick -khaled souf -Kim Eik -Kir Kolyshkin -Kotaro Yoshimatsu -Krasi Georgiev -Kris-Mikael Krister -Kun Zhang -Kunal Kushwaha -Kyle Mitofsky -Lachlan Cooper -Lai Jiangshan -Lars Kellogg-Stedman -Laura Frank -Laurent Erignoux -Lee Gaines -Lei Jitang -Lennie -Leo Gallucci -Leonid Skorospelov -Lewis Daly -Li Yi -Li Yi -Liang-Chi Hsieh -Lifubang -Lihua Tang -Lily Guo -Lin Lu -Linus Heckemann -Liping Xue -Liron Levin -liwenqi -lixiaobing10051267 -Lloyd Dewolf -Lorenzo Fontana -Louis Opter -Luca Favatella -Luca Marturana -Lucas Chan -Luka Hartwig -Lukas Heeren -Lukasz Zajaczkowski -Lydell Manganti -Lénaïc Huard -Ma Shimiao -Mabin -Maciej Kalisz -Madhav Puri -Madhu Venugopal -Madhur Batra -Malte Janduda -Manjunath A Kumatagi -Mansi Nahar -mapk0y -Marc Bihlmaier -Marc Cornellà -Marco Mariani -Marco Vedovati -Marcus Martins -Marianna Tessel -Marius Ileana -Marius Sturm -Mark Oates -Marsh Macy -Martin Mosegaard Amdisen -Mary Anthony -Mason Fish -Mason Malone -Mateusz Major -Mathieu Champlon -Mathieu Rollet -Matt Gucci -Matt Robenolt -Matteo Orefice -Matthew Heon -Matthieu Hauglustaine -Mauro Porras P -Max Shytikov -Maxime Petazzoni -Maximillian Fan Xavier -Mei ChunTao -Metal <2466052+tedhexaflow@users.noreply.github.com> -Micah Zoltu -Michael A. Smith -Michael Bridgen -Michael Crosby -Michael Friis -Michael Irwin -Michael Käufl -Michael Prokop -Michael Scharf -Michael Spetsiotis -Michael Steinert -Michael West -Michal Minář -Michał Czeraszkiewicz -Miguel Angel Alvarez Cabrerizo -Mihai Borobocea -Mihuleacc Sergiu -Mike Brown -Mike Casas -Mike Dalton -Mike Danese -Mike Dillon -Mike Goelzer -Mike MacCana -mikelinjie <294893458@qq.com> -Mikhail Vasin -Milind Chawre -Mindaugas Rukas -Miroslav Gula -Misty Stanley-Jones -Mohammad Banikazemi -Mohammed Aaqib Ansari -Mohini Anne Dsouza -Moorthy RS -Morgan Bauer -Morten Hekkvang -Morten Linderud -Moysés Borges -Mozi <29089388+pzhlkj6612@users.noreply.github.com> -Mrunal Patel -muicoder -Murukesh Mohanan -Muthukumar R -Máximo Cuadros -Mårten Cassel -Nace Oroz -Nahum Shalman -Nalin Dahyabhai -Nao YONASHIRO -Nassim 'Nass' Eddequiouaq -Natalie Parker -Nate Brennand -Nathan Hsieh -Nathan LeClaire -Nathan McCauley -Neil Peterson -Nick Adcock -Nick Santos -Nico Stapelbroek -Nicola Kabar -Nicolas Borboën -Nicolas De Loof -Nikhil Chawla -Nikolas Garofil -Nikolay Milovanov -Nir Soffer -Nishant Totla -NIWA Hideyuki -Noah Treuhaft -O.S. Tezer -Odin Ugedal -ohmystack -OKA Naoya -Oliver Pomeroy -Olle Jonsson -Olli Janatuinen -Oscar Wieman -Otto Kekäläinen -Ovidio Mallo -Pascal Borreli -Patrick Böänziger -Patrick Hemmer -Patrick Lang -Paul -Paul Kehrer -Paul Lietar -Paul Mulders -Paul Weaver -Pavel Pospisil -Paweł Gronowski -Paweł Pokrywka -Paweł Szczekutowicz -Peeyush Gupta -Per Lundberg -Peter Dave Hello -Peter Edge -Peter Hsu -Peter Jaffe -Peter Kehl -Peter Nagy -Peter Salvatore -Peter Waller -Phil Estes -Philip Alexander Etling -Philipp Gillé -Philipp Schmied -Phong Tran -pidster -Pieter E Smit -pixelistik -Pratik Karki -Prayag Verma -Preston Cowley -Pure White -Qiang Huang -Qinglan Peng -qudongfang -Raghavendra K T -Rahul Kadyan -Rahul Zoldyck -Ravi Shekhar Jethani -Ray Tsang -Reficul -Remy Suen -Renaud Gaubert -Ricardo N Feliciano -Rich Moyse -Richard Chen Zheng <58443436+rchenzheng@users.noreply.github.com> -Richard Mathie -Richard Scothern -Rick Wieman -Ritesh H Shukla -Riyaz Faizullabhoy -Rob Gulewich -Robert Wallis -Robin Naundorf -Robin Speekenbrink -Roch Feuillade -Rodolfo Ortiz -Rogelio Canedo -Rohan Verma -Roland Kammerer -Roman Dudin -Rory Hunter -Ross Boucher -Rubens Figueiredo -Rui Cao -Ryan Belgrave -Ryan Detzel -Ryan Stelly -Ryan Wilson-Perkin -Ryan Zhang -Sainath Grandhi -Sakeven Jiang -Sally O'Malley -Sam Neirinck -Sam Thibault -Samarth Shah -Sambuddha Basu -Sami Tabet -Samuel Cochran -Samuel Karp -Sandro Jäckel -Santhosh Manohar -Sargun Dhillon -Saswat Bhattacharya -Scott Brenner -Scott Collier -Sean Christopherson -Sean Rodman -Sebastiaan van Stijn -Sergey Tryuber -Serhat Gülçiçek -Sevki Hasirci -Shaun Kaasten -Sheng Yang -Shijiang Wei -Shishir Mahajan -Shoubhik Bose -Shukui Yang -Sian Lerk Lau -Sidhartha Mani -sidharthamani -Silvin Lubecki -Simei He -Simon Ferquel -Simon Heimberg -Sindhu S -Slava Semushin -Solomon Hykes -Song Gao -Spencer Brown -Spring Lee -squeegels -Srini Brahmaroutu -Stefan S. -Stefan Scherer -Stefan Weil -Stephane Jeandeaux -Stephen Day -Stephen Rust -Steve Durrheimer -Steve Richards -Steven Burgess -Stoica-Marcu Floris-Andrei -Subhajit Ghosh -Sun Jianbo -Sune Keller -Sungwon Han -Sunny Gogoi -Sven Dowideit -Sylvain Baubeau -Sébastien HOUZÉ -T K Sourabh -TAGOMORI Satoshi -taiji-tech -Takeshi Koenuma -Takuya Noguchi -Taylor Jones -Teiva Harsanyi -Tejaswini Duggaraju -Tengfei Wang -Teppei Fukuda -Thatcher Peskens -Thibault Coupin -Thomas Gazagnaire -Thomas Krzero -Thomas Leonard -Thomas Léveil -Thomas Riccardi -Thomas Swift -Tianon Gravi -Tianyi Wang -Tibor Vass -Tim Dettrick -Tim Hockin -Tim Sampson -Tim Smith -Tim Waugh -Tim Wraight -timfeirg -Timothy Hobbs -Tobias Bradtke -Tobias Gesellchen -Todd Whiteman -Tom Denham -Tom Fotherby -Tom Klingenberg -Tom Milligan -Tom X. Tobin -Tomas Bäckman -Tomas Tomecek -Tomasz Kopczynski -Tomáš Hrčka -Tony Abboud -Tõnis Tiigi -Trapier Marshall -Travis Cline -Tristan Carel -Tycho Andersen -Tycho Andersen -uhayate -Ulrich Bareth -Ulysses Souza -Umesh Yadav -Valentin Lorentz -Vardan Pogosian -Venkateswara Reddy Bukkasamudram -Veres Lajos -Victor Vieux -Victoria Bialas -Viktor Stanchev -Vimal Raghubir -Vincent Batts -Vincent Bernat -Vincent Demeester -Vincent Woo -Vishnu Kannan -Vivek Goyal -Wang Jie -Wang Lei -Wang Long -Wang Ping -Wang Xing -Wang Yuexiao -Wang Yumu <37442693@qq.com> -Wataru Ishida -Wayne Song -Wen Cheng Ma -Wenzhi Liang -Wes Morgan -Wewang Xiaorenfine -William Henry -Xianglin Gao -Xiaodong Liu -Xiaodong Zhang -Xiaoxi He -Xinbo Weng -Xuecong Liao -Yan Feng -Yanqiang Miao -Yassine Tijani -Yi EungJun -Ying Li -Yong Tang -Yosef Fertel -Yu Peng -Yuan Sun -Yue Zhang -Yunxiang Huang -Zachary Romero -Zander Mackie -zebrilee -Zeel B Patel -Zhang Kun -Zhang Wei -Zhang Wentao -ZhangHang -zhenghenghuo -Zhou Hao -Zhoulin Xie -Zhu Guihua -Álex González -Álvaro Lázaro -Átila Camurça Alves -Александр Менщиков <__Singleton__@hackerdom.ru> -徐俊杰 diff --git a/vendor/github.com/docker/cli/LICENSE b/vendor/github.com/docker/cli/LICENSE deleted file mode 100644 index 9c8e20ab8..000000000 --- a/vendor/github.com/docker/cli/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2013-2017 Docker, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - https://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/docker/cli/NOTICE b/vendor/github.com/docker/cli/NOTICE deleted file mode 100644 index 58b19b6d1..000000000 --- a/vendor/github.com/docker/cli/NOTICE +++ /dev/null @@ -1,19 +0,0 @@ -Docker -Copyright 2012-2017 Docker, Inc. - -This product includes software developed at Docker, Inc. (https://www.docker.com). - -This product contains software (https://github.com/creack/pty) developed -by Keith Rarick, licensed under the MIT License. - -The following is courtesy of our legal counsel: - - -Use and transfer of Docker may be subject to certain restrictions by the -United States and other governments. -It is your responsibility to ensure that your use and/or transfer does not -violate applicable laws. - -For more information, please see https://www.bis.doc.gov - -See also https://www.apache.org/dev/crypto.html and/or seek legal counsel. diff --git a/vendor/github.com/docker/cli/cli-plugins/manager/candidate.go b/vendor/github.com/docker/cli/cli-plugins/manager/candidate.go deleted file mode 100644 index 752b1cb0e..000000000 --- a/vendor/github.com/docker/cli/cli-plugins/manager/candidate.go +++ /dev/null @@ -1,23 +0,0 @@ -package manager - -import ( - exec "golang.org/x/sys/execabs" -) - -// Candidate represents a possible plugin candidate, for mocking purposes -type Candidate interface { - Path() string - Metadata() ([]byte, error) -} - -type candidate struct { - path string -} - -func (c *candidate) Path() string { - return c.path -} - -func (c *candidate) Metadata() ([]byte, error) { - return exec.Command(c.path, MetadataSubcommandName).Output() -} diff --git a/vendor/github.com/docker/cli/cli-plugins/manager/cobra.go b/vendor/github.com/docker/cli/cli-plugins/manager/cobra.go deleted file mode 100644 index be3a05820..000000000 --- a/vendor/github.com/docker/cli/cli-plugins/manager/cobra.go +++ /dev/null @@ -1,100 +0,0 @@ -package manager - -import ( - "fmt" - "os" - "sync" - - "github.com/docker/cli/cli/command" - "github.com/spf13/cobra" -) - -const ( - // CommandAnnotationPlugin is added to every stub command added by - // AddPluginCommandStubs with the value "true" and so can be - // used to distinguish plugin stubs from regular commands. - CommandAnnotationPlugin = "com.docker.cli.plugin" - - // CommandAnnotationPluginVendor is added to every stub command - // added by AddPluginCommandStubs and contains the vendor of - // that plugin. - CommandAnnotationPluginVendor = "com.docker.cli.plugin.vendor" - - // CommandAnnotationPluginVersion is added to every stub command - // added by AddPluginCommandStubs and contains the version of - // that plugin. - CommandAnnotationPluginVersion = "com.docker.cli.plugin.version" - - // CommandAnnotationPluginInvalid is added to any stub command - // added by AddPluginCommandStubs for an invalid command (that - // is, one which failed it's candidate test) and contains the - // reason for the failure. - CommandAnnotationPluginInvalid = "com.docker.cli.plugin-invalid" -) - -var pluginCommandStubsOnce sync.Once - -// AddPluginCommandStubs adds a stub cobra.Commands for each valid and invalid -// plugin. The command stubs will have several annotations added, see -// `CommandAnnotationPlugin*`. -func AddPluginCommandStubs(dockerCli command.Cli, rootCmd *cobra.Command) (err error) { - pluginCommandStubsOnce.Do(func() { - var plugins []Plugin - plugins, err = ListPlugins(dockerCli, rootCmd) - if err != nil { - return - } - for _, p := range plugins { - p := p - vendor := p.Vendor - if vendor == "" { - vendor = "unknown" - } - annotations := map[string]string{ - CommandAnnotationPlugin: "true", - CommandAnnotationPluginVendor: vendor, - CommandAnnotationPluginVersion: p.Version, - } - if p.Err != nil { - annotations[CommandAnnotationPluginInvalid] = p.Err.Error() - } - rootCmd.AddCommand(&cobra.Command{ - Use: p.Name, - Short: p.ShortDescription, - Run: func(_ *cobra.Command, _ []string) {}, - Annotations: annotations, - DisableFlagParsing: true, - RunE: func(cmd *cobra.Command, args []string) error { - flags := rootCmd.PersistentFlags() - flags.SetOutput(nil) - perr := flags.Parse(args) - if perr != nil { - return err - } - if flags.Changed("help") { - cmd.HelpFunc()(rootCmd, args) - return nil - } - return fmt.Errorf("docker: '%s' is not a docker command.\nSee 'docker --help'", cmd.Name()) - }, - ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - // Delegate completion to plugin - cargs := []string{p.Path, cobra.ShellCompRequestCmd, p.Name} - cargs = append(cargs, args...) - cargs = append(cargs, toComplete) - os.Args = cargs - runCommand, runErr := PluginRunCommand(dockerCli, p.Name, cmd) - if runErr != nil { - return nil, cobra.ShellCompDirectiveError - } - runErr = runCommand.Run() - if runErr == nil { - os.Exit(0) // plugin already rendered complete data - } - return nil, cobra.ShellCompDirectiveError - }, - }) - } - }) - return err -} diff --git a/vendor/github.com/docker/cli/cli-plugins/manager/error.go b/vendor/github.com/docker/cli/cli-plugins/manager/error.go deleted file mode 100644 index 11822d660..000000000 --- a/vendor/github.com/docker/cli/cli-plugins/manager/error.go +++ /dev/null @@ -1,48 +0,0 @@ -package manager - -import ( - "github.com/pkg/errors" -) - -// pluginError is set as Plugin.Err by NewPlugin if the plugin -// candidate fails one of the candidate tests. This exists primarily -// to implement encoding.TextMarshaller such that rendering a plugin as JSON -// (e.g. for `docker info -f '{{json .CLIPlugins}}'`) renders the Err -// field as a useful string and not just `{}`. See -// https://github.com/golang/go/issues/10748 for some discussion -// around why the builtin error type doesn't implement this. -type pluginError struct { - cause error -} - -// Error satisfies the core error interface for pluginError. -func (e *pluginError) Error() string { - return e.cause.Error() -} - -// Cause satisfies the errors.causer interface for pluginError. -func (e *pluginError) Cause() error { - return e.cause -} - -// Unwrap provides compatibility for Go 1.13 error chains. -func (e *pluginError) Unwrap() error { - return e.cause -} - -// MarshalText marshalls the pluginError into a textual form. -func (e *pluginError) MarshalText() (text []byte, err error) { - return []byte(e.cause.Error()), nil -} - -// wrapAsPluginError wraps an error in a pluginError with an -// additional message, analogous to errors.Wrapf. -func wrapAsPluginError(err error, msg string) error { - return &pluginError{cause: errors.Wrap(err, msg)} -} - -// NewPluginError creates a new pluginError, analogous to -// errors.Errorf. -func NewPluginError(msg string, args ...interface{}) error { - return &pluginError{cause: errors.Errorf(msg, args...)} -} diff --git a/vendor/github.com/docker/cli/cli-plugins/manager/manager.go b/vendor/github.com/docker/cli/cli-plugins/manager/manager.go deleted file mode 100644 index 3ce96876d..000000000 --- a/vendor/github.com/docker/cli/cli-plugins/manager/manager.go +++ /dev/null @@ -1,247 +0,0 @@ -package manager - -import ( - "context" - "os" - "path/filepath" - "sort" - "strings" - "sync" - - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/config" - "github.com/fvbommel/sortorder" - "github.com/spf13/cobra" - "golang.org/x/sync/errgroup" - exec "golang.org/x/sys/execabs" -) - -// ReexecEnvvar is the name of an ennvar which is set to the command -// used to originally invoke the docker CLI when executing a -// plugin. Assuming $PATH and $CWD remain unchanged this should allow -// the plugin to re-execute the original CLI. -const ReexecEnvvar = "DOCKER_CLI_PLUGIN_ORIGINAL_CLI_COMMAND" - -// errPluginNotFound is the error returned when a plugin could not be found. -type errPluginNotFound string - -func (e errPluginNotFound) NotFound() {} - -func (e errPluginNotFound) Error() string { - return "Error: No such CLI plugin: " + string(e) -} - -type notFound interface{ NotFound() } - -// IsNotFound is true if the given error is due to a plugin not being found. -func IsNotFound(err error) bool { - if e, ok := err.(*pluginError); ok { - err = e.Cause() - } - _, ok := err.(notFound) - return ok -} - -func getPluginDirs(dockerCli command.Cli) ([]string, error) { - var pluginDirs []string - - if cfg := dockerCli.ConfigFile(); cfg != nil { - pluginDirs = append(pluginDirs, cfg.CLIPluginsExtraDirs...) - } - pluginDir, err := config.Path("cli-plugins") - if err != nil { - return nil, err - } - - pluginDirs = append(pluginDirs, pluginDir) - pluginDirs = append(pluginDirs, defaultSystemPluginDirs...) - return pluginDirs, nil -} - -func addPluginCandidatesFromDir(res map[string][]string, d string) error { - dentries, err := os.ReadDir(d) - if err != nil { - return err - } - for _, dentry := range dentries { - switch dentry.Type() & os.ModeType { - case 0, os.ModeSymlink: - // Regular file or symlink, keep going - default: - // Something else, ignore. - continue - } - name := dentry.Name() - if !strings.HasPrefix(name, NamePrefix) { - continue - } - name = strings.TrimPrefix(name, NamePrefix) - var err error - if name, err = trimExeSuffix(name); err != nil { - continue - } - res[name] = append(res[name], filepath.Join(d, dentry.Name())) - } - return nil -} - -// listPluginCandidates returns a map from plugin name to the list of (unvalidated) Candidates. The list is in descending order of priority. -func listPluginCandidates(dirs []string) (map[string][]string, error) { - result := make(map[string][]string) - for _, d := range dirs { - // Silently ignore any directories which we cannot - // Stat (e.g. due to permissions or anything else) or - // which is not a directory. - if fi, err := os.Stat(d); err != nil || !fi.IsDir() { - continue - } - if err := addPluginCandidatesFromDir(result, d); err != nil { - // Silently ignore paths which don't exist. - if os.IsNotExist(err) { - continue - } - return nil, err // Or return partial result? - } - } - return result, nil -} - -// GetPlugin returns a plugin on the system by its name -func GetPlugin(name string, dockerCli command.Cli, rootcmd *cobra.Command) (*Plugin, error) { - pluginDirs, err := getPluginDirs(dockerCli) - if err != nil { - return nil, err - } - - candidates, err := listPluginCandidates(pluginDirs) - if err != nil { - return nil, err - } - - if paths, ok := candidates[name]; ok { - if len(paths) == 0 { - return nil, errPluginNotFound(name) - } - c := &candidate{paths[0]} - p, err := newPlugin(c, rootcmd.Commands()) - if err != nil { - return nil, err - } - if !IsNotFound(p.Err) { - p.ShadowedPaths = paths[1:] - } - return &p, nil - } - - return nil, errPluginNotFound(name) -} - -// ListPlugins produces a list of the plugins available on the system -func ListPlugins(dockerCli command.Cli, rootcmd *cobra.Command) ([]Plugin, error) { - pluginDirs, err := getPluginDirs(dockerCli) - if err != nil { - return nil, err - } - - candidates, err := listPluginCandidates(pluginDirs) - if err != nil { - return nil, err - } - - var plugins []Plugin - var mu sync.Mutex - eg, _ := errgroup.WithContext(context.TODO()) - cmds := rootcmd.Commands() - for _, paths := range candidates { - func(paths []string) { - eg.Go(func() error { - if len(paths) == 0 { - return nil - } - c := &candidate{paths[0]} - p, err := newPlugin(c, cmds) - if err != nil { - return err - } - if !IsNotFound(p.Err) { - p.ShadowedPaths = paths[1:] - mu.Lock() - defer mu.Unlock() - plugins = append(plugins, p) - } - return nil - }) - }(paths) - } - if err := eg.Wait(); err != nil { - return nil, err - } - - sort.Slice(plugins, func(i, j int) bool { - return sortorder.NaturalLess(plugins[i].Name, plugins[j].Name) - }) - - return plugins, nil -} - -// PluginRunCommand returns an "os/exec".Cmd which when .Run() will execute the named plugin. -// The rootcmd argument is referenced to determine the set of builtin commands in order to detect conficts. -// The error returned satisfies the IsNotFound() predicate if no plugin was found or if the first candidate plugin was invalid somehow. -func PluginRunCommand(dockerCli command.Cli, name string, rootcmd *cobra.Command) (*exec.Cmd, error) { - // This uses the full original args, not the args which may - // have been provided by cobra to our caller. This is because - // they lack e.g. global options which we must propagate here. - args := os.Args[1:] - if !pluginNameRe.MatchString(name) { - // We treat this as "not found" so that callers will - // fallback to their "invalid" command path. - return nil, errPluginNotFound(name) - } - exename := addExeSuffix(NamePrefix + name) - pluginDirs, err := getPluginDirs(dockerCli) - if err != nil { - return nil, err - } - - for _, d := range pluginDirs { - path := filepath.Join(d, exename) - - // We stat here rather than letting the exec tell us - // ENOENT because the latter does not distinguish a - // file not existing from its dynamic loader or one of - // its libraries not existing. - if _, err := os.Stat(path); os.IsNotExist(err) { - continue - } - - c := &candidate{path: path} - plugin, err := newPlugin(c, rootcmd.Commands()) - if err != nil { - return nil, err - } - if plugin.Err != nil { - // TODO: why are we not returning plugin.Err? - return nil, errPluginNotFound(name) - } - cmd := exec.Command(plugin.Path, args...) - // Using dockerCli.{In,Out,Err}() here results in a hang until something is input. - // See: - https://github.com/golang/go/issues/10338 - // - https://github.com/golang/go/commit/d000e8742a173aa0659584aa01b7ba2834ba28ab - // os.Stdin is a *os.File which avoids this behaviour. We don't need the functionality - // of the wrappers here anyway. - cmd.Stdin = os.Stdin - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - - cmd.Env = os.Environ() - cmd.Env = append(cmd.Env, ReexecEnvvar+"="+os.Args[0]) - - return cmd, nil - } - return nil, errPluginNotFound(name) -} - -// IsPluginCommand checks if the given cmd is a plugin-stub. -func IsPluginCommand(cmd *cobra.Command) bool { - return cmd.Annotations[CommandAnnotationPlugin] == "true" -} diff --git a/vendor/github.com/docker/cli/cli-plugins/manager/manager_unix.go b/vendor/github.com/docker/cli/cli-plugins/manager/manager_unix.go deleted file mode 100644 index 6aa5b9e5c..000000000 --- a/vendor/github.com/docker/cli/cli-plugins/manager/manager_unix.go +++ /dev/null @@ -1,9 +0,0 @@ -//go:build !windows -// +build !windows - -package manager - -var defaultSystemPluginDirs = []string{ - "/usr/local/lib/docker/cli-plugins", "/usr/local/libexec/docker/cli-plugins", - "/usr/lib/docker/cli-plugins", "/usr/libexec/docker/cli-plugins", -} diff --git a/vendor/github.com/docker/cli/cli-plugins/manager/manager_windows.go b/vendor/github.com/docker/cli/cli-plugins/manager/manager_windows.go deleted file mode 100644 index 2ce5a7597..000000000 --- a/vendor/github.com/docker/cli/cli-plugins/manager/manager_windows.go +++ /dev/null @@ -1,11 +0,0 @@ -package manager - -import ( - "os" - "path/filepath" -) - -var defaultSystemPluginDirs = []string{ - filepath.Join(os.Getenv("ProgramData"), "Docker", "cli-plugins"), - filepath.Join(os.Getenv("ProgramFiles"), "Docker", "cli-plugins"), -} diff --git a/vendor/github.com/docker/cli/cli-plugins/manager/metadata.go b/vendor/github.com/docker/cli/cli-plugins/manager/metadata.go deleted file mode 100644 index 5aaf5ca11..000000000 --- a/vendor/github.com/docker/cli/cli-plugins/manager/metadata.go +++ /dev/null @@ -1,29 +0,0 @@ -package manager - -const ( - // NamePrefix is the prefix required on all plugin binary names - NamePrefix = "docker-" - - // MetadataSubcommandName is the name of the plugin subcommand - // which must be supported by every plugin and returns the - // plugin metadata. - MetadataSubcommandName = "docker-cli-plugin-metadata" -) - -// Metadata provided by the plugin. -type Metadata struct { - // SchemaVersion describes the version of this struct. Mandatory, must be "0.1.0" - SchemaVersion string `json:",omitempty"` - // Vendor is the name of the plugin vendor. Mandatory - Vendor string `json:",omitempty"` - // Version is the optional version of this plugin. - Version string `json:",omitempty"` - // ShortDescription should be suitable for a single line help message. - ShortDescription string `json:",omitempty"` - // URL is a pointer to the plugin's homepage. - URL string `json:",omitempty"` - // Experimental specifies whether the plugin is experimental. - // - // Deprecated: experimental features are now always enabled in the CLI - Experimental bool `json:",omitempty"` -} diff --git a/vendor/github.com/docker/cli/cli-plugins/manager/plugin.go b/vendor/github.com/docker/cli/cli-plugins/manager/plugin.go deleted file mode 100644 index 58ed6db72..000000000 --- a/vendor/github.com/docker/cli/cli-plugins/manager/plugin.go +++ /dev/null @@ -1,102 +0,0 @@ -package manager - -import ( - "encoding/json" - "path/filepath" - "regexp" - "strings" - - "github.com/pkg/errors" - "github.com/spf13/cobra" -) - -var pluginNameRe = regexp.MustCompile("^[a-z][a-z0-9]*$") - -// Plugin represents a potential plugin with all it's metadata. -type Plugin struct { - Metadata - - Name string `json:",omitempty"` - Path string `json:",omitempty"` - - // Err is non-nil if the plugin failed one of the candidate tests. - Err error `json:",omitempty"` - - // ShadowedPaths contains the paths of any other plugins which this plugin takes precedence over. - ShadowedPaths []string `json:",omitempty"` -} - -// newPlugin determines if the given candidate is valid and returns a -// Plugin. If the candidate fails one of the tests then `Plugin.Err` -// is set, and is always a `pluginError`, but the `Plugin` is still -// returned with no error. An error is only returned due to a -// non-recoverable error. -func newPlugin(c Candidate, cmds []*cobra.Command) (Plugin, error) { - path := c.Path() - if path == "" { - return Plugin{}, errors.New("plugin candidate path cannot be empty") - } - - // The candidate listing process should have skipped anything - // which would fail here, so there are all real errors. - fullname := filepath.Base(path) - if fullname == "." { - return Plugin{}, errors.Errorf("unable to determine basename of plugin candidate %q", path) - } - var err error - if fullname, err = trimExeSuffix(fullname); err != nil { - return Plugin{}, errors.Wrapf(err, "plugin candidate %q", path) - } - if !strings.HasPrefix(fullname, NamePrefix) { - return Plugin{}, errors.Errorf("plugin candidate %q: does not have %q prefix", path, NamePrefix) - } - - p := Plugin{ - Name: strings.TrimPrefix(fullname, NamePrefix), - Path: path, - } - - // Now apply the candidate tests, so these update p.Err. - if !pluginNameRe.MatchString(p.Name) { - p.Err = NewPluginError("plugin candidate %q did not match %q", p.Name, pluginNameRe.String()) - return p, nil - } - - for _, cmd := range cmds { - // Ignore conflicts with commands which are - // just plugin stubs (i.e. from a previous - // call to AddPluginCommandStubs). - if IsPluginCommand(cmd) { - continue - } - if cmd.Name() == p.Name { - p.Err = NewPluginError("plugin %q duplicates builtin command", p.Name) - return p, nil - } - if cmd.HasAlias(p.Name) { - p.Err = NewPluginError("plugin %q duplicates an alias of builtin command %q", p.Name, cmd.Name()) - return p, nil - } - } - - // We are supposed to check for relevant execute permissions here. Instead we rely on an attempt to execute. - meta, err := c.Metadata() - if err != nil { - p.Err = wrapAsPluginError(err, "failed to fetch metadata") - return p, nil - } - - if err := json.Unmarshal(meta, &p.Metadata); err != nil { - p.Err = wrapAsPluginError(err, "invalid metadata") - return p, nil - } - if p.Metadata.SchemaVersion != "0.1.0" { - p.Err = NewPluginError("plugin SchemaVersion %q is not valid, must be 0.1.0", p.Metadata.SchemaVersion) - return p, nil - } - if p.Metadata.Vendor == "" { - p.Err = NewPluginError("plugin metadata does not define a vendor") - return p, nil - } - return p, nil -} diff --git a/vendor/github.com/docker/cli/cli-plugins/manager/suffix_unix.go b/vendor/github.com/docker/cli/cli-plugins/manager/suffix_unix.go deleted file mode 100644 index 8d5a5c3e7..000000000 --- a/vendor/github.com/docker/cli/cli-plugins/manager/suffix_unix.go +++ /dev/null @@ -1,12 +0,0 @@ -//go:build !windows -// +build !windows - -package manager - -func trimExeSuffix(s string) (string, error) { - return s, nil -} - -func addExeSuffix(s string) string { - return s -} diff --git a/vendor/github.com/docker/cli/cli-plugins/manager/suffix_windows.go b/vendor/github.com/docker/cli/cli-plugins/manager/suffix_windows.go deleted file mode 100644 index 53b507c87..000000000 --- a/vendor/github.com/docker/cli/cli-plugins/manager/suffix_windows.go +++ /dev/null @@ -1,26 +0,0 @@ -package manager - -import ( - "path/filepath" - "strings" - - "github.com/pkg/errors" -) - -// This is made slightly more complex due to needing to be case insensitive. -func trimExeSuffix(s string) (string, error) { - ext := filepath.Ext(s) - if ext == "" { - return "", errors.Errorf("path %q lacks required file extension", s) - } - - exe := ".exe" - if !strings.EqualFold(ext, exe) { - return "", errors.Errorf("path %q lacks required %q suffix", s, exe) - } - return strings.TrimSuffix(s, ext), nil -} - -func addExeSuffix(s string) string { - return s + ".exe" -} diff --git a/vendor/github.com/docker/cli/cli/cobra.go b/vendor/github.com/docker/cli/cli/cobra.go deleted file mode 100644 index c6ce31dcc..000000000 --- a/vendor/github.com/docker/cli/cli/cobra.go +++ /dev/null @@ -1,529 +0,0 @@ -package cli - -import ( - "fmt" - "os" - "path/filepath" - "sort" - "strings" - - pluginmanager "github.com/docker/cli/cli-plugins/manager" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/config" - cliflags "github.com/docker/cli/cli/flags" - "github.com/docker/docker/pkg/homedir" - "github.com/docker/docker/registry" - "github.com/fvbommel/sortorder" - "github.com/moby/term" - "github.com/morikuni/aec" - "github.com/pkg/errors" - "github.com/spf13/cobra" - "github.com/spf13/pflag" -) - -// setupCommonRootCommand contains the setup common to -// SetupRootCommand and SetupPluginRootCommand. -func setupCommonRootCommand(rootCmd *cobra.Command) (*cliflags.ClientOptions, *pflag.FlagSet, *cobra.Command) { - opts := cliflags.NewClientOptions() - flags := rootCmd.Flags() - - flags.StringVar(&opts.ConfigDir, "config", config.Dir(), "Location of client config files") - opts.InstallFlags(flags) - - cobra.AddTemplateFunc("add", func(a, b int) int { return a + b }) - cobra.AddTemplateFunc("hasAliases", hasAliases) - cobra.AddTemplateFunc("hasSubCommands", hasSubCommands) - cobra.AddTemplateFunc("hasTopCommands", hasTopCommands) - cobra.AddTemplateFunc("hasManagementSubCommands", hasManagementSubCommands) - cobra.AddTemplateFunc("hasSwarmSubCommands", hasSwarmSubCommands) - cobra.AddTemplateFunc("hasInvalidPlugins", hasInvalidPlugins) - cobra.AddTemplateFunc("topCommands", topCommands) - cobra.AddTemplateFunc("commandAliases", commandAliases) - cobra.AddTemplateFunc("operationSubCommands", operationSubCommands) - cobra.AddTemplateFunc("managementSubCommands", managementSubCommands) - cobra.AddTemplateFunc("orchestratorSubCommands", orchestratorSubCommands) - cobra.AddTemplateFunc("invalidPlugins", invalidPlugins) - cobra.AddTemplateFunc("wrappedFlagUsages", wrappedFlagUsages) - cobra.AddTemplateFunc("vendorAndVersion", vendorAndVersion) - cobra.AddTemplateFunc("invalidPluginReason", invalidPluginReason) - cobra.AddTemplateFunc("isPlugin", isPlugin) - cobra.AddTemplateFunc("isExperimental", isExperimental) - cobra.AddTemplateFunc("hasAdditionalHelp", hasAdditionalHelp) - cobra.AddTemplateFunc("additionalHelp", additionalHelp) - cobra.AddTemplateFunc("decoratedName", decoratedName) - - rootCmd.SetUsageTemplate(usageTemplate) - rootCmd.SetHelpTemplate(helpTemplate) - rootCmd.SetFlagErrorFunc(FlagErrorFunc) - rootCmd.SetHelpCommand(helpCommand) - - rootCmd.PersistentFlags().BoolP("help", "h", false, "Print usage") - rootCmd.PersistentFlags().MarkShorthandDeprecated("help", "please use --help") - rootCmd.PersistentFlags().Lookup("help").Hidden = true - - rootCmd.Annotations = map[string]string{ - "additionalHelp": "For more help on how to use Docker, head to https://docs.docker.com/go/guides/", - "docs.code-delimiter": `"`, // https://github.com/docker/cli-docs-tool/blob/77abede22166eaea4af7335096bdcedd043f5b19/annotation/annotation.go#L20-L22 - } - - // Configure registry.CertsDir() when running in rootless-mode - if os.Getenv("ROOTLESSKIT_STATE_DIR") != "" { - if configHome, err := homedir.GetConfigHome(); err == nil { - registry.SetCertsDir(filepath.Join(configHome, "docker/certs.d")) - } - } - - return opts, flags, helpCommand -} - -// SetupRootCommand sets default usage, help, and error handling for the -// root command. -func SetupRootCommand(rootCmd *cobra.Command) (*cliflags.ClientOptions, *pflag.FlagSet, *cobra.Command) { - rootCmd.SetVersionTemplate("Docker version {{.Version}}\n") - return setupCommonRootCommand(rootCmd) -} - -// SetupPluginRootCommand sets default usage, help and error handling for a plugin root command. -func SetupPluginRootCommand(rootCmd *cobra.Command) (*cliflags.ClientOptions, *pflag.FlagSet) { - opts, flags, _ := setupCommonRootCommand(rootCmd) - return opts, flags -} - -// FlagErrorFunc prints an error message which matches the format of the -// docker/cli/cli error messages -func FlagErrorFunc(cmd *cobra.Command, err error) error { - if err == nil { - return nil - } - - usage := "" - if cmd.HasSubCommands() { - usage = "\n\n" + cmd.UsageString() - } - return StatusError{ - Status: fmt.Sprintf("%s\nSee '%s --help'.%s", err, cmd.CommandPath(), usage), - StatusCode: 125, - } -} - -// TopLevelCommand encapsulates a top-level cobra command (either -// docker CLI or a plugin) and global flag handling logic necessary -// for plugins. -type TopLevelCommand struct { - cmd *cobra.Command - dockerCli *command.DockerCli - opts *cliflags.ClientOptions - flags *pflag.FlagSet - args []string -} - -// NewTopLevelCommand returns a new TopLevelCommand object -func NewTopLevelCommand(cmd *cobra.Command, dockerCli *command.DockerCli, opts *cliflags.ClientOptions, flags *pflag.FlagSet) *TopLevelCommand { - return &TopLevelCommand{ - cmd: cmd, - dockerCli: dockerCli, - opts: opts, - flags: flags, - args: os.Args[1:], - } -} - -// SetArgs sets the args (default os.Args[:1] used to invoke the command -func (tcmd *TopLevelCommand) SetArgs(args []string) { - tcmd.args = args - tcmd.cmd.SetArgs(args) -} - -// SetFlag sets a flag in the local flag set of the top-level command -func (tcmd *TopLevelCommand) SetFlag(name, value string) { - tcmd.cmd.Flags().Set(name, value) -} - -// HandleGlobalFlags takes care of parsing global flags defined on the -// command, it returns the underlying cobra command and the args it -// will be called with (or an error). -// -// On success the caller is responsible for calling Initialize() -// before calling `Execute` on the returned command. -func (tcmd *TopLevelCommand) HandleGlobalFlags() (*cobra.Command, []string, error) { - cmd := tcmd.cmd - - // We manually parse the global arguments and find the - // subcommand in order to properly deal with plugins. We rely - // on the root command never having any non-flag arguments. We - // create our own FlagSet so that we can configure it - // (e.g. `SetInterspersed` below) in an idempotent way. - flags := pflag.NewFlagSet(cmd.Name(), pflag.ContinueOnError) - - // We need !interspersed to ensure we stop at the first - // potential command instead of accumulating it into - // flags.Args() and then continuing on and finding other - // arguments which we try and treat as globals (when they are - // actually arguments to the subcommand). - flags.SetInterspersed(false) - - // We need the single parse to see both sets of flags. - flags.AddFlagSet(cmd.Flags()) - flags.AddFlagSet(cmd.PersistentFlags()) - // Now parse the global flags, up to (but not including) the - // first command. The result will be that all the remaining - // arguments are in `flags.Args()`. - if err := flags.Parse(tcmd.args); err != nil { - // Our FlagErrorFunc uses the cli, make sure it is initialized - if err := tcmd.Initialize(); err != nil { - return nil, nil, err - } - return nil, nil, cmd.FlagErrorFunc()(cmd, err) - } - - return cmd, flags.Args(), nil -} - -// Initialize finalises global option parsing and initializes the docker client. -func (tcmd *TopLevelCommand) Initialize(ops ...command.InitializeOpt) error { - tcmd.opts.SetDefaultOptions(tcmd.flags) - return tcmd.dockerCli.Initialize(tcmd.opts, ops...) -} - -// VisitAll will traverse all commands from the root. -// This is different from the VisitAll of cobra.Command where only parents -// are checked. -func VisitAll(root *cobra.Command, fn func(*cobra.Command)) { - for _, cmd := range root.Commands() { - VisitAll(cmd, fn) - } - fn(root) -} - -// DisableFlagsInUseLine sets the DisableFlagsInUseLine flag on all -// commands within the tree rooted at cmd. -func DisableFlagsInUseLine(cmd *cobra.Command) { - VisitAll(cmd, func(ccmd *cobra.Command) { - // do not add a `[flags]` to the end of the usage line. - ccmd.DisableFlagsInUseLine = true - }) -} - -// HasCompletionArg returns true if a cobra completion arg request is found. -func HasCompletionArg(args []string) bool { - for _, arg := range args { - if arg == cobra.ShellCompRequestCmd || arg == cobra.ShellCompNoDescRequestCmd { - return true - } - } - return false -} - -var helpCommand = &cobra.Command{ - Use: "help [command]", - Short: "Help about the command", - PersistentPreRun: func(cmd *cobra.Command, args []string) {}, - PersistentPostRun: func(cmd *cobra.Command, args []string) {}, - RunE: func(c *cobra.Command, args []string) error { - cmd, args, e := c.Root().Find(args) - if cmd == nil || e != nil || len(args) > 0 { - return errors.Errorf("unknown help topic: %v", strings.Join(args, " ")) - } - helpFunc := cmd.HelpFunc() - helpFunc(cmd, args) - return nil - }, -} - -func isExperimental(cmd *cobra.Command) bool { - if _, ok := cmd.Annotations["experimentalCLI"]; ok { - return true - } - var experimental bool - cmd.VisitParents(func(cmd *cobra.Command) { - if _, ok := cmd.Annotations["experimentalCLI"]; ok { - experimental = true - } - }) - return experimental -} - -func additionalHelp(cmd *cobra.Command) string { - if msg, ok := cmd.Annotations["additionalHelp"]; ok { - out := cmd.OutOrStderr() - if _, isTerminal := term.GetFdInfo(out); !isTerminal { - return msg - } - style := aec.EmptyBuilder.Bold().ANSI - return style.Apply(msg) - } - return "" -} - -func hasAdditionalHelp(cmd *cobra.Command) bool { - return additionalHelp(cmd) != "" -} - -func isPlugin(cmd *cobra.Command) bool { - return pluginmanager.IsPluginCommand(cmd) -} - -func hasAliases(cmd *cobra.Command) bool { - return len(cmd.Aliases) > 0 || cmd.Annotations["aliases"] != "" -} - -func hasSubCommands(cmd *cobra.Command) bool { - return len(operationSubCommands(cmd)) > 0 -} - -func hasManagementSubCommands(cmd *cobra.Command) bool { - return len(managementSubCommands(cmd)) > 0 -} - -func hasSwarmSubCommands(cmd *cobra.Command) bool { - return len(orchestratorSubCommands(cmd)) > 0 -} - -func hasInvalidPlugins(cmd *cobra.Command) bool { - return len(invalidPlugins(cmd)) > 0 -} - -func hasTopCommands(cmd *cobra.Command) bool { - return len(topCommands(cmd)) > 0 -} - -// commandAliases is a templating function to return aliases for the command, -// formatted as the full command as they're called (contrary to the default -// Aliases function, which only returns the subcommand). -func commandAliases(cmd *cobra.Command) string { - if cmd.Annotations["aliases"] != "" { - return cmd.Annotations["aliases"] - } - var parentPath string - if cmd.HasParent() { - parentPath = cmd.Parent().CommandPath() + " " - } - aliases := cmd.CommandPath() - for _, alias := range cmd.Aliases { - aliases += ", " + parentPath + alias - } - return aliases -} - -func topCommands(cmd *cobra.Command) []*cobra.Command { - cmds := []*cobra.Command{} - if cmd.Parent() != nil { - // for now, only use top-commands for the root-command, and skip - // for sub-commands - return cmds - } - for _, sub := range cmd.Commands() { - if isPlugin(sub) || !sub.IsAvailableCommand() { - continue - } - if _, ok := sub.Annotations["category-top"]; ok { - cmds = append(cmds, sub) - } - } - sort.SliceStable(cmds, func(i, j int) bool { - return sortorder.NaturalLess(cmds[i].Annotations["category-top"], cmds[j].Annotations["category-top"]) - }) - return cmds -} - -func operationSubCommands(cmd *cobra.Command) []*cobra.Command { - cmds := []*cobra.Command{} - for _, sub := range cmd.Commands() { - if isPlugin(sub) { - continue - } - if _, ok := sub.Annotations["category-top"]; ok { - if cmd.Parent() == nil { - // for now, only use top-commands for the root-command - continue - } - } - if sub.IsAvailableCommand() && !sub.HasSubCommands() { - cmds = append(cmds, sub) - } - } - return cmds -} - -func wrappedFlagUsages(cmd *cobra.Command) string { - width := 80 - if ws, err := term.GetWinsize(0); err == nil { - width = int(ws.Width) - } - return cmd.Flags().FlagUsagesWrapped(width - 1) -} - -func decoratedName(cmd *cobra.Command) string { - decoration := " " - if isPlugin(cmd) { - decoration = "*" - } - return cmd.Name() + decoration -} - -func vendorAndVersion(cmd *cobra.Command) string { - if vendor, ok := cmd.Annotations[pluginmanager.CommandAnnotationPluginVendor]; ok && isPlugin(cmd) { - version := "" - if v, ok := cmd.Annotations[pluginmanager.CommandAnnotationPluginVersion]; ok && v != "" { - version = ", " + v - } - return fmt.Sprintf("(%s%s)", vendor, version) - } - return "" -} - -func managementSubCommands(cmd *cobra.Command) []*cobra.Command { - cmds := []*cobra.Command{} - for _, sub := range allManagementSubCommands(cmd) { - if _, ok := sub.Annotations["swarm"]; ok { - continue - } - cmds = append(cmds, sub) - } - return cmds -} - -func orchestratorSubCommands(cmd *cobra.Command) []*cobra.Command { - cmds := []*cobra.Command{} - for _, sub := range allManagementSubCommands(cmd) { - if _, ok := sub.Annotations["swarm"]; ok { - cmds = append(cmds, sub) - } - } - return cmds -} - -func allManagementSubCommands(cmd *cobra.Command) []*cobra.Command { - cmds := []*cobra.Command{} - for _, sub := range cmd.Commands() { - if isPlugin(sub) { - if invalidPluginReason(sub) == "" { - cmds = append(cmds, sub) - } - continue - } - if sub.IsAvailableCommand() && sub.HasSubCommands() { - cmds = append(cmds, sub) - } - } - return cmds -} - -func invalidPlugins(cmd *cobra.Command) []*cobra.Command { - cmds := []*cobra.Command{} - for _, sub := range cmd.Commands() { - if !isPlugin(sub) { - continue - } - if invalidPluginReason(sub) != "" { - cmds = append(cmds, sub) - } - } - return cmds -} - -func invalidPluginReason(cmd *cobra.Command) string { - return cmd.Annotations[pluginmanager.CommandAnnotationPluginInvalid] -} - -const usageTemplate = `Usage: - -{{- if not .HasSubCommands}} {{.UseLine}}{{end}} -{{- if .HasSubCommands}} {{ .CommandPath}}{{- if .HasAvailableFlags}} [OPTIONS]{{end}} COMMAND{{end}} - -{{if ne .Long ""}}{{ .Long | trim }}{{ else }}{{ .Short | trim }}{{end}} -{{- if isExperimental .}} - -EXPERIMENTAL: - {{.CommandPath}} is an experimental feature. - Experimental features provide early access to product functionality. These - features may change between releases without warning, or can be removed from a - future release. Learn more about experimental features in our documentation: - https://docs.docker.com/go/experimental/ - -{{- end}} -{{- if hasAliases . }} - -Aliases: - {{ commandAliases . }} - -{{- end}} -{{- if .HasExample}} - -Examples: -{{ .Example }} - -{{- end}} -{{- if .HasParent}} -{{- if .HasAvailableFlags}} - -Options: -{{ wrappedFlagUsages . | trimRightSpace}} - -{{- end}} -{{- end}} -{{- if hasTopCommands .}} - -Common Commands: -{{- range topCommands .}} - {{rpad (decoratedName .) (add .NamePadding 1)}}{{.Short}} -{{- end}} -{{- end}} -{{- if hasManagementSubCommands . }} - -Management Commands: - -{{- range managementSubCommands . }} - {{rpad (decoratedName .) (add .NamePadding 1)}}{{.Short}}{{ if isPlugin .}} {{vendorAndVersion .}}{{ end}} -{{- end}} - -{{- end}} -{{- if hasSwarmSubCommands . }} - -Swarm Commands: - -{{- range orchestratorSubCommands . }} - {{rpad (decoratedName .) (add .NamePadding 1)}}{{.Short}}{{ if isPlugin .}} {{vendorAndVersion .}}{{ end}} -{{- end}} - -{{- end}} -{{- if hasSubCommands .}} - -Commands: - -{{- range operationSubCommands . }} - {{rpad .Name .NamePadding }} {{.Short}} -{{- end}} -{{- end}} - -{{- if hasInvalidPlugins . }} - -Invalid Plugins: - -{{- range invalidPlugins . }} - {{rpad .Name .NamePadding }} {{invalidPluginReason .}} -{{- end}} - -{{- end}} -{{- if not .HasParent}} -{{- if .HasAvailableFlags}} - -Global Options: -{{ wrappedFlagUsages . | trimRightSpace}} - -{{- end}} -{{- end}} - -{{- if .HasSubCommands }} - -Run '{{.CommandPath}} COMMAND --help' for more information on a command. -{{- end}} -{{- if hasAdditionalHelp .}} - -{{ additionalHelp . }} - -{{- end}} -` - -const helpTemplate = ` -{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}` diff --git a/vendor/github.com/docker/cli/cli/command/cli.go b/vendor/github.com/docker/cli/cli/command/cli.go deleted file mode 100644 index 1551c14da..000000000 --- a/vendor/github.com/docker/cli/cli/command/cli.go +++ /dev/null @@ -1,536 +0,0 @@ -package command - -import ( - "context" - "fmt" - "io" - "os" - "path/filepath" - "runtime" - "strconv" - "sync" - "time" - - "github.com/docker/cli/cli/config" - "github.com/docker/cli/cli/config/configfile" - dcontext "github.com/docker/cli/cli/context" - "github.com/docker/cli/cli/context/docker" - "github.com/docker/cli/cli/context/store" - "github.com/docker/cli/cli/debug" - cliflags "github.com/docker/cli/cli/flags" - manifeststore "github.com/docker/cli/cli/manifest/store" - registryclient "github.com/docker/cli/cli/registry/client" - "github.com/docker/cli/cli/streams" - "github.com/docker/cli/cli/trust" - "github.com/docker/cli/cli/version" - dopts "github.com/docker/cli/opts" - "github.com/docker/docker/api" - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/registry" - "github.com/docker/docker/api/types/swarm" - "github.com/docker/docker/client" - "github.com/docker/go-connections/tlsconfig" - "github.com/pkg/errors" - "github.com/spf13/cobra" - notaryclient "github.com/theupdateframework/notary/client" -) - -const defaultInitTimeout = 2 * time.Second - -// Streams is an interface which exposes the standard input and output streams -type Streams interface { - In() *streams.In - Out() *streams.Out - Err() io.Writer -} - -// Cli represents the docker command line client. -type Cli interface { - Client() client.APIClient - Streams - SetIn(in *streams.In) - Apply(ops ...DockerCliOption) error - ConfigFile() *configfile.ConfigFile - ServerInfo() ServerInfo - NotaryClient(imgRefAndAuth trust.ImageRefAndAuth, actions []string) (notaryclient.Repository, error) - DefaultVersion() string - CurrentVersion() string - ManifestStore() manifeststore.Store - RegistryClient(bool) registryclient.RegistryClient - ContentTrustEnabled() bool - BuildKitEnabled() (bool, error) - ContextStore() store.Store - CurrentContext() string - DockerEndpoint() docker.Endpoint -} - -// DockerCli is an instance the docker command line client. -// Instances of the client can be returned from NewDockerCli. -type DockerCli struct { - configFile *configfile.ConfigFile - options *cliflags.ClientOptions - in *streams.In - out *streams.Out - err io.Writer - client client.APIClient - serverInfo ServerInfo - contentTrust bool - contextStore store.Store - currentContext string - init sync.Once - initErr error - dockerEndpoint docker.Endpoint - contextStoreConfig store.Config - initTimeout time.Duration -} - -// DefaultVersion returns api.defaultVersion. -func (cli *DockerCli) DefaultVersion() string { - return api.DefaultVersion -} - -// CurrentVersion returns the API version currently negotiated, or the default -// version otherwise. -func (cli *DockerCli) CurrentVersion() string { - _ = cli.initialize() - if cli.client == nil { - return api.DefaultVersion - } - return cli.client.ClientVersion() -} - -// Client returns the APIClient -func (cli *DockerCli) Client() client.APIClient { - if err := cli.initialize(); err != nil { - _, _ = fmt.Fprintf(cli.Err(), "Failed to initialize: %s\n", err) - os.Exit(1) - } - return cli.client -} - -// Out returns the writer used for stdout -func (cli *DockerCli) Out() *streams.Out { - return cli.out -} - -// Err returns the writer used for stderr -func (cli *DockerCli) Err() io.Writer { - return cli.err -} - -// SetIn sets the reader used for stdin -func (cli *DockerCli) SetIn(in *streams.In) { - cli.in = in -} - -// In returns the reader used for stdin -func (cli *DockerCli) In() *streams.In { - return cli.in -} - -// ShowHelp shows the command help. -func ShowHelp(err io.Writer) func(*cobra.Command, []string) error { - return func(cmd *cobra.Command, args []string) error { - cmd.SetOut(err) - cmd.HelpFunc()(cmd, args) - return nil - } -} - -// ConfigFile returns the ConfigFile -func (cli *DockerCli) ConfigFile() *configfile.ConfigFile { - // TODO(thaJeztah): when would this happen? Is this only in tests (where cli.Initialize() is not called first?) - if cli.configFile == nil { - cli.configFile = config.LoadDefaultConfigFile(cli.err) - } - return cli.configFile -} - -// ServerInfo returns the server version details for the host this client is -// connected to -func (cli *DockerCli) ServerInfo() ServerInfo { - _ = cli.initialize() - return cli.serverInfo -} - -// ContentTrustEnabled returns whether content trust has been enabled by an -// environment variable. -func (cli *DockerCli) ContentTrustEnabled() bool { - return cli.contentTrust -} - -// BuildKitEnabled returns buildkit is enabled or not. -func (cli *DockerCli) BuildKitEnabled() (bool, error) { - // use DOCKER_BUILDKIT env var value if set and not empty - if v := os.Getenv("DOCKER_BUILDKIT"); v != "" { - enabled, err := strconv.ParseBool(v) - if err != nil { - return false, errors.Wrap(err, "DOCKER_BUILDKIT environment variable expects boolean value") - } - return enabled, nil - } - // if a builder alias is defined, we are using BuildKit - aliasMap := cli.ConfigFile().Aliases - if _, ok := aliasMap["builder"]; ok { - return true, nil - } - // otherwise, assume BuildKit is enabled but - // not if wcow reported from server side - return cli.ServerInfo().OSType != "windows", nil -} - -// ManifestStore returns a store for local manifests -func (cli *DockerCli) ManifestStore() manifeststore.Store { - // TODO: support override default location from config file - return manifeststore.NewStore(filepath.Join(config.Dir(), "manifests")) -} - -// RegistryClient returns a client for communicating with a Docker distribution -// registry -func (cli *DockerCli) RegistryClient(allowInsecure bool) registryclient.RegistryClient { - resolver := func(ctx context.Context, index *registry.IndexInfo) registry.AuthConfig { - return ResolveAuthConfig(ctx, cli, index) - } - return registryclient.NewRegistryClient(resolver, UserAgent(), allowInsecure) -} - -// InitializeOpt is the type of the functional options passed to DockerCli.Initialize -type InitializeOpt func(dockerCli *DockerCli) error - -// WithInitializeClient is passed to DockerCli.Initialize by callers who wish to set a particular API Client for use by the CLI. -func WithInitializeClient(makeClient func(dockerCli *DockerCli) (client.APIClient, error)) InitializeOpt { - return func(dockerCli *DockerCli) error { - var err error - dockerCli.client, err = makeClient(dockerCli) - return err - } -} - -// Initialize the dockerCli runs initialization that must happen after command -// line flags are parsed. -func (cli *DockerCli) Initialize(opts *cliflags.ClientOptions, ops ...InitializeOpt) error { - for _, o := range ops { - if err := o(cli); err != nil { - return err - } - } - cliflags.SetLogLevel(opts.LogLevel) - - if opts.ConfigDir != "" { - config.SetDir(opts.ConfigDir) - } - - if opts.Debug { - debug.Enable() - } - if opts.Context != "" && len(opts.Hosts) > 0 { - return errors.New("conflicting options: either specify --host or --context, not both") - } - - cli.options = opts - cli.configFile = config.LoadDefaultConfigFile(cli.err) - cli.currentContext = resolveContextName(cli.options, cli.configFile) - cli.contextStore = &ContextStoreWithDefault{ - Store: store.New(config.ContextStoreDir(), cli.contextStoreConfig), - Resolver: func() (*DefaultContext, error) { - return ResolveDefaultContext(cli.options, cli.contextStoreConfig) - }, - } - return nil -} - -// NewAPIClientFromFlags creates a new APIClient from command line flags -func NewAPIClientFromFlags(opts *cliflags.ClientOptions, configFile *configfile.ConfigFile) (client.APIClient, error) { - if opts.Context != "" && len(opts.Hosts) > 0 { - return nil, errors.New("conflicting options: either specify --host or --context, not both") - } - - storeConfig := DefaultContextStoreConfig() - contextStore := &ContextStoreWithDefault{ - Store: store.New(config.ContextStoreDir(), storeConfig), - Resolver: func() (*DefaultContext, error) { - return ResolveDefaultContext(opts, storeConfig) - }, - } - endpoint, err := resolveDockerEndpoint(contextStore, resolveContextName(opts, configFile)) - if err != nil { - return nil, errors.Wrap(err, "unable to resolve docker endpoint") - } - return newAPIClientFromEndpoint(endpoint, configFile) -} - -func newAPIClientFromEndpoint(ep docker.Endpoint, configFile *configfile.ConfigFile) (client.APIClient, error) { - clientOpts, err := ep.ClientOpts() - if err != nil { - return nil, err - } - customHeaders := make(map[string]string, len(configFile.HTTPHeaders)) - for k, v := range configFile.HTTPHeaders { - customHeaders[k] = v - } - customHeaders["User-Agent"] = UserAgent() - clientOpts = append(clientOpts, client.WithHTTPHeaders(customHeaders)) - return client.NewClientWithOpts(clientOpts...) -} - -func resolveDockerEndpoint(s store.Reader, contextName string) (docker.Endpoint, error) { - if s == nil { - return docker.Endpoint{}, fmt.Errorf("no context store initialized") - } - ctxMeta, err := s.GetMetadata(contextName) - if err != nil { - return docker.Endpoint{}, err - } - epMeta, err := docker.EndpointFromContext(ctxMeta) - if err != nil { - return docker.Endpoint{}, err - } - return docker.WithTLSData(s, contextName, epMeta) -} - -// Resolve the Docker endpoint for the default context (based on config, env vars and CLI flags) -func resolveDefaultDockerEndpoint(opts *cliflags.ClientOptions) (docker.Endpoint, error) { - host, err := getServerHost(opts.Hosts, opts.TLSOptions) - if err != nil { - return docker.Endpoint{}, err - } - - var ( - skipTLSVerify bool - tlsData *dcontext.TLSData - ) - - if opts.TLSOptions != nil { - skipTLSVerify = opts.TLSOptions.InsecureSkipVerify - tlsData, err = dcontext.TLSDataFromFiles(opts.TLSOptions.CAFile, opts.TLSOptions.CertFile, opts.TLSOptions.KeyFile) - if err != nil { - return docker.Endpoint{}, err - } - } - - return docker.Endpoint{ - EndpointMeta: docker.EndpointMeta{ - Host: host, - SkipTLSVerify: skipTLSVerify, - }, - TLSData: tlsData, - }, nil -} - -func (cli *DockerCli) getInitTimeout() time.Duration { - if cli.initTimeout != 0 { - return cli.initTimeout - } - return defaultInitTimeout -} - -func (cli *DockerCli) initializeFromClient() { - ctx := context.Background() - ctx, cancel := context.WithTimeout(ctx, cli.getInitTimeout()) - defer cancel() - - ping, err := cli.client.Ping(ctx) - if err != nil { - // Default to true if we fail to connect to daemon - cli.serverInfo = ServerInfo{HasExperimental: true} - - if ping.APIVersion != "" { - cli.client.NegotiateAPIVersionPing(ping) - } - return - } - - cli.serverInfo = ServerInfo{ - HasExperimental: ping.Experimental, - OSType: ping.OSType, - BuildkitVersion: ping.BuilderVersion, - SwarmStatus: ping.SwarmStatus, - } - cli.client.NegotiateAPIVersionPing(ping) -} - -// NotaryClient provides a Notary Repository to interact with signed metadata for an image -func (cli *DockerCli) NotaryClient(imgRefAndAuth trust.ImageRefAndAuth, actions []string) (notaryclient.Repository, error) { - return trust.GetNotaryRepository(cli.In(), cli.Out(), UserAgent(), imgRefAndAuth.RepoInfo(), imgRefAndAuth.AuthConfig(), actions...) -} - -// ContextStore returns the ContextStore -func (cli *DockerCli) ContextStore() store.Store { - return cli.contextStore -} - -// CurrentContext returns the current context name, based on flags, -// environment variables and the cli configuration file, in the following -// order of preference: -// -// 1. The "--context" command-line option. -// 2. The "DOCKER_CONTEXT" environment variable. -// 3. The current context as configured through the in "currentContext" -// field in the CLI configuration file ("~/.docker/config.json"). -// 4. If no context is configured, use the "default" context. -// -// # Fallbacks for backward-compatibility -// -// To preserve backward-compatibility with the "pre-contexts" behavior, -// the "default" context is used if: -// -// - The "--host" option is set -// - The "DOCKER_HOST" ([client.EnvOverrideHost]) environment variable is set -// to a non-empty value. -// -// In these cases, the default context is used, which uses the host as -// specified in "DOCKER_HOST", and TLS config from flags/env vars. -// -// Setting both the "--context" and "--host" flags is ambiguous and results -// in an error when the cli is started. -// -// CurrentContext does not validate if the given context exists or if it's -// valid; errors may occur when trying to use it. -func (cli *DockerCli) CurrentContext() string { - return cli.currentContext -} - -// CurrentContext returns the current context name, based on flags, -// environment variables and the cli configuration file. It does not -// validate if the given context exists or if it's valid; errors may -// occur when trying to use it. -// -// Refer to [DockerCli.CurrentContext] above for further details. -func resolveContextName(opts *cliflags.ClientOptions, config *configfile.ConfigFile) string { - if opts != nil && opts.Context != "" { - return opts.Context - } - if opts != nil && len(opts.Hosts) > 0 { - return DefaultContextName - } - if os.Getenv(client.EnvOverrideHost) != "" { - return DefaultContextName - } - if ctxName := os.Getenv("DOCKER_CONTEXT"); ctxName != "" { - return ctxName - } - if config != nil && config.CurrentContext != "" { - // We don't validate if this context exists: errors may occur when trying to use it. - return config.CurrentContext - } - return DefaultContextName -} - -// DockerEndpoint returns the current docker endpoint -func (cli *DockerCli) DockerEndpoint() docker.Endpoint { - if err := cli.initialize(); err != nil { - // Note that we're not terminating here, as this function may be used - // in cases where we're able to continue. - _, _ = fmt.Fprintf(cli.Err(), "%v\n", cli.initErr) - } - return cli.dockerEndpoint -} - -func (cli *DockerCli) getDockerEndPoint() (ep docker.Endpoint, err error) { - cn := cli.CurrentContext() - if cn == DefaultContextName { - return resolveDefaultDockerEndpoint(cli.options) - } - return resolveDockerEndpoint(cli.contextStore, cn) -} - -func (cli *DockerCli) initialize() error { - cli.init.Do(func() { - cli.dockerEndpoint, cli.initErr = cli.getDockerEndPoint() - if cli.initErr != nil { - cli.initErr = errors.Wrap(cli.initErr, "unable to resolve docker endpoint") - return - } - if cli.client == nil { - if cli.client, cli.initErr = newAPIClientFromEndpoint(cli.dockerEndpoint, cli.configFile); cli.initErr != nil { - return - } - } - cli.initializeFromClient() - }) - return cli.initErr -} - -// Apply all the operation on the cli -func (cli *DockerCli) Apply(ops ...DockerCliOption) error { - for _, op := range ops { - if err := op(cli); err != nil { - return err - } - } - return nil -} - -// ServerInfo stores details about the supported features and platform of the -// server -type ServerInfo struct { - HasExperimental bool - OSType string - BuildkitVersion types.BuilderVersion - - // SwarmStatus provides information about the current swarm status of the - // engine, obtained from the "Swarm" header in the API response. - // - // It can be a nil struct if the API version does not provide this header - // in the ping response, or if an error occurred, in which case the client - // should use other ways to get the current swarm status, such as the /swarm - // endpoint. - SwarmStatus *swarm.Status -} - -// NewDockerCli returns a DockerCli instance with all operators applied on it. -// It applies by default the standard streams, and the content trust from -// environment. -func NewDockerCli(ops ...DockerCliOption) (*DockerCli, error) { - defaultOps := []DockerCliOption{ - WithContentTrustFromEnv(), - WithDefaultContextStoreConfig(), - WithStandardStreams(), - } - ops = append(defaultOps, ops...) - - cli := &DockerCli{} - if err := cli.Apply(ops...); err != nil { - return nil, err - } - return cli, nil -} - -func getServerHost(hosts []string, tlsOptions *tlsconfig.Options) (string, error) { - var host string - switch len(hosts) { - case 0: - host = os.Getenv(client.EnvOverrideHost) - case 1: - host = hosts[0] - default: - return "", errors.New("Please specify only one -H") - } - - return dopts.ParseHost(tlsOptions != nil, host) -} - -// UserAgent returns the user agent string used for making API requests -func UserAgent() string { - return "Docker-Client/" + version.Version + " (" + runtime.GOOS + ")" -} - -var defaultStoreEndpoints = []store.NamedTypeGetter{ - store.EndpointTypeGetter(docker.DockerEndpoint, func() interface{} { return &docker.EndpointMeta{} }), -} - -// RegisterDefaultStoreEndpoints registers a new named endpoint -// metadata type with the default context store config, so that -// endpoint will be supported by stores using the config returned by -// DefaultContextStoreConfig. -func RegisterDefaultStoreEndpoints(ep ...store.NamedTypeGetter) { - defaultStoreEndpoints = append(defaultStoreEndpoints, ep...) -} - -// DefaultContextStoreConfig returns a new store.Config with the default set of endpoints configured. -func DefaultContextStoreConfig() store.Config { - return store.NewConfig( - func() interface{} { return &DockerContext{} }, - defaultStoreEndpoints..., - ) -} diff --git a/vendor/github.com/docker/cli/cli/command/cli_options.go b/vendor/github.com/docker/cli/cli/command/cli_options.go deleted file mode 100644 index d714947cb..000000000 --- a/vendor/github.com/docker/cli/cli/command/cli_options.go +++ /dev/null @@ -1,97 +0,0 @@ -package command - -import ( - "io" - "os" - "strconv" - - "github.com/docker/cli/cli/streams" - "github.com/docker/docker/client" - "github.com/moby/term" -) - -// DockerCliOption applies a modification on a DockerCli. -type DockerCliOption func(cli *DockerCli) error - -// WithStandardStreams sets a cli in, out and err streams with the standard streams. -func WithStandardStreams() DockerCliOption { - return func(cli *DockerCli) error { - // Set terminal emulation based on platform as required. - stdin, stdout, stderr := term.StdStreams() - cli.in = streams.NewIn(stdin) - cli.out = streams.NewOut(stdout) - cli.err = stderr - return nil - } -} - -// WithCombinedStreams uses the same stream for the output and error streams. -func WithCombinedStreams(combined io.Writer) DockerCliOption { - return func(cli *DockerCli) error { - cli.out = streams.NewOut(combined) - cli.err = combined - return nil - } -} - -// WithInputStream sets a cli input stream. -func WithInputStream(in io.ReadCloser) DockerCliOption { - return func(cli *DockerCli) error { - cli.in = streams.NewIn(in) - return nil - } -} - -// WithOutputStream sets a cli output stream. -func WithOutputStream(out io.Writer) DockerCliOption { - return func(cli *DockerCli) error { - cli.out = streams.NewOut(out) - return nil - } -} - -// WithErrorStream sets a cli error stream. -func WithErrorStream(err io.Writer) DockerCliOption { - return func(cli *DockerCli) error { - cli.err = err - return nil - } -} - -// WithContentTrustFromEnv enables content trust on a cli from environment variable DOCKER_CONTENT_TRUST value. -func WithContentTrustFromEnv() DockerCliOption { - return func(cli *DockerCli) error { - cli.contentTrust = false - if e := os.Getenv("DOCKER_CONTENT_TRUST"); e != "" { - if t, err := strconv.ParseBool(e); t || err != nil { - // treat any other value as true - cli.contentTrust = true - } - } - return nil - } -} - -// WithContentTrust enables content trust on a cli. -func WithContentTrust(enabled bool) DockerCliOption { - return func(cli *DockerCli) error { - cli.contentTrust = enabled - return nil - } -} - -// WithDefaultContextStoreConfig configures the cli to use the default context store configuration. -func WithDefaultContextStoreConfig() DockerCliOption { - return func(cli *DockerCli) error { - cli.contextStoreConfig = DefaultContextStoreConfig() - return nil - } -} - -// WithAPIClient configures the cli to use the given API client. -func WithAPIClient(c client.APIClient) DockerCliOption { - return func(cli *DockerCli) error { - cli.client = c - return nil - } -} diff --git a/vendor/github.com/docker/cli/cli/command/completion/functions.go b/vendor/github.com/docker/cli/cli/command/completion/functions.go deleted file mode 100644 index 40f0b5263..000000000 --- a/vendor/github.com/docker/cli/cli/command/completion/functions.go +++ /dev/null @@ -1,99 +0,0 @@ -package completion - -import ( - "os" - - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/formatter" - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/volume" - "github.com/spf13/cobra" -) - -// ValidArgsFn a function to be used by cobra command as `ValidArgsFunction` to offer command line completion -type ValidArgsFn func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) - -// ImageNames offers completion for images present within the local store -func ImageNames(dockerCli command.Cli) ValidArgsFn { - return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - list, err := dockerCli.Client().ImageList(cmd.Context(), types.ImageListOptions{}) - if err != nil { - return nil, cobra.ShellCompDirectiveError - } - var names []string - for _, image := range list { - names = append(names, image.RepoTags...) - } - return names, cobra.ShellCompDirectiveNoFileComp - } -} - -// ContainerNames offers completion for container names and IDs -// By default, only names are returned. -// Set DOCKER_COMPLETION_SHOW_CONTAINER_IDS=yes to also complete IDs. -func ContainerNames(dockerCli command.Cli, all bool, filters ...func(types.Container) bool) ValidArgsFn { - return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - list, err := dockerCli.Client().ContainerList(cmd.Context(), types.ContainerListOptions{ - All: all, - }) - if err != nil { - return nil, cobra.ShellCompDirectiveError - } - - showContainerIDs := os.Getenv("DOCKER_COMPLETION_SHOW_CONTAINER_IDS") == "yes" - - var names []string - for _, container := range list { - skip := false - for _, fn := range filters { - if !fn(container) { - skip = true - break - } - } - if skip { - continue - } - if showContainerIDs { - names = append(names, container.ID) - } - names = append(names, formatter.StripNamePrefix(container.Names)...) - } - return names, cobra.ShellCompDirectiveNoFileComp - } -} - -// VolumeNames offers completion for volumes -func VolumeNames(dockerCli command.Cli) ValidArgsFn { - return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - list, err := dockerCli.Client().VolumeList(cmd.Context(), volume.ListOptions{}) - if err != nil { - return nil, cobra.ShellCompDirectiveError - } - var names []string - for _, vol := range list.Volumes { - names = append(names, vol.Name) - } - return names, cobra.ShellCompDirectiveNoFileComp - } -} - -// NetworkNames offers completion for networks -func NetworkNames(dockerCli command.Cli) ValidArgsFn { - return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - list, err := dockerCli.Client().NetworkList(cmd.Context(), types.NetworkListOptions{}) - if err != nil { - return nil, cobra.ShellCompDirectiveError - } - var names []string - for _, network := range list { - names = append(names, network.Name) - } - return names, cobra.ShellCompDirectiveNoFileComp - } -} - -// NoComplete is used for commands where there's no relevant completion -func NoComplete(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) { - return nil, cobra.ShellCompDirectiveNoFileComp -} diff --git a/vendor/github.com/docker/cli/cli/command/container/attach.go b/vendor/github.com/docker/cli/cli/command/container/attach.go deleted file mode 100644 index bd17696b8..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/attach.go +++ /dev/null @@ -1,181 +0,0 @@ -package container - -import ( - "context" - "fmt" - "io" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/client" - "github.com/moby/sys/signal" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" - "github.com/spf13/cobra" -) - -type attachOptions struct { - noStdin bool - proxy bool - detachKeys string - - container string -} - -func inspectContainerAndCheckState(ctx context.Context, cli client.APIClient, args string) (*types.ContainerJSON, error) { - c, err := cli.ContainerInspect(ctx, args) - if err != nil { - return nil, err - } - if !c.State.Running { - return nil, errors.New("You cannot attach to a stopped container, start it first") - } - if c.State.Paused { - return nil, errors.New("You cannot attach to a paused container, unpause it first") - } - if c.State.Restarting { - return nil, errors.New("You cannot attach to a restarting container, wait until it is running") - } - - return &c, nil -} - -// NewAttachCommand creates a new cobra.Command for `docker attach` -func NewAttachCommand(dockerCli command.Cli) *cobra.Command { - var opts attachOptions - - cmd := &cobra.Command{ - Use: "attach [OPTIONS] CONTAINER", - Short: "Attach local standard input, output, and error streams to a running container", - Args: cli.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - opts.container = args[0] - return runAttach(dockerCli, &opts) - }, - Annotations: map[string]string{ - "aliases": "docker container attach, docker attach", - }, - ValidArgsFunction: completion.ContainerNames(dockerCli, false, func(container types.Container) bool { - return container.State != "paused" - }), - } - - flags := cmd.Flags() - flags.BoolVar(&opts.noStdin, "no-stdin", false, "Do not attach STDIN") - flags.BoolVar(&opts.proxy, "sig-proxy", true, "Proxy all received signals to the process") - flags.StringVar(&opts.detachKeys, "detach-keys", "", "Override the key sequence for detaching a container") - return cmd -} - -func runAttach(dockerCli command.Cli, opts *attachOptions) error { - ctx := context.Background() - client := dockerCli.Client() - - // request channel to wait for client - resultC, errC := client.ContainerWait(ctx, opts.container, "") - - c, err := inspectContainerAndCheckState(ctx, client, opts.container) - if err != nil { - return err - } - - if err := dockerCli.In().CheckTty(!opts.noStdin, c.Config.Tty); err != nil { - return err - } - - if opts.detachKeys != "" { - dockerCli.ConfigFile().DetachKeys = opts.detachKeys - } - - options := types.ContainerAttachOptions{ - Stream: true, - Stdin: !opts.noStdin && c.Config.OpenStdin, - Stdout: true, - Stderr: true, - DetachKeys: dockerCli.ConfigFile().DetachKeys, - } - - var in io.ReadCloser - if options.Stdin { - in = dockerCli.In() - } - - if opts.proxy && !c.Config.Tty { - sigc := notifyAllSignals() - go ForwardAllSignals(ctx, dockerCli, opts.container, sigc) - defer signal.StopCatch(sigc) - } - - resp, errAttach := client.ContainerAttach(ctx, opts.container, options) - if errAttach != nil { - return errAttach - } - defer resp.Close() - - // If use docker attach command to attach to a stop container, it will return - // "You cannot attach to a stopped container" error, it's ok, but when - // attach to a running container, it(docker attach) use inspect to check - // the container's state, if it pass the state check on the client side, - // and then the container is stopped, docker attach command still attach to - // the container and not exit. - // - // Recheck the container's state to avoid attach block. - _, err = inspectContainerAndCheckState(ctx, client, opts.container) - if err != nil { - return err - } - - if c.Config.Tty && dockerCli.Out().IsTerminal() { - resizeTTY(ctx, dockerCli, opts.container) - } - - streamer := hijackedIOStreamer{ - streams: dockerCli, - inputStream: in, - outputStream: dockerCli.Out(), - errorStream: dockerCli.Err(), - resp: resp, - tty: c.Config.Tty, - detachKeys: options.DetachKeys, - } - - if err := streamer.stream(ctx); err != nil { - return err - } - - return getExitStatus(errC, resultC) -} - -func getExitStatus(errC <-chan error, resultC <-chan container.WaitResponse) error { - select { - case result := <-resultC: - if result.Error != nil { - return fmt.Errorf(result.Error.Message) - } - if result.StatusCode != 0 { - return cli.StatusError{StatusCode: int(result.StatusCode)} - } - case err := <-errC: - return err - } - - return nil -} - -func resizeTTY(ctx context.Context, dockerCli command.Cli, containerID string) { - height, width := dockerCli.Out().GetTtySize() - // To handle the case where a user repeatedly attaches/detaches without resizing their - // terminal, the only way to get the shell prompt to display for attaches 2+ is to artificially - // resize it, then go back to normal. Without this, every attach after the first will - // require the user to manually resize or hit enter. - resizeTtyTo(ctx, dockerCli.Client(), containerID, height+1, width+1, false) - - // After the above resizing occurs, the call to MonitorTtySize below will handle resetting back - // to the actual size. - if err := MonitorTtySize(ctx, dockerCli, containerID, false); err != nil { - logrus.Debugf("Error monitoring TTY size: %s", err) - } -} diff --git a/vendor/github.com/docker/cli/cli/command/container/cmd.go b/vendor/github.com/docker/cli/cli/command/container/cmd.go deleted file mode 100644 index dcf8116ef..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/cmd.go +++ /dev/null @@ -1,45 +0,0 @@ -package container - -import ( - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/spf13/cobra" -) - -// NewContainerCommand returns a cobra command for `container` subcommands -func NewContainerCommand(dockerCli command.Cli) *cobra.Command { - cmd := &cobra.Command{ - Use: "container", - Short: "Manage containers", - Args: cli.NoArgs, - RunE: command.ShowHelp(dockerCli.Err()), - } - cmd.AddCommand( - NewAttachCommand(dockerCli), - NewCommitCommand(dockerCli), - NewCopyCommand(dockerCli), - NewCreateCommand(dockerCli), - NewDiffCommand(dockerCli), - NewExecCommand(dockerCli), - NewExportCommand(dockerCli), - NewKillCommand(dockerCli), - NewLogsCommand(dockerCli), - NewPauseCommand(dockerCli), - NewPortCommand(dockerCli), - NewRenameCommand(dockerCli), - NewRestartCommand(dockerCli), - NewRmCommand(dockerCli), - NewRunCommand(dockerCli), - NewStartCommand(dockerCli), - NewStatsCommand(dockerCli), - NewStopCommand(dockerCli), - NewTopCommand(dockerCli), - NewUnpauseCommand(dockerCli), - NewUpdateCommand(dockerCli), - NewWaitCommand(dockerCli), - newListCommand(dockerCli), - newInspectCommand(dockerCli), - NewPruneCommand(dockerCli), - ) - return cmd -} diff --git a/vendor/github.com/docker/cli/cli/command/container/commit.go b/vendor/github.com/docker/cli/cli/command/container/commit.go deleted file mode 100644 index 39b8db9a5..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/commit.go +++ /dev/null @@ -1,80 +0,0 @@ -package container - -import ( - "context" - "fmt" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/docker/cli/opts" - "github.com/docker/docker/api/types" - "github.com/spf13/cobra" -) - -type commitOptions struct { - container string - reference string - - pause bool - comment string - author string - changes opts.ListOpts -} - -// NewCommitCommand creates a new cobra.Command for `docker commit` -func NewCommitCommand(dockerCli command.Cli) *cobra.Command { - var options commitOptions - - cmd := &cobra.Command{ - Use: "commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]", - Short: "Create a new image from a container's changes", - Args: cli.RequiresRangeArgs(1, 2), - RunE: func(cmd *cobra.Command, args []string) error { - options.container = args[0] - if len(args) > 1 { - options.reference = args[1] - } - return runCommit(dockerCli, &options) - }, - Annotations: map[string]string{ - "aliases": "docker container commit, docker commit", - }, - ValidArgsFunction: completion.ContainerNames(dockerCli, false), - } - - flags := cmd.Flags() - flags.SetInterspersed(false) - - flags.BoolVarP(&options.pause, "pause", "p", true, "Pause container during commit") - flags.StringVarP(&options.comment, "message", "m", "", "Commit message") - flags.StringVarP(&options.author, "author", "a", "", `Author (e.g., "John Hannibal Smith ")`) - - options.changes = opts.NewListOpts(nil) - flags.VarP(&options.changes, "change", "c", "Apply Dockerfile instruction to the created image") - - return cmd -} - -func runCommit(dockerCli command.Cli, options *commitOptions) error { - ctx := context.Background() - - name := options.container - reference := options.reference - - commitOptions := types.ContainerCommitOptions{ - Reference: reference, - Comment: options.comment, - Author: options.author, - Changes: options.changes.GetAll(), - Pause: options.pause, - } - - response, err := dockerCli.Client().ContainerCommit(ctx, name, commitOptions) - if err != nil { - return err - } - - fmt.Fprintln(dockerCli.Out(), response.ID) - return nil -} diff --git a/vendor/github.com/docker/cli/cli/command/container/cp.go b/vendor/github.com/docker/cli/cli/command/container/cp.go deleted file mode 100644 index 5ef409ca8..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/cp.go +++ /dev/null @@ -1,453 +0,0 @@ -package container - -import ( - "bytes" - "context" - "fmt" - "io" - "os" - "os/signal" - "path/filepath" - "strings" - "sync/atomic" - "time" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/streams" - "github.com/docker/docker/api/types" - "github.com/docker/docker/pkg/archive" - "github.com/docker/docker/pkg/system" - units "github.com/docker/go-units" - "github.com/morikuni/aec" - "github.com/pkg/errors" - "github.com/spf13/cobra" -) - -type copyOptions struct { - source string - destination string - followLink bool - copyUIDGID bool - quiet bool -} - -type copyDirection int - -const ( - fromContainer copyDirection = 1 << iota - toContainer - acrossContainers = fromContainer | toContainer -) - -type cpConfig struct { - followLink bool - copyUIDGID bool - quiet bool - sourcePath string - destPath string - container string -} - -// copyProgressPrinter wraps io.ReadCloser to print progress information when -// copying files to/from a container. -type copyProgressPrinter struct { - io.ReadCloser - total *int64 -} - -const ( - copyToContainerHeader = "Copying to container - " - copyFromContainerHeader = "Copying from container - " - copyProgressUpdateThreshold = 75 * time.Millisecond -) - -func (pt *copyProgressPrinter) Read(p []byte) (int, error) { - n, err := pt.ReadCloser.Read(p) - atomic.AddInt64(pt.total, int64(n)) - return n, err -} - -func copyProgress(ctx context.Context, dst io.Writer, header string, total *int64) (func(), <-chan struct{}) { - done := make(chan struct{}) - if !streams.NewOut(dst).IsTerminal() { - close(done) - return func() {}, done - } - - fmt.Fprint(dst, aec.Save) - fmt.Fprint(dst, "Preparing to copy...") - - restore := func() { - fmt.Fprint(dst, aec.Restore) - fmt.Fprint(dst, aec.EraseLine(aec.EraseModes.All)) - } - - go func() { - defer close(done) - fmt.Fprint(dst, aec.Hide) - defer fmt.Fprint(dst, aec.Show) - - fmt.Fprint(dst, aec.Restore) - fmt.Fprint(dst, aec.EraseLine(aec.EraseModes.All)) - fmt.Fprint(dst, header) - - var last int64 - fmt.Fprint(dst, progressHumanSize(last)) - - buf := bytes.NewBuffer(nil) - ticker := time.NewTicker(copyProgressUpdateThreshold) - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - n := atomic.LoadInt64(total) - if n == last { - // Don't write to the terminal, if we don't need to. - continue - } - - // Write to the buffer first to avoid flickering and context switching - fmt.Fprint(buf, aec.Column(uint(len(header)+1))) - fmt.Fprint(buf, aec.EraseLine(aec.EraseModes.Tail)) - fmt.Fprint(buf, progressHumanSize(n)) - - buf.WriteTo(dst) - buf.Reset() - last += n - } - } - }() - return restore, done -} - -// NewCopyCommand creates a new `docker cp` command -func NewCopyCommand(dockerCli command.Cli) *cobra.Command { - var opts copyOptions - - cmd := &cobra.Command{ - Use: `cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|- - docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH`, - Short: "Copy files/folders between a container and the local filesystem", - Long: strings.Join([]string{ - "Copy files/folders between a container and the local filesystem\n", - "\nUse '-' as the source to read a tar archive from stdin\n", - "and extract it to a directory destination in a container.\n", - "Use '-' as the destination to stream a tar archive of a\n", - "container source to stdout.", - }, ""), - Args: cli.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - if args[0] == "" { - return errors.New("source can not be empty") - } - if args[1] == "" { - return errors.New("destination can not be empty") - } - opts.source = args[0] - opts.destination = args[1] - if !cmd.Flag("quiet").Changed { - // User did not specify "quiet" flag; suppress output if no terminal is attached - opts.quiet = !dockerCli.Out().IsTerminal() - } - return runCopy(dockerCli, opts) - }, - Annotations: map[string]string{ - "aliases": "docker container cp, docker cp", - }, - } - - flags := cmd.Flags() - flags.BoolVarP(&opts.followLink, "follow-link", "L", false, "Always follow symbol link in SRC_PATH") - flags.BoolVarP(&opts.copyUIDGID, "archive", "a", false, "Archive mode (copy all uid/gid information)") - flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Suppress progress output during copy. Progress output is automatically suppressed if no terminal is attached") - return cmd -} - -func progressHumanSize(n int64) string { - return units.HumanSizeWithPrecision(float64(n), 3) -} - -func runCopy(dockerCli command.Cli, opts copyOptions) error { - srcContainer, srcPath := splitCpArg(opts.source) - destContainer, destPath := splitCpArg(opts.destination) - - copyConfig := cpConfig{ - followLink: opts.followLink, - copyUIDGID: opts.copyUIDGID, - quiet: opts.quiet, - sourcePath: srcPath, - destPath: destPath, - } - - var direction copyDirection - if srcContainer != "" { - direction |= fromContainer - copyConfig.container = srcContainer - } - if destContainer != "" { - direction |= toContainer - copyConfig.container = destContainer - } - - ctx := context.Background() - - switch direction { - case fromContainer: - return copyFromContainer(ctx, dockerCli, copyConfig) - case toContainer: - return copyToContainer(ctx, dockerCli, copyConfig) - case acrossContainers: - return errors.New("copying between containers is not supported") - default: - return errors.New("must specify at least one container source") - } -} - -func resolveLocalPath(localPath string) (absPath string, err error) { - if absPath, err = filepath.Abs(localPath); err != nil { - return - } - return archive.PreserveTrailingDotOrSeparator(absPath, localPath), nil -} - -func copyFromContainer(ctx context.Context, dockerCli command.Cli, copyConfig cpConfig) (err error) { - dstPath := copyConfig.destPath - srcPath := copyConfig.sourcePath - - if dstPath != "-" { - // Get an absolute destination path. - dstPath, err = resolveLocalPath(dstPath) - if err != nil { - return err - } - } - - if err := command.ValidateOutputPath(dstPath); err != nil { - return err - } - - client := dockerCli.Client() - // if client requests to follow symbol link, then must decide target file to be copied - var rebaseName string - if copyConfig.followLink { - srcStat, err := client.ContainerStatPath(ctx, copyConfig.container, srcPath) - - // If the destination is a symbolic link, we should follow it. - if err == nil && srcStat.Mode&os.ModeSymlink != 0 { - linkTarget := srcStat.LinkTarget - if !system.IsAbs(linkTarget) { - // Join with the parent directory. - srcParent, _ := archive.SplitPathDirEntry(srcPath) - linkTarget = filepath.Join(srcParent, linkTarget) - } - - linkTarget, rebaseName = archive.GetRebaseName(srcPath, linkTarget) - srcPath = linkTarget - } - - } - - ctx, cancel := signal.NotifyContext(ctx, os.Interrupt) - defer cancel() - - content, stat, err := client.CopyFromContainer(ctx, copyConfig.container, srcPath) - if err != nil { - return err - } - defer content.Close() - - if dstPath == "-" { - _, err = io.Copy(dockerCli.Out(), content) - return err - } - - srcInfo := archive.CopyInfo{ - Path: srcPath, - Exists: true, - IsDir: stat.Mode.IsDir(), - RebaseName: rebaseName, - } - - var copiedSize int64 - if !copyConfig.quiet { - content = ©ProgressPrinter{ - ReadCloser: content, - total: &copiedSize, - } - } - - preArchive := content - if len(srcInfo.RebaseName) != 0 { - _, srcBase := archive.SplitPathDirEntry(srcInfo.Path) - preArchive = archive.RebaseArchiveEntries(content, srcBase, srcInfo.RebaseName) - } - - if copyConfig.quiet { - return archive.CopyTo(preArchive, srcInfo, dstPath) - } - - restore, done := copyProgress(ctx, dockerCli.Err(), copyFromContainerHeader, &copiedSize) - res := archive.CopyTo(preArchive, srcInfo, dstPath) - cancel() - <-done - restore() - fmt.Fprintln(dockerCli.Err(), "Successfully copied", progressHumanSize(copiedSize), "to", dstPath) - - return res -} - -// In order to get the copy behavior right, we need to know information -// about both the source and destination. The API is a simple tar -// archive/extract API but we can use the stat info header about the -// destination to be more informed about exactly what the destination is. -func copyToContainer(ctx context.Context, dockerCli command.Cli, copyConfig cpConfig) (err error) { - srcPath := copyConfig.sourcePath - dstPath := copyConfig.destPath - - if srcPath != "-" { - // Get an absolute source path. - srcPath, err = resolveLocalPath(srcPath) - if err != nil { - return err - } - } - - client := dockerCli.Client() - // Prepare destination copy info by stat-ing the container path. - dstInfo := archive.CopyInfo{Path: dstPath} - dstStat, err := client.ContainerStatPath(ctx, copyConfig.container, dstPath) - - // If the destination is a symbolic link, we should evaluate it. - if err == nil && dstStat.Mode&os.ModeSymlink != 0 { - linkTarget := dstStat.LinkTarget - if !system.IsAbs(linkTarget) { - // Join with the parent directory. - dstParent, _ := archive.SplitPathDirEntry(dstPath) - linkTarget = filepath.Join(dstParent, linkTarget) - } - - dstInfo.Path = linkTarget - dstStat, err = client.ContainerStatPath(ctx, copyConfig.container, linkTarget) - } - - // Validate the destination path - if err := command.ValidateOutputPathFileMode(dstStat.Mode); err != nil { - return errors.Wrapf(err, `destination "%s:%s" must be a directory or a regular file`, copyConfig.container, dstPath) - } - - // Ignore any error and assume that the parent directory of the destination - // path exists, in which case the copy may still succeed. If there is any - // type of conflict (e.g., non-directory overwriting an existing directory - // or vice versa) the extraction will fail. If the destination simply did - // not exist, but the parent directory does, the extraction will still - // succeed. - if err == nil { - dstInfo.Exists, dstInfo.IsDir = true, dstStat.Mode.IsDir() - } - - var ( - content io.ReadCloser - resolvedDstPath string - copiedSize int64 - ) - - if srcPath == "-" { - content = os.Stdin - resolvedDstPath = dstInfo.Path - if !dstInfo.IsDir { - return errors.Errorf("destination \"%s:%s\" must be a directory", copyConfig.container, dstPath) - } - } else { - // Prepare source copy info. - srcInfo, err := archive.CopyInfoSourcePath(srcPath, copyConfig.followLink) - if err != nil { - return err - } - - srcArchive, err := archive.TarResource(srcInfo) - if err != nil { - return err - } - defer srcArchive.Close() - - // With the stat info about the local source as well as the - // destination, we have enough information to know whether we need to - // alter the archive that we upload so that when the server extracts - // it to the specified directory in the container we get the desired - // copy behavior. - - // See comments in the implementation of `archive.PrepareArchiveCopy` - // for exactly what goes into deciding how and whether the source - // archive needs to be altered for the correct copy behavior when it is - // extracted. This function also infers from the source and destination - // info which directory to extract to, which may be the parent of the - // destination that the user specified. - dstDir, preparedArchive, err := archive.PrepareArchiveCopy(srcArchive, srcInfo, dstInfo) - if err != nil { - return err - } - defer preparedArchive.Close() - - resolvedDstPath = dstDir - content = preparedArchive - if !copyConfig.quiet { - content = ©ProgressPrinter{ - ReadCloser: content, - total: &copiedSize, - } - } - } - - options := types.CopyToContainerOptions{ - AllowOverwriteDirWithFile: false, - CopyUIDGID: copyConfig.copyUIDGID, - } - - if copyConfig.quiet { - return client.CopyToContainer(ctx, copyConfig.container, resolvedDstPath, content, options) - } - - ctx, cancel := signal.NotifyContext(ctx, os.Interrupt) - restore, done := copyProgress(ctx, dockerCli.Err(), copyToContainerHeader, &copiedSize) - res := client.CopyToContainer(ctx, copyConfig.container, resolvedDstPath, content, options) - cancel() - <-done - restore() - fmt.Fprintln(dockerCli.Err(), "Successfully copied", progressHumanSize(copiedSize), "to", copyConfig.container+":"+dstInfo.Path) - - return res -} - -// We use `:` as a delimiter between CONTAINER and PATH, but `:` could also be -// in a valid LOCALPATH, like `file:name.txt`. We can resolve this ambiguity by -// requiring a LOCALPATH with a `:` to be made explicit with a relative or -// absolute path: -// -// `/path/to/file:name.txt` or `./file:name.txt` -// -// This is apparently how `scp` handles this as well: -// -// http://www.cyberciti.biz/faq/rsync-scp-file-name-with-colon-punctuation-in-it/ -// -// We can't simply check for a filepath separator because container names may -// have a separator, e.g., "host0/cname1" if container is in a Docker cluster, -// so we have to check for a `/` or `.` prefix. Also, in the case of a Windows -// client, a `:` could be part of an absolute Windows path, in which case it -// is immediately proceeded by a backslash. -func splitCpArg(arg string) (container, path string) { - if system.IsAbs(arg) { - // Explicit local absolute path, e.g., `C:\foo` or `/foo`. - return "", arg - } - - container, path, ok := strings.Cut(arg, ":") - if !ok || strings.HasPrefix(container, ".") { - // Either there's no `:` in the arg - // OR it's an explicit local relative path like `./file:name.txt`. - return "", arg - } - - return container, path -} diff --git a/vendor/github.com/docker/cli/cli/command/container/create.go b/vendor/github.com/docker/cli/cli/command/container/create.go deleted file mode 100644 index 18c432f76..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/create.go +++ /dev/null @@ -1,328 +0,0 @@ -package container - -import ( - "context" - "fmt" - "io" - "os" - "regexp" - - "github.com/containerd/containerd/platforms" - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/docker/cli/cli/command/image" - "github.com/docker/cli/cli/streams" - "github.com/docker/cli/opts" - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/versions" - apiclient "github.com/docker/docker/client" - "github.com/docker/docker/pkg/jsonmessage" - specs "github.com/opencontainers/image-spec/specs-go/v1" - "github.com/pkg/errors" - "github.com/spf13/cobra" - "github.com/spf13/pflag" -) - -// Pull constants -const ( - PullImageAlways = "always" - PullImageMissing = "missing" // Default (matches previous behavior) - PullImageNever = "never" -) - -type createOptions struct { - name string - platform string - untrusted bool - pull string // always, missing, never - quiet bool -} - -// NewCreateCommand creates a new cobra.Command for `docker create` -func NewCreateCommand(dockerCli command.Cli) *cobra.Command { - var options createOptions - var copts *containerOptions - - cmd := &cobra.Command{ - Use: "create [OPTIONS] IMAGE [COMMAND] [ARG...]", - Short: "Create a new container", - Args: cli.RequiresMinArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - copts.Image = args[0] - if len(args) > 1 { - copts.Args = args[1:] - } - return runCreate(dockerCli, cmd.Flags(), &options, copts) - }, - Annotations: map[string]string{ - "aliases": "docker container create, docker create", - }, - ValidArgsFunction: completion.ImageNames(dockerCli), - } - - flags := cmd.Flags() - flags.SetInterspersed(false) - - flags.StringVar(&options.name, "name", "", "Assign a name to the container") - flags.StringVar(&options.pull, "pull", PullImageMissing, `Pull image before creating ("`+PullImageAlways+`", "|`+PullImageMissing+`", "`+PullImageNever+`")`) - flags.BoolVarP(&options.quiet, "quiet", "q", false, "Suppress the pull output") - - // Add an explicit help that doesn't have a `-h` to prevent the conflict - // with hostname - flags.Bool("help", false, "Print usage") - - command.AddPlatformFlag(flags, &options.platform) - command.AddTrustVerificationFlags(flags, &options.untrusted, dockerCli.ContentTrustEnabled()) - copts = addFlags(flags) - return cmd -} - -func runCreate(dockerCli command.Cli, flags *pflag.FlagSet, options *createOptions, copts *containerOptions) error { - if err := validatePullOpt(options.pull); err != nil { - reportError(dockerCli.Err(), "create", err.Error(), true) - return cli.StatusError{StatusCode: 125} - } - proxyConfig := dockerCli.ConfigFile().ParseProxyConfig(dockerCli.Client().DaemonHost(), opts.ConvertKVStringsToMapWithNil(copts.env.GetAll())) - newEnv := []string{} - for k, v := range proxyConfig { - if v == nil { - newEnv = append(newEnv, k) - } else { - newEnv = append(newEnv, fmt.Sprintf("%s=%s", k, *v)) - } - } - copts.env = *opts.NewListOptsRef(&newEnv, nil) - containerCfg, err := parse(flags, copts, dockerCli.ServerInfo().OSType) - if err != nil { - reportError(dockerCli.Err(), "create", err.Error(), true) - return cli.StatusError{StatusCode: 125} - } - if err = validateAPIVersion(containerCfg, dockerCli.Client().ClientVersion()); err != nil { - reportError(dockerCli.Err(), "create", err.Error(), true) - return cli.StatusError{StatusCode: 125} - } - response, err := createContainer(context.Background(), dockerCli, containerCfg, options) - if err != nil { - return err - } - fmt.Fprintln(dockerCli.Out(), response.ID) - return nil -} - -// FIXME(thaJeztah): this is the only code-path that uses APIClient.ImageCreate. Rewrite this to use the regular "pull" code (or vice-versa). -func pullImage(ctx context.Context, dockerCli command.Cli, image string, opts *createOptions) error { - encodedAuth, err := command.RetrieveAuthTokenFromImage(ctx, dockerCli, image) - if err != nil { - return err - } - - responseBody, err := dockerCli.Client().ImageCreate(ctx, image, types.ImageCreateOptions{ - RegistryAuth: encodedAuth, - Platform: opts.platform, - }) - if err != nil { - return err - } - defer responseBody.Close() - - out := dockerCli.Err() - if opts.quiet { - out = io.Discard - } - return jsonmessage.DisplayJSONMessagesToStream(responseBody, streams.NewOut(out), nil) -} - -type cidFile struct { - path string - file *os.File - written bool -} - -func (cid *cidFile) Close() error { - if cid.file == nil { - return nil - } - cid.file.Close() - - if cid.written { - return nil - } - if err := os.Remove(cid.path); err != nil { - return errors.Wrapf(err, "failed to remove the CID file '%s'", cid.path) - } - - return nil -} - -func (cid *cidFile) Write(id string) error { - if cid.file == nil { - return nil - } - if _, err := cid.file.Write([]byte(id)); err != nil { - return errors.Wrap(err, "failed to write the container ID to the file") - } - cid.written = true - return nil -} - -func newCIDFile(path string) (*cidFile, error) { - if path == "" { - return &cidFile{}, nil - } - if _, err := os.Stat(path); err == nil { - return nil, errors.Errorf("container ID file found, make sure the other container isn't running or delete %s", path) - } - - f, err := os.Create(path) - if err != nil { - return nil, errors.Wrap(err, "failed to create the container ID file") - } - - return &cidFile{path: path, file: f}, nil -} - -//nolint:gocyclo -func createContainer(ctx context.Context, dockerCli command.Cli, containerCfg *containerConfig, opts *createOptions) (*container.CreateResponse, error) { - config := containerCfg.Config - hostConfig := containerCfg.HostConfig - networkingConfig := containerCfg.NetworkingConfig - - warnOnOomKillDisable(*hostConfig, dockerCli.Err()) - warnOnLocalhostDNS(*hostConfig, dockerCli.Err()) - - var ( - trustedRef reference.Canonical - namedRef reference.Named - ) - - containerIDFile, err := newCIDFile(hostConfig.ContainerIDFile) - if err != nil { - return nil, err - } - defer containerIDFile.Close() - - ref, err := reference.ParseAnyReference(config.Image) - if err != nil { - return nil, err - } - if named, ok := ref.(reference.Named); ok { - namedRef = reference.TagNameOnly(named) - - if taggedRef, ok := namedRef.(reference.NamedTagged); ok && !opts.untrusted { - var err error - trustedRef, err = image.TrustedReference(ctx, dockerCli, taggedRef) - if err != nil { - return nil, err - } - config.Image = reference.FamiliarString(trustedRef) - } - } - - pullAndTagImage := func() error { - if err := pullImage(ctx, dockerCli, config.Image, opts); err != nil { - return err - } - if taggedRef, ok := namedRef.(reference.NamedTagged); ok && trustedRef != nil { - return image.TagTrusted(ctx, dockerCli, trustedRef, taggedRef) - } - return nil - } - - var platform *specs.Platform - // Engine API version 1.41 first introduced the option to specify platform on - // create. It will produce an error if you try to set a platform on older API - // versions, so check the API version here to maintain backwards - // compatibility for CLI users. - if opts.platform != "" && versions.GreaterThanOrEqualTo(dockerCli.Client().ClientVersion(), "1.41") { - p, err := platforms.Parse(opts.platform) - if err != nil { - return nil, errors.Wrap(err, "error parsing specified platform") - } - platform = &p - } - - if opts.pull == PullImageAlways { - if err := pullAndTagImage(); err != nil { - return nil, err - } - } - - hostConfig.ConsoleSize[0], hostConfig.ConsoleSize[1] = dockerCli.Out().GetTtySize() - - response, err := dockerCli.Client().ContainerCreate(ctx, config, hostConfig, networkingConfig, platform, opts.name) - if err != nil { - // Pull image if it does not exist locally and we have the PullImageMissing option. Default behavior. - if apiclient.IsErrNotFound(err) && namedRef != nil && opts.pull == PullImageMissing { - if !opts.quiet { - // we don't want to write to stdout anything apart from container.ID - fmt.Fprintf(dockerCli.Err(), "Unable to find image '%s' locally\n", reference.FamiliarString(namedRef)) - } - - if err := pullAndTagImage(); err != nil { - return nil, err - } - - var retryErr error - response, retryErr = dockerCli.Client().ContainerCreate(ctx, config, hostConfig, networkingConfig, platform, opts.name) - if retryErr != nil { - return nil, retryErr - } - } else { - return nil, err - } - } - - for _, w := range response.Warnings { - fmt.Fprintf(dockerCli.Err(), "WARNING: %s\n", w) - } - err = containerIDFile.Write(response.ID) - return &response, err -} - -func warnOnOomKillDisable(hostConfig container.HostConfig, stderr io.Writer) { - if hostConfig.OomKillDisable != nil && *hostConfig.OomKillDisable && hostConfig.Memory == 0 { - fmt.Fprintln(stderr, "WARNING: Disabling the OOM killer on containers without setting a '-m/--memory' limit may be dangerous.") - } -} - -// check the DNS settings passed via --dns against localhost regexp to warn if -// they are trying to set a DNS to a localhost address -func warnOnLocalhostDNS(hostConfig container.HostConfig, stderr io.Writer) { - for _, dnsIP := range hostConfig.DNS { - if isLocalhost(dnsIP) { - fmt.Fprintf(stderr, "WARNING: Localhost DNS setting (--dns=%s) may fail in containers.\n", dnsIP) - return - } - } -} - -// IPLocalhost is a regex pattern for IPv4 or IPv6 loopback range. -const ipLocalhost = `((127\.([0-9]{1,3}\.){2}[0-9]{1,3})|(::1)$)` - -var localhostIPRegexp = regexp.MustCompile(ipLocalhost) - -// IsLocalhost returns true if ip matches the localhost IP regular expression. -// Used for determining if nameserver settings are being passed which are -// localhost addresses -func isLocalhost(ip string) bool { - return localhostIPRegexp.MatchString(ip) -} - -func validatePullOpt(val string) error { - switch val { - case PullImageAlways, PullImageMissing, PullImageNever, "": - // valid option, but nothing to do yet - return nil - default: - return fmt.Errorf( - "invalid pull option: '%s': must be one of %q, %q or %q", - val, - PullImageAlways, - PullImageMissing, - PullImageNever, - ) - } -} diff --git a/vendor/github.com/docker/cli/cli/command/container/diff.go b/vendor/github.com/docker/cli/cli/command/container/diff.go deleted file mode 100644 index c0951b28f..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/diff.go +++ /dev/null @@ -1,52 +0,0 @@ -package container - -import ( - "context" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/docker/cli/cli/command/formatter" - "github.com/pkg/errors" - "github.com/spf13/cobra" -) - -type diffOptions struct { - container string -} - -// NewDiffCommand creates a new cobra.Command for `docker diff` -func NewDiffCommand(dockerCli command.Cli) *cobra.Command { - var opts diffOptions - - return &cobra.Command{ - Use: "diff CONTAINER", - Short: "Inspect changes to files or directories on a container's filesystem", - Args: cli.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - opts.container = args[0] - return runDiff(dockerCli, &opts) - }, - Annotations: map[string]string{ - "aliases": "docker container diff, docker diff", - }, - ValidArgsFunction: completion.ContainerNames(dockerCli, false), - } -} - -func runDiff(dockerCli command.Cli, opts *diffOptions) error { - if opts.container == "" { - return errors.New("Container name cannot be empty") - } - ctx := context.Background() - - changes, err := dockerCli.Client().ContainerDiff(ctx, opts.container) - if err != nil { - return err - } - diffCtx := formatter.Context{ - Output: dockerCli.Out(), - Format: NewDiffFormat("{{.Type}} {{.Path}}"), - } - return DiffFormatWrite(diffCtx, changes) -} diff --git a/vendor/github.com/docker/cli/cli/command/container/exec.go b/vendor/github.com/docker/cli/cli/command/container/exec.go deleted file mode 100644 index 3160aaba8..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/exec.go +++ /dev/null @@ -1,266 +0,0 @@ -package container - -import ( - "context" - "fmt" - "io" - "os" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/docker/cli/cli/config/configfile" - "github.com/docker/cli/opts" - "github.com/docker/docker/api/types" - apiclient "github.com/docker/docker/client" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" - "github.com/spf13/cobra" -) - -// ExecOptions group options for `exec` command -type ExecOptions struct { - DetachKeys string - Interactive bool - TTY bool - Detach bool - User string - Privileged bool - Env opts.ListOpts - Workdir string - Container string - Command []string - EnvFile opts.ListOpts -} - -// NewExecOptions creates a new ExecOptions -func NewExecOptions() ExecOptions { - return ExecOptions{ - Env: opts.NewListOpts(opts.ValidateEnv), - EnvFile: opts.NewListOpts(nil), - } -} - -// NewExecCommand creates a new cobra.Command for `docker exec` -func NewExecCommand(dockerCli command.Cli) *cobra.Command { - options := NewExecOptions() - - cmd := &cobra.Command{ - Use: "exec [OPTIONS] CONTAINER COMMAND [ARG...]", - Short: "Execute a command in a running container", - Args: cli.RequiresMinArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - options.Container = args[0] - options.Command = args[1:] - return RunExec(dockerCli, options) - }, - ValidArgsFunction: completion.ContainerNames(dockerCli, false, func(container types.Container) bool { - return container.State != "paused" - }), - Annotations: map[string]string{ - "category-top": "2", - "aliases": "docker container exec, docker exec", - }, - } - - flags := cmd.Flags() - flags.SetInterspersed(false) - - flags.StringVarP(&options.DetachKeys, "detach-keys", "", "", "Override the key sequence for detaching a container") - flags.BoolVarP(&options.Interactive, "interactive", "i", false, "Keep STDIN open even if not attached") - flags.BoolVarP(&options.TTY, "tty", "t", false, "Allocate a pseudo-TTY") - flags.BoolVarP(&options.Detach, "detach", "d", false, "Detached mode: run command in the background") - flags.StringVarP(&options.User, "user", "u", "", `Username or UID (format: "[:]")`) - flags.BoolVarP(&options.Privileged, "privileged", "", false, "Give extended privileges to the command") - flags.VarP(&options.Env, "env", "e", "Set environment variables") - flags.SetAnnotation("env", "version", []string{"1.25"}) - flags.Var(&options.EnvFile, "env-file", "Read in a file of environment variables") - flags.SetAnnotation("env-file", "version", []string{"1.25"}) - flags.StringVarP(&options.Workdir, "workdir", "w", "", "Working directory inside the container") - flags.SetAnnotation("workdir", "version", []string{"1.35"}) - - cmd.RegisterFlagCompletionFunc( - "env", - func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return os.Environ(), cobra.ShellCompDirectiveNoFileComp - }, - ) - cmd.RegisterFlagCompletionFunc( - "env-file", - func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return nil, cobra.ShellCompDirectiveDefault // _filedir - }, - ) - - return cmd -} - -// RunExec executes an `exec` command -func RunExec(dockerCli command.Cli, options ExecOptions) error { - execConfig, err := parseExec(options, dockerCli.ConfigFile()) - if err != nil { - return err - } - - ctx := context.Background() - client := dockerCli.Client() - - // We need to check the tty _before_ we do the ContainerExecCreate, because - // otherwise if we error out we will leak execIDs on the server (and - // there's no easy way to clean those up). But also in order to make "not - // exist" errors take precedence we do a dummy inspect first. - if _, err := client.ContainerInspect(ctx, options.Container); err != nil { - return err - } - if !execConfig.Detach { - if err := dockerCli.In().CheckTty(execConfig.AttachStdin, execConfig.Tty); err != nil { - return err - } - } - - fillConsoleSize(execConfig, dockerCli) - - response, err := client.ContainerExecCreate(ctx, options.Container, *execConfig) - if err != nil { - return err - } - - execID := response.ID - if execID == "" { - return errors.New("exec ID empty") - } - - if execConfig.Detach { - execStartCheck := types.ExecStartCheck{ - Detach: execConfig.Detach, - Tty: execConfig.Tty, - ConsoleSize: execConfig.ConsoleSize, - } - return client.ContainerExecStart(ctx, execID, execStartCheck) - } - return interactiveExec(ctx, dockerCli, execConfig, execID) -} - -func fillConsoleSize(execConfig *types.ExecConfig, dockerCli command.Cli) { - if execConfig.Tty { - height, width := dockerCli.Out().GetTtySize() - execConfig.ConsoleSize = &[2]uint{height, width} - } -} - -func interactiveExec(ctx context.Context, dockerCli command.Cli, execConfig *types.ExecConfig, execID string) error { - // Interactive exec requested. - var ( - out, stderr io.Writer - in io.ReadCloser - ) - - if execConfig.AttachStdin { - in = dockerCli.In() - } - if execConfig.AttachStdout { - out = dockerCli.Out() - } - if execConfig.AttachStderr { - if execConfig.Tty { - stderr = dockerCli.Out() - } else { - stderr = dockerCli.Err() - } - } - fillConsoleSize(execConfig, dockerCli) - - client := dockerCli.Client() - execStartCheck := types.ExecStartCheck{ - Tty: execConfig.Tty, - ConsoleSize: execConfig.ConsoleSize, - } - resp, err := client.ContainerExecAttach(ctx, execID, execStartCheck) - if err != nil { - return err - } - defer resp.Close() - - errCh := make(chan error, 1) - - go func() { - defer close(errCh) - errCh <- func() error { - streamer := hijackedIOStreamer{ - streams: dockerCli, - inputStream: in, - outputStream: out, - errorStream: stderr, - resp: resp, - tty: execConfig.Tty, - detachKeys: execConfig.DetachKeys, - } - - return streamer.stream(ctx) - }() - }() - - if execConfig.Tty && dockerCli.In().IsTerminal() { - if err := MonitorTtySize(ctx, dockerCli, execID, true); err != nil { - fmt.Fprintln(dockerCli.Err(), "Error monitoring TTY size:", err) - } - } - - if err := <-errCh; err != nil { - logrus.Debugf("Error hijack: %s", err) - return err - } - - return getExecExitStatus(ctx, client, execID) -} - -func getExecExitStatus(ctx context.Context, client apiclient.ContainerAPIClient, execID string) error { - resp, err := client.ContainerExecInspect(ctx, execID) - if err != nil { - // If we can't connect, then the daemon probably died. - if !apiclient.IsErrConnectionFailed(err) { - return err - } - return cli.StatusError{StatusCode: -1} - } - status := resp.ExitCode - if status != 0 { - return cli.StatusError{StatusCode: status} - } - return nil -} - -// parseExec parses the specified args for the specified command and generates -// an ExecConfig from it. -func parseExec(execOpts ExecOptions, configFile *configfile.ConfigFile) (*types.ExecConfig, error) { - execConfig := &types.ExecConfig{ - User: execOpts.User, - Privileged: execOpts.Privileged, - Tty: execOpts.TTY, - Cmd: execOpts.Command, - Detach: execOpts.Detach, - WorkingDir: execOpts.Workdir, - } - - // collect all the environment variables for the container - var err error - if execConfig.Env, err = opts.ReadKVEnvStrings(execOpts.EnvFile.GetAll(), execOpts.Env.GetAll()); err != nil { - return nil, err - } - - // If -d is not set, attach to everything by default - if !execOpts.Detach { - execConfig.AttachStdout = true - execConfig.AttachStderr = true - if execOpts.Interactive { - execConfig.AttachStdin = true - } - } - - if execOpts.DetachKeys != "" { - execConfig.DetachKeys = execOpts.DetachKeys - } else { - execConfig.DetachKeys = configFile.DetachKeys - } - return execConfig, nil -} diff --git a/vendor/github.com/docker/cli/cli/command/container/export.go b/vendor/github.com/docker/cli/cli/command/container/export.go deleted file mode 100644 index 1871686d9..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/export.go +++ /dev/null @@ -1,67 +0,0 @@ -package container - -import ( - "context" - "io" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/pkg/errors" - "github.com/spf13/cobra" -) - -type exportOptions struct { - container string - output string -} - -// NewExportCommand creates a new `docker export` command -func NewExportCommand(dockerCli command.Cli) *cobra.Command { - var opts exportOptions - - cmd := &cobra.Command{ - Use: "export [OPTIONS] CONTAINER", - Short: "Export a container's filesystem as a tar archive", - Args: cli.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - opts.container = args[0] - return runExport(dockerCli, opts) - }, - Annotations: map[string]string{ - "aliases": "docker container export, docker export", - }, - ValidArgsFunction: completion.ContainerNames(dockerCli, true), - } - - flags := cmd.Flags() - - flags.StringVarP(&opts.output, "output", "o", "", "Write to a file, instead of STDOUT") - - return cmd -} - -func runExport(dockerCli command.Cli, opts exportOptions) error { - if opts.output == "" && dockerCli.Out().IsTerminal() { - return errors.New("cowardly refusing to save to a terminal. Use the -o flag or redirect") - } - - if err := command.ValidateOutputPath(opts.output); err != nil { - return errors.Wrap(err, "failed to export container") - } - - clnt := dockerCli.Client() - - responseBody, err := clnt.ContainerExport(context.Background(), opts.container) - if err != nil { - return err - } - defer responseBody.Close() - - if opts.output == "" { - _, err := io.Copy(dockerCli.Out(), responseBody) - return err - } - - return command.CopyToFile(opts.output, responseBody) -} diff --git a/vendor/github.com/docker/cli/cli/command/container/formatter_diff.go b/vendor/github.com/docker/cli/cli/command/container/formatter_diff.go deleted file mode 100644 index 8baf11bfa..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/formatter_diff.go +++ /dev/null @@ -1,61 +0,0 @@ -package container - -import ( - "github.com/docker/cli/cli/command/formatter" - "github.com/docker/docker/api/types/container" -) - -const ( - defaultDiffTableFormat = "table {{.Type}}\t{{.Path}}" - - changeTypeHeader = "CHANGE TYPE" - pathHeader = "PATH" -) - -// NewDiffFormat returns a format for use with a diff Context -func NewDiffFormat(source string) formatter.Format { - switch source { - case formatter.TableFormatKey: - return defaultDiffTableFormat - } - return formatter.Format(source) -} - -// DiffFormatWrite writes formatted diff using the Context -func DiffFormatWrite(ctx formatter.Context, changes []container.FilesystemChange) error { - render := func(format func(subContext formatter.SubContext) error) error { - for _, change := range changes { - if err := format(&diffContext{c: change}); err != nil { - return err - } - } - return nil - } - return ctx.Write(newDiffContext(), render) -} - -type diffContext struct { - formatter.HeaderContext - c container.FilesystemChange -} - -func newDiffContext() *diffContext { - diffCtx := diffContext{} - diffCtx.Header = formatter.SubHeaderContext{ - "Type": changeTypeHeader, - "Path": pathHeader, - } - return &diffCtx -} - -func (d *diffContext) MarshalJSON() ([]byte, error) { - return formatter.MarshalJSON(d) -} - -func (d *diffContext) Type() string { - return d.c.Kind.String() -} - -func (d *diffContext) Path() string { - return d.c.Path -} diff --git a/vendor/github.com/docker/cli/cli/command/container/formatter_stats.go b/vendor/github.com/docker/cli/cli/command/container/formatter_stats.go deleted file mode 100644 index c079c913f..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/formatter_stats.go +++ /dev/null @@ -1,229 +0,0 @@ -package container - -import ( - "strconv" - "sync" - - "github.com/docker/cli/cli/command/formatter" - "github.com/docker/docker/pkg/stringid" - units "github.com/docker/go-units" -) - -const ( - winOSType = "windows" - defaultStatsTableFormat = "table {{.ID}}\t{{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.MemPerc}}\t{{.NetIO}}\t{{.BlockIO}}\t{{.PIDs}}" - winDefaultStatsTableFormat = "table {{.ID}}\t{{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.NetIO}}\t{{.BlockIO}}" - - containerHeader = "CONTAINER" - cpuPercHeader = "CPU %" - netIOHeader = "NET I/O" - blockIOHeader = "BLOCK I/O" - memPercHeader = "MEM %" // Used only on Linux - winMemUseHeader = "PRIV WORKING SET" // Used only on Windows - memUseHeader = "MEM USAGE / LIMIT" // Used only on Linux - pidsHeader = "PIDS" // Used only on Linux -) - -// StatsEntry represents represents the statistics data collected from a container -type StatsEntry struct { - Container string - Name string - ID string - CPUPercentage float64 - Memory float64 // On Windows this is the private working set - MemoryLimit float64 // Not used on Windows - MemoryPercentage float64 // Not used on Windows - NetworkRx float64 - NetworkTx float64 - BlockRead float64 - BlockWrite float64 - PidsCurrent uint64 // Not used on Windows - IsInvalid bool -} - -// Stats represents an entity to store containers statistics synchronously -type Stats struct { - mutex sync.RWMutex - StatsEntry - err error -} - -// GetError returns the container statistics error. -// This is used to determine whether the statistics are valid or not -func (cs *Stats) GetError() error { - cs.mutex.RLock() - defer cs.mutex.RUnlock() - return cs.err -} - -// SetErrorAndReset zeroes all the container statistics and store the error. -// It is used when receiving time out error during statistics collecting to reduce lock overhead -func (cs *Stats) SetErrorAndReset(err error) { - cs.mutex.Lock() - defer cs.mutex.Unlock() - cs.CPUPercentage = 0 - cs.Memory = 0 - cs.MemoryPercentage = 0 - cs.MemoryLimit = 0 - cs.NetworkRx = 0 - cs.NetworkTx = 0 - cs.BlockRead = 0 - cs.BlockWrite = 0 - cs.PidsCurrent = 0 - cs.err = err - cs.IsInvalid = true -} - -// SetError sets container statistics error -func (cs *Stats) SetError(err error) { - cs.mutex.Lock() - defer cs.mutex.Unlock() - cs.err = err - if err != nil { - cs.IsInvalid = true - } -} - -// SetStatistics set the container statistics -func (cs *Stats) SetStatistics(s StatsEntry) { - cs.mutex.Lock() - defer cs.mutex.Unlock() - s.Container = cs.Container - cs.StatsEntry = s -} - -// GetStatistics returns container statistics with other meta data such as the container name -func (cs *Stats) GetStatistics() StatsEntry { - cs.mutex.RLock() - defer cs.mutex.RUnlock() - return cs.StatsEntry -} - -// NewStatsFormat returns a format for rendering an CStatsContext -func NewStatsFormat(source, osType string) formatter.Format { - if source == formatter.TableFormatKey { - if osType == winOSType { - return winDefaultStatsTableFormat - } - return defaultStatsTableFormat - } - return formatter.Format(source) -} - -// NewStats returns a new Stats entity and sets in it the given name -func NewStats(container string) *Stats { - return &Stats{StatsEntry: StatsEntry{Container: container}} -} - -// statsFormatWrite renders the context for a list of containers statistics -func statsFormatWrite(ctx formatter.Context, Stats []StatsEntry, osType string, trunc bool) error { - render := func(format func(subContext formatter.SubContext) error) error { - for _, cstats := range Stats { - statsCtx := &statsContext{ - s: cstats, - os: osType, - trunc: trunc, - } - if err := format(statsCtx); err != nil { - return err - } - } - return nil - } - memUsage := memUseHeader - if osType == winOSType { - memUsage = winMemUseHeader - } - statsCtx := statsContext{} - statsCtx.Header = formatter.SubHeaderContext{ - "Container": containerHeader, - "Name": formatter.NameHeader, - "ID": formatter.ContainerIDHeader, - "CPUPerc": cpuPercHeader, - "MemUsage": memUsage, - "MemPerc": memPercHeader, - "NetIO": netIOHeader, - "BlockIO": blockIOHeader, - "PIDs": pidsHeader, - } - statsCtx.os = osType - return ctx.Write(&statsCtx, render) -} - -type statsContext struct { - formatter.HeaderContext - s StatsEntry - os string - trunc bool -} - -func (c *statsContext) MarshalJSON() ([]byte, error) { - return formatter.MarshalJSON(c) -} - -func (c *statsContext) Container() string { - return c.s.Container -} - -func (c *statsContext) Name() string { - if len(c.s.Name) > 1 { - return c.s.Name[1:] - } - return "--" -} - -func (c *statsContext) ID() string { - if c.trunc { - return stringid.TruncateID(c.s.ID) - } - return c.s.ID -} - -func (c *statsContext) CPUPerc() string { - if c.s.IsInvalid { - return "--" - } - return formatPercentage(c.s.CPUPercentage) -} - -func (c *statsContext) MemUsage() string { - if c.s.IsInvalid { - return "-- / --" - } - if c.os == winOSType { - return units.BytesSize(c.s.Memory) - } - return units.BytesSize(c.s.Memory) + " / " + units.BytesSize(c.s.MemoryLimit) -} - -func (c *statsContext) MemPerc() string { - if c.s.IsInvalid || c.os == winOSType { - return "--" - } - return formatPercentage(c.s.MemoryPercentage) -} - -func (c *statsContext) NetIO() string { - if c.s.IsInvalid { - return "--" - } - return units.HumanSizeWithPrecision(c.s.NetworkRx, 3) + " / " + units.HumanSizeWithPrecision(c.s.NetworkTx, 3) -} - -func (c *statsContext) BlockIO() string { - if c.s.IsInvalid { - return "--" - } - return units.HumanSizeWithPrecision(c.s.BlockRead, 3) + " / " + units.HumanSizeWithPrecision(c.s.BlockWrite, 3) -} - -func (c *statsContext) PIDs() string { - if c.s.IsInvalid || c.os == winOSType { - return "--" - } - return strconv.FormatUint(c.s.PidsCurrent, 10) -} - -func formatPercentage(val float64) string { - return strconv.FormatFloat(val, 'f', 2, 64) + "%" -} diff --git a/vendor/github.com/docker/cli/cli/command/container/hijack.go b/vendor/github.com/docker/cli/cli/command/container/hijack.go deleted file mode 100644 index 7ecf5f505..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/hijack.go +++ /dev/null @@ -1,207 +0,0 @@ -package container - -import ( - "context" - "fmt" - "io" - "runtime" - "sync" - - "github.com/docker/cli/cli/command" - "github.com/docker/docker/api/types" - "github.com/docker/docker/pkg/ioutils" - "github.com/docker/docker/pkg/stdcopy" - "github.com/moby/term" - "github.com/sirupsen/logrus" -) - -// The default escape key sequence: ctrl-p, ctrl-q -// TODO: This could be moved to `pkg/term`. -var defaultEscapeKeys = []byte{16, 17} - -// A hijackedIOStreamer handles copying input to and output from streams to the -// connection. -type hijackedIOStreamer struct { - streams command.Streams - inputStream io.ReadCloser - outputStream io.Writer - errorStream io.Writer - - resp types.HijackedResponse - - tty bool - detachKeys string -} - -// stream handles setting up the IO and then begins streaming stdin/stdout -// to/from the hijacked connection, blocking until it is either done reading -// output, the user inputs the detach key sequence when in TTY mode, or when -// the given context is cancelled. -func (h *hijackedIOStreamer) stream(ctx context.Context) error { - restoreInput, err := h.setupInput() - if err != nil { - return fmt.Errorf("unable to setup input stream: %s", err) - } - - defer restoreInput() - - outputDone := h.beginOutputStream(restoreInput) - inputDone, detached := h.beginInputStream(restoreInput) - - select { - case err := <-outputDone: - return err - case <-inputDone: - // Input stream has closed. - if h.outputStream != nil || h.errorStream != nil { - // Wait for output to complete streaming. - select { - case err := <-outputDone: - return err - case <-ctx.Done(): - return ctx.Err() - } - } - return nil - case err := <-detached: - // Got a detach key sequence. - return err - case <-ctx.Done(): - return ctx.Err() - } -} - -func (h *hijackedIOStreamer) setupInput() (restore func(), err error) { - if h.inputStream == nil || !h.tty { - // No need to setup input TTY. - // The restore func is a nop. - return func() {}, nil - } - - if err := setRawTerminal(h.streams); err != nil { - return nil, fmt.Errorf("unable to set IO streams as raw terminal: %s", err) - } - - // Use sync.Once so we may call restore multiple times but ensure we - // only restore the terminal once. - var restoreOnce sync.Once - restore = func() { - restoreOnce.Do(func() { - restoreTerminal(h.streams, h.inputStream) - }) - } - - // Wrap the input to detect detach escape sequence. - // Use default escape keys if an invalid sequence is given. - escapeKeys := defaultEscapeKeys - if h.detachKeys != "" { - customEscapeKeys, err := term.ToBytes(h.detachKeys) - if err != nil { - logrus.Warnf("invalid detach escape keys, using default: %s", err) - } else { - escapeKeys = customEscapeKeys - } - } - - h.inputStream = ioutils.NewReadCloserWrapper(term.NewEscapeProxy(h.inputStream, escapeKeys), h.inputStream.Close) - - return restore, nil -} - -func (h *hijackedIOStreamer) beginOutputStream(restoreInput func()) <-chan error { - if h.outputStream == nil && h.errorStream == nil { - // There is no need to copy output. - return nil - } - - outputDone := make(chan error) - go func() { - var err error - - // When TTY is ON, use regular copy - if h.outputStream != nil && h.tty { - _, err = io.Copy(h.outputStream, h.resp.Reader) - // We should restore the terminal as soon as possible - // once the connection ends so any following print - // messages will be in normal type. - restoreInput() - } else { - _, err = stdcopy.StdCopy(h.outputStream, h.errorStream, h.resp.Reader) - } - - logrus.Debug("[hijack] End of stdout") - - if err != nil { - logrus.Debugf("Error receiveStdout: %s", err) - } - - outputDone <- err - }() - - return outputDone -} - -func (h *hijackedIOStreamer) beginInputStream(restoreInput func()) (doneC <-chan struct{}, detachedC <-chan error) { - inputDone := make(chan struct{}) - detached := make(chan error) - - go func() { - if h.inputStream != nil { - _, err := io.Copy(h.resp.Conn, h.inputStream) - // We should restore the terminal as soon as possible - // once the connection ends so any following print - // messages will be in normal type. - restoreInput() - - logrus.Debug("[hijack] End of stdin") - - if _, ok := err.(term.EscapeError); ok { - detached <- err - return - } - - if err != nil { - // This error will also occur on the receive - // side (from stdout) where it will be - // propagated back to the caller. - logrus.Debugf("Error sendStdin: %s", err) - } - } - - if err := h.resp.CloseWrite(); err != nil { - logrus.Debugf("Couldn't send EOF: %s", err) - } - - close(inputDone) - }() - - return inputDone, detached -} - -func setRawTerminal(streams command.Streams) error { - if err := streams.In().SetRawTerminal(); err != nil { - return err - } - return streams.Out().SetRawTerminal() -} - -func restoreTerminal(streams command.Streams, in io.Closer) error { - streams.In().RestoreTerminal() - streams.Out().RestoreTerminal() - // WARNING: DO NOT REMOVE THE OS CHECKS !!! - // For some reason this Close call blocks on darwin.. - // As the client exits right after, simply discard the close - // until we find a better solution. - // - // This can also cause the client on Windows to get stuck in Win32 CloseHandle() - // in some cases. See https://github.com/docker/docker/issues/28267#issuecomment-288237442 - // Tracked internally at Microsoft by VSO #11352156. In the - // Windows case, you hit this if you are using the native/v2 console, - // not the "legacy" console, and you start the client in a new window. eg - // `start docker run --rm -it microsoft/nanoserver cmd /s /c echo foobar` - // will hang. Remove start, and it won't repro. - if in != nil && runtime.GOOS != "darwin" && runtime.GOOS != "windows" { - return in.Close() - } - return nil -} diff --git a/vendor/github.com/docker/cli/cli/command/container/inspect.go b/vendor/github.com/docker/cli/cli/command/container/inspect.go deleted file mode 100644 index b9e320b82..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/inspect.go +++ /dev/null @@ -1,50 +0,0 @@ -package container - -import ( - "context" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/docker/cli/cli/command/inspect" - flagsHelper "github.com/docker/cli/cli/flags" - "github.com/spf13/cobra" -) - -type inspectOptions struct { - format string - size bool - refs []string -} - -// newInspectCommand creates a new cobra.Command for `docker container inspect` -func newInspectCommand(dockerCli command.Cli) *cobra.Command { - var opts inspectOptions - - cmd := &cobra.Command{ - Use: "inspect [OPTIONS] CONTAINER [CONTAINER...]", - Short: "Display detailed information on one or more containers", - Args: cli.RequiresMinArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - opts.refs = args - return runInspect(dockerCli, opts) - }, - ValidArgsFunction: completion.ContainerNames(dockerCli, true), - } - - flags := cmd.Flags() - flags.StringVarP(&opts.format, "format", "f", "", flagsHelper.InspectFormatHelp) - flags.BoolVarP(&opts.size, "size", "s", false, "Display total file sizes") - - return cmd -} - -func runInspect(dockerCli command.Cli, opts inspectOptions) error { - client := dockerCli.Client() - ctx := context.Background() - - getRefFunc := func(ref string) (interface{}, []byte, error) { - return client.ContainerInspectWithRaw(ctx, ref, opts.size) - } - return inspect.Inspect(dockerCli.Out(), opts.refs, opts.format, getRefFunc) -} diff --git a/vendor/github.com/docker/cli/cli/command/container/kill.go b/vendor/github.com/docker/cli/cli/command/container/kill.go deleted file mode 100644 index 2483a2243..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/kill.go +++ /dev/null @@ -1,61 +0,0 @@ -package container - -import ( - "context" - "fmt" - "strings" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/pkg/errors" - "github.com/spf13/cobra" -) - -type killOptions struct { - signal string - - containers []string -} - -// NewKillCommand creates a new cobra.Command for `docker kill` -func NewKillCommand(dockerCli command.Cli) *cobra.Command { - var opts killOptions - - cmd := &cobra.Command{ - Use: "kill [OPTIONS] CONTAINER [CONTAINER...]", - Short: "Kill one or more running containers", - Args: cli.RequiresMinArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - opts.containers = args - return runKill(dockerCli, &opts) - }, - Annotations: map[string]string{ - "aliases": "docker container kill, docker kill", - }, - ValidArgsFunction: completion.ContainerNames(dockerCli, false), - } - - flags := cmd.Flags() - flags.StringVarP(&opts.signal, "signal", "s", "", "Signal to send to the container") - return cmd -} - -func runKill(dockerCli command.Cli, opts *killOptions) error { - var errs []string - ctx := context.Background() - errChan := parallelOperation(ctx, opts.containers, func(ctx context.Context, container string) error { - return dockerCli.Client().ContainerKill(ctx, container, opts.signal) - }) - for _, name := range opts.containers { - if err := <-errChan; err != nil { - errs = append(errs, err.Error()) - } else { - fmt.Fprintln(dockerCli.Out(), name) - } - } - if len(errs) > 0 { - return errors.New(strings.Join(errs, "\n")) - } - return nil -} diff --git a/vendor/github.com/docker/cli/cli/command/container/list.go b/vendor/github.com/docker/cli/cli/command/container/list.go deleted file mode 100644 index 471e4e1c4..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/list.go +++ /dev/null @@ -1,143 +0,0 @@ -package container - -import ( - "context" - "io" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/docker/cli/cli/command/formatter" - flagsHelper "github.com/docker/cli/cli/flags" - "github.com/docker/cli/opts" - "github.com/docker/cli/templates" - "github.com/docker/docker/api/types" - "github.com/pkg/errors" - "github.com/spf13/cobra" -) - -type psOptions struct { - quiet bool - size bool - sizeChanged bool - all bool - noTrunc bool - nLatest bool - last int - format string - filter opts.FilterOpt -} - -// NewPsCommand creates a new cobra.Command for `docker ps` -func NewPsCommand(dockerCli command.Cli) *cobra.Command { - options := psOptions{filter: opts.NewFilterOpt()} - - cmd := &cobra.Command{ - Use: "ps [OPTIONS]", - Short: "List containers", - Args: cli.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - options.sizeChanged = cmd.Flags().Changed("size") - return runPs(dockerCli, &options) - }, - Annotations: map[string]string{ - "category-top": "3", - "aliases": "docker container ls, docker container list, docker container ps, docker ps", - }, - ValidArgsFunction: completion.NoComplete, - } - - flags := cmd.Flags() - - flags.BoolVarP(&options.quiet, "quiet", "q", false, "Only display container IDs") - flags.BoolVarP(&options.size, "size", "s", false, "Display total file sizes") - flags.BoolVarP(&options.all, "all", "a", false, "Show all containers (default shows just running)") - flags.BoolVar(&options.noTrunc, "no-trunc", false, "Don't truncate output") - flags.BoolVarP(&options.nLatest, "latest", "l", false, "Show the latest created container (includes all states)") - flags.IntVarP(&options.last, "last", "n", -1, "Show n last created containers (includes all states)") - flags.StringVarP(&options.format, "format", "", "", flagsHelper.FormatHelp) - flags.VarP(&options.filter, "filter", "f", "Filter output based on conditions provided") - - return cmd -} - -func newListCommand(dockerCli command.Cli) *cobra.Command { - cmd := *NewPsCommand(dockerCli) - cmd.Aliases = []string{"ps", "list"} - cmd.Use = "ls [OPTIONS]" - return &cmd -} - -func buildContainerListOptions(opts *psOptions) (*types.ContainerListOptions, error) { - options := &types.ContainerListOptions{ - All: opts.all, - Limit: opts.last, - Size: opts.size, - Filters: opts.filter.Value(), - } - - if opts.nLatest && opts.last == -1 { - options.Limit = 1 - } - - // always validate template when `--format` is used, for consistency - if len(opts.format) > 0 { - tmpl, err := templates.NewParse("", opts.format) - if err != nil { - return nil, errors.Wrap(err, "failed to parse template") - } - - optionsProcessor := formatter.NewContainerContext() - - // This shouldn't error out but swallowing the error makes it harder - // to track down if preProcessor issues come up. - if err := tmpl.Execute(io.Discard, optionsProcessor); err != nil { - return nil, errors.Wrap(err, "failed to execute template") - } - - // if `size` was not explicitly set to false (with `--size=false`) - // and `--quiet` is not set, request size if the template requires it - if !opts.quiet && !options.Size && !opts.sizeChanged { - // The --size option isn't set, but .Size may be used in the template. - // Parse and execute the given template to detect if the .Size field is - // used. If it is, then automatically enable the --size option. See #24696 - // - // Only requesting container size information when needed is an optimization, - // because calculating the size is a costly operation. - - if _, ok := optionsProcessor.FieldsUsed["Size"]; ok { - options.Size = true - } - } - } - - return options, nil -} - -func runPs(dockerCli command.Cli, options *psOptions) error { - ctx := context.Background() - - if len(options.format) == 0 { - // load custom psFormat from CLI config (if any) - options.format = dockerCli.ConfigFile().PsFormat - } else if options.quiet { - _, _ = dockerCli.Err().Write([]byte("WARNING: Ignoring custom format, because both --format and --quiet are set.\n")) - } - - listOptions, err := buildContainerListOptions(options) - if err != nil { - return err - } - - containers, err := dockerCli.Client().ContainerList(ctx, *listOptions) - if err != nil { - return err - } - - containerCtx := formatter.Context{ - Output: dockerCli.Out(), - Format: formatter.NewContainerFormat(options.format, options.quiet, listOptions.Size), - Trunc: !options.noTrunc, - } - return formatter.ContainerWrite(containerCtx, containers) -} diff --git a/vendor/github.com/docker/cli/cli/command/container/logs.go b/vendor/github.com/docker/cli/cli/command/container/logs.go deleted file mode 100644 index 0fd7cfd0c..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/logs.go +++ /dev/null @@ -1,85 +0,0 @@ -package container - -import ( - "context" - "io" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/docker/docker/api/types" - "github.com/docker/docker/pkg/stdcopy" - "github.com/spf13/cobra" -) - -type logsOptions struct { - follow bool - since string - until string - timestamps bool - details bool - tail string - - container string -} - -// NewLogsCommand creates a new cobra.Command for `docker logs` -func NewLogsCommand(dockerCli command.Cli) *cobra.Command { - var opts logsOptions - - cmd := &cobra.Command{ - Use: "logs [OPTIONS] CONTAINER", - Short: "Fetch the logs of a container", - Args: cli.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - opts.container = args[0] - return runLogs(dockerCli, &opts) - }, - Annotations: map[string]string{ - "aliases": "docker container logs, docker logs", - }, - ValidArgsFunction: completion.ContainerNames(dockerCli, true), - } - - flags := cmd.Flags() - flags.BoolVarP(&opts.follow, "follow", "f", false, "Follow log output") - flags.StringVar(&opts.since, "since", "", `Show logs since timestamp (e.g. "2013-01-02T13:23:37Z") or relative (e.g. "42m" for 42 minutes)`) - flags.StringVar(&opts.until, "until", "", `Show logs before a timestamp (e.g. "2013-01-02T13:23:37Z") or relative (e.g. "42m" for 42 minutes)`) - flags.SetAnnotation("until", "version", []string{"1.35"}) - flags.BoolVarP(&opts.timestamps, "timestamps", "t", false, "Show timestamps") - flags.BoolVar(&opts.details, "details", false, "Show extra details provided to logs") - flags.StringVarP(&opts.tail, "tail", "n", "all", "Number of lines to show from the end of the logs") - return cmd -} - -func runLogs(dockerCli command.Cli, opts *logsOptions) error { - ctx := context.Background() - - c, err := dockerCli.Client().ContainerInspect(ctx, opts.container) - if err != nil { - return err - } - - options := types.ContainerLogsOptions{ - ShowStdout: true, - ShowStderr: true, - Since: opts.since, - Until: opts.until, - Timestamps: opts.timestamps, - Follow: opts.follow, - Tail: opts.tail, - Details: opts.details, - } - responseBody, err := dockerCli.Client().ContainerLogs(ctx, c.ID, options) - if err != nil { - return err - } - defer responseBody.Close() - - if c.Config.Tty { - _, err = io.Copy(dockerCli.Out(), responseBody) - } else { - _, err = stdcopy.StdCopy(dockerCli.Out(), dockerCli.Err(), responseBody) - } - return err -} diff --git a/vendor/github.com/docker/cli/cli/command/container/opts.go b/vendor/github.com/docker/cli/cli/command/container/opts.go deleted file mode 100644 index fa8f1c9d0..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/opts.go +++ /dev/null @@ -1,1072 +0,0 @@ -package container - -import ( - "bytes" - "encoding/json" - "fmt" - "os" - "path" - "path/filepath" - "reflect" - "regexp" - "strconv" - "strings" - "time" - - "github.com/docker/cli/cli/compose/loader" - "github.com/docker/cli/opts" - "github.com/docker/docker/api/types/container" - mounttypes "github.com/docker/docker/api/types/mount" - networktypes "github.com/docker/docker/api/types/network" - "github.com/docker/docker/api/types/strslice" - "github.com/docker/docker/api/types/versions" - "github.com/docker/docker/errdefs" - "github.com/docker/go-connections/nat" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" - "github.com/spf13/pflag" -) - -var deviceCgroupRuleRegexp = regexp.MustCompile(`^[acb] ([0-9]+|\*):([0-9]+|\*) [rwm]{1,3}$`) - -// containerOptions is a data object with all the options for creating a container -type containerOptions struct { - attach opts.ListOpts - volumes opts.ListOpts - tmpfs opts.ListOpts - mounts opts.MountOpt - blkioWeightDevice opts.WeightdeviceOpt - deviceReadBps opts.ThrottledeviceOpt - deviceWriteBps opts.ThrottledeviceOpt - links opts.ListOpts - aliases opts.ListOpts - linkLocalIPs opts.ListOpts - deviceReadIOps opts.ThrottledeviceOpt - deviceWriteIOps opts.ThrottledeviceOpt - env opts.ListOpts - labels opts.ListOpts - deviceCgroupRules opts.ListOpts - devices opts.ListOpts - gpus opts.GpuOpts - ulimits *opts.UlimitOpt - sysctls *opts.MapOpts - publish opts.ListOpts - expose opts.ListOpts - dns opts.ListOpts - dnsSearch opts.ListOpts - dnsOptions opts.ListOpts - extraHosts opts.ListOpts - volumesFrom opts.ListOpts - envFile opts.ListOpts - capAdd opts.ListOpts - capDrop opts.ListOpts - groupAdd opts.ListOpts - securityOpt opts.ListOpts - storageOpt opts.ListOpts - labelsFile opts.ListOpts - loggingOpts opts.ListOpts - privileged bool - pidMode string - utsMode string - usernsMode string - cgroupnsMode string - publishAll bool - stdin bool - tty bool - oomKillDisable bool - oomScoreAdj int - containerIDFile string - entrypoint string - hostname string - domainname string - memory opts.MemBytes - memoryReservation opts.MemBytes - memorySwap opts.MemSwapBytes - kernelMemory opts.MemBytes - user string - workingDir string - cpuCount int64 - cpuShares int64 - cpuPercent int64 - cpuPeriod int64 - cpuRealtimePeriod int64 - cpuRealtimeRuntime int64 - cpuQuota int64 - cpus opts.NanoCPUs - cpusetCpus string - cpusetMems string - blkioWeight uint16 - ioMaxBandwidth opts.MemBytes - ioMaxIOps uint64 - swappiness int64 - netMode opts.NetworkOpt - macAddress string - ipv4Address string - ipv6Address string - ipcMode string - pidsLimit int64 - restartPolicy string - readonlyRootfs bool - loggingDriver string - cgroupParent string - volumeDriver string - stopSignal string - stopTimeout int - isolation string - shmSize opts.MemBytes - noHealthcheck bool - healthCmd string - healthInterval time.Duration - healthTimeout time.Duration - healthStartPeriod time.Duration - healthRetries int - runtime string - autoRemove bool - init bool - annotations *opts.MapOpts - - Image string - Args []string -} - -// addFlags adds all command line flags that will be used by parse to the FlagSet -func addFlags(flags *pflag.FlagSet) *containerOptions { - copts := &containerOptions{ - aliases: opts.NewListOpts(nil), - attach: opts.NewListOpts(validateAttach), - blkioWeightDevice: opts.NewWeightdeviceOpt(opts.ValidateWeightDevice), - capAdd: opts.NewListOpts(nil), - capDrop: opts.NewListOpts(nil), - dns: opts.NewListOpts(opts.ValidateIPAddress), - dnsOptions: opts.NewListOpts(nil), - dnsSearch: opts.NewListOpts(opts.ValidateDNSSearch), - deviceCgroupRules: opts.NewListOpts(validateDeviceCgroupRule), - deviceReadBps: opts.NewThrottledeviceOpt(opts.ValidateThrottleBpsDevice), - deviceReadIOps: opts.NewThrottledeviceOpt(opts.ValidateThrottleIOpsDevice), - deviceWriteBps: opts.NewThrottledeviceOpt(opts.ValidateThrottleBpsDevice), - deviceWriteIOps: opts.NewThrottledeviceOpt(opts.ValidateThrottleIOpsDevice), - devices: opts.NewListOpts(nil), // devices can only be validated after we know the server OS - env: opts.NewListOpts(opts.ValidateEnv), - envFile: opts.NewListOpts(nil), - expose: opts.NewListOpts(nil), - extraHosts: opts.NewListOpts(opts.ValidateExtraHost), - groupAdd: opts.NewListOpts(nil), - labels: opts.NewListOpts(opts.ValidateLabel), - labelsFile: opts.NewListOpts(nil), - linkLocalIPs: opts.NewListOpts(nil), - links: opts.NewListOpts(opts.ValidateLink), - loggingOpts: opts.NewListOpts(nil), - publish: opts.NewListOpts(nil), - securityOpt: opts.NewListOpts(nil), - storageOpt: opts.NewListOpts(nil), - sysctls: opts.NewMapOpts(nil, opts.ValidateSysctl), - tmpfs: opts.NewListOpts(nil), - ulimits: opts.NewUlimitOpt(nil), - volumes: opts.NewListOpts(nil), - volumesFrom: opts.NewListOpts(nil), - annotations: opts.NewMapOpts(nil, nil), - } - - // General purpose flags - flags.VarP(&copts.attach, "attach", "a", "Attach to STDIN, STDOUT or STDERR") - flags.Var(&copts.deviceCgroupRules, "device-cgroup-rule", "Add a rule to the cgroup allowed devices list") - flags.Var(&copts.devices, "device", "Add a host device to the container") - flags.Var(&copts.gpus, "gpus", "GPU devices to add to the container ('all' to pass all GPUs)") - flags.SetAnnotation("gpus", "version", []string{"1.40"}) - flags.VarP(&copts.env, "env", "e", "Set environment variables") - flags.Var(&copts.envFile, "env-file", "Read in a file of environment variables") - flags.StringVar(&copts.entrypoint, "entrypoint", "", "Overwrite the default ENTRYPOINT of the image") - flags.Var(&copts.groupAdd, "group-add", "Add additional groups to join") - flags.StringVarP(&copts.hostname, "hostname", "h", "", "Container host name") - flags.StringVar(&copts.domainname, "domainname", "", "Container NIS domain name") - flags.BoolVarP(&copts.stdin, "interactive", "i", false, "Keep STDIN open even if not attached") - flags.VarP(&copts.labels, "label", "l", "Set meta data on a container") - flags.Var(&copts.labelsFile, "label-file", "Read in a line delimited file of labels") - flags.BoolVar(&copts.readonlyRootfs, "read-only", false, "Mount the container's root filesystem as read only") - flags.StringVar(&copts.restartPolicy, "restart", "no", "Restart policy to apply when a container exits") - flags.StringVar(&copts.stopSignal, "stop-signal", "", "Signal to stop the container") - flags.IntVar(&copts.stopTimeout, "stop-timeout", 0, "Timeout (in seconds) to stop a container") - flags.SetAnnotation("stop-timeout", "version", []string{"1.25"}) - flags.Var(copts.sysctls, "sysctl", "Sysctl options") - flags.BoolVarP(&copts.tty, "tty", "t", false, "Allocate a pseudo-TTY") - flags.Var(copts.ulimits, "ulimit", "Ulimit options") - flags.StringVarP(&copts.user, "user", "u", "", "Username or UID (format: [:])") - flags.StringVarP(&copts.workingDir, "workdir", "w", "", "Working directory inside the container") - flags.BoolVar(&copts.autoRemove, "rm", false, "Automatically remove the container when it exits") - - // Security - flags.Var(&copts.capAdd, "cap-add", "Add Linux capabilities") - flags.Var(&copts.capDrop, "cap-drop", "Drop Linux capabilities") - flags.BoolVar(&copts.privileged, "privileged", false, "Give extended privileges to this container") - flags.Var(&copts.securityOpt, "security-opt", "Security Options") - flags.StringVar(&copts.usernsMode, "userns", "", "User namespace to use") - flags.StringVar(&copts.cgroupnsMode, "cgroupns", "", `Cgroup namespace to use (host|private) -'host': Run the container in the Docker host's cgroup namespace -'private': Run the container in its own private cgroup namespace -'': Use the cgroup namespace as configured by the - default-cgroupns-mode option on the daemon (default)`) - flags.SetAnnotation("cgroupns", "version", []string{"1.41"}) - - // Network and port publishing flag - flags.Var(&copts.extraHosts, "add-host", "Add a custom host-to-IP mapping (host:ip)") - flags.Var(&copts.dns, "dns", "Set custom DNS servers") - // We allow for both "--dns-opt" and "--dns-option", although the latter is the recommended way. - // This is to be consistent with service create/update - flags.Var(&copts.dnsOptions, "dns-opt", "Set DNS options") - flags.Var(&copts.dnsOptions, "dns-option", "Set DNS options") - flags.MarkHidden("dns-opt") - flags.Var(&copts.dnsSearch, "dns-search", "Set custom DNS search domains") - flags.Var(&copts.expose, "expose", "Expose a port or a range of ports") - flags.StringVar(&copts.ipv4Address, "ip", "", "IPv4 address (e.g., 172.30.100.104)") - flags.StringVar(&copts.ipv6Address, "ip6", "", "IPv6 address (e.g., 2001:db8::33)") - flags.Var(&copts.links, "link", "Add link to another container") - flags.Var(&copts.linkLocalIPs, "link-local-ip", "Container IPv4/IPv6 link-local addresses") - flags.StringVar(&copts.macAddress, "mac-address", "", "Container MAC address (e.g., 92:d0:c6:0a:29:33)") - flags.VarP(&copts.publish, "publish", "p", "Publish a container's port(s) to the host") - flags.BoolVarP(&copts.publishAll, "publish-all", "P", false, "Publish all exposed ports to random ports") - // We allow for both "--net" and "--network", although the latter is the recommended way. - flags.Var(&copts.netMode, "net", "Connect a container to a network") - flags.Var(&copts.netMode, "network", "Connect a container to a network") - flags.MarkHidden("net") - // We allow for both "--net-alias" and "--network-alias", although the latter is the recommended way. - flags.Var(&copts.aliases, "net-alias", "Add network-scoped alias for the container") - flags.Var(&copts.aliases, "network-alias", "Add network-scoped alias for the container") - flags.MarkHidden("net-alias") - - // Logging and storage - flags.StringVar(&copts.loggingDriver, "log-driver", "", "Logging driver for the container") - flags.StringVar(&copts.volumeDriver, "volume-driver", "", "Optional volume driver for the container") - flags.Var(&copts.loggingOpts, "log-opt", "Log driver options") - flags.Var(&copts.storageOpt, "storage-opt", "Storage driver options for the container") - flags.Var(&copts.tmpfs, "tmpfs", "Mount a tmpfs directory") - flags.Var(&copts.volumesFrom, "volumes-from", "Mount volumes from the specified container(s)") - flags.VarP(&copts.volumes, "volume", "v", "Bind mount a volume") - flags.Var(&copts.mounts, "mount", "Attach a filesystem mount to the container") - - // Health-checking - flags.StringVar(&copts.healthCmd, "health-cmd", "", "Command to run to check health") - flags.DurationVar(&copts.healthInterval, "health-interval", 0, "Time between running the check (ms|s|m|h) (default 0s)") - flags.IntVar(&copts.healthRetries, "health-retries", 0, "Consecutive failures needed to report unhealthy") - flags.DurationVar(&copts.healthTimeout, "health-timeout", 0, "Maximum time to allow one check to run (ms|s|m|h) (default 0s)") - flags.DurationVar(&copts.healthStartPeriod, "health-start-period", 0, "Start period for the container to initialize before starting health-retries countdown (ms|s|m|h) (default 0s)") - flags.SetAnnotation("health-start-period", "version", []string{"1.29"}) - flags.BoolVar(&copts.noHealthcheck, "no-healthcheck", false, "Disable any container-specified HEALTHCHECK") - - // Resource management - flags.Uint16Var(&copts.blkioWeight, "blkio-weight", 0, "Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)") - flags.Var(&copts.blkioWeightDevice, "blkio-weight-device", "Block IO weight (relative device weight)") - flags.StringVar(&copts.containerIDFile, "cidfile", "", "Write the container ID to the file") - flags.StringVar(&copts.cpusetCpus, "cpuset-cpus", "", "CPUs in which to allow execution (0-3, 0,1)") - flags.StringVar(&copts.cpusetMems, "cpuset-mems", "", "MEMs in which to allow execution (0-3, 0,1)") - flags.Int64Var(&copts.cpuCount, "cpu-count", 0, "CPU count (Windows only)") - flags.SetAnnotation("cpu-count", "ostype", []string{"windows"}) - flags.Int64Var(&copts.cpuPercent, "cpu-percent", 0, "CPU percent (Windows only)") - flags.SetAnnotation("cpu-percent", "ostype", []string{"windows"}) - flags.Int64Var(&copts.cpuPeriod, "cpu-period", 0, "Limit CPU CFS (Completely Fair Scheduler) period") - flags.Int64Var(&copts.cpuQuota, "cpu-quota", 0, "Limit CPU CFS (Completely Fair Scheduler) quota") - flags.Int64Var(&copts.cpuRealtimePeriod, "cpu-rt-period", 0, "Limit CPU real-time period in microseconds") - flags.SetAnnotation("cpu-rt-period", "version", []string{"1.25"}) - flags.Int64Var(&copts.cpuRealtimeRuntime, "cpu-rt-runtime", 0, "Limit CPU real-time runtime in microseconds") - flags.SetAnnotation("cpu-rt-runtime", "version", []string{"1.25"}) - flags.Int64VarP(&copts.cpuShares, "cpu-shares", "c", 0, "CPU shares (relative weight)") - flags.Var(&copts.cpus, "cpus", "Number of CPUs") - flags.SetAnnotation("cpus", "version", []string{"1.25"}) - flags.Var(&copts.deviceReadBps, "device-read-bps", "Limit read rate (bytes per second) from a device") - flags.Var(&copts.deviceReadIOps, "device-read-iops", "Limit read rate (IO per second) from a device") - flags.Var(&copts.deviceWriteBps, "device-write-bps", "Limit write rate (bytes per second) to a device") - flags.Var(&copts.deviceWriteIOps, "device-write-iops", "Limit write rate (IO per second) to a device") - flags.Var(&copts.ioMaxBandwidth, "io-maxbandwidth", "Maximum IO bandwidth limit for the system drive (Windows only)") - flags.SetAnnotation("io-maxbandwidth", "ostype", []string{"windows"}) - flags.Uint64Var(&copts.ioMaxIOps, "io-maxiops", 0, "Maximum IOps limit for the system drive (Windows only)") - flags.SetAnnotation("io-maxiops", "ostype", []string{"windows"}) - flags.Var(&copts.kernelMemory, "kernel-memory", "Kernel memory limit") - flags.VarP(&copts.memory, "memory", "m", "Memory limit") - flags.Var(&copts.memoryReservation, "memory-reservation", "Memory soft limit") - flags.Var(&copts.memorySwap, "memory-swap", "Swap limit equal to memory plus swap: '-1' to enable unlimited swap") - flags.Int64Var(&copts.swappiness, "memory-swappiness", -1, "Tune container memory swappiness (0 to 100)") - flags.BoolVar(&copts.oomKillDisable, "oom-kill-disable", false, "Disable OOM Killer") - flags.IntVar(&copts.oomScoreAdj, "oom-score-adj", 0, "Tune host's OOM preferences (-1000 to 1000)") - flags.Int64Var(&copts.pidsLimit, "pids-limit", 0, "Tune container pids limit (set -1 for unlimited)") - - // Low-level execution (cgroups, namespaces, ...) - flags.StringVar(&copts.cgroupParent, "cgroup-parent", "", "Optional parent cgroup for the container") - flags.StringVar(&copts.ipcMode, "ipc", "", "IPC mode to use") - flags.StringVar(&copts.isolation, "isolation", "", "Container isolation technology") - flags.StringVar(&copts.pidMode, "pid", "", "PID namespace to use") - flags.Var(&copts.shmSize, "shm-size", "Size of /dev/shm") - flags.StringVar(&copts.utsMode, "uts", "", "UTS namespace to use") - flags.StringVar(&copts.runtime, "runtime", "", "Runtime to use for this container") - - flags.BoolVar(&copts.init, "init", false, "Run an init inside the container that forwards signals and reaps processes") - flags.SetAnnotation("init", "version", []string{"1.25"}) - - flags.Var(copts.annotations, "annotation", "Add an annotation to the container (passed through to the OCI runtime)") - flags.SetAnnotation("annotation", "version", []string{"1.43"}) - - return copts -} - -type containerConfig struct { - Config *container.Config - HostConfig *container.HostConfig - NetworkingConfig *networktypes.NetworkingConfig -} - -// parse parses the args for the specified command and generates a Config, -// a HostConfig and returns them with the specified command. -// If the specified args are not valid, it will return an error. -// -//nolint:gocyclo -func parse(flags *pflag.FlagSet, copts *containerOptions, serverOS string) (*containerConfig, error) { - var ( - attachStdin = copts.attach.Get("stdin") - attachStdout = copts.attach.Get("stdout") - attachStderr = copts.attach.Get("stderr") - ) - - // Validate the input mac address - if copts.macAddress != "" { - if _, err := opts.ValidateMACAddress(copts.macAddress); err != nil { - return nil, errors.Errorf("%s is not a valid mac address", copts.macAddress) - } - } - if copts.stdin { - attachStdin = true - } - // If -a is not set, attach to stdout and stderr - if copts.attach.Len() == 0 { - attachStdout = true - attachStderr = true - } - - var err error - - swappiness := copts.swappiness - if swappiness != -1 && (swappiness < 0 || swappiness > 100) { - return nil, errors.Errorf("invalid value: %d. Valid memory swappiness range is 0-100", swappiness) - } - - mounts := copts.mounts.Value() - if len(mounts) > 0 && copts.volumeDriver != "" { - logrus.Warn("`--volume-driver` is ignored for volumes specified via `--mount`. Use `--mount type=volume,volume-driver=...` instead.") - } - var binds []string - volumes := copts.volumes.GetMap() - // add any bind targets to the list of container volumes - for bind := range copts.volumes.GetMap() { - parsed, err := loader.ParseVolume(bind) - if err != nil { - return nil, err - } - - if parsed.Source != "" { - toBind := bind - - if parsed.Type == string(mounttypes.TypeBind) { - if hostPart, targetPath, ok := strings.Cut(bind, ":"); ok { - if strings.HasPrefix(hostPart, "."+string(filepath.Separator)) || hostPart == "." { - if absHostPart, err := filepath.Abs(hostPart); err == nil { - hostPart = absHostPart - } - } - toBind = hostPart + ":" + targetPath - } - } - - // after creating the bind mount we want to delete it from the copts.volumes values because - // we do not want bind mounts being committed to image configs - binds = append(binds, toBind) - // We should delete from the map (`volumes`) here, as deleting from copts.volumes will not work if - // there are duplicates entries. - delete(volumes, bind) - } - } - - // Can't evaluate options passed into --tmpfs until we actually mount - tmpfs := make(map[string]string) - for _, t := range copts.tmpfs.GetAll() { - k, v, _ := strings.Cut(t, ":") - tmpfs[k] = v - } - - var ( - runCmd strslice.StrSlice - entrypoint strslice.StrSlice - ) - - if len(copts.Args) > 0 { - runCmd = copts.Args - } - - if copts.entrypoint != "" { - entrypoint = strslice.StrSlice{copts.entrypoint} - } else if flags.Changed("entrypoint") { - // if `--entrypoint=` is parsed then Entrypoint is reset - entrypoint = []string{""} - } - - publishOpts := copts.publish.GetAll() - var ( - ports map[nat.Port]struct{} - portBindings map[nat.Port][]nat.PortBinding - convertedOpts []string - ) - - convertedOpts, err = convertToStandardNotation(publishOpts) - if err != nil { - return nil, err - } - - ports, portBindings, err = nat.ParsePortSpecs(convertedOpts) - if err != nil { - return nil, err - } - - // Merge in exposed ports to the map of published ports - for _, e := range copts.expose.GetAll() { - if strings.Contains(e, ":") { - return nil, errors.Errorf("invalid port format for --expose: %s", e) - } - // support two formats for expose, original format /[] - // or /[] - proto, port := nat.SplitProtoPort(e) - // parse the start and end port and create a sequence of ports to expose - // if expose a port, the start and end port are the same - start, end, err := nat.ParsePortRange(port) - if err != nil { - return nil, errors.Errorf("invalid range format for --expose: %s, error: %s", e, err) - } - for i := start; i <= end; i++ { - p, err := nat.NewPort(proto, strconv.FormatUint(i, 10)) - if err != nil { - return nil, err - } - if _, exists := ports[p]; !exists { - ports[p] = struct{}{} - } - } - } - - // validate and parse device mappings. Note we do late validation of the - // device path (as opposed to during flag parsing), as at the time we are - // parsing flags, we haven't yet sent a _ping to the daemon to determine - // what operating system it is. - deviceMappings := []container.DeviceMapping{} - for _, device := range copts.devices.GetAll() { - var ( - validated string - deviceMapping container.DeviceMapping - err error - ) - validated, err = validateDevice(device, serverOS) - if err != nil { - return nil, err - } - deviceMapping, err = parseDevice(validated, serverOS) - if err != nil { - return nil, err - } - deviceMappings = append(deviceMappings, deviceMapping) - } - - // collect all the environment variables for the container - envVariables, err := opts.ReadKVEnvStrings(copts.envFile.GetAll(), copts.env.GetAll()) - if err != nil { - return nil, err - } - - // collect all the labels for the container - labels, err := opts.ReadKVStrings(copts.labelsFile.GetAll(), copts.labels.GetAll()) - if err != nil { - return nil, err - } - - pidMode := container.PidMode(copts.pidMode) - if !pidMode.Valid() { - return nil, errors.Errorf("--pid: invalid PID mode") - } - - utsMode := container.UTSMode(copts.utsMode) - if !utsMode.Valid() { - return nil, errors.Errorf("--uts: invalid UTS mode") - } - - usernsMode := container.UsernsMode(copts.usernsMode) - if !usernsMode.Valid() { - return nil, errors.Errorf("--userns: invalid USER mode") - } - - cgroupnsMode := container.CgroupnsMode(copts.cgroupnsMode) - if !cgroupnsMode.Valid() { - return nil, errors.Errorf("--cgroupns: invalid CGROUP mode") - } - - restartPolicy, err := opts.ParseRestartPolicy(copts.restartPolicy) - if err != nil { - return nil, err - } - - loggingOpts, err := parseLoggingOpts(copts.loggingDriver, copts.loggingOpts.GetAll()) - if err != nil { - return nil, err - } - - securityOpts, err := parseSecurityOpts(copts.securityOpt.GetAll()) - if err != nil { - return nil, err - } - - securityOpts, maskedPaths, readonlyPaths := parseSystemPaths(securityOpts) - - storageOpts, err := parseStorageOpts(copts.storageOpt.GetAll()) - if err != nil { - return nil, err - } - - // Healthcheck - var healthConfig *container.HealthConfig - haveHealthSettings := copts.healthCmd != "" || - copts.healthInterval != 0 || - copts.healthTimeout != 0 || - copts.healthStartPeriod != 0 || - copts.healthRetries != 0 - if copts.noHealthcheck { - if haveHealthSettings { - return nil, errors.Errorf("--no-healthcheck conflicts with --health-* options") - } - healthConfig = &container.HealthConfig{Test: strslice.StrSlice{"NONE"}} - } else if haveHealthSettings { - var probe strslice.StrSlice - if copts.healthCmd != "" { - probe = []string{"CMD-SHELL", copts.healthCmd} - } - if copts.healthInterval < 0 { - return nil, errors.Errorf("--health-interval cannot be negative") - } - if copts.healthTimeout < 0 { - return nil, errors.Errorf("--health-timeout cannot be negative") - } - if copts.healthRetries < 0 { - return nil, errors.Errorf("--health-retries cannot be negative") - } - if copts.healthStartPeriod < 0 { - return nil, fmt.Errorf("--health-start-period cannot be negative") - } - - healthConfig = &container.HealthConfig{ - Test: probe, - Interval: copts.healthInterval, - Timeout: copts.healthTimeout, - StartPeriod: copts.healthStartPeriod, - Retries: copts.healthRetries, - } - } - - resources := container.Resources{ - CgroupParent: copts.cgroupParent, - Memory: copts.memory.Value(), - MemoryReservation: copts.memoryReservation.Value(), - MemorySwap: copts.memorySwap.Value(), - MemorySwappiness: &copts.swappiness, - KernelMemory: copts.kernelMemory.Value(), - OomKillDisable: &copts.oomKillDisable, - NanoCPUs: copts.cpus.Value(), - CPUCount: copts.cpuCount, - CPUPercent: copts.cpuPercent, - CPUShares: copts.cpuShares, - CPUPeriod: copts.cpuPeriod, - CpusetCpus: copts.cpusetCpus, - CpusetMems: copts.cpusetMems, - CPUQuota: copts.cpuQuota, - CPURealtimePeriod: copts.cpuRealtimePeriod, - CPURealtimeRuntime: copts.cpuRealtimeRuntime, - PidsLimit: &copts.pidsLimit, - BlkioWeight: copts.blkioWeight, - BlkioWeightDevice: copts.blkioWeightDevice.GetList(), - BlkioDeviceReadBps: copts.deviceReadBps.GetList(), - BlkioDeviceWriteBps: copts.deviceWriteBps.GetList(), - BlkioDeviceReadIOps: copts.deviceReadIOps.GetList(), - BlkioDeviceWriteIOps: copts.deviceWriteIOps.GetList(), - IOMaximumIOps: copts.ioMaxIOps, - IOMaximumBandwidth: uint64(copts.ioMaxBandwidth), - Ulimits: copts.ulimits.GetList(), - DeviceCgroupRules: copts.deviceCgroupRules.GetAll(), - Devices: deviceMappings, - DeviceRequests: copts.gpus.Value(), - } - - config := &container.Config{ - Hostname: copts.hostname, - Domainname: copts.domainname, - ExposedPorts: ports, - User: copts.user, - Tty: copts.tty, - OpenStdin: copts.stdin, - AttachStdin: attachStdin, - AttachStdout: attachStdout, - AttachStderr: attachStderr, - Env: envVariables, - Cmd: runCmd, - Image: copts.Image, - Volumes: volumes, - MacAddress: copts.macAddress, - Entrypoint: entrypoint, - WorkingDir: copts.workingDir, - Labels: opts.ConvertKVStringsToMap(labels), - StopSignal: copts.stopSignal, - Healthcheck: healthConfig, - } - if flags.Changed("stop-timeout") { - config.StopTimeout = &copts.stopTimeout - } - - hostConfig := &container.HostConfig{ - Binds: binds, - ContainerIDFile: copts.containerIDFile, - OomScoreAdj: copts.oomScoreAdj, - AutoRemove: copts.autoRemove, - Privileged: copts.privileged, - PortBindings: portBindings, - Links: copts.links.GetAll(), - PublishAllPorts: copts.publishAll, - // Make sure the dns fields are never nil. - // New containers don't ever have those fields nil, - // but pre created containers can still have those nil values. - // See https://github.com/docker/docker/pull/17779 - // for a more detailed explanation on why we don't want that. - DNS: copts.dns.GetAllOrEmpty(), - DNSSearch: copts.dnsSearch.GetAllOrEmpty(), - DNSOptions: copts.dnsOptions.GetAllOrEmpty(), - ExtraHosts: copts.extraHosts.GetAll(), - VolumesFrom: copts.volumesFrom.GetAll(), - IpcMode: container.IpcMode(copts.ipcMode), - NetworkMode: container.NetworkMode(copts.netMode.NetworkMode()), - PidMode: pidMode, - UTSMode: utsMode, - UsernsMode: usernsMode, - CgroupnsMode: cgroupnsMode, - CapAdd: strslice.StrSlice(copts.capAdd.GetAll()), - CapDrop: strslice.StrSlice(copts.capDrop.GetAll()), - GroupAdd: copts.groupAdd.GetAll(), - RestartPolicy: restartPolicy, - SecurityOpt: securityOpts, - StorageOpt: storageOpts, - ReadonlyRootfs: copts.readonlyRootfs, - LogConfig: container.LogConfig{Type: copts.loggingDriver, Config: loggingOpts}, - VolumeDriver: copts.volumeDriver, - Isolation: container.Isolation(copts.isolation), - ShmSize: copts.shmSize.Value(), - Resources: resources, - Tmpfs: tmpfs, - Sysctls: copts.sysctls.GetAll(), - Runtime: copts.runtime, - Mounts: mounts, - MaskedPaths: maskedPaths, - ReadonlyPaths: readonlyPaths, - Annotations: copts.annotations.GetAll(), - } - - if copts.autoRemove && !hostConfig.RestartPolicy.IsNone() { - return nil, errors.Errorf("Conflicting options: --restart and --rm") - } - - // only set this value if the user provided the flag, else it should default to nil - if flags.Changed("init") { - hostConfig.Init = &copts.init - } - - // When allocating stdin in attached mode, close stdin at client disconnect - if config.OpenStdin && config.AttachStdin { - config.StdinOnce = true - } - - networkingConfig := &networktypes.NetworkingConfig{ - EndpointsConfig: make(map[string]*networktypes.EndpointSettings), - } - - networkingConfig.EndpointsConfig, err = parseNetworkOpts(copts) - if err != nil { - return nil, err - } - - return &containerConfig{ - Config: config, - HostConfig: hostConfig, - NetworkingConfig: networkingConfig, - }, nil -} - -// parseNetworkOpts converts --network advanced options to endpoint-specs, and combines -// them with the old --network-alias and --links. If returns an error if conflicting options -// are found. -// -// this function may return _multiple_ endpoints, which is not currently supported -// by the daemon, but may be in future; it's up to the daemon to produce an error -// in case that is not supported. -func parseNetworkOpts(copts *containerOptions) (map[string]*networktypes.EndpointSettings, error) { - var ( - endpoints = make(map[string]*networktypes.EndpointSettings, len(copts.netMode.Value())) - hasUserDefined, hasNonUserDefined bool - ) - - for i, n := range copts.netMode.Value() { - n := n - if container.NetworkMode(n.Target).IsUserDefined() { - hasUserDefined = true - } else { - hasNonUserDefined = true - } - if i == 0 { - // The first network corresponds with what was previously the "only" - // network, and what would be used when using the non-advanced syntax - // `--network-alias`, `--link`, `--ip`, `--ip6`, and `--link-local-ip` - // are set on this network, to preserve backward compatibility with - // the non-advanced notation - if err := applyContainerOptions(&n, copts); err != nil { - return nil, err - } - } - ep, err := parseNetworkAttachmentOpt(n) - if err != nil { - return nil, err - } - if _, ok := endpoints[n.Target]; ok { - return nil, errdefs.InvalidParameter(errors.Errorf("network %q is specified multiple times", n.Target)) - } - - // For backward compatibility: if no custom options are provided for the network, - // and only a single network is specified, omit the endpoint-configuration - // on the client (the daemon will still create it when creating the container) - if i == 0 && len(copts.netMode.Value()) == 1 { - if ep == nil || reflect.DeepEqual(*ep, networktypes.EndpointSettings{}) { - continue - } - } - endpoints[n.Target] = ep - } - if hasUserDefined && hasNonUserDefined { - return nil, errdefs.InvalidParameter(errors.New("conflicting options: cannot attach both user-defined and non-user-defined network-modes")) - } - return endpoints, nil -} - -func applyContainerOptions(n *opts.NetworkAttachmentOpts, copts *containerOptions) error { - // TODO should copts.MacAddress actually be set on the first network? (currently it's not) - // TODO should we error if _any_ advanced option is used? (i.e. forbid to combine advanced notation with the "old" flags (`--network-alias`, `--link`, `--ip`, `--ip6`)? - if len(n.Aliases) > 0 && copts.aliases.Len() > 0 { - return errdefs.InvalidParameter(errors.New("conflicting options: cannot specify both --network-alias and per-network alias")) - } - if len(n.Links) > 0 && copts.links.Len() > 0 { - return errdefs.InvalidParameter(errors.New("conflicting options: cannot specify both --link and per-network links")) - } - if n.IPv4Address != "" && copts.ipv4Address != "" { - return errdefs.InvalidParameter(errors.New("conflicting options: cannot specify both --ip and per-network IPv4 address")) - } - if n.IPv6Address != "" && copts.ipv6Address != "" { - return errdefs.InvalidParameter(errors.New("conflicting options: cannot specify both --ip6 and per-network IPv6 address")) - } - if copts.aliases.Len() > 0 { - n.Aliases = make([]string, copts.aliases.Len()) - copy(n.Aliases, copts.aliases.GetAll()) - } - if copts.links.Len() > 0 { - n.Links = make([]string, copts.links.Len()) - copy(n.Links, copts.links.GetAll()) - } - if copts.ipv4Address != "" { - n.IPv4Address = copts.ipv4Address - } - if copts.ipv6Address != "" { - n.IPv6Address = copts.ipv6Address - } - - // TODO should linkLocalIPs be added to the _first_ network only, or to _all_ networks? (should this be a per-network option as well?) - if copts.linkLocalIPs.Len() > 0 { - n.LinkLocalIPs = make([]string, copts.linkLocalIPs.Len()) - copy(n.LinkLocalIPs, copts.linkLocalIPs.GetAll()) - } - return nil -} - -func parseNetworkAttachmentOpt(ep opts.NetworkAttachmentOpts) (*networktypes.EndpointSettings, error) { - if strings.TrimSpace(ep.Target) == "" { - return nil, errors.New("no name set for network") - } - if !container.NetworkMode(ep.Target).IsUserDefined() { - if len(ep.Aliases) > 0 { - return nil, errors.New("network-scoped aliases are only supported for user-defined networks") - } - if len(ep.Links) > 0 { - return nil, errors.New("links are only supported for user-defined networks") - } - } - - epConfig := &networktypes.EndpointSettings{} - epConfig.Aliases = append(epConfig.Aliases, ep.Aliases...) - if len(ep.DriverOpts) > 0 { - epConfig.DriverOpts = make(map[string]string) - epConfig.DriverOpts = ep.DriverOpts - } - if len(ep.Links) > 0 { - epConfig.Links = ep.Links - } - if ep.IPv4Address != "" || ep.IPv6Address != "" || len(ep.LinkLocalIPs) > 0 { - epConfig.IPAMConfig = &networktypes.EndpointIPAMConfig{ - IPv4Address: ep.IPv4Address, - IPv6Address: ep.IPv6Address, - LinkLocalIPs: ep.LinkLocalIPs, - } - } - return epConfig, nil -} - -func convertToStandardNotation(ports []string) ([]string, error) { - optsList := []string{} - for _, publish := range ports { - if strings.Contains(publish, "=") { - params := map[string]string{"protocol": "tcp"} - for _, param := range strings.Split(publish, ",") { - k, v, ok := strings.Cut(param, "=") - if !ok || k == "" { - return optsList, errors.Errorf("invalid publish opts format (should be name=value but got '%s')", param) - } - params[k] = v - } - optsList = append(optsList, fmt.Sprintf("%s:%s/%s", params["published"], params["target"], params["protocol"])) - } else { - optsList = append(optsList, publish) - } - } - return optsList, nil -} - -func parseLoggingOpts(loggingDriver string, loggingOpts []string) (map[string]string, error) { - loggingOptsMap := opts.ConvertKVStringsToMap(loggingOpts) - if loggingDriver == "none" && len(loggingOpts) > 0 { - return map[string]string{}, errors.Errorf("invalid logging opts for driver %s", loggingDriver) - } - return loggingOptsMap, nil -} - -// takes a local seccomp daemon, reads the file contents for sending to the daemon -func parseSecurityOpts(securityOpts []string) ([]string, error) { - for key, opt := range securityOpts { - k, v, ok := strings.Cut(opt, "=") - if !ok && k != "no-new-privileges" { - k, v, ok = strings.Cut(opt, ":") - } - if (!ok || v == "") && k != "no-new-privileges" { - // "no-new-privileges" is the only option that does not require a value. - return securityOpts, errors.Errorf("Invalid --security-opt: %q", opt) - } - if k == "seccomp" && v != "unconfined" { - f, err := os.ReadFile(v) - if err != nil { - return securityOpts, errors.Errorf("opening seccomp profile (%s) failed: %v", v, err) - } - b := bytes.NewBuffer(nil) - if err := json.Compact(b, f); err != nil { - return securityOpts, errors.Errorf("compacting json for seccomp profile (%s) failed: %v", v, err) - } - securityOpts[key] = fmt.Sprintf("seccomp=%s", b.Bytes()) - } - } - - return securityOpts, nil -} - -// parseSystemPaths checks if `systempaths=unconfined` security option is set, -// and returns the `MaskedPaths` and `ReadonlyPaths` accordingly. An updated -// list of security options is returned with this option removed, because the -// `unconfined` option is handled client-side, and should not be sent to the -// daemon. -func parseSystemPaths(securityOpts []string) (filtered, maskedPaths, readonlyPaths []string) { - filtered = securityOpts[:0] - for _, opt := range securityOpts { - if opt == "systempaths=unconfined" { - maskedPaths = []string{} - readonlyPaths = []string{} - } else { - filtered = append(filtered, opt) - } - } - - return filtered, maskedPaths, readonlyPaths -} - -// parses storage options per container into a map -func parseStorageOpts(storageOpts []string) (map[string]string, error) { - m := make(map[string]string) - for _, option := range storageOpts { - k, v, ok := strings.Cut(option, "=") - if !ok { - return nil, errors.Errorf("invalid storage option") - } - m[k] = v - } - return m, nil -} - -// parseDevice parses a device mapping string to a container.DeviceMapping struct -func parseDevice(device, serverOS string) (container.DeviceMapping, error) { - switch serverOS { - case "linux": - return parseLinuxDevice(device) - case "windows": - return parseWindowsDevice(device) - } - return container.DeviceMapping{}, errors.Errorf("unknown server OS: %s", serverOS) -} - -// parseLinuxDevice parses a device mapping string to a container.DeviceMapping struct -// knowing that the target is a Linux daemon -func parseLinuxDevice(device string) (container.DeviceMapping, error) { - var src, dst string - permissions := "rwm" - // We expect 3 parts at maximum; limit to 4 parts to detect invalid options. - arr := strings.SplitN(device, ":", 4) - switch len(arr) { - case 3: - permissions = arr[2] - fallthrough - case 2: - if validDeviceMode(arr[1]) { - permissions = arr[1] - } else { - dst = arr[1] - } - fallthrough - case 1: - src = arr[0] - default: - return container.DeviceMapping{}, errors.Errorf("invalid device specification: %s", device) - } - - if dst == "" { - dst = src - } - - deviceMapping := container.DeviceMapping{ - PathOnHost: src, - PathInContainer: dst, - CgroupPermissions: permissions, - } - return deviceMapping, nil -} - -// parseWindowsDevice parses a device mapping string to a container.DeviceMapping struct -// knowing that the target is a Windows daemon -func parseWindowsDevice(device string) (container.DeviceMapping, error) { - return container.DeviceMapping{PathOnHost: device}, nil -} - -// validateDeviceCgroupRule validates a device cgroup rule string format -// It will make sure 'val' is in the form: -// -// 'type major:minor mode' -func validateDeviceCgroupRule(val string) (string, error) { - if deviceCgroupRuleRegexp.MatchString(val) { - return val, nil - } - - return val, errors.Errorf("invalid device cgroup format '%s'", val) -} - -// validDeviceMode checks if the mode for device is valid or not. -// Valid mode is a composition of r (read), w (write), and m (mknod). -func validDeviceMode(mode string) bool { - legalDeviceMode := map[rune]bool{ - 'r': true, - 'w': true, - 'm': true, - } - if mode == "" { - return false - } - for _, c := range mode { - if !legalDeviceMode[c] { - return false - } - legalDeviceMode[c] = false - } - return true -} - -// validateDevice validates a path for devices -func validateDevice(val string, serverOS string) (string, error) { - switch serverOS { - case "linux": - return validateLinuxPath(val, validDeviceMode) - case "windows": - // Windows does validation entirely server-side - return val, nil - } - return "", errors.Errorf("unknown server OS: %s", serverOS) -} - -// validateLinuxPath is the implementation of validateDevice knowing that the -// target server operating system is a Linux daemon. -// It will make sure 'val' is in the form: -// -// [host-dir:]container-path[:mode] -// -// It also validates the device mode. -func validateLinuxPath(val string, validator func(string) bool) (string, error) { - var containerPath string - var mode string - - if strings.Count(val, ":") > 2 { - return val, errors.Errorf("bad format for path: %s", val) - } - - split := strings.SplitN(val, ":", 3) - if split[0] == "" { - return val, errors.Errorf("bad format for path: %s", val) - } - switch len(split) { - case 1: - containerPath = split[0] - val = path.Clean(containerPath) - case 2: - if isValid := validator(split[1]); isValid { - containerPath = split[0] - mode = split[1] - val = fmt.Sprintf("%s:%s", path.Clean(containerPath), mode) - } else { - containerPath = split[1] - val = fmt.Sprintf("%s:%s", split[0], path.Clean(containerPath)) - } - case 3: - containerPath = split[1] - mode = split[2] - if isValid := validator(split[2]); !isValid { - return val, errors.Errorf("bad mode specified: %s", mode) - } - val = fmt.Sprintf("%s:%s:%s", split[0], containerPath, mode) - } - - if !path.IsAbs(containerPath) { - return val, errors.Errorf("%s is not an absolute path", containerPath) - } - return val, nil -} - -// validateAttach validates that the specified string is a valid attach option. -func validateAttach(val string) (string, error) { - s := strings.ToLower(val) - for _, str := range []string{"stdin", "stdout", "stderr"} { - if s == str { - return s, nil - } - } - return val, errors.Errorf("valid streams are STDIN, STDOUT and STDERR") -} - -func validateAPIVersion(c *containerConfig, serverAPIVersion string) error { - for _, m := range c.HostConfig.Mounts { - if m.BindOptions != nil && m.BindOptions.NonRecursive && versions.LessThan(serverAPIVersion, "1.40") { - return errors.Errorf("bind-nonrecursive requires API v1.40 or later") - } - } - return nil -} diff --git a/vendor/github.com/docker/cli/cli/command/container/pause.go b/vendor/github.com/docker/cli/cli/command/container/pause.go deleted file mode 100644 index aec3c4cb1..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/pause.go +++ /dev/null @@ -1,57 +0,0 @@ -package container - -import ( - "context" - "fmt" - "strings" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/docker/docker/api/types" - "github.com/pkg/errors" - "github.com/spf13/cobra" -) - -type pauseOptions struct { - containers []string -} - -// NewPauseCommand creates a new cobra.Command for `docker pause` -func NewPauseCommand(dockerCli command.Cli) *cobra.Command { - var opts pauseOptions - - return &cobra.Command{ - Use: "pause CONTAINER [CONTAINER...]", - Short: "Pause all processes within one or more containers", - Args: cli.RequiresMinArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - opts.containers = args - return runPause(dockerCli, &opts) - }, - Annotations: map[string]string{ - "aliases": "docker container pause, docker pause", - }, - ValidArgsFunction: completion.ContainerNames(dockerCli, false, func(container types.Container) bool { - return container.State != "paused" - }), - } -} - -func runPause(dockerCli command.Cli, opts *pauseOptions) error { - ctx := context.Background() - - var errs []string - errChan := parallelOperation(ctx, opts.containers, dockerCli.Client().ContainerPause) - for _, container := range opts.containers { - if err := <-errChan; err != nil { - errs = append(errs, err.Error()) - continue - } - fmt.Fprintln(dockerCli.Out(), container) - } - if len(errs) > 0 { - return errors.New(strings.Join(errs, "\n")) - } - return nil -} diff --git a/vendor/github.com/docker/cli/cli/command/container/port.go b/vendor/github.com/docker/cli/cli/command/container/port.go deleted file mode 100644 index e8e39efa2..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/port.go +++ /dev/null @@ -1,95 +0,0 @@ -package container - -import ( - "context" - "fmt" - "net" - "sort" - "strconv" - "strings" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/docker/go-connections/nat" - "github.com/fvbommel/sortorder" - "github.com/pkg/errors" - "github.com/spf13/cobra" -) - -type portOptions struct { - container string - - port string -} - -// NewPortCommand creates a new cobra.Command for `docker port` -func NewPortCommand(dockerCli command.Cli) *cobra.Command { - var opts portOptions - - cmd := &cobra.Command{ - Use: "port CONTAINER [PRIVATE_PORT[/PROTO]]", - Short: "List port mappings or a specific mapping for the container", - Args: cli.RequiresRangeArgs(1, 2), - RunE: func(cmd *cobra.Command, args []string) error { - opts.container = args[0] - if len(args) > 1 { - opts.port = args[1] - } - return runPort(dockerCli, &opts) - }, - Annotations: map[string]string{ - "aliases": "docker container port, docker port", - }, - ValidArgsFunction: completion.ContainerNames(dockerCli, false), - } - return cmd -} - -// runPort shows the port mapping for a given container. Optionally, it -// allows showing the mapping for a specific (container)port and proto. -// -// TODO(thaJeztah): currently this defaults to show the TCP port if no -// proto is specified. We should consider changing this to "any" protocol -// for the given private port. -func runPort(dockerCli command.Cli, opts *portOptions) error { - ctx := context.Background() - - c, err := dockerCli.Client().ContainerInspect(ctx, opts.container) - if err != nil { - return err - } - - var out []string - if opts.port != "" { - port, proto, _ := strings.Cut(opts.port, "/") - if proto == "" { - proto = "tcp" - } - if _, err = strconv.ParseUint(port, 10, 16); err != nil { - return errors.Wrapf(err, "Error: invalid port (%s)", port) - } - frontends, exists := c.NetworkSettings.Ports[nat.Port(port+"/"+proto)] - if !exists || frontends == nil { - return errors.Errorf("Error: No public port '%s' published for %s", opts.port, opts.container) - } - for _, frontend := range frontends { - out = append(out, net.JoinHostPort(frontend.HostIP, frontend.HostPort)) - } - } else { - for from, frontends := range c.NetworkSettings.Ports { - for _, frontend := range frontends { - out = append(out, fmt.Sprintf("%s -> %s", from, net.JoinHostPort(frontend.HostIP, frontend.HostPort))) - } - } - } - - if len(out) > 0 { - sort.Slice(out, func(i, j int) bool { - return sortorder.NaturalLess(out[i], out[j]) - }) - _, _ = fmt.Fprintln(dockerCli.Out(), strings.Join(out, "\n")) - } - - return nil -} diff --git a/vendor/github.com/docker/cli/cli/command/container/prune.go b/vendor/github.com/docker/cli/cli/command/container/prune.go deleted file mode 100644 index 868560ef7..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/prune.go +++ /dev/null @@ -1,80 +0,0 @@ -package container - -import ( - "context" - "fmt" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/docker/cli/opts" - units "github.com/docker/go-units" - "github.com/spf13/cobra" -) - -type pruneOptions struct { - force bool - filter opts.FilterOpt -} - -// NewPruneCommand returns a new cobra prune command for containers -func NewPruneCommand(dockerCli command.Cli) *cobra.Command { - options := pruneOptions{filter: opts.NewFilterOpt()} - - cmd := &cobra.Command{ - Use: "prune [OPTIONS]", - Short: "Remove all stopped containers", - Args: cli.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - spaceReclaimed, output, err := runPrune(dockerCli, options) - if err != nil { - return err - } - if output != "" { - fmt.Fprintln(dockerCli.Out(), output) - } - fmt.Fprintln(dockerCli.Out(), "Total reclaimed space:", units.HumanSize(float64(spaceReclaimed))) - return nil - }, - Annotations: map[string]string{"version": "1.25"}, - ValidArgsFunction: completion.NoComplete, - } - - flags := cmd.Flags() - flags.BoolVarP(&options.force, "force", "f", false, "Do not prompt for confirmation") - flags.Var(&options.filter, "filter", `Provide filter values (e.g. "until=")`) - - return cmd -} - -const warning = `WARNING! This will remove all stopped containers. -Are you sure you want to continue?` - -func runPrune(dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint64, output string, err error) { - pruneFilters := command.PruneFilters(dockerCli, options.filter.Value()) - - if !options.force && !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), warning) { - return 0, "", nil - } - - report, err := dockerCli.Client().ContainersPrune(context.Background(), pruneFilters) - if err != nil { - return 0, "", err - } - - if len(report.ContainersDeleted) > 0 { - output = "Deleted Containers:\n" - for _, id := range report.ContainersDeleted { - output += id + "\n" - } - spaceReclaimed = report.SpaceReclaimed - } - - return spaceReclaimed, output, nil -} - -// RunPrune calls the Container Prune API -// This returns the amount of space reclaimed and a detailed output string -func RunPrune(dockerCli command.Cli, _ bool, filter opts.FilterOpt) (uint64, string, error) { - return runPrune(dockerCli, pruneOptions{force: true, filter: filter}) -} diff --git a/vendor/github.com/docker/cli/cli/command/container/rename.go b/vendor/github.com/docker/cli/cli/command/container/rename.go deleted file mode 100644 index faed72b51..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/rename.go +++ /dev/null @@ -1,56 +0,0 @@ -package container - -import ( - "context" - "fmt" - "strings" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/pkg/errors" - "github.com/spf13/cobra" -) - -type renameOptions struct { - oldName string - newName string -} - -// NewRenameCommand creates a new cobra.Command for `docker rename` -func NewRenameCommand(dockerCli command.Cli) *cobra.Command { - var opts renameOptions - - cmd := &cobra.Command{ - Use: "rename CONTAINER NEW_NAME", - Short: "Rename a container", - Args: cli.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - opts.oldName = args[0] - opts.newName = args[1] - return runRename(dockerCli, &opts) - }, - Annotations: map[string]string{ - "aliases": "docker container rename, docker rename", - }, - ValidArgsFunction: completion.ContainerNames(dockerCli, true), - } - return cmd -} - -func runRename(dockerCli command.Cli, opts *renameOptions) error { - ctx := context.Background() - - oldName := strings.TrimSpace(opts.oldName) - newName := strings.TrimSpace(opts.newName) - - if oldName == "" || newName == "" { - return errors.New("Error: Neither old nor new names may be empty") - } - - if err := dockerCli.Client().ContainerRename(ctx, oldName, newName); err != nil { - fmt.Fprintln(dockerCli.Err(), err) - return errors.Errorf("Error: failed to rename container named %s", oldName) - } - return nil -} diff --git a/vendor/github.com/docker/cli/cli/command/container/restart.go b/vendor/github.com/docker/cli/cli/command/container/restart.go deleted file mode 100644 index ce22b2c27..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/restart.go +++ /dev/null @@ -1,71 +0,0 @@ -package container - -import ( - "context" - "fmt" - "strings" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/docker/docker/api/types/container" - "github.com/pkg/errors" - "github.com/spf13/cobra" -) - -type restartOptions struct { - signal string - timeout int - timeoutChanged bool - - containers []string -} - -// NewRestartCommand creates a new cobra.Command for `docker restart` -func NewRestartCommand(dockerCli command.Cli) *cobra.Command { - var opts restartOptions - - cmd := &cobra.Command{ - Use: "restart [OPTIONS] CONTAINER [CONTAINER...]", - Short: "Restart one or more containers", - Args: cli.RequiresMinArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - opts.containers = args - opts.timeoutChanged = cmd.Flags().Changed("time") - return runRestart(dockerCli, &opts) - }, - Annotations: map[string]string{ - "aliases": "docker container restart, docker restart", - }, - ValidArgsFunction: completion.ContainerNames(dockerCli, true), - } - - flags := cmd.Flags() - flags.StringVarP(&opts.signal, "signal", "s", "", "Signal to send to the container") - flags.IntVarP(&opts.timeout, "time", "t", 0, "Seconds to wait before killing the container") - return cmd -} - -func runRestart(dockerCli command.Cli, opts *restartOptions) error { - ctx := context.Background() - var errs []string - var timeout *int - if opts.timeoutChanged { - timeout = &opts.timeout - } - for _, name := range opts.containers { - err := dockerCli.Client().ContainerRestart(ctx, name, container.StopOptions{ - Signal: opts.signal, - Timeout: timeout, - }) - if err != nil { - errs = append(errs, err.Error()) - continue - } - _, _ = fmt.Fprintln(dockerCli.Out(), name) - } - if len(errs) > 0 { - return errors.New(strings.Join(errs, "\n")) - } - return nil -} diff --git a/vendor/github.com/docker/cli/cli/command/container/rm.go b/vendor/github.com/docker/cli/cli/command/container/rm.go deleted file mode 100644 index 70a78e84f..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/rm.go +++ /dev/null @@ -1,84 +0,0 @@ -package container - -import ( - "context" - "fmt" - "strings" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/docker/docker/api/types" - "github.com/docker/docker/errdefs" - "github.com/pkg/errors" - "github.com/spf13/cobra" -) - -type rmOptions struct { - rmVolumes bool - rmLink bool - force bool - - containers []string -} - -// NewRmCommand creates a new cobra.Command for `docker rm` -func NewRmCommand(dockerCli command.Cli) *cobra.Command { - var opts rmOptions - - cmd := &cobra.Command{ - Use: "rm [OPTIONS] CONTAINER [CONTAINER...]", - Aliases: []string{"remove"}, - Short: "Remove one or more containers", - Args: cli.RequiresMinArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - opts.containers = args - return runRm(dockerCli, &opts) - }, - Annotations: map[string]string{ - "aliases": "docker container rm, docker container remove, docker rm", - }, - ValidArgsFunction: completion.ContainerNames(dockerCli, true), - } - - flags := cmd.Flags() - flags.BoolVarP(&opts.rmVolumes, "volumes", "v", false, "Remove anonymous volumes associated with the container") - flags.BoolVarP(&opts.rmLink, "link", "l", false, "Remove the specified link") - flags.BoolVarP(&opts.force, "force", "f", false, "Force the removal of a running container (uses SIGKILL)") - return cmd -} - -func runRm(dockerCli command.Cli, opts *rmOptions) error { - ctx := context.Background() - - var errs []string - options := types.ContainerRemoveOptions{ - RemoveVolumes: opts.rmVolumes, - RemoveLinks: opts.rmLink, - Force: opts.force, - } - - errChan := parallelOperation(ctx, opts.containers, func(ctx context.Context, container string) error { - container = strings.Trim(container, "/") - if container == "" { - return errors.New("Container name cannot be empty") - } - return dockerCli.Client().ContainerRemove(ctx, container, options) - }) - - for _, name := range opts.containers { - if err := <-errChan; err != nil { - if opts.force && errdefs.IsNotFound(err) { - fmt.Fprintln(dockerCli.Err(), err) - continue - } - errs = append(errs, err.Error()) - continue - } - fmt.Fprintln(dockerCli.Out(), name) - } - if len(errs) > 0 { - return errors.New(strings.Join(errs, "\n")) - } - return nil -} diff --git a/vendor/github.com/docker/cli/cli/command/container/run.go b/vendor/github.com/docker/cli/cli/command/container/run.go deleted file mode 100644 index c7e680e76..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/run.go +++ /dev/null @@ -1,317 +0,0 @@ -package container - -import ( - "context" - "fmt" - "io" - "os" - "strings" - "syscall" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/docker/cli/opts" - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/container" - "github.com/moby/sys/signal" - "github.com/moby/term" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" - "github.com/spf13/cobra" - "github.com/spf13/pflag" -) - -type runOptions struct { - createOptions - detach bool - sigProxy bool - detachKeys string -} - -// NewRunCommand create a new `docker run` command -func NewRunCommand(dockerCli command.Cli) *cobra.Command { - var options runOptions - var copts *containerOptions - - cmd := &cobra.Command{ - Use: "run [OPTIONS] IMAGE [COMMAND] [ARG...]", - Short: "Create and run a new container from an image", - Args: cli.RequiresMinArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - copts.Image = args[0] - if len(args) > 1 { - copts.Args = args[1:] - } - return runRun(dockerCli, cmd.Flags(), &options, copts) - }, - ValidArgsFunction: completion.ImageNames(dockerCli), - Annotations: map[string]string{ - "category-top": "1", - "aliases": "docker container run, docker run", - }, - } - - flags := cmd.Flags() - flags.SetInterspersed(false) - - // These are flags not stored in Config/HostConfig - flags.BoolVarP(&options.detach, "detach", "d", false, "Run container in background and print container ID") - flags.BoolVar(&options.sigProxy, "sig-proxy", true, "Proxy received signals to the process") - flags.StringVar(&options.name, "name", "", "Assign a name to the container") - flags.StringVar(&options.detachKeys, "detach-keys", "", "Override the key sequence for detaching a container") - flags.StringVar(&options.pull, "pull", PullImageMissing, `Pull image before running ("`+PullImageAlways+`", "`+PullImageMissing+`", "`+PullImageNever+`")`) - flags.BoolVarP(&options.quiet, "quiet", "q", false, "Suppress the pull output") - - // Add an explicit help that doesn't have a `-h` to prevent the conflict - // with hostname - flags.Bool("help", false, "Print usage") - - command.AddPlatformFlag(flags, &options.platform) - command.AddTrustVerificationFlags(flags, &options.untrusted, dockerCli.ContentTrustEnabled()) - copts = addFlags(flags) - - cmd.RegisterFlagCompletionFunc( - "env", - func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return os.Environ(), cobra.ShellCompDirectiveNoFileComp - }, - ) - cmd.RegisterFlagCompletionFunc( - "env-file", - func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return nil, cobra.ShellCompDirectiveDefault - }, - ) - cmd.RegisterFlagCompletionFunc( - "network", - completion.NetworkNames(dockerCli), - ) - return cmd -} - -func runRun(dockerCli command.Cli, flags *pflag.FlagSet, ropts *runOptions, copts *containerOptions) error { - if err := validatePullOpt(ropts.pull); err != nil { - reportError(dockerCli.Err(), "run", err.Error(), true) - return cli.StatusError{StatusCode: 125} - } - proxyConfig := dockerCli.ConfigFile().ParseProxyConfig(dockerCli.Client().DaemonHost(), opts.ConvertKVStringsToMapWithNil(copts.env.GetAll())) - newEnv := []string{} - for k, v := range proxyConfig { - if v == nil { - newEnv = append(newEnv, k) - } else { - newEnv = append(newEnv, fmt.Sprintf("%s=%s", k, *v)) - } - } - copts.env = *opts.NewListOptsRef(&newEnv, nil) - containerCfg, err := parse(flags, copts, dockerCli.ServerInfo().OSType) - // just in case the parse does not exit - if err != nil { - reportError(dockerCli.Err(), "run", err.Error(), true) - return cli.StatusError{StatusCode: 125} - } - if err = validateAPIVersion(containerCfg, dockerCli.CurrentVersion()); err != nil { - reportError(dockerCli.Err(), "run", err.Error(), true) - return cli.StatusError{StatusCode: 125} - } - return runContainer(dockerCli, ropts, copts, containerCfg) -} - -//nolint:gocyclo -func runContainer(dockerCli command.Cli, opts *runOptions, copts *containerOptions, containerCfg *containerConfig) error { - config := containerCfg.Config - stdout, stderr := dockerCli.Out(), dockerCli.Err() - client := dockerCli.Client() - - config.ArgsEscaped = false - - if !opts.detach { - if err := dockerCli.In().CheckTty(config.AttachStdin, config.Tty); err != nil { - return err - } - } else { - if copts.attach.Len() != 0 { - return errors.New("Conflicting options: -a and -d") - } - - config.AttachStdin = false - config.AttachStdout = false - config.AttachStderr = false - config.StdinOnce = false - } - - ctx, cancelFun := context.WithCancel(context.Background()) - defer cancelFun() - - createResponse, err := createContainer(ctx, dockerCli, containerCfg, &opts.createOptions) - if err != nil { - reportError(stderr, "run", err.Error(), true) - return runStartContainerErr(err) - } - if opts.sigProxy { - sigc := notifyAllSignals() - go ForwardAllSignals(ctx, dockerCli, createResponse.ID, sigc) - defer signal.StopCatch(sigc) - } - - var ( - waitDisplayID chan struct{} - errCh chan error - ) - if !config.AttachStdout && !config.AttachStderr { - // Make this asynchronous to allow the client to write to stdin before having to read the ID - waitDisplayID = make(chan struct{}) - go func() { - defer close(waitDisplayID) - fmt.Fprintln(stdout, createResponse.ID) - }() - } - attach := config.AttachStdin || config.AttachStdout || config.AttachStderr - if attach { - if opts.detachKeys != "" { - dockerCli.ConfigFile().DetachKeys = opts.detachKeys - } - - closeFn, err := attachContainer(ctx, dockerCli, &errCh, config, createResponse.ID) - if err != nil { - return err - } - defer closeFn() - } - - statusChan := waitExitOrRemoved(ctx, dockerCli, createResponse.ID, copts.autoRemove) - - // start the container - if err := client.ContainerStart(ctx, createResponse.ID, types.ContainerStartOptions{}); err != nil { - // If we have hijackedIOStreamer, we should notify - // hijackedIOStreamer we are going to exit and wait - // to avoid the terminal are not restored. - if attach { - cancelFun() - <-errCh - } - - reportError(stderr, "run", err.Error(), false) - if copts.autoRemove { - // wait container to be removed - <-statusChan - } - return runStartContainerErr(err) - } - - if (config.AttachStdin || config.AttachStdout || config.AttachStderr) && config.Tty && dockerCli.Out().IsTerminal() { - if err := MonitorTtySize(ctx, dockerCli, createResponse.ID, false); err != nil { - fmt.Fprintln(stderr, "Error monitoring TTY size:", err) - } - } - - if errCh != nil { - if err := <-errCh; err != nil { - if _, ok := err.(term.EscapeError); ok { - // The user entered the detach escape sequence. - return nil - } - - logrus.Debugf("Error hijack: %s", err) - return err - } - } - - // Detached mode: wait for the id to be displayed and return. - if !config.AttachStdout && !config.AttachStderr { - // Detached mode - <-waitDisplayID - return nil - } - - status := <-statusChan - if status != 0 { - return cli.StatusError{StatusCode: status} - } - return nil -} - -func attachContainer(ctx context.Context, dockerCli command.Cli, errCh *chan error, config *container.Config, containerID string) (func(), error) { - options := types.ContainerAttachOptions{ - Stream: true, - Stdin: config.AttachStdin, - Stdout: config.AttachStdout, - Stderr: config.AttachStderr, - DetachKeys: dockerCli.ConfigFile().DetachKeys, - } - - resp, errAttach := dockerCli.Client().ContainerAttach(ctx, containerID, options) - if errAttach != nil { - return nil, errAttach - } - - var ( - out, cerr io.Writer - in io.ReadCloser - ) - if config.AttachStdin { - in = dockerCli.In() - } - if config.AttachStdout { - out = dockerCli.Out() - } - if config.AttachStderr { - if config.Tty { - cerr = dockerCli.Out() - } else { - cerr = dockerCli.Err() - } - } - - ch := make(chan error, 1) - *errCh = ch - - go func() { - ch <- func() error { - streamer := hijackedIOStreamer{ - streams: dockerCli, - inputStream: in, - outputStream: out, - errorStream: cerr, - resp: resp, - tty: config.Tty, - detachKeys: options.DetachKeys, - } - - if errHijack := streamer.stream(ctx); errHijack != nil { - return errHijack - } - return errAttach - }() - }() - return resp.Close, nil -} - -// reportError is a utility method that prints a user-friendly message -// containing the error that occurred during parsing and a suggestion to get help -func reportError(stderr io.Writer, name string, str string, withHelp bool) { - str = strings.TrimSuffix(str, ".") + "." - if withHelp { - str += "\nSee 'docker " + name + " --help'." - } - _, _ = fmt.Fprintln(stderr, "docker:", str) -} - -// if container start fails with 'not found'/'no such' error, return 127 -// if container start fails with 'permission denied' error, return 126 -// return 125 for generic docker daemon failures -func runStartContainerErr(err error) error { - trimmedErr := strings.TrimPrefix(err.Error(), "Error response from daemon: ") - statusError := cli.StatusError{StatusCode: 125} - if strings.Contains(trimmedErr, "executable file not found") || - strings.Contains(trimmedErr, "no such file or directory") || - strings.Contains(trimmedErr, "system cannot find the file specified") { - statusError = cli.StatusError{StatusCode: 127} - } else if strings.Contains(trimmedErr, syscall.EACCES.Error()) || - strings.Contains(trimmedErr, syscall.EISDIR.Error()) { - statusError = cli.StatusError{StatusCode: 126} - } - - return statusError -} diff --git a/vendor/github.com/docker/cli/cli/command/container/signals.go b/vendor/github.com/docker/cli/cli/command/container/signals.go deleted file mode 100644 index b8b746df5..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/signals.go +++ /dev/null @@ -1,61 +0,0 @@ -package container - -import ( - "context" - "os" - gosignal "os/signal" - - "github.com/docker/cli/cli/command" - "github.com/moby/sys/signal" - "github.com/sirupsen/logrus" -) - -// ForwardAllSignals forwards signals to the container -// -// The channel you pass in must already be setup to receive any signals you want to forward. -func ForwardAllSignals(ctx context.Context, cli command.Cli, cid string, sigc <-chan os.Signal) { - var ( - s os.Signal - ok bool - ) - for { - select { - case s, ok = <-sigc: - if !ok { - return - } - case <-ctx.Done(): - return - } - - if s == signal.SIGCHLD || s == signal.SIGPIPE { - continue - } - - // In go1.14+, the go runtime issues SIGURG as an interrupt to support pre-emptable system calls on Linux. - // Since we can't forward that along we'll check that here. - if isRuntimeSig(s) { - continue - } - var sig string - for sigStr, sigN := range signal.SignalMap { - if sigN == s { - sig = sigStr - break - } - } - if sig == "" { - continue - } - - if err := cli.Client().ContainerKill(ctx, cid, sig); err != nil { - logrus.Debugf("Error sending signal: %s", err) - } - } -} - -func notifyAllSignals() chan os.Signal { - sigc := make(chan os.Signal, 128) - gosignal.Notify(sigc) - return sigc -} diff --git a/vendor/github.com/docker/cli/cli/command/container/signals_unix.go b/vendor/github.com/docker/cli/cli/command/container/signals_unix.go deleted file mode 100644 index 757abbf16..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/signals_unix.go +++ /dev/null @@ -1,14 +0,0 @@ -//go:build !windows -// +build !windows - -package container - -import ( - "os" - - "golang.org/x/sys/unix" -) - -func isRuntimeSig(s os.Signal) bool { - return s == unix.SIGURG -} diff --git a/vendor/github.com/docker/cli/cli/command/container/signals_windows.go b/vendor/github.com/docker/cli/cli/command/container/signals_windows.go deleted file mode 100644 index 1e51b952f..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/signals_windows.go +++ /dev/null @@ -1,7 +0,0 @@ -package container - -import "os" - -func isRuntimeSig(_ os.Signal) bool { - return false -} diff --git a/vendor/github.com/docker/cli/cli/command/container/start.go b/vendor/github.com/docker/cli/cli/command/container/start.go deleted file mode 100644 index 9a8a083e6..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/start.go +++ /dev/null @@ -1,214 +0,0 @@ -package container - -import ( - "context" - "fmt" - "io" - "strings" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/docker/docker/api/types" - "github.com/moby/sys/signal" - "github.com/moby/term" - "github.com/pkg/errors" - "github.com/spf13/cobra" -) - -// StartOptions group options for `start` command -type StartOptions struct { - Attach bool - OpenStdin bool - DetachKeys string - Checkpoint string - CheckpointDir string - - Containers []string -} - -// NewStartOptions creates a new StartOptions -func NewStartOptions() StartOptions { - return StartOptions{} -} - -// NewStartCommand creates a new cobra.Command for `docker start` -func NewStartCommand(dockerCli command.Cli) *cobra.Command { - var opts StartOptions - - cmd := &cobra.Command{ - Use: "start [OPTIONS] CONTAINER [CONTAINER...]", - Short: "Start one or more stopped containers", - Args: cli.RequiresMinArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - opts.Containers = args - return RunStart(dockerCli, &opts) - }, - Annotations: map[string]string{ - "aliases": "docker container start, docker start", - }, - ValidArgsFunction: completion.ContainerNames(dockerCli, true, func(container types.Container) bool { - return container.State == "exited" || container.State == "created" - }), - } - - flags := cmd.Flags() - flags.BoolVarP(&opts.Attach, "attach", "a", false, "Attach STDOUT/STDERR and forward signals") - flags.BoolVarP(&opts.OpenStdin, "interactive", "i", false, "Attach container's STDIN") - flags.StringVar(&opts.DetachKeys, "detach-keys", "", "Override the key sequence for detaching a container") - - flags.StringVar(&opts.Checkpoint, "checkpoint", "", "Restore from this checkpoint") - flags.SetAnnotation("checkpoint", "experimental", nil) - flags.SetAnnotation("checkpoint", "ostype", []string{"linux"}) - flags.StringVar(&opts.CheckpointDir, "checkpoint-dir", "", "Use a custom checkpoint storage directory") - flags.SetAnnotation("checkpoint-dir", "experimental", nil) - flags.SetAnnotation("checkpoint-dir", "ostype", []string{"linux"}) - return cmd -} - -// RunStart executes a `start` command -// -//nolint:gocyclo -func RunStart(dockerCli command.Cli, opts *StartOptions) error { - ctx, cancelFun := context.WithCancel(context.Background()) - defer cancelFun() - - if opts.Attach || opts.OpenStdin { - // We're going to attach to a container. - // 1. Ensure we only have one container. - if len(opts.Containers) > 1 { - return errors.New("you cannot start and attach multiple containers at once") - } - - // 2. Attach to the container. - container := opts.Containers[0] - c, err := dockerCli.Client().ContainerInspect(ctx, container) - if err != nil { - return err - } - - // We always use c.ID instead of container to maintain consistency during `docker start` - if !c.Config.Tty { - sigc := notifyAllSignals() - go ForwardAllSignals(ctx, dockerCli, c.ID, sigc) - defer signal.StopCatch(sigc) - } - - if opts.DetachKeys != "" { - dockerCli.ConfigFile().DetachKeys = opts.DetachKeys - } - - options := types.ContainerAttachOptions{ - Stream: true, - Stdin: opts.OpenStdin && c.Config.OpenStdin, - Stdout: true, - Stderr: true, - DetachKeys: dockerCli.ConfigFile().DetachKeys, - } - - var in io.ReadCloser - - if options.Stdin { - in = dockerCli.In() - } - - resp, errAttach := dockerCli.Client().ContainerAttach(ctx, c.ID, options) - if errAttach != nil { - return errAttach - } - defer resp.Close() - - cErr := make(chan error, 1) - - go func() { - cErr <- func() error { - streamer := hijackedIOStreamer{ - streams: dockerCli, - inputStream: in, - outputStream: dockerCli.Out(), - errorStream: dockerCli.Err(), - resp: resp, - tty: c.Config.Tty, - detachKeys: options.DetachKeys, - } - - errHijack := streamer.stream(ctx) - if errHijack == nil { - return errAttach - } - return errHijack - }() - }() - - // 3. We should open a channel for receiving status code of the container - // no matter it's detached, removed on daemon side(--rm) or exit normally. - statusChan := waitExitOrRemoved(ctx, dockerCli, c.ID, c.HostConfig.AutoRemove) - startOptions := types.ContainerStartOptions{ - CheckpointID: opts.Checkpoint, - CheckpointDir: opts.CheckpointDir, - } - - // 4. Start the container. - if err := dockerCli.Client().ContainerStart(ctx, c.ID, startOptions); err != nil { - cancelFun() - <-cErr - if c.HostConfig.AutoRemove { - // wait container to be removed - <-statusChan - } - return err - } - - // 5. Wait for attachment to break. - if c.Config.Tty && dockerCli.Out().IsTerminal() { - if err := MonitorTtySize(ctx, dockerCli, c.ID, false); err != nil { - fmt.Fprintln(dockerCli.Err(), "Error monitoring TTY size:", err) - } - } - if attachErr := <-cErr; attachErr != nil { - if _, ok := attachErr.(term.EscapeError); ok { - // The user entered the detach escape sequence. - return nil - } - return attachErr - } - - if status := <-statusChan; status != 0 { - return cli.StatusError{StatusCode: status} - } - } else if opts.Checkpoint != "" { - if len(opts.Containers) > 1 { - return errors.New("you cannot restore multiple containers at once") - } - container := opts.Containers[0] - startOptions := types.ContainerStartOptions{ - CheckpointID: opts.Checkpoint, - CheckpointDir: opts.CheckpointDir, - } - return dockerCli.Client().ContainerStart(ctx, container, startOptions) - - } else { - // We're not going to attach to anything. - // Start as many containers as we want. - return startContainersWithoutAttachments(ctx, dockerCli, opts.Containers) - } - - return nil -} - -func startContainersWithoutAttachments(ctx context.Context, dockerCli command.Cli, containers []string) error { - var failedContainers []string - for _, container := range containers { - if err := dockerCli.Client().ContainerStart(ctx, container, types.ContainerStartOptions{}); err != nil { - fmt.Fprintln(dockerCli.Err(), err) - failedContainers = append(failedContainers, container) - continue - } - fmt.Fprintln(dockerCli.Out(), container) - } - - if len(failedContainers) > 0 { - return errors.Errorf("Error: failed to start containers: %s", strings.Join(failedContainers, ", ")) - } - return nil -} diff --git a/vendor/github.com/docker/cli/cli/command/container/stats.go b/vendor/github.com/docker/cli/cli/command/container/stats.go deleted file mode 100644 index c0c4f0e0e..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/stats.go +++ /dev/null @@ -1,259 +0,0 @@ -package container - -import ( - "context" - "fmt" - "io" - "strings" - "sync" - "time" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/docker/cli/cli/command/formatter" - flagsHelper "github.com/docker/cli/cli/flags" - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/events" - "github.com/docker/docker/api/types/filters" - "github.com/pkg/errors" - "github.com/spf13/cobra" -) - -type statsOptions struct { - all bool - noStream bool - noTrunc bool - format string - containers []string -} - -// NewStatsCommand creates a new cobra.Command for `docker stats` -func NewStatsCommand(dockerCli command.Cli) *cobra.Command { - var opts statsOptions - - cmd := &cobra.Command{ - Use: "stats [OPTIONS] [CONTAINER...]", - Short: "Display a live stream of container(s) resource usage statistics", - Args: cli.RequiresMinArgs(0), - RunE: func(cmd *cobra.Command, args []string) error { - opts.containers = args - return runStats(dockerCli, &opts) - }, - Annotations: map[string]string{ - "aliases": "docker container stats, docker stats", - }, - ValidArgsFunction: completion.ContainerNames(dockerCli, false), - } - - flags := cmd.Flags() - flags.BoolVarP(&opts.all, "all", "a", false, "Show all containers (default shows just running)") - flags.BoolVar(&opts.noStream, "no-stream", false, "Disable streaming stats and only pull the first result") - flags.BoolVar(&opts.noTrunc, "no-trunc", false, "Do not truncate output") - flags.StringVar(&opts.format, "format", "", flagsHelper.FormatHelp) - return cmd -} - -// runStats displays a live stream of resource usage statistics for one or more containers. -// This shows real-time information on CPU usage, memory usage, and network I/O. -// -//nolint:gocyclo -func runStats(dockerCli command.Cli, opts *statsOptions) error { - showAll := len(opts.containers) == 0 - closeChan := make(chan error) - - ctx := context.Background() - - // monitorContainerEvents watches for container creation and removal (only - // used when calling `docker stats` without arguments). - monitorContainerEvents := func(started chan<- struct{}, c chan events.Message, stopped <-chan struct{}) { - f := filters.NewArgs() - f.Add("type", "container") - options := types.EventsOptions{ - Filters: f, - } - - eventq, errq := dockerCli.Client().Events(ctx, options) - - // Whether we successfully subscribed to eventq or not, we can now - // unblock the main goroutine. - close(started) - defer close(c) - - for { - select { - case <-stopped: - return - case event := <-eventq: - c <- event - case err := <-errq: - closeChan <- err - return - } - } - } - - // Get the daemonOSType if not set already - if daemonOSType == "" { - svctx := context.Background() - sv, err := dockerCli.Client().ServerVersion(svctx) - if err != nil { - return err - } - daemonOSType = sv.Os - } - - // waitFirst is a WaitGroup to wait first stat data's reach for each container - waitFirst := &sync.WaitGroup{} - - cStats := stats{} - // getContainerList simulates creation event for all previously existing - // containers (only used when calling `docker stats` without arguments). - getContainerList := func() { - options := types.ContainerListOptions{ - All: opts.all, - } - cs, err := dockerCli.Client().ContainerList(ctx, options) - if err != nil { - closeChan <- err - } - for _, container := range cs { - s := NewStats(container.ID[:12]) - if cStats.add(s) { - waitFirst.Add(1) - go collect(ctx, s, dockerCli.Client(), !opts.noStream, waitFirst) - } - } - } - - if showAll { - // If no names were specified, start a long running goroutine which - // monitors container events. We make sure we're subscribed before - // retrieving the list of running containers to avoid a race where we - // would "miss" a creation. - started := make(chan struct{}) - eh := command.InitEventHandler() - eh.Handle("create", func(e events.Message) { - if opts.all { - s := NewStats(e.ID[:12]) - if cStats.add(s) { - waitFirst.Add(1) - go collect(ctx, s, dockerCli.Client(), !opts.noStream, waitFirst) - } - } - }) - - eh.Handle("start", func(e events.Message) { - s := NewStats(e.ID[:12]) - if cStats.add(s) { - waitFirst.Add(1) - go collect(ctx, s, dockerCli.Client(), !opts.noStream, waitFirst) - } - }) - - eh.Handle("die", func(e events.Message) { - if !opts.all { - cStats.remove(e.ID[:12]) - } - }) - - eventChan := make(chan events.Message) - go eh.Watch(eventChan) - stopped := make(chan struct{}) - go monitorContainerEvents(started, eventChan, stopped) - defer close(stopped) - <-started - - // Start a short-lived goroutine to retrieve the initial list of - // containers. - getContainerList() - - // make sure each container get at least one valid stat data - waitFirst.Wait() - } else { - // Artificially send creation events for the containers we were asked to - // monitor (same code path than we use when monitoring all containers). - for _, name := range opts.containers { - s := NewStats(name) - if cStats.add(s) { - waitFirst.Add(1) - go collect(ctx, s, dockerCli.Client(), !opts.noStream, waitFirst) - } - } - - // We don't expect any asynchronous errors: closeChan can be closed. - close(closeChan) - - // make sure each container get at least one valid stat data - waitFirst.Wait() - - var errs []string - cStats.mu.RLock() - for _, c := range cStats.cs { - if err := c.GetError(); err != nil { - errs = append(errs, err.Error()) - } - } - cStats.mu.RUnlock() - if len(errs) > 0 { - return errors.New(strings.Join(errs, "\n")) - } - } - - format := opts.format - if len(format) == 0 { - if len(dockerCli.ConfigFile().StatsFormat) > 0 { - format = dockerCli.ConfigFile().StatsFormat - } else { - format = formatter.TableFormatKey - } - } - statsCtx := formatter.Context{ - Output: dockerCli.Out(), - Format: NewStatsFormat(format, daemonOSType), - } - cleanScreen := func() { - if !opts.noStream { - fmt.Fprint(dockerCli.Out(), "\033[2J") - fmt.Fprint(dockerCli.Out(), "\033[H") - } - } - - var err error - ticker := time.NewTicker(500 * time.Millisecond) - defer ticker.Stop() - for range ticker.C { - cleanScreen() - ccstats := []StatsEntry{} - cStats.mu.RLock() - for _, c := range cStats.cs { - ccstats = append(ccstats, c.GetStatistics()) - } - cStats.mu.RUnlock() - if err = statsFormatWrite(statsCtx, ccstats, daemonOSType, !opts.noTrunc); err != nil { - break - } - if len(cStats.cs) == 0 && !showAll { - break - } - if opts.noStream { - break - } - select { - case err, ok := <-closeChan: - if ok { - if err != nil { - // this is suppressing "unexpected EOF" in the cli when the - // daemon restarts so it shutdowns cleanly - if err == io.ErrUnexpectedEOF { - return nil - } - return err - } - } - default: - // just skip - } - } - return err -} diff --git a/vendor/github.com/docker/cli/cli/command/container/stats_helpers.go b/vendor/github.com/docker/cli/cli/command/container/stats_helpers.go deleted file mode 100644 index 5ea7f665d..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/stats_helpers.go +++ /dev/null @@ -1,258 +0,0 @@ -package container - -import ( - "context" - "encoding/json" - "io" - "sync" - "time" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/client" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" -) - -type stats struct { - mu sync.RWMutex - cs []*Stats -} - -// daemonOSType is set once we have at least one stat for a container -// from the daemon. It is used to ensure we print the right header based -// on the daemon platform. -var daemonOSType string - -func (s *stats) add(cs *Stats) bool { - s.mu.Lock() - defer s.mu.Unlock() - if _, exists := s.isKnownContainer(cs.Container); !exists { - s.cs = append(s.cs, cs) - return true - } - return false -} - -func (s *stats) remove(id string) { - s.mu.Lock() - if i, exists := s.isKnownContainer(id); exists { - s.cs = append(s.cs[:i], s.cs[i+1:]...) - } - s.mu.Unlock() -} - -func (s *stats) isKnownContainer(cid string) (int, bool) { - for i, c := range s.cs { - if c.Container == cid { - return i, true - } - } - return -1, false -} - -func collect(ctx context.Context, s *Stats, cli client.APIClient, streamStats bool, waitFirst *sync.WaitGroup) { - logrus.Debugf("collecting stats for %s", s.Container) - var ( - getFirst bool - previousCPU uint64 - previousSystem uint64 - u = make(chan error, 1) - ) - - defer func() { - // if error happens and we get nothing of stats, release wait group whatever - if !getFirst { - getFirst = true - waitFirst.Done() - } - }() - - response, err := cli.ContainerStats(ctx, s.Container, streamStats) - if err != nil { - s.SetError(err) - return - } - defer response.Body.Close() - - dec := json.NewDecoder(response.Body) - go func() { - for { - var ( - v *types.StatsJSON - memPercent, cpuPercent float64 - blkRead, blkWrite uint64 // Only used on Linux - mem, memLimit float64 - pidsStatsCurrent uint64 - ) - - if err := dec.Decode(&v); err != nil { - dec = json.NewDecoder(io.MultiReader(dec.Buffered(), response.Body)) - u <- err - if err == io.EOF { - break - } - time.Sleep(100 * time.Millisecond) - continue - } - - daemonOSType = response.OSType - - if daemonOSType != "windows" { - previousCPU = v.PreCPUStats.CPUUsage.TotalUsage - previousSystem = v.PreCPUStats.SystemUsage - cpuPercent = calculateCPUPercentUnix(previousCPU, previousSystem, v) - blkRead, blkWrite = calculateBlockIO(v.BlkioStats) - mem = calculateMemUsageUnixNoCache(v.MemoryStats) - memLimit = float64(v.MemoryStats.Limit) - memPercent = calculateMemPercentUnixNoCache(memLimit, mem) - pidsStatsCurrent = v.PidsStats.Current - } else { - cpuPercent = calculateCPUPercentWindows(v) - blkRead = v.StorageStats.ReadSizeBytes - blkWrite = v.StorageStats.WriteSizeBytes - mem = float64(v.MemoryStats.PrivateWorkingSet) - } - netRx, netTx := calculateNetwork(v.Networks) - s.SetStatistics(StatsEntry{ - Name: v.Name, - ID: v.ID, - CPUPercentage: cpuPercent, - Memory: mem, - MemoryPercentage: memPercent, - MemoryLimit: memLimit, - NetworkRx: netRx, - NetworkTx: netTx, - BlockRead: float64(blkRead), - BlockWrite: float64(blkWrite), - PidsCurrent: pidsStatsCurrent, - }) - u <- nil - if !streamStats { - return - } - } - }() - for { - select { - case <-time.After(2 * time.Second): - // zero out the values if we have not received an update within - // the specified duration. - s.SetErrorAndReset(errors.New("timeout waiting for stats")) - // if this is the first stat you get, release WaitGroup - if !getFirst { - getFirst = true - waitFirst.Done() - } - case err := <-u: - s.SetError(err) - if err == io.EOF { - break - } - if err != nil { - continue - } - // if this is the first stat you get, release WaitGroup - if !getFirst { - getFirst = true - waitFirst.Done() - } - } - if !streamStats { - return - } - } -} - -func calculateCPUPercentUnix(previousCPU, previousSystem uint64, v *types.StatsJSON) float64 { - var ( - cpuPercent = 0.0 - // calculate the change for the cpu usage of the container in between readings - cpuDelta = float64(v.CPUStats.CPUUsage.TotalUsage) - float64(previousCPU) - // calculate the change for the entire system between readings - systemDelta = float64(v.CPUStats.SystemUsage) - float64(previousSystem) - onlineCPUs = float64(v.CPUStats.OnlineCPUs) - ) - - if onlineCPUs == 0.0 { - onlineCPUs = float64(len(v.CPUStats.CPUUsage.PercpuUsage)) - } - if systemDelta > 0.0 && cpuDelta > 0.0 { - cpuPercent = (cpuDelta / systemDelta) * onlineCPUs * 100.0 - } - return cpuPercent -} - -func calculateCPUPercentWindows(v *types.StatsJSON) float64 { - // Max number of 100ns intervals between the previous time read and now - possIntervals := uint64(v.Read.Sub(v.PreRead).Nanoseconds()) // Start with number of ns intervals - possIntervals /= 100 // Convert to number of 100ns intervals - possIntervals *= uint64(v.NumProcs) // Multiple by the number of processors - - // Intervals used - intervalsUsed := v.CPUStats.CPUUsage.TotalUsage - v.PreCPUStats.CPUUsage.TotalUsage - - // Percentage avoiding divide-by-zero - if possIntervals > 0 { - return float64(intervalsUsed) / float64(possIntervals) * 100.0 - } - return 0.00 -} - -func calculateBlockIO(blkio types.BlkioStats) (uint64, uint64) { - var blkRead, blkWrite uint64 - for _, bioEntry := range blkio.IoServiceBytesRecursive { - if len(bioEntry.Op) == 0 { - continue - } - switch bioEntry.Op[0] { - case 'r', 'R': - blkRead = blkRead + bioEntry.Value - case 'w', 'W': - blkWrite = blkWrite + bioEntry.Value - } - } - return blkRead, blkWrite -} - -func calculateNetwork(network map[string]types.NetworkStats) (float64, float64) { - var rx, tx float64 - - for _, v := range network { - rx += float64(v.RxBytes) - tx += float64(v.TxBytes) - } - return rx, tx -} - -// calculateMemUsageUnixNoCache calculate memory usage of the container. -// Cache is intentionally excluded to avoid misinterpretation of the output. -// -// On cgroup v1 host, the result is `mem.Usage - mem.Stats["total_inactive_file"]` . -// On cgroup v2 host, the result is `mem.Usage - mem.Stats["inactive_file"] `. -// -// This definition is consistent with cadvisor and containerd/CRI. -// * https://github.com/google/cadvisor/commit/307d1b1cb320fef66fab02db749f07a459245451 -// * https://github.com/containerd/cri/commit/6b8846cdf8b8c98c1d965313d66bc8489166059a -// -// On Docker 19.03 and older, the result was `mem.Usage - mem.Stats["cache"]`. -// See https://github.com/moby/moby/issues/40727 for the background. -func calculateMemUsageUnixNoCache(mem types.MemoryStats) float64 { - // cgroup v1 - if v, isCgroup1 := mem.Stats["total_inactive_file"]; isCgroup1 && v < mem.Usage { - return float64(mem.Usage - v) - } - // cgroup v2 - if v := mem.Stats["inactive_file"]; v < mem.Usage { - return float64(mem.Usage - v) - } - return float64(mem.Usage) -} - -func calculateMemPercentUnixNoCache(limit float64, usedNoCache float64) float64 { - // MemoryStats.Limit will never be 0 unless the container is not running and we haven't - // got any data from cgroup - if limit != 0 { - return usedNoCache / limit * 100.0 - } - return 0 -} diff --git a/vendor/github.com/docker/cli/cli/command/container/stop.go b/vendor/github.com/docker/cli/cli/command/container/stop.go deleted file mode 100644 index 1cff0741b..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/stop.go +++ /dev/null @@ -1,73 +0,0 @@ -package container - -import ( - "context" - "fmt" - "strings" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/docker/docker/api/types/container" - "github.com/pkg/errors" - "github.com/spf13/cobra" -) - -type stopOptions struct { - signal string - timeout int - timeoutChanged bool - - containers []string -} - -// NewStopCommand creates a new cobra.Command for `docker stop` -func NewStopCommand(dockerCli command.Cli) *cobra.Command { - var opts stopOptions - - cmd := &cobra.Command{ - Use: "stop [OPTIONS] CONTAINER [CONTAINER...]", - Short: "Stop one or more running containers", - Args: cli.RequiresMinArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - opts.containers = args - opts.timeoutChanged = cmd.Flags().Changed("time") - return runStop(dockerCli, &opts) - }, - Annotations: map[string]string{ - "aliases": "docker container stop, docker stop", - }, - ValidArgsFunction: completion.ContainerNames(dockerCli, false), - } - - flags := cmd.Flags() - flags.StringVarP(&opts.signal, "signal", "s", "", "Signal to send to the container") - flags.IntVarP(&opts.timeout, "time", "t", 0, "Seconds to wait before killing the container") - return cmd -} - -func runStop(dockerCli command.Cli, opts *stopOptions) error { - var timeout *int - if opts.timeoutChanged { - timeout = &opts.timeout - } - - errChan := parallelOperation(context.Background(), opts.containers, func(ctx context.Context, id string) error { - return dockerCli.Client().ContainerStop(ctx, id, container.StopOptions{ - Signal: opts.signal, - Timeout: timeout, - }) - }) - var errs []string - for _, ctr := range opts.containers { - if err := <-errChan; err != nil { - errs = append(errs, err.Error()) - continue - } - _, _ = fmt.Fprintln(dockerCli.Out(), ctr) - } - if len(errs) > 0 { - return errors.New(strings.Join(errs, "\n")) - } - return nil -} diff --git a/vendor/github.com/docker/cli/cli/command/container/top.go b/vendor/github.com/docker/cli/cli/command/container/top.go deleted file mode 100644 index 0ba6557cd..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/top.go +++ /dev/null @@ -1,62 +0,0 @@ -package container - -import ( - "context" - "fmt" - "strings" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/docker/cli/cli/command/formatter/tabwriter" - "github.com/spf13/cobra" -) - -type topOptions struct { - container string - - args []string -} - -// NewTopCommand creates a new cobra.Command for `docker top` -func NewTopCommand(dockerCli command.Cli) *cobra.Command { - var opts topOptions - - cmd := &cobra.Command{ - Use: "top CONTAINER [ps OPTIONS]", - Short: "Display the running processes of a container", - Args: cli.RequiresMinArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - opts.container = args[0] - opts.args = args[1:] - return runTop(dockerCli, &opts) - }, - Annotations: map[string]string{ - "aliases": "docker container top, docker top", - }, - ValidArgsFunction: completion.ContainerNames(dockerCli, false), - } - - flags := cmd.Flags() - flags.SetInterspersed(false) - - return cmd -} - -func runTop(dockerCli command.Cli, opts *topOptions) error { - ctx := context.Background() - - procList, err := dockerCli.Client().ContainerTop(ctx, opts.container, opts.args) - if err != nil { - return err - } - - w := tabwriter.NewWriter(dockerCli.Out(), 20, 1, 3, ' ', 0) - fmt.Fprintln(w, strings.Join(procList.Titles, "\t")) - - for _, proc := range procList.Processes { - fmt.Fprintln(w, strings.Join(proc, "\t")) - } - w.Flush() - return nil -} diff --git a/vendor/github.com/docker/cli/cli/command/container/tty.go b/vendor/github.com/docker/cli/cli/command/container/tty.go deleted file mode 100644 index 1d287b006..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/tty.go +++ /dev/null @@ -1,97 +0,0 @@ -package container - -import ( - "context" - "fmt" - "os" - gosignal "os/signal" - "runtime" - "time" - - "github.com/docker/cli/cli/command" - "github.com/docker/docker/api/types" - "github.com/docker/docker/client" - "github.com/moby/sys/signal" - "github.com/sirupsen/logrus" -) - -// resizeTtyTo resizes tty to specific height and width -func resizeTtyTo(ctx context.Context, client client.ContainerAPIClient, id string, height, width uint, isExec bool) error { - if height == 0 && width == 0 { - return nil - } - - options := types.ResizeOptions{ - Height: height, - Width: width, - } - - var err error - if isExec { - err = client.ContainerExecResize(ctx, id, options) - } else { - err = client.ContainerResize(ctx, id, options) - } - - if err != nil { - logrus.Debugf("Error resize: %s\r", err) - } - return err -} - -// resizeTty is to resize the tty with cli out's tty size -func resizeTty(ctx context.Context, cli command.Cli, id string, isExec bool) error { - height, width := cli.Out().GetTtySize() - return resizeTtyTo(ctx, cli.Client(), id, height, width, isExec) -} - -// initTtySize is to init the tty's size to the same as the window, if there is an error, it will retry 10 times. -func initTtySize(ctx context.Context, cli command.Cli, id string, isExec bool, resizeTtyFunc func(ctx context.Context, cli command.Cli, id string, isExec bool) error) { - rttyFunc := resizeTtyFunc - if rttyFunc == nil { - rttyFunc = resizeTty - } - if err := rttyFunc(ctx, cli, id, isExec); err != nil { - go func() { - var err error - for retry := 0; retry < 10; retry++ { - time.Sleep(time.Duration(retry+1) * 10 * time.Millisecond) - if err = rttyFunc(ctx, cli, id, isExec); err == nil { - break - } - } - if err != nil { - fmt.Fprintln(cli.Err(), "failed to resize tty, using default size") - } - }() - } -} - -// MonitorTtySize updates the container tty size when the terminal tty changes size -func MonitorTtySize(ctx context.Context, cli command.Cli, id string, isExec bool) error { - initTtySize(ctx, cli, id, isExec, resizeTty) - if runtime.GOOS == "windows" { - go func() { - prevH, prevW := cli.Out().GetTtySize() - for { - time.Sleep(time.Millisecond * 250) - h, w := cli.Out().GetTtySize() - - if prevW != w || prevH != h { - resizeTty(ctx, cli, id, isExec) - } - prevH = h - prevW = w - } - }() - } else { - sigchan := make(chan os.Signal, 1) - gosignal.Notify(sigchan, signal.SIGWINCH) - go func() { - for range sigchan { - resizeTty(ctx, cli, id, isExec) - } - }() - } - return nil -} diff --git a/vendor/github.com/docker/cli/cli/command/container/unpause.go b/vendor/github.com/docker/cli/cli/command/container/unpause.go deleted file mode 100644 index 1e155c7c8..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/unpause.go +++ /dev/null @@ -1,58 +0,0 @@ -package container - -import ( - "context" - "fmt" - "strings" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/docker/docker/api/types" - "github.com/pkg/errors" - "github.com/spf13/cobra" -) - -type unpauseOptions struct { - containers []string -} - -// NewUnpauseCommand creates a new cobra.Command for `docker unpause` -func NewUnpauseCommand(dockerCli command.Cli) *cobra.Command { - var opts unpauseOptions - - cmd := &cobra.Command{ - Use: "unpause CONTAINER [CONTAINER...]", - Short: "Unpause all processes within one or more containers", - Args: cli.RequiresMinArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - opts.containers = args - return runUnpause(dockerCli, &opts) - }, - Annotations: map[string]string{ - "aliases": "docker container unpause, docker unpause", - }, - ValidArgsFunction: completion.ContainerNames(dockerCli, false, func(container types.Container) bool { - return container.State == "paused" - }), - } - return cmd -} - -func runUnpause(dockerCli command.Cli, opts *unpauseOptions) error { - ctx := context.Background() - - var errs []string - errChan := parallelOperation(ctx, opts.containers, dockerCli.Client().ContainerUnpause) - for _, container := range opts.containers { - if err := <-errChan; err != nil { - errs = append(errs, err.Error()) - continue - } - fmt.Fprintln(dockerCli.Out(), container) - } - if len(errs) > 0 { - return errors.New(strings.Join(errs, "\n")) - } - return nil -} diff --git a/vendor/github.com/docker/cli/cli/command/container/update.go b/vendor/github.com/docker/cli/cli/command/container/update.go deleted file mode 100644 index 0e53ceb9d..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/update.go +++ /dev/null @@ -1,151 +0,0 @@ -package container - -import ( - "context" - "fmt" - "strings" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/docker/cli/opts" - containertypes "github.com/docker/docker/api/types/container" - "github.com/pkg/errors" - "github.com/spf13/cobra" -) - -type updateOptions struct { - blkioWeight uint16 - cpuPeriod int64 - cpuQuota int64 - cpuRealtimePeriod int64 - cpuRealtimeRuntime int64 - cpusetCpus string - cpusetMems string - cpuShares int64 - memory opts.MemBytes - memoryReservation opts.MemBytes - memorySwap opts.MemSwapBytes - kernelMemory opts.MemBytes - restartPolicy string - pidsLimit int64 - cpus opts.NanoCPUs - - nFlag int - - containers []string -} - -// NewUpdateCommand creates a new cobra.Command for `docker update` -func NewUpdateCommand(dockerCli command.Cli) *cobra.Command { - var options updateOptions - - cmd := &cobra.Command{ - Use: "update [OPTIONS] CONTAINER [CONTAINER...]", - Short: "Update configuration of one or more containers", - Args: cli.RequiresMinArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - options.containers = args - options.nFlag = cmd.Flags().NFlag() - return runUpdate(dockerCli, &options) - }, - Annotations: map[string]string{ - "aliases": "docker container update, docker update", - }, - ValidArgsFunction: completion.ContainerNames(dockerCli, true), - } - - flags := cmd.Flags() - flags.Uint16Var(&options.blkioWeight, "blkio-weight", 0, `Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)`) - flags.Int64Var(&options.cpuPeriod, "cpu-period", 0, "Limit CPU CFS (Completely Fair Scheduler) period") - flags.Int64Var(&options.cpuQuota, "cpu-quota", 0, "Limit CPU CFS (Completely Fair Scheduler) quota") - flags.Int64Var(&options.cpuRealtimePeriod, "cpu-rt-period", 0, "Limit the CPU real-time period in microseconds") - flags.SetAnnotation("cpu-rt-period", "version", []string{"1.25"}) - flags.Int64Var(&options.cpuRealtimeRuntime, "cpu-rt-runtime", 0, "Limit the CPU real-time runtime in microseconds") - flags.SetAnnotation("cpu-rt-runtime", "version", []string{"1.25"}) - flags.StringVar(&options.cpusetCpus, "cpuset-cpus", "", "CPUs in which to allow execution (0-3, 0,1)") - flags.StringVar(&options.cpusetMems, "cpuset-mems", "", "MEMs in which to allow execution (0-3, 0,1)") - flags.Int64VarP(&options.cpuShares, "cpu-shares", "c", 0, "CPU shares (relative weight)") - flags.VarP(&options.memory, "memory", "m", "Memory limit") - flags.Var(&options.memoryReservation, "memory-reservation", "Memory soft limit") - flags.Var(&options.memorySwap, "memory-swap", `Swap limit equal to memory plus swap: -1 to enable unlimited swap`) - flags.Var(&options.kernelMemory, "kernel-memory", "Kernel memory limit (deprecated)") - // --kernel-memory is deprecated on API v1.42 and up, but our current annotations - // do not support only showing on < API-version. This option is no longer supported - // by runc, so hiding it unconditionally. - flags.SetAnnotation("kernel-memory", "deprecated", nil) - flags.MarkHidden("kernel-memory") - - flags.StringVar(&options.restartPolicy, "restart", "", "Restart policy to apply when a container exits") - flags.Int64Var(&options.pidsLimit, "pids-limit", 0, `Tune container pids limit (set -1 for unlimited)`) - flags.SetAnnotation("pids-limit", "version", []string{"1.40"}) - - flags.Var(&options.cpus, "cpus", "Number of CPUs") - flags.SetAnnotation("cpus", "version", []string{"1.29"}) - - return cmd -} - -func runUpdate(dockerCli command.Cli, options *updateOptions) error { - var err error - - if options.nFlag == 0 { - return errors.New("you must provide one or more flags when using this command") - } - - var restartPolicy containertypes.RestartPolicy - if options.restartPolicy != "" { - restartPolicy, err = opts.ParseRestartPolicy(options.restartPolicy) - if err != nil { - return err - } - } - - resources := containertypes.Resources{ - BlkioWeight: options.blkioWeight, - CpusetCpus: options.cpusetCpus, - CpusetMems: options.cpusetMems, - CPUShares: options.cpuShares, - Memory: options.memory.Value(), - MemoryReservation: options.memoryReservation.Value(), - MemorySwap: options.memorySwap.Value(), - KernelMemory: options.kernelMemory.Value(), - CPUPeriod: options.cpuPeriod, - CPUQuota: options.cpuQuota, - CPURealtimePeriod: options.cpuRealtimePeriod, - CPURealtimeRuntime: options.cpuRealtimeRuntime, - NanoCPUs: options.cpus.Value(), - } - - if options.pidsLimit != 0 { - resources.PidsLimit = &options.pidsLimit - } - - updateConfig := containertypes.UpdateConfig{ - Resources: resources, - RestartPolicy: restartPolicy, - } - - ctx := context.Background() - - var ( - warns []string - errs []string - ) - for _, container := range options.containers { - r, err := dockerCli.Client().ContainerUpdate(ctx, container, updateConfig) - if err != nil { - errs = append(errs, err.Error()) - } else { - fmt.Fprintln(dockerCli.Out(), container) - } - warns = append(warns, r.Warnings...) - } - if len(warns) > 0 { - fmt.Fprintln(dockerCli.Out(), strings.Join(warns, "\n")) - } - if len(errs) > 0 { - return errors.New(strings.Join(errs, "\n")) - } - return nil -} diff --git a/vendor/github.com/docker/cli/cli/command/container/utils.go b/vendor/github.com/docker/cli/cli/command/container/utils.go deleted file mode 100644 index f32926141..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/utils.go +++ /dev/null @@ -1,162 +0,0 @@ -package container - -import ( - "context" - "strconv" - - "github.com/docker/cli/cli/command" - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/events" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/versions" - "github.com/sirupsen/logrus" -) - -func waitExitOrRemoved(ctx context.Context, dockerCli command.Cli, containerID string, waitRemove bool) <-chan int { - if len(containerID) == 0 { - // containerID can never be empty - panic("Internal Error: waitExitOrRemoved needs a containerID as parameter") - } - - // Older versions used the Events API, and even older versions did not - // support server-side removal. This legacyWaitExitOrRemoved method - // preserves that old behavior and any issues it may have. - if versions.LessThan(dockerCli.Client().ClientVersion(), "1.30") { - return legacyWaitExitOrRemoved(ctx, dockerCli, containerID, waitRemove) - } - - condition := container.WaitConditionNextExit - if waitRemove { - condition = container.WaitConditionRemoved - } - - resultC, errC := dockerCli.Client().ContainerWait(ctx, containerID, condition) - - statusC := make(chan int) - go func() { - select { - case result := <-resultC: - if result.Error != nil { - logrus.Errorf("Error waiting for container: %v", result.Error.Message) - statusC <- 125 - } else { - statusC <- int(result.StatusCode) - } - case err := <-errC: - logrus.Errorf("error waiting for container: %v", err) - statusC <- 125 - } - }() - - return statusC -} - -func legacyWaitExitOrRemoved(ctx context.Context, dockerCli command.Cli, containerID string, waitRemove bool) <-chan int { - var removeErr error - statusChan := make(chan int) - exitCode := 125 - - // Get events via Events API - f := filters.NewArgs() - f.Add("type", "container") - f.Add("container", containerID) - options := types.EventsOptions{ - Filters: f, - } - eventCtx, cancel := context.WithCancel(ctx) - eventq, errq := dockerCli.Client().Events(eventCtx, options) - - eventProcessor := func(e events.Message) bool { - stopProcessing := false - switch e.Status { - case "die": - if v, ok := e.Actor.Attributes["exitCode"]; ok { - code, cerr := strconv.Atoi(v) - if cerr != nil { - logrus.Errorf("failed to convert exitcode '%q' to int: %v", v, cerr) - } else { - exitCode = code - } - } - if !waitRemove { - stopProcessing = true - } else { - // If we are talking to an older daemon, `AutoRemove` is not supported. - // We need to fall back to the old behavior, which is client-side removal - if versions.LessThan(dockerCli.Client().ClientVersion(), "1.25") { - go func() { - removeErr = dockerCli.Client().ContainerRemove(ctx, containerID, types.ContainerRemoveOptions{RemoveVolumes: true}) - if removeErr != nil { - logrus.Errorf("error removing container: %v", removeErr) - cancel() // cancel the event Q - } - }() - } - } - case "detach": - exitCode = 0 - stopProcessing = true - case "destroy": - stopProcessing = true - } - return stopProcessing - } - - go func() { - defer func() { - statusChan <- exitCode // must always send an exit code or the caller will block - cancel() - }() - - for { - select { - case <-eventCtx.Done(): - if removeErr != nil { - return - } - case evt := <-eventq: - if eventProcessor(evt) { - return - } - case err := <-errq: - logrus.Errorf("error getting events from daemon: %v", err) - return - } - } - }() - - return statusChan -} - -func parallelOperation(ctx context.Context, containers []string, op func(ctx context.Context, container string) error) chan error { - if len(containers) == 0 { - return nil - } - const defaultParallel int = 50 - sem := make(chan struct{}, defaultParallel) - errChan := make(chan error) - - // make sure result is printed in correct order - output := map[string]chan error{} - for _, c := range containers { - output[c] = make(chan error, 1) - } - go func() { - for _, c := range containers { - err := <-output[c] - errChan <- err - } - }() - - go func() { - for _, c := range containers { - sem <- struct{}{} // Wait for active queue sem to drain. - go func(container string) { - output[container] <- op(ctx, container) - <-sem - }(c) - } - }() - return errChan -} diff --git a/vendor/github.com/docker/cli/cli/command/container/wait.go b/vendor/github.com/docker/cli/cli/command/container/wait.go deleted file mode 100644 index df782e3a7..000000000 --- a/vendor/github.com/docker/cli/cli/command/container/wait.go +++ /dev/null @@ -1,58 +0,0 @@ -package container - -import ( - "context" - "fmt" - "strings" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/pkg/errors" - "github.com/spf13/cobra" -) - -type waitOptions struct { - containers []string -} - -// NewWaitCommand creates a new cobra.Command for `docker wait` -func NewWaitCommand(dockerCli command.Cli) *cobra.Command { - var opts waitOptions - - cmd := &cobra.Command{ - Use: "wait CONTAINER [CONTAINER...]", - Short: "Block until one or more containers stop, then print their exit codes", - Args: cli.RequiresMinArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - opts.containers = args - return runWait(dockerCli, &opts) - }, - Annotations: map[string]string{ - "aliases": "docker container wait, docker wait", - }, - ValidArgsFunction: completion.ContainerNames(dockerCli, false), - } - - return cmd -} - -func runWait(dockerCli command.Cli, opts *waitOptions) error { - ctx := context.Background() - - var errs []string - for _, container := range opts.containers { - resultC, errC := dockerCli.Client().ContainerWait(ctx, container, "") - - select { - case result := <-resultC: - fmt.Fprintf(dockerCli.Out(), "%d\n", result.StatusCode) - case err := <-errC: - errs = append(errs, err.Error()) - } - } - if len(errs) > 0 { - return errors.New(strings.Join(errs, "\n")) - } - return nil -} diff --git a/vendor/github.com/docker/cli/cli/command/context.go b/vendor/github.com/docker/cli/cli/command/context.go deleted file mode 100644 index 29a2be860..000000000 --- a/vendor/github.com/docker/cli/cli/command/context.go +++ /dev/null @@ -1,65 +0,0 @@ -package command - -import ( - "encoding/json" - "errors" - - "github.com/docker/cli/cli/context/store" -) - -// DockerContext is a typed representation of what we put in Context metadata -type DockerContext struct { - Description string - AdditionalFields map[string]interface{} -} - -// MarshalJSON implements custom JSON marshalling -func (dc DockerContext) MarshalJSON() ([]byte, error) { - s := map[string]interface{}{} - if dc.Description != "" { - s["Description"] = dc.Description - } - if dc.AdditionalFields != nil { - for k, v := range dc.AdditionalFields { - s[k] = v - } - } - return json.Marshal(s) -} - -// UnmarshalJSON implements custom JSON marshalling -func (dc *DockerContext) UnmarshalJSON(payload []byte) error { - var data map[string]interface{} - if err := json.Unmarshal(payload, &data); err != nil { - return err - } - for k, v := range data { - switch k { - case "Description": - dc.Description = v.(string) - default: - if dc.AdditionalFields == nil { - dc.AdditionalFields = make(map[string]interface{}) - } - dc.AdditionalFields[k] = v - } - } - return nil -} - -// GetDockerContext extracts metadata from stored context metadata -func GetDockerContext(storeMetadata store.Metadata) (DockerContext, error) { - if storeMetadata.Metadata == nil { - // can happen if we save endpoints before assigning a context metadata - // it is totally valid, and we should return a default initialized value - return DockerContext{}, nil - } - res, ok := storeMetadata.Metadata.(DockerContext) - if !ok { - return DockerContext{}, errors.New("context metadata is not a valid DockerContext") - } - if storeMetadata.Name == DefaultContextName { - res.Description = "Current DOCKER_HOST based configuration" - } - return res, nil -} diff --git a/vendor/github.com/docker/cli/cli/command/defaultcontextstore.go b/vendor/github.com/docker/cli/cli/command/defaultcontextstore.go deleted file mode 100644 index 95f89fc6f..000000000 --- a/vendor/github.com/docker/cli/cli/command/defaultcontextstore.go +++ /dev/null @@ -1,191 +0,0 @@ -package command - -import ( - "github.com/docker/cli/cli/context/docker" - "github.com/docker/cli/cli/context/store" - cliflags "github.com/docker/cli/cli/flags" - "github.com/docker/docker/errdefs" - "github.com/pkg/errors" -) - -const ( - // DefaultContextName is the name reserved for the default context (config & env based) - DefaultContextName = "default" -) - -// DefaultContext contains the default context data for all endpoints -type DefaultContext struct { - Meta store.Metadata - TLS store.ContextTLSData -} - -// DefaultContextResolver is a function which resolves the default context base on the configuration and the env variables -type DefaultContextResolver func() (*DefaultContext, error) - -// ContextStoreWithDefault implements the store.Store interface with a support for the default context -type ContextStoreWithDefault struct { - store.Store - Resolver DefaultContextResolver -} - -// EndpointDefaultResolver is implemented by any EndpointMeta object -// which wants to be able to populate the store with whatever their default is. -type EndpointDefaultResolver interface { - // ResolveDefault returns values suitable for storing in store.Metadata.Endpoints - // and store.ContextTLSData.Endpoints. - // - // An error is only returned for something fatal, not simply - // the lack of a default (e.g. because the config file which - // would contain it is missing). If there is no default then - // returns nil, nil, nil. - ResolveDefault() (interface{}, *store.EndpointTLSData, error) -} - -// ResolveDefaultContext creates a Metadata for the current CLI invocation parameters -func ResolveDefaultContext(opts *cliflags.ClientOptions, config store.Config) (*DefaultContext, error) { - contextTLSData := store.ContextTLSData{ - Endpoints: make(map[string]store.EndpointTLSData), - } - contextMetadata := store.Metadata{ - Endpoints: make(map[string]interface{}), - Metadata: DockerContext{ - Description: "", - }, - Name: DefaultContextName, - } - - dockerEP, err := resolveDefaultDockerEndpoint(opts) - if err != nil { - return nil, err - } - contextMetadata.Endpoints[docker.DockerEndpoint] = dockerEP.EndpointMeta - if dockerEP.TLSData != nil { - contextTLSData.Endpoints[docker.DockerEndpoint] = *dockerEP.TLSData.ToStoreTLSData() - } - - if err := config.ForeachEndpointType(func(n string, get store.TypeGetter) error { - if n == docker.DockerEndpoint { // handled above - return nil - } - ep := get() - if i, ok := ep.(EndpointDefaultResolver); ok { - meta, tls, err := i.ResolveDefault() - if err != nil { - return err - } - if meta == nil { - return nil - } - contextMetadata.Endpoints[n] = meta - if tls != nil { - contextTLSData.Endpoints[n] = *tls - } - } - // Nothing to be done - return nil - }); err != nil { - return nil, err - } - - return &DefaultContext{Meta: contextMetadata, TLS: contextTLSData}, nil -} - -// List implements store.Store's List -func (s *ContextStoreWithDefault) List() ([]store.Metadata, error) { - contextList, err := s.Store.List() - if err != nil { - return nil, err - } - defaultContext, err := s.Resolver() - if err != nil { - return nil, err - } - return append(contextList, defaultContext.Meta), nil -} - -// CreateOrUpdate is not allowed for the default context and fails -func (s *ContextStoreWithDefault) CreateOrUpdate(meta store.Metadata) error { - if meta.Name == DefaultContextName { - return errdefs.InvalidParameter(errors.New("default context cannot be created nor updated")) - } - return s.Store.CreateOrUpdate(meta) -} - -// Remove is not allowed for the default context and fails -func (s *ContextStoreWithDefault) Remove(name string) error { - if name == DefaultContextName { - return errdefs.InvalidParameter(errors.New("default context cannot be removed")) - } - return s.Store.Remove(name) -} - -// GetMetadata implements store.Store's GetMetadata -func (s *ContextStoreWithDefault) GetMetadata(name string) (store.Metadata, error) { - if name == DefaultContextName { - defaultContext, err := s.Resolver() - if err != nil { - return store.Metadata{}, err - } - return defaultContext.Meta, nil - } - return s.Store.GetMetadata(name) -} - -// ResetTLSMaterial is not implemented for default context and fails -func (s *ContextStoreWithDefault) ResetTLSMaterial(name string, data *store.ContextTLSData) error { - if name == DefaultContextName { - return errdefs.InvalidParameter(errors.New("default context cannot be edited")) - } - return s.Store.ResetTLSMaterial(name, data) -} - -// ResetEndpointTLSMaterial is not implemented for default context and fails -func (s *ContextStoreWithDefault) ResetEndpointTLSMaterial(contextName string, endpointName string, data *store.EndpointTLSData) error { - if contextName == DefaultContextName { - return errdefs.InvalidParameter(errors.New("default context cannot be edited")) - } - return s.Store.ResetEndpointTLSMaterial(contextName, endpointName, data) -} - -// ListTLSFiles implements store.Store's ListTLSFiles -func (s *ContextStoreWithDefault) ListTLSFiles(name string) (map[string]store.EndpointFiles, error) { - if name == DefaultContextName { - defaultContext, err := s.Resolver() - if err != nil { - return nil, err - } - tlsfiles := make(map[string]store.EndpointFiles) - for epName, epTLSData := range defaultContext.TLS.Endpoints { - var files store.EndpointFiles - for filename := range epTLSData.Files { - files = append(files, filename) - } - tlsfiles[epName] = files - } - return tlsfiles, nil - } - return s.Store.ListTLSFiles(name) -} - -// GetTLSData implements store.Store's GetTLSData -func (s *ContextStoreWithDefault) GetTLSData(contextName, endpointName, fileName string) ([]byte, error) { - if contextName == DefaultContextName { - defaultContext, err := s.Resolver() - if err != nil { - return nil, err - } - if defaultContext.TLS.Endpoints[endpointName].Files[fileName] == nil { - return nil, errdefs.NotFound(errors.Errorf("TLS data for %s/%s/%s does not exist", DefaultContextName, endpointName, fileName)) - } - return defaultContext.TLS.Endpoints[endpointName].Files[fileName], nil - } - return s.Store.GetTLSData(contextName, endpointName, fileName) -} - -// GetStorageInfo implements store.Store's GetStorageInfo -func (s *ContextStoreWithDefault) GetStorageInfo(contextName string) store.StorageInfo { - if contextName == DefaultContextName { - return store.StorageInfo{MetadataPath: "", TLSPath: ""} - } - return s.Store.GetStorageInfo(contextName) -} diff --git a/vendor/github.com/docker/cli/cli/command/events_utils.go b/vendor/github.com/docker/cli/cli/command/events_utils.go deleted file mode 100644 index 6a2907c53..000000000 --- a/vendor/github.com/docker/cli/cli/command/events_utils.go +++ /dev/null @@ -1,47 +0,0 @@ -package command - -import ( - "sync" - - "github.com/docker/docker/api/types/events" - "github.com/sirupsen/logrus" -) - -// EventHandler is abstract interface for user to customize -// own handle functions of each type of events -type EventHandler interface { - Handle(action string, h func(events.Message)) - Watch(c <-chan events.Message) -} - -// InitEventHandler initializes and returns an EventHandler -func InitEventHandler() EventHandler { - return &eventHandler{handlers: make(map[string]func(events.Message))} -} - -type eventHandler struct { - handlers map[string]func(events.Message) - mu sync.Mutex -} - -func (w *eventHandler) Handle(action string, h func(events.Message)) { - w.mu.Lock() - w.handlers[action] = h - w.mu.Unlock() -} - -// Watch ranges over the passed in event chan and processes the events based on the -// handlers created for a given action. -// To stop watching, close the event chan. -func (w *eventHandler) Watch(c <-chan events.Message) { - for e := range c { - w.mu.Lock() - h, exists := w.handlers[e.Action] - w.mu.Unlock() - if !exists { - continue - } - logrus.Debugf("event handler: received event: %v", e) - go h(e) - } -} diff --git a/vendor/github.com/docker/cli/cli/command/formatter/buildcache.go b/vendor/github.com/docker/cli/cli/command/formatter/buildcache.go deleted file mode 100644 index f6fbe72d3..000000000 --- a/vendor/github.com/docker/cli/cli/command/formatter/buildcache.go +++ /dev/null @@ -1,183 +0,0 @@ -package formatter - -import ( - "fmt" - "sort" - "strings" - "time" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/pkg/stringid" - "github.com/docker/go-units" -) - -const ( - defaultBuildCacheTableFormat = "table {{.ID}}\t{{.Type}}\t{{.Size}}\t{{.CreatedSince}}\t{{.LastUsedSince}}\t{{.UsageCount}}\t{{.Shared}}\t{{.Description}}" - - cacheIDHeader = "CACHE ID" - cacheTypeHeader = "CACHE TYPE" - parentHeader = "PARENT" - lastUsedSinceHeader = "LAST USED" - usageCountHeader = "USAGE" - inUseHeader = "IN USE" - sharedHeader = "SHARED" -) - -// NewBuildCacheFormat returns a Format for rendering using a Context -func NewBuildCacheFormat(source string, quiet bool) Format { - switch source { - case TableFormatKey: - if quiet { - return DefaultQuietFormat - } - return Format(defaultBuildCacheTableFormat) - case RawFormatKey: - if quiet { - return `build_cache_id: {{.ID}}` - } - format := `build_cache_id: {{.ID}} -parent_id: {{.Parent}} -build_cache_type: {{.CacheType}} -description: {{.Description}} -created_at: {{.CreatedAt}} -created_since: {{.CreatedSince}} -last_used_at: {{.LastUsedAt}} -last_used_since: {{.LastUsedSince}} -usage_count: {{.UsageCount}} -in_use: {{.InUse}} -shared: {{.Shared}} -` - return Format(format) - } - return Format(source) -} - -func buildCacheSort(buildCache []*types.BuildCache) { - sort.Slice(buildCache, func(i, j int) bool { - lui, luj := buildCache[i].LastUsedAt, buildCache[j].LastUsedAt - switch { - case lui == nil && luj == nil: - return strings.Compare(buildCache[i].ID, buildCache[j].ID) < 0 - case lui == nil: - return true - case luj == nil: - return false - case lui.Equal(*luj): - return strings.Compare(buildCache[i].ID, buildCache[j].ID) < 0 - default: - return lui.Before(*luj) - } - }) -} - -// BuildCacheWrite renders the context for a list of containers -func BuildCacheWrite(ctx Context, buildCaches []*types.BuildCache) error { - render := func(format func(subContext SubContext) error) error { - buildCacheSort(buildCaches) - for _, bc := range buildCaches { - err := format(&buildCacheContext{trunc: ctx.Trunc, v: bc}) - if err != nil { - return err - } - } - return nil - } - return ctx.Write(newBuildCacheContext(), render) -} - -type buildCacheContext struct { - HeaderContext - trunc bool - v *types.BuildCache -} - -func newBuildCacheContext() *buildCacheContext { - buildCacheCtx := buildCacheContext{} - buildCacheCtx.Header = SubHeaderContext{ - "ID": cacheIDHeader, - "Parent": parentHeader, - "CacheType": cacheTypeHeader, - "Size": SizeHeader, - "CreatedSince": CreatedSinceHeader, - "LastUsedSince": lastUsedSinceHeader, - "UsageCount": usageCountHeader, - "InUse": inUseHeader, - "Shared": sharedHeader, - "Description": DescriptionHeader, - } - return &buildCacheCtx -} - -func (c *buildCacheContext) MarshalJSON() ([]byte, error) { - return MarshalJSON(c) -} - -func (c *buildCacheContext) ID() string { - id := c.v.ID - if c.trunc { - id = stringid.TruncateID(c.v.ID) - } - if c.v.InUse { - return id + "*" - } - return id -} - -func (c *buildCacheContext) Parent() string { - var parent string - if len(c.v.Parents) > 0 { - parent = strings.Join(c.v.Parents, ", ") - } else { - parent = c.v.Parent //nolint:staticcheck // Ignore SA1019: Field was deprecated in API v1.42, but kept for backward compatibility - } - if c.trunc { - return stringid.TruncateID(parent) - } - return parent -} - -func (c *buildCacheContext) CacheType() string { - return c.v.Type -} - -func (c *buildCacheContext) Description() string { - return c.v.Description -} - -func (c *buildCacheContext) Size() string { - return units.HumanSizeWithPrecision(float64(c.v.Size), 3) -} - -func (c *buildCacheContext) CreatedAt() string { - return c.v.CreatedAt.String() -} - -func (c *buildCacheContext) CreatedSince() string { - return units.HumanDuration(time.Now().UTC().Sub(c.v.CreatedAt)) + " ago" -} - -func (c *buildCacheContext) LastUsedAt() string { - if c.v.LastUsedAt == nil { - return "" - } - return c.v.LastUsedAt.String() -} - -func (c *buildCacheContext) LastUsedSince() string { - if c.v.LastUsedAt == nil { - return "" - } - return units.HumanDuration(time.Now().UTC().Sub(*c.v.LastUsedAt)) + " ago" -} - -func (c *buildCacheContext) UsageCount() string { - return fmt.Sprintf("%d", c.v.UsageCount) -} - -func (c *buildCacheContext) InUse() string { - return fmt.Sprintf("%t", c.v.InUse) -} - -func (c *buildCacheContext) Shared() string { - return fmt.Sprintf("%t", c.v.Shared) -} diff --git a/vendor/github.com/docker/cli/cli/command/formatter/container.go b/vendor/github.com/docker/cli/cli/command/formatter/container.go deleted file mode 100644 index 60ad2fa40..000000000 --- a/vendor/github.com/docker/cli/cli/command/formatter/container.go +++ /dev/null @@ -1,392 +0,0 @@ -package formatter - -import ( - "fmt" - "sort" - "strconv" - "strings" - "time" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" - "github.com/docker/docker/pkg/stringid" - "github.com/docker/go-units" -) - -const ( - defaultContainerTableFormat = "table {{.ID}}\t{{.Image}}\t{{.Command}}\t{{.RunningFor}}\t{{.Status}}\t{{.Ports}}\t{{.Names}}" - - namesHeader = "NAMES" - commandHeader = "COMMAND" - runningForHeader = "CREATED" - mountsHeader = "MOUNTS" - localVolumes = "LOCAL VOLUMES" - networksHeader = "NETWORKS" -) - -// NewContainerFormat returns a Format for rendering using a Context -func NewContainerFormat(source string, quiet bool, size bool) Format { - switch source { - case TableFormatKey, "": // table formatting is the default if none is set. - if quiet { - return DefaultQuietFormat - } - format := defaultContainerTableFormat - if size { - format += `\t{{.Size}}` - } - return Format(format) - case RawFormatKey: - if quiet { - return `container_id: {{.ID}}` - } - format := `container_id: {{.ID}} -image: {{.Image}} -command: {{.Command}} -created_at: {{.CreatedAt}} -state: {{- pad .State 1 0}} -status: {{- pad .Status 1 0}} -names: {{.Names}} -labels: {{- pad .Labels 1 0}} -ports: {{- pad .Ports 1 0}} -` - if size { - format += `size: {{.Size}}\n` - } - return Format(format) - default: // custom format - if quiet { - return DefaultQuietFormat - } - return Format(source) - } -} - -// ContainerWrite renders the context for a list of containers -func ContainerWrite(ctx Context, containers []types.Container) error { - render := func(format func(subContext SubContext) error) error { - for _, container := range containers { - err := format(&ContainerContext{trunc: ctx.Trunc, c: container}) - if err != nil { - return err - } - } - return nil - } - return ctx.Write(NewContainerContext(), render) -} - -// ContainerContext is a struct used for rendering a list of containers in a Go template. -type ContainerContext struct { - HeaderContext - trunc bool - c types.Container - - // FieldsUsed is used in the pre-processing step to detect which fields are - // used in the template. It's currently only used to detect use of the .Size - // field which (if used) automatically sets the '--size' option when making - // the API call. - FieldsUsed map[string]interface{} -} - -// NewContainerContext creates a new context for rendering containers -func NewContainerContext() *ContainerContext { - containerCtx := ContainerContext{} - containerCtx.Header = SubHeaderContext{ - "ID": ContainerIDHeader, - "Names": namesHeader, - "Image": ImageHeader, - "Command": commandHeader, - "CreatedAt": CreatedAtHeader, - "RunningFor": runningForHeader, - "Ports": PortsHeader, - "State": StateHeader, - "Status": StatusHeader, - "Size": SizeHeader, - "Labels": LabelsHeader, - "Mounts": mountsHeader, - "LocalVolumes": localVolumes, - "Networks": networksHeader, - } - return &containerCtx -} - -// MarshalJSON makes ContainerContext implement json.Marshaler -func (c *ContainerContext) MarshalJSON() ([]byte, error) { - return MarshalJSON(c) -} - -// ID returns the container's ID as a string. Depending on the `--no-trunc` -// option being set, the full or truncated ID is returned. -func (c *ContainerContext) ID() string { - if c.trunc { - return stringid.TruncateID(c.c.ID) - } - return c.c.ID -} - -// Names returns a comma-separated string of the container's names, with their -// slash (/) prefix stripped. Additional names for the container (related to the -// legacy `--link` feature) are omitted. -func (c *ContainerContext) Names() string { - names := StripNamePrefix(c.c.Names) - if c.trunc { - for _, name := range names { - if len(strings.Split(name, "/")) == 1 { - names = []string{name} - break - } - } - } - return strings.Join(names, ",") -} - -// StripNamePrefix removes prefix from string, typically container names as returned by `ContainersList` API -func StripNamePrefix(ss []string) []string { - sss := make([]string, len(ss)) - for i, s := range ss { - sss[i] = s[1:] - } - return sss -} - -// Image returns the container's image reference. If the trunc option is set, -// the image's registry digest can be included. -func (c *ContainerContext) Image() string { - if c.c.Image == "" { - return "" - } - if c.trunc { - if trunc := stringid.TruncateID(c.c.ImageID); trunc == stringid.TruncateID(c.c.Image) { - return trunc - } - // truncate digest if no-trunc option was not selected - ref, err := reference.ParseNormalizedNamed(c.c.Image) - if err == nil { - if nt, ok := ref.(reference.NamedTagged); ok { - // case for when a tag is provided - if namedTagged, err := reference.WithTag(reference.TrimNamed(nt), nt.Tag()); err == nil { - return reference.FamiliarString(namedTagged) - } - } else { - // case for when a tag is not provided - named := reference.TrimNamed(ref) - return reference.FamiliarString(named) - } - } - } - - return c.c.Image -} - -// Command returns's the container's command. If the trunc option is set, the -// returned command is truncated (ellipsized). -func (c *ContainerContext) Command() string { - command := c.c.Command - if c.trunc { - command = Ellipsis(command, 20) - } - return strconv.Quote(command) -} - -// CreatedAt returns the "Created" date/time of the container as a unix timestamp. -func (c *ContainerContext) CreatedAt() string { - return time.Unix(c.c.Created, 0).String() -} - -// RunningFor returns a human-readable representation of the duration for which -// the container has been running. -// -// Note that this duration is calculated on the client, and as such is influenced -// by clock skew between the client and the daemon. -func (c *ContainerContext) RunningFor() string { - createdAt := time.Unix(c.c.Created, 0) - return units.HumanDuration(time.Now().UTC().Sub(createdAt)) + " ago" -} - -// Ports returns a comma-separated string representing open ports of the container -// e.g. "0.0.0.0:80->9090/tcp, 9988/tcp" -// it's used by command 'docker ps' -// Both published and exposed ports are included. -func (c *ContainerContext) Ports() string { - return DisplayablePorts(c.c.Ports) -} - -// State returns the container's current state (e.g. "running" or "paused") -func (c *ContainerContext) State() string { - return c.c.State -} - -// Status returns the container's status in a human readable form (for example, -// "Up 24 hours" or "Exited (0) 8 days ago") -func (c *ContainerContext) Status() string { - return c.c.Status -} - -// Size returns the container's size and virtual size (e.g. "2B (virtual 21.5MB)") -func (c *ContainerContext) Size() string { - if c.FieldsUsed == nil { - c.FieldsUsed = map[string]interface{}{} - } - c.FieldsUsed["Size"] = struct{}{} - srw := units.HumanSizeWithPrecision(float64(c.c.SizeRw), 3) - sv := units.HumanSizeWithPrecision(float64(c.c.SizeRootFs), 3) - - sf := srw - if c.c.SizeRootFs > 0 { - sf = fmt.Sprintf("%s (virtual %s)", srw, sv) - } - return sf -} - -// Labels returns a comma-separated string of labels present on the container. -func (c *ContainerContext) Labels() string { - if c.c.Labels == nil { - return "" - } - - var joinLabels []string - for k, v := range c.c.Labels { - joinLabels = append(joinLabels, fmt.Sprintf("%s=%s", k, v)) - } - return strings.Join(joinLabels, ",") -} - -// Label returns the value of the label with the given name or an empty string -// if the given label does not exist. -func (c *ContainerContext) Label(name string) string { - if c.c.Labels == nil { - return "" - } - return c.c.Labels[name] -} - -// Mounts returns a comma-separated string of mount names present on the container. -// If the trunc option is set, names can be truncated (ellipsized). -func (c *ContainerContext) Mounts() string { - var name string - var mounts []string - for _, m := range c.c.Mounts { - if m.Name == "" { - name = m.Source - } else { - name = m.Name - } - if c.trunc { - name = Ellipsis(name, 15) - } - mounts = append(mounts, name) - } - return strings.Join(mounts, ",") -} - -// LocalVolumes returns the number of volumes using the "local" volume driver. -func (c *ContainerContext) LocalVolumes() string { - count := 0 - for _, m := range c.c.Mounts { - if m.Driver == "local" { - count++ - } - } - - return fmt.Sprintf("%d", count) -} - -// Networks returns a comma-separated string of networks that the container is -// attached to. -func (c *ContainerContext) Networks() string { - if c.c.NetworkSettings == nil { - return "" - } - - networks := []string{} - for k := range c.c.NetworkSettings.Networks { - networks = append(networks, k) - } - - return strings.Join(networks, ",") -} - -// DisplayablePorts returns formatted string representing open ports of container -// e.g. "0.0.0.0:80->9090/tcp, 9988/tcp" -// it's used by command 'docker ps' -func DisplayablePorts(ports []types.Port) string { - type portGroup struct { - first uint16 - last uint16 - } - groupMap := make(map[string]*portGroup) - var result []string - var hostMappings []string - var groupMapKeys []string - sort.Slice(ports, func(i, j int) bool { - return comparePorts(ports[i], ports[j]) - }) - - for _, port := range ports { - current := port.PrivatePort - portKey := port.Type - if port.IP != "" { - if port.PublicPort != current { - hostMappings = append(hostMappings, fmt.Sprintf("%s:%d->%d/%s", port.IP, port.PublicPort, port.PrivatePort, port.Type)) - continue - } - portKey = fmt.Sprintf("%s/%s", port.IP, port.Type) - } - group := groupMap[portKey] - - if group == nil { - groupMap[portKey] = &portGroup{first: current, last: current} - // record order that groupMap keys are created - groupMapKeys = append(groupMapKeys, portKey) - continue - } - if current == (group.last + 1) { - group.last = current - continue - } - - result = append(result, formGroup(portKey, group.first, group.last)) - groupMap[portKey] = &portGroup{first: current, last: current} - } - for _, portKey := range groupMapKeys { - g := groupMap[portKey] - result = append(result, formGroup(portKey, g.first, g.last)) - } - result = append(result, hostMappings...) - return strings.Join(result, ", ") -} - -func formGroup(key string, start, last uint16) string { - parts := strings.Split(key, "/") - groupType := parts[0] - var ip string - if len(parts) > 1 { - ip = parts[0] - groupType = parts[1] - } - group := strconv.Itoa(int(start)) - if start != last { - group = fmt.Sprintf("%s-%d", group, last) - } - if ip != "" { - group = fmt.Sprintf("%s:%s->%s", ip, group, group) - } - return fmt.Sprintf("%s/%s", group, groupType) -} - -func comparePorts(i, j types.Port) bool { - if i.PrivatePort != j.PrivatePort { - return i.PrivatePort < j.PrivatePort - } - - if i.IP != j.IP { - return i.IP < j.IP - } - - if i.PublicPort != j.PublicPort { - return i.PublicPort < j.PublicPort - } - - return i.Type < j.Type -} diff --git a/vendor/github.com/docker/cli/cli/command/formatter/context.go b/vendor/github.com/docker/cli/cli/command/formatter/context.go deleted file mode 100644 index 985a6ff32..000000000 --- a/vendor/github.com/docker/cli/cli/command/formatter/context.go +++ /dev/null @@ -1,86 +0,0 @@ -package formatter - -const ( - // ClientContextTableFormat is the default client context format. - ClientContextTableFormat = "table {{.Name}}{{if .Current}} *{{end}}\t{{.Description}}\t{{.DockerEndpoint}}\t{{.Error}}" - - dockerEndpointHeader = "DOCKER ENDPOINT" - quietContextFormat = "{{.Name}}" - - maxErrLength = 45 -) - -// NewClientContextFormat returns a Format for rendering using a Context -func NewClientContextFormat(source string, quiet bool) Format { - if quiet { - return quietContextFormat - } - if source == TableFormatKey { - return ClientContextTableFormat - } - return Format(source) -} - -// ClientContext is a context for display -type ClientContext struct { - Name string - Description string - DockerEndpoint string - Current bool - Error string -} - -// ClientContextWrite writes formatted contexts using the Context -func ClientContextWrite(ctx Context, contexts []*ClientContext) error { - render := func(format func(subContext SubContext) error) error { - for _, context := range contexts { - if err := format(&clientContextContext{c: context}); err != nil { - return err - } - } - return nil - } - return ctx.Write(newClientContextContext(), render) -} - -type clientContextContext struct { - HeaderContext - c *ClientContext -} - -func newClientContextContext() *clientContextContext { - ctx := clientContextContext{} - ctx.Header = SubHeaderContext{ - "Name": NameHeader, - "Description": DescriptionHeader, - "DockerEndpoint": dockerEndpointHeader, - "Error": ErrorHeader, - } - return &ctx -} - -func (c *clientContextContext) MarshalJSON() ([]byte, error) { - return MarshalJSON(c) -} - -func (c *clientContextContext) Current() bool { - return c.c.Current -} - -func (c *clientContextContext) Name() string { - return c.c.Name -} - -func (c *clientContextContext) Description() string { - return c.c.Description -} - -func (c *clientContextContext) DockerEndpoint() string { - return c.c.DockerEndpoint -} - -// Error returns the truncated error (if any) that occurred when loading the context. -func (c *clientContextContext) Error() string { - // TODO(thaJeztah) add "--no-trunc" option to context ls and set default to 30 cols to match "docker service ps" - return Ellipsis(c.c.Error, maxErrLength) -} diff --git a/vendor/github.com/docker/cli/cli/command/formatter/custom.go b/vendor/github.com/docker/cli/cli/command/formatter/custom.go deleted file mode 100644 index 2d6c979c3..000000000 --- a/vendor/github.com/docker/cli/cli/command/formatter/custom.go +++ /dev/null @@ -1,48 +0,0 @@ -package formatter - -import "strings" - -// Common header constants -const ( - CreatedSinceHeader = "CREATED" - CreatedAtHeader = "CREATED AT" - SizeHeader = "SIZE" - LabelsHeader = "LABELS" - NameHeader = "NAME" - DescriptionHeader = "DESCRIPTION" - DriverHeader = "DRIVER" - ScopeHeader = "SCOPE" - StateHeader = "STATE" - StatusHeader = "STATUS" - PortsHeader = "PORTS" - ImageHeader = "IMAGE" - ErrorHeader = "ERROR" - ContainerIDHeader = "CONTAINER ID" -) - -// SubContext defines what Context implementation should provide -type SubContext interface { - FullHeader() interface{} -} - -// SubHeaderContext is a map destined to formatter header (table format) -type SubHeaderContext map[string]string - -// Label returns the header label for the specified string -func (c SubHeaderContext) Label(name string) string { - n := strings.Split(name, ".") - r := strings.NewReplacer("-", " ", "_", " ") - h := r.Replace(n[len(n)-1]) - - return h -} - -// HeaderContext provides the subContext interface for managing headers -type HeaderContext struct { - Header interface{} -} - -// FullHeader returns the header as an interface -func (c *HeaderContext) FullHeader() interface{} { - return c.Header -} diff --git a/vendor/github.com/docker/cli/cli/command/formatter/disk_usage.go b/vendor/github.com/docker/cli/cli/command/formatter/disk_usage.go deleted file mode 100644 index 320056544..000000000 --- a/vendor/github.com/docker/cli/cli/command/formatter/disk_usage.go +++ /dev/null @@ -1,476 +0,0 @@ -package formatter - -import ( - "bytes" - "fmt" - "strconv" - "strings" - "text/template" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/volume" - units "github.com/docker/go-units" -) - -const ( - defaultDiskUsageImageTableFormat = "table {{.Repository}}\t{{.Tag}}\t{{.ID}}\t{{.CreatedSince}}\t{{.Size}}\t{{.SharedSize}}\t{{.UniqueSize}}\t{{.Containers}}" - defaultDiskUsageContainerTableFormat = "table {{.ID}}\t{{.Image}}\t{{.Command}}\t{{.LocalVolumes}}\t{{.Size}}\t{{.RunningFor}}\t{{.Status}}\t{{.Names}}" - defaultDiskUsageVolumeTableFormat = "table {{.Name}}\t{{.Links}}\t{{.Size}}" - defaultDiskUsageBuildCacheTableFormat = "table {{.ID}}\t{{.CacheType}}\t{{.Size}}\t{{.CreatedSince}}\t{{.LastUsedSince}}\t{{.UsageCount}}\t{{.Shared}}" - defaultDiskUsageTableFormat = "table {{.Type}}\t{{.TotalCount}}\t{{.Active}}\t{{.Size}}\t{{.Reclaimable}}" - - typeHeader = "TYPE" - totalHeader = "TOTAL" - activeHeader = "ACTIVE" - reclaimableHeader = "RECLAIMABLE" - containersHeader = "CONTAINERS" - sharedSizeHeader = "SHARED SIZE" - uniqueSizeHeader = "UNIQUE SIZE" -) - -// DiskUsageContext contains disk usage specific information required by the formatter, encapsulate a Context struct. -type DiskUsageContext struct { - Context - Verbose bool - LayersSize int64 - Images []*types.ImageSummary - Containers []*types.Container - Volumes []*volume.Volume - BuildCache []*types.BuildCache - BuilderSize int64 -} - -func (ctx *DiskUsageContext) startSubsection(format string) (*template.Template, error) { - ctx.buffer = bytes.NewBufferString("") - ctx.header = "" - ctx.Format = Format(format) - ctx.preFormat() - - return ctx.parseFormat() -} - -// NewDiskUsageFormat returns a format for rendering an DiskUsageContext -func NewDiskUsageFormat(source string, verbose bool) Format { - switch { - case verbose && source == RawFormatKey: - format := `{{range .Images}}type: Image -` + NewImageFormat(source, false, true) + ` -{{end -}} -{{range .Containers}}type: Container -` + NewContainerFormat(source, false, true) + ` -{{end -}} -{{range .Volumes}}type: Volume -` + NewVolumeFormat(source, false) + ` -{{end -}} -{{range .BuildCache}}type: Build Cache -` + NewBuildCacheFormat(source, false) + ` -{{end -}}` - return format - case !verbose && source == TableFormatKey: - return Format(defaultDiskUsageTableFormat) - case !verbose && source == RawFormatKey: - format := `type: {{.Type}} -total: {{.TotalCount}} -active: {{.Active}} -size: {{.Size}} -reclaimable: {{.Reclaimable}} -` - return Format(format) - default: - return Format(source) - } -} - -func (ctx *DiskUsageContext) Write() (err error) { - if ctx.Verbose { - return ctx.verboseWrite() - } - ctx.buffer = bytes.NewBufferString("") - ctx.preFormat() - - tmpl, err := ctx.parseFormat() - if err != nil { - return err - } - - err = ctx.contextFormat(tmpl, &diskUsageImagesContext{ - totalSize: ctx.LayersSize, - images: ctx.Images, - }) - if err != nil { - return err - } - err = ctx.contextFormat(tmpl, &diskUsageContainersContext{ - containers: ctx.Containers, - }) - if err != nil { - return err - } - - err = ctx.contextFormat(tmpl, &diskUsageVolumesContext{ - volumes: ctx.Volumes, - }) - if err != nil { - return err - } - - err = ctx.contextFormat(tmpl, &diskUsageBuilderContext{ - builderSize: ctx.BuilderSize, - buildCache: ctx.BuildCache, - }) - if err != nil { - return err - } - - diskUsageContainersCtx := diskUsageContainersContext{containers: []*types.Container{}} - diskUsageContainersCtx.Header = SubHeaderContext{ - "Type": typeHeader, - "TotalCount": totalHeader, - "Active": activeHeader, - "Size": SizeHeader, - "Reclaimable": reclaimableHeader, - } - ctx.postFormat(tmpl, &diskUsageContainersCtx) - - return err -} - -type diskUsageContext struct { - Images []*imageContext - Containers []*ContainerContext - Volumes []*volumeContext - BuildCache []*buildCacheContext -} - -func (ctx *DiskUsageContext) verboseWrite() error { - duc := &diskUsageContext{ - Images: make([]*imageContext, 0, len(ctx.Images)), - Containers: make([]*ContainerContext, 0, len(ctx.Containers)), - Volumes: make([]*volumeContext, 0, len(ctx.Volumes)), - BuildCache: make([]*buildCacheContext, 0, len(ctx.BuildCache)), - } - trunc := ctx.Format.IsTable() - - // First images - for _, i := range ctx.Images { - repo := "" - tag := "" - if len(i.RepoTags) > 0 && !isDangling(*i) { - // Only show the first tag - ref, err := reference.ParseNormalizedNamed(i.RepoTags[0]) - if err != nil { - continue - } - if nt, ok := ref.(reference.NamedTagged); ok { - repo = reference.FamiliarName(ref) - tag = nt.Tag() - } - } - - duc.Images = append(duc.Images, &imageContext{ - repo: repo, - tag: tag, - trunc: trunc, - i: *i, - }) - } - - // Now containers - for _, c := range ctx.Containers { - // Don't display the virtual size - c.SizeRootFs = 0 - duc.Containers = append(duc.Containers, &ContainerContext{trunc: trunc, c: *c}) - } - - // And volumes - for _, v := range ctx.Volumes { - duc.Volumes = append(duc.Volumes, &volumeContext{v: *v}) - } - - // And build cache - buildCacheSort(ctx.BuildCache) - for _, v := range ctx.BuildCache { - duc.BuildCache = append(duc.BuildCache, &buildCacheContext{v: v, trunc: trunc}) - } - - if ctx.Format == TableFormatKey { - return ctx.verboseWriteTable(duc) - } - - ctx.preFormat() - tmpl, err := ctx.parseFormat() - if err != nil { - return err - } - return tmpl.Execute(ctx.Output, duc) -} - -func (ctx *DiskUsageContext) verboseWriteTable(duc *diskUsageContext) error { - tmpl, err := ctx.startSubsection(defaultDiskUsageImageTableFormat) - if err != nil { - return err - } - ctx.Output.Write([]byte("Images space usage:\n\n")) - for _, img := range duc.Images { - if err := ctx.contextFormat(tmpl, img); err != nil { - return err - } - } - ctx.postFormat(tmpl, newImageContext()) - - tmpl, err = ctx.startSubsection(defaultDiskUsageContainerTableFormat) - if err != nil { - return err - } - ctx.Output.Write([]byte("\nContainers space usage:\n\n")) - for _, c := range duc.Containers { - if err := ctx.contextFormat(tmpl, c); err != nil { - return err - } - } - ctx.postFormat(tmpl, NewContainerContext()) - - tmpl, err = ctx.startSubsection(defaultDiskUsageVolumeTableFormat) - if err != nil { - return err - } - ctx.Output.Write([]byte("\nLocal Volumes space usage:\n\n")) - for _, v := range duc.Volumes { - if err := ctx.contextFormat(tmpl, v); err != nil { - return err - } - } - ctx.postFormat(tmpl, newVolumeContext()) - - tmpl, err = ctx.startSubsection(defaultDiskUsageBuildCacheTableFormat) - if err != nil { - return err - } - fmt.Fprintf(ctx.Output, "\nBuild cache usage: %s\n\n", units.HumanSize(float64(ctx.BuilderSize))) - for _, v := range duc.BuildCache { - if err := ctx.contextFormat(tmpl, v); err != nil { - return err - } - } - ctx.postFormat(tmpl, newBuildCacheContext()) - - return nil -} - -type diskUsageImagesContext struct { - HeaderContext - totalSize int64 - images []*types.ImageSummary -} - -func (c *diskUsageImagesContext) MarshalJSON() ([]byte, error) { - return MarshalJSON(c) -} - -func (c *diskUsageImagesContext) Type() string { - return "Images" -} - -func (c *diskUsageImagesContext) TotalCount() string { - return strconv.Itoa(len(c.images)) -} - -func (c *diskUsageImagesContext) Active() string { - used := 0 - for _, i := range c.images { - if i.Containers > 0 { - used++ - } - } - - return strconv.Itoa(used) -} - -func (c *diskUsageImagesContext) Size() string { - return units.HumanSize(float64(c.totalSize)) -} - -func (c *diskUsageImagesContext) Reclaimable() string { - var used int64 - - for _, i := range c.images { - if i.Containers != 0 { - if i.Size == -1 || i.SharedSize == -1 { - continue - } - used += i.Size - i.SharedSize - } - } - - reclaimable := c.totalSize - used - if c.totalSize > 0 { - return fmt.Sprintf("%s (%v%%)", units.HumanSize(float64(reclaimable)), (reclaimable*100)/c.totalSize) - } - return units.HumanSize(float64(reclaimable)) -} - -type diskUsageContainersContext struct { - HeaderContext - containers []*types.Container -} - -func (c *diskUsageContainersContext) MarshalJSON() ([]byte, error) { - return MarshalJSON(c) -} - -func (c *diskUsageContainersContext) Type() string { - return "Containers" -} - -func (c *diskUsageContainersContext) TotalCount() string { - return strconv.Itoa(len(c.containers)) -} - -func (c *diskUsageContainersContext) isActive(container types.Container) bool { - return strings.Contains(container.State, "running") || - strings.Contains(container.State, "paused") || - strings.Contains(container.State, "restarting") -} - -func (c *diskUsageContainersContext) Active() string { - used := 0 - for _, container := range c.containers { - if c.isActive(*container) { - used++ - } - } - - return strconv.Itoa(used) -} - -func (c *diskUsageContainersContext) Size() string { - var size int64 - - for _, container := range c.containers { - size += container.SizeRw - } - - return units.HumanSize(float64(size)) -} - -func (c *diskUsageContainersContext) Reclaimable() string { - var reclaimable int64 - var totalSize int64 - - for _, container := range c.containers { - if !c.isActive(*container) { - reclaimable += container.SizeRw - } - totalSize += container.SizeRw - } - - if totalSize > 0 { - return fmt.Sprintf("%s (%v%%)", units.HumanSize(float64(reclaimable)), (reclaimable*100)/totalSize) - } - - return units.HumanSize(float64(reclaimable)) -} - -type diskUsageVolumesContext struct { - HeaderContext - volumes []*volume.Volume -} - -func (c *diskUsageVolumesContext) MarshalJSON() ([]byte, error) { - return MarshalJSON(c) -} - -func (c *diskUsageVolumesContext) Type() string { - return "Local Volumes" -} - -func (c *diskUsageVolumesContext) TotalCount() string { - return strconv.Itoa(len(c.volumes)) -} - -func (c *diskUsageVolumesContext) Active() string { - used := 0 - for _, v := range c.volumes { - if v.UsageData.RefCount > 0 { - used++ - } - } - - return strconv.Itoa(used) -} - -func (c *diskUsageVolumesContext) Size() string { - var size int64 - - for _, v := range c.volumes { - if v.UsageData.Size != -1 { - size += v.UsageData.Size - } - } - - return units.HumanSize(float64(size)) -} - -func (c *diskUsageVolumesContext) Reclaimable() string { - var reclaimable int64 - var totalSize int64 - - for _, v := range c.volumes { - if v.UsageData.Size != -1 { - if v.UsageData.RefCount == 0 { - reclaimable += v.UsageData.Size - } - totalSize += v.UsageData.Size - } - } - - if totalSize > 0 { - return fmt.Sprintf("%s (%v%%)", units.HumanSize(float64(reclaimable)), (reclaimable*100)/totalSize) - } - - return units.HumanSize(float64(reclaimable)) -} - -type diskUsageBuilderContext struct { - HeaderContext - builderSize int64 - buildCache []*types.BuildCache -} - -func (c *diskUsageBuilderContext) MarshalJSON() ([]byte, error) { - return MarshalJSON(c) -} - -func (c *diskUsageBuilderContext) Type() string { - return "Build Cache" -} - -func (c *diskUsageBuilderContext) TotalCount() string { - return strconv.Itoa(len(c.buildCache)) -} - -func (c *diskUsageBuilderContext) Active() string { - numActive := 0 - for _, bc := range c.buildCache { - if bc.InUse { - numActive++ - } - } - return strconv.Itoa(numActive) -} - -func (c *diskUsageBuilderContext) Size() string { - return units.HumanSize(float64(c.builderSize)) -} - -func (c *diskUsageBuilderContext) Reclaimable() string { - var inUseBytes int64 - for _, bc := range c.buildCache { - if bc.InUse && !bc.Shared { - inUseBytes += bc.Size - } - } - - return units.HumanSize(float64(c.builderSize - inUseBytes)) -} diff --git a/vendor/github.com/docker/cli/cli/command/formatter/displayutils.go b/vendor/github.com/docker/cli/cli/command/formatter/displayutils.go deleted file mode 100644 index 0c3b6ebbb..000000000 --- a/vendor/github.com/docker/cli/cli/command/formatter/displayutils.go +++ /dev/null @@ -1,61 +0,0 @@ -package formatter - -import ( - "unicode/utf8" - - "golang.org/x/text/width" -) - -// charWidth returns the number of horizontal positions a character occupies, -// and is used to account for wide characters when displaying strings. -// -// In a broad sense, wide characters include East Asian Wide, East Asian Full-width, -// (when not in East Asian context) see http://unicode.org/reports/tr11/. -func charWidth(r rune) int { - switch width.LookupRune(r).Kind() { - case width.EastAsianWide, width.EastAsianFullwidth: - return 2 - default: - return 1 - } -} - -// Ellipsis truncates a string to fit within maxDisplayWidth, and appends ellipsis (…). -// For maxDisplayWidth of 1 and lower, no ellipsis is appended. -// For maxDisplayWidth of 1, first char of string will return even if its width > 1. -func Ellipsis(s string, maxDisplayWidth int) string { - if maxDisplayWidth <= 0 { - return "" - } - rs := []rune(s) - if maxDisplayWidth == 1 { - return string(rs[0]) - } - - byteLen := len(s) - if byteLen == utf8.RuneCountInString(s) { - if byteLen <= maxDisplayWidth { - return s - } - return string(rs[:maxDisplayWidth-1]) + "…" - } - - var ( - display []int - displayWidth int - ) - for _, r := range rs { - cw := charWidth(r) - displayWidth += cw - display = append(display, displayWidth) - } - if displayWidth <= maxDisplayWidth { - return s - } - for i := range display { - if display[i] <= maxDisplayWidth-1 && display[i+1] > maxDisplayWidth-1 { - return string(rs[:i+1]) + "…" - } - } - return s -} diff --git a/vendor/github.com/docker/cli/cli/command/formatter/formatter.go b/vendor/github.com/docker/cli/cli/command/formatter/formatter.go deleted file mode 100644 index 55c5ea6e0..000000000 --- a/vendor/github.com/docker/cli/cli/command/formatter/formatter.go +++ /dev/null @@ -1,128 +0,0 @@ -package formatter - -import ( - "bytes" - "io" - "strings" - "text/template" - - "github.com/docker/cli/cli/command/formatter/tabwriter" - "github.com/docker/cli/templates" - "github.com/pkg/errors" -) - -// Format keys used to specify certain kinds of output formats -const ( - TableFormatKey = "table" - RawFormatKey = "raw" - PrettyFormatKey = "pretty" - JSONFormatKey = "json" - - DefaultQuietFormat = "{{.ID}}" - JSONFormat = "{{json .}}" -) - -// Format is the format string rendered using the Context -type Format string - -// IsTable returns true if the format is a table-type format -func (f Format) IsTable() bool { - return strings.HasPrefix(string(f), TableFormatKey) -} - -// IsJSON returns true if the format is the json format -func (f Format) IsJSON() bool { - return string(f) == JSONFormatKey -} - -// Contains returns true if the format contains the substring -func (f Format) Contains(sub string) bool { - return strings.Contains(string(f), sub) -} - -// Context contains information required by the formatter to print the output as desired. -type Context struct { - // Output is the output stream to which the formatted string is written. - Output io.Writer - // Format is used to choose raw, table or custom format for the output. - Format Format - // Trunc when set to true will truncate the output of certain fields such as Container ID. - Trunc bool - - // internal element - finalFormat string - header interface{} - buffer *bytes.Buffer -} - -func (c *Context) preFormat() { - c.finalFormat = string(c.Format) - // TODO: handle this in the Format type - switch { - case c.Format.IsTable(): - c.finalFormat = c.finalFormat[len(TableFormatKey):] - case c.Format.IsJSON(): - c.finalFormat = JSONFormat - } - - c.finalFormat = strings.Trim(c.finalFormat, " ") - r := strings.NewReplacer(`\t`, "\t", `\n`, "\n") - c.finalFormat = r.Replace(c.finalFormat) -} - -func (c *Context) parseFormat() (*template.Template, error) { - tmpl, err := templates.Parse(c.finalFormat) - if err != nil { - return tmpl, errors.Wrap(err, "template parsing error") - } - return tmpl, err -} - -func (c *Context) postFormat(tmpl *template.Template, subContext SubContext) { - if c.Format.IsTable() { - t := tabwriter.NewWriter(c.Output, 10, 1, 3, ' ', 0) - buffer := bytes.NewBufferString("") - tmpl.Funcs(templates.HeaderFunctions).Execute(buffer, subContext.FullHeader()) - buffer.WriteTo(t) - t.Write([]byte("\n")) - c.buffer.WriteTo(t) - t.Flush() - } else { - c.buffer.WriteTo(c.Output) - } -} - -func (c *Context) contextFormat(tmpl *template.Template, subContext SubContext) error { - if err := tmpl.Execute(c.buffer, subContext); err != nil { - return errors.Wrap(err, "template parsing error") - } - if c.Format.IsTable() && c.header != nil { - c.header = subContext.FullHeader() - } - c.buffer.WriteString("\n") - return nil -} - -// SubFormat is a function type accepted by Write() -type SubFormat func(func(SubContext) error) error - -// Write the template to the buffer using this Context -func (c *Context) Write(sub SubContext, f SubFormat) error { - c.buffer = bytes.NewBufferString("") - c.preFormat() - - tmpl, err := c.parseFormat() - if err != nil { - return err - } - - subFormat := func(subContext SubContext) error { - return c.contextFormat(tmpl, subContext) - } - if err := f(subFormat); err != nil { - return err - } - - c.postFormat(tmpl, sub) - return nil -} diff --git a/vendor/github.com/docker/cli/cli/command/formatter/image.go b/vendor/github.com/docker/cli/cli/command/formatter/image.go deleted file mode 100644 index 503c1011a..000000000 --- a/vendor/github.com/docker/cli/cli/command/formatter/image.go +++ /dev/null @@ -1,284 +0,0 @@ -package formatter - -import ( - "fmt" - "time" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" - "github.com/docker/docker/pkg/stringid" - units "github.com/docker/go-units" -) - -const ( - defaultImageTableFormat = "table {{.Repository}}\t{{.Tag}}\t{{.ID}}\t{{if .CreatedSince }}{{.CreatedSince}}{{else}}N/A{{end}}\t{{.Size}}" - defaultImageTableFormatWithDigest = "table {{.Repository}}\t{{.Tag}}\t{{.Digest}}\t{{.ID}}\t{{if .CreatedSince }}{{.CreatedSince}}{{else}}N/A{{end}}\t{{.Size}}" - - imageIDHeader = "IMAGE ID" - repositoryHeader = "REPOSITORY" - tagHeader = "TAG" - digestHeader = "DIGEST" -) - -// ImageContext contains image specific information required by the formatter, encapsulate a Context struct. -type ImageContext struct { - Context - Digest bool -} - -func isDangling(image types.ImageSummary) bool { - if len(image.RepoTags) == 0 && len(image.RepoDigests) == 0 { - return true - } - return len(image.RepoTags) == 1 && image.RepoTags[0] == ":" && len(image.RepoDigests) == 1 && image.RepoDigests[0] == "@" -} - -// NewImageFormat returns a format for rendering an ImageContext -func NewImageFormat(source string, quiet bool, digest bool) Format { - switch source { - case TableFormatKey: - switch { - case quiet: - return DefaultQuietFormat - case digest: - return defaultImageTableFormatWithDigest - default: - return defaultImageTableFormat - } - case RawFormatKey: - switch { - case quiet: - return `image_id: {{.ID}}` - case digest: - return `repository: {{ .Repository }} -tag: {{.Tag}} -digest: {{.Digest}} -image_id: {{.ID}} -created_at: {{.CreatedAt}} -virtual_size: {{.Size}} -` - default: - return `repository: {{ .Repository }} -tag: {{.Tag}} -image_id: {{.ID}} -created_at: {{.CreatedAt}} -virtual_size: {{.Size}} -` - } - } - - format := Format(source) - if format.IsTable() && digest && !format.Contains("{{.Digest}}") { - format += "\t{{.Digest}}" - } - return format -} - -// ImageWrite writes the formatter images using the ImageContext -func ImageWrite(ctx ImageContext, images []types.ImageSummary) error { - render := func(format func(subContext SubContext) error) error { - return imageFormat(ctx, images, format) - } - return ctx.Write(newImageContext(), render) -} - -// needDigest determines whether the image digest should be ignored or not when writing image context -func needDigest(ctx ImageContext) bool { - return ctx.Digest || ctx.Format.Contains("{{.Digest}}") -} - -func imageFormat(ctx ImageContext, images []types.ImageSummary, format func(subContext SubContext) error) error { - for _, image := range images { - formatted := []*imageContext{} - if isDangling(image) { - formatted = append(formatted, &imageContext{ - trunc: ctx.Trunc, - i: image, - repo: "", - tag: "", - digest: "", - }) - } else { - formatted = imageFormatTaggedAndDigest(ctx, image) - } - for _, imageCtx := range formatted { - if err := format(imageCtx); err != nil { - return err - } - } - } - return nil -} - -func imageFormatTaggedAndDigest(ctx ImageContext, image types.ImageSummary) []*imageContext { - repoTags := map[string][]string{} - repoDigests := map[string][]string{} - images := []*imageContext{} - - for _, refString := range image.RepoTags { - ref, err := reference.ParseNormalizedNamed(refString) - if err != nil { - continue - } - if nt, ok := ref.(reference.NamedTagged); ok { - familiarRef := reference.FamiliarName(ref) - repoTags[familiarRef] = append(repoTags[familiarRef], nt.Tag()) - } - } - for _, refString := range image.RepoDigests { - ref, err := reference.ParseNormalizedNamed(refString) - if err != nil { - continue - } - if c, ok := ref.(reference.Canonical); ok { - familiarRef := reference.FamiliarName(ref) - repoDigests[familiarRef] = append(repoDigests[familiarRef], c.Digest().String()) - } - } - - addImage := func(repo, tag, digest string) { - image := &imageContext{ - trunc: ctx.Trunc, - i: image, - repo: repo, - tag: tag, - digest: digest, - } - images = append(images, image) - } - - for repo, tags := range repoTags { - digests := repoDigests[repo] - - // Do not display digests as their own row - delete(repoDigests, repo) - - if !needDigest(ctx) { - // Ignore digest references, just show tag once - digests = nil - } - - for _, tag := range tags { - if len(digests) == 0 { - addImage(repo, tag, "") - continue - } - // Display the digests for each tag - for _, dgst := range digests { - addImage(repo, tag, dgst) - } - - } - } - - // Show rows for remaining digest only references - for repo, digests := range repoDigests { - // If digests are displayed, show row per digest - if ctx.Digest { - for _, dgst := range digests { - addImage(repo, "", dgst) - } - } else { - addImage(repo, "", "") - } - } - return images -} - -type imageContext struct { - HeaderContext - trunc bool - i types.ImageSummary - repo string - tag string - digest string -} - -func newImageContext() *imageContext { - imageCtx := imageContext{} - imageCtx.Header = SubHeaderContext{ - "ID": imageIDHeader, - "Repository": repositoryHeader, - "Tag": tagHeader, - "Digest": digestHeader, - "CreatedSince": CreatedSinceHeader, - "CreatedAt": CreatedAtHeader, - "Size": SizeHeader, - "Containers": containersHeader, - "VirtualSize": SizeHeader, // Deprecated: VirtualSize is deprecated, and equivalent to Size. - "SharedSize": sharedSizeHeader, - "UniqueSize": uniqueSizeHeader, - } - return &imageCtx -} - -func (c *imageContext) MarshalJSON() ([]byte, error) { - return MarshalJSON(c) -} - -func (c *imageContext) ID() string { - if c.trunc { - return stringid.TruncateID(c.i.ID) - } - return c.i.ID -} - -func (c *imageContext) Repository() string { - return c.repo -} - -func (c *imageContext) Tag() string { - return c.tag -} - -func (c *imageContext) Digest() string { - return c.digest -} - -func (c *imageContext) CreatedSince() string { - createdAt := time.Unix(c.i.Created, 0) - - if createdAt.IsZero() { - return "" - } - - return units.HumanDuration(time.Now().UTC().Sub(createdAt)) + " ago" -} - -func (c *imageContext) CreatedAt() string { - return time.Unix(c.i.Created, 0).String() -} - -func (c *imageContext) Size() string { - return units.HumanSizeWithPrecision(float64(c.i.Size), 3) -} - -func (c *imageContext) Containers() string { - if c.i.Containers == -1 { - return "N/A" - } - return fmt.Sprintf("%d", c.i.Containers) -} - -// VirtualSize shows the virtual size of the image and all of its parent -// images. Starting with docker 1.10, images are self-contained, and -// the VirtualSize is identical to Size. -// -// Deprecated: VirtualSize is deprecated, and equivalent to [imageContext.Size]. -func (c *imageContext) VirtualSize() string { - return units.HumanSize(float64(c.i.Size)) -} - -func (c *imageContext) SharedSize() string { - if c.i.SharedSize == -1 { - return "N/A" - } - return units.HumanSize(float64(c.i.SharedSize)) -} - -func (c *imageContext) UniqueSize() string { - if c.i.Size == -1 || c.i.SharedSize == -1 { - return "N/A" - } - return units.HumanSize(float64(c.i.Size - c.i.SharedSize)) -} diff --git a/vendor/github.com/docker/cli/cli/command/formatter/reflect.go b/vendor/github.com/docker/cli/cli/command/formatter/reflect.go deleted file mode 100644 index 9d153bc98..000000000 --- a/vendor/github.com/docker/cli/cli/command/formatter/reflect.go +++ /dev/null @@ -1,68 +0,0 @@ -package formatter - -import ( - "encoding/json" - "reflect" - "unicode" - - "github.com/pkg/errors" -) - -// MarshalJSON marshals x into json -// It differs a bit from encoding/json MarshalJSON function for formatter -func MarshalJSON(x interface{}) ([]byte, error) { - m, err := marshalMap(x) - if err != nil { - return nil, err - } - return json.Marshal(m) -} - -// marshalMap marshals x to map[string]interface{} -func marshalMap(x interface{}) (map[string]interface{}, error) { - val := reflect.ValueOf(x) - if val.Kind() != reflect.Ptr { - return nil, errors.Errorf("expected a pointer to a struct, got %v", val.Kind()) - } - if val.IsNil() { - return nil, errors.Errorf("expected a pointer to a struct, got nil pointer") - } - valElem := val.Elem() - if valElem.Kind() != reflect.Struct { - return nil, errors.Errorf("expected a pointer to a struct, got a pointer to %v", valElem.Kind()) - } - typ := val.Type() - m := make(map[string]interface{}) - for i := 0; i < val.NumMethod(); i++ { - k, v, err := marshalForMethod(typ.Method(i), val.Method(i)) - if err != nil { - return nil, err - } - if k != "" { - m[k] = v - } - } - return m, nil -} - -var unmarshallableNames = map[string]struct{}{"FullHeader": {}} - -// marshalForMethod returns the map key and the map value for marshalling the method. -// It returns ("", nil, nil) for valid but non-marshallable parameter. (e.g. "unexportedFunc()") -func marshalForMethod(typ reflect.Method, val reflect.Value) (string, interface{}, error) { - if val.Kind() != reflect.Func { - return "", nil, errors.Errorf("expected func, got %v", val.Kind()) - } - name, numIn, numOut := typ.Name, val.Type().NumIn(), val.Type().NumOut() - _, blackListed := unmarshallableNames[name] - // FIXME: In text/template, (numOut == 2) is marshallable, - // if the type of the second param is error. - marshallable := unicode.IsUpper(rune(name[0])) && !blackListed && - numIn == 0 && numOut == 1 - if !marshallable { - return "", nil, nil - } - result := val.Call(make([]reflect.Value, numIn)) - intf := result[0].Interface() - return name, intf, nil -} diff --git a/vendor/github.com/docker/cli/cli/command/formatter/tabwriter/tabwriter.go b/vendor/github.com/docker/cli/cli/command/formatter/tabwriter/tabwriter.go deleted file mode 100644 index b5f6793ac..000000000 --- a/vendor/github.com/docker/cli/cli/command/formatter/tabwriter/tabwriter.go +++ /dev/null @@ -1,604 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package tabwriter implements a write filter (tabwriter.Writer) that -// translates tabbed columns in input into properly aligned text. -// -// The package is using the Elastic Tabstops algorithm described at -// http://nickgravgaard.com/elastictabstops/index.html. -// -// The text/tabwriter package is frozen and is not accepting new features. - -// based on https://github.com/golang/go/blob/master/src/text/tabwriter/tabwriter.go Last modified 690ac40 on 31 Jan - -//nolint:gocyclo,nakedret,revive,stylecheck,unused // ignore linting errors, so that we can stick close to upstream -package tabwriter - -import ( - "io" - - "github.com/mattn/go-runewidth" -) - -// ---------------------------------------------------------------------------- -// Filter implementation - -// A cell represents a segment of text terminated by tabs or line breaks. -// The text itself is stored in a separate buffer; cell only describes the -// segment's size in bytes, its width in runes, and whether it's an htab -// ('\t') terminated cell. -type cell struct { - size int // cell size in bytes - width int // cell width in runes - htab bool // true if the cell is terminated by an htab ('\t') -} - -// A Writer is a filter that inserts padding around tab-delimited -// columns in its input to align them in the output. -// -// The Writer treats incoming bytes as UTF-8-encoded text consisting -// of cells terminated by horizontal ('\t') or vertical ('\v') tabs, -// and newline ('\n') or formfeed ('\f') characters; both newline and -// formfeed act as line breaks. -// -// Tab-terminated cells in contiguous lines constitute a column. The -// Writer inserts padding as needed to make all cells in a column have -// the same width, effectively aligning the columns. It assumes that -// all characters have the same width, except for tabs for which a -// tabwidth must be specified. Column cells must be tab-terminated, not -// tab-separated: non-tab terminated trailing text at the end of a line -// forms a cell but that cell is not part of an aligned column. -// For instance, in this example (where | stands for a horizontal tab): -// -// aaaa|bbb|d -// aa |b |dd -// a | -// aa |cccc|eee -// -// the b and c are in distinct columns (the b column is not contiguous -// all the way). The d and e are not in a column at all (there's no -// terminating tab, nor would the column be contiguous). -// -// The Writer assumes that all Unicode code points have the same width; -// this may not be true in some fonts or if the string contains combining -// characters. -// -// If DiscardEmptyColumns is set, empty columns that are terminated -// entirely by vertical (or "soft") tabs are discarded. Columns -// terminated by horizontal (or "hard") tabs are not affected by -// this flag. -// -// If a Writer is configured to filter HTML, HTML tags and entities -// are passed through. The widths of tags and entities are -// assumed to be zero (tags) and one (entities) for formatting purposes. -// -// A segment of text may be escaped by bracketing it with Escape -// characters. The tabwriter passes escaped text segments through -// unchanged. In particular, it does not interpret any tabs or line -// breaks within the segment. If the StripEscape flag is set, the -// Escape characters are stripped from the output; otherwise they -// are passed through as well. For the purpose of formatting, the -// width of the escaped text is always computed excluding the Escape -// characters. -// -// The formfeed character acts like a newline but it also terminates -// all columns in the current line (effectively calling Flush). Tab- -// terminated cells in the next line start new columns. Unless found -// inside an HTML tag or inside an escaped text segment, formfeed -// characters appear as newlines in the output. -// -// The Writer must buffer input internally, because proper spacing -// of one line may depend on the cells in future lines. Clients must -// call Flush when done calling Write. -type Writer struct { - // configuration - output io.Writer - minwidth int - tabwidth int - padding int - padbytes [8]byte - flags uint - - // current state - buf []byte // collected text excluding tabs or line breaks - pos int // buffer position up to which cell.width of incomplete cell has been computed - cell cell // current incomplete cell; cell.width is up to buf[pos] excluding ignored sections - endChar byte // terminating char of escaped sequence (Escape for escapes, '>', ';' for HTML tags/entities, or 0) - lines [][]cell // list of lines; each line is a list of cells - widths []int // list of column widths in runes - re-used during formatting -} - -// addLine adds a new line. -// flushed is a hint indicating whether the underlying writer was just flushed. -// If so, the previous line is not likely to be a good indicator of the new line's cells. -func (b *Writer) addLine(flushed bool) { - // Grow slice instead of appending, - // as that gives us an opportunity - // to re-use an existing []cell. - if n := len(b.lines) + 1; n <= cap(b.lines) { - b.lines = b.lines[:n] - b.lines[n-1] = b.lines[n-1][:0] - } else { - b.lines = append(b.lines, nil) - } - - if !flushed { - // The previous line is probably a good indicator - // of how many cells the current line will have. - // If the current line's capacity is smaller than that, - // abandon it and make a new one. - if n := len(b.lines); n >= 2 { - if prev := len(b.lines[n-2]); prev > cap(b.lines[n-1]) { - b.lines[n-1] = make([]cell, 0, prev) - } - } - } -} - -// Reset the current state. -func (b *Writer) reset() { - b.buf = b.buf[:0] - b.pos = 0 - b.cell = cell{} - b.endChar = 0 - b.lines = b.lines[0:0] - b.widths = b.widths[0:0] - b.addLine(true) -} - -// Internal representation (current state): -// -// - all text written is appended to buf; tabs and line breaks are stripped away -// - at any given time there is a (possibly empty) incomplete cell at the end -// (the cell starts after a tab or line break) -// - cell.size is the number of bytes belonging to the cell so far -// - cell.width is text width in runes of that cell from the start of the cell to -// position pos; html tags and entities are excluded from this width if html -// filtering is enabled -// - the sizes and widths of processed text are kept in the lines list -// which contains a list of cells for each line -// - the widths list is a temporary list with current widths used during -// formatting; it is kept in Writer because it's re-used -// -// |<---------- size ---------->| -// | | -// |<- width ->|<- ignored ->| | -// | | | | -// [---processed---tab------------......] -// ^ ^ ^ -// | | | -// buf start of incomplete cell pos - -// Formatting can be controlled with these flags. -const ( - // Ignore html tags and treat entities (starting with '&' - // and ending in ';') as single characters (width = 1). - FilterHTML uint = 1 << iota - - // Strip Escape characters bracketing escaped text segments - // instead of passing them through unchanged with the text. - StripEscape - - // Force right-alignment of cell content. - // Default is left-alignment. - AlignRight - - // Handle empty columns as if they were not present in - // the input in the first place. - DiscardEmptyColumns - - // Always use tabs for indentation columns (i.e., padding of - // leading empty cells on the left) independent of padchar. - TabIndent - - // Print a vertical bar ('|') between columns (after formatting). - // Discarded columns appear as zero-width columns ("||"). - Debug -) - -// A Writer must be initialized with a call to Init. The first parameter (output) -// specifies the filter output. The remaining parameters control the formatting: -// -// minwidth minimal cell width including any padding -// tabwidth width of tab characters (equivalent number of spaces) -// padding padding added to a cell before computing its width -// padchar ASCII char used for padding -// if padchar == '\t', the Writer will assume that the -// width of a '\t' in the formatted output is tabwidth, -// and cells are left-aligned independent of align_left -// (for correct-looking results, tabwidth must correspond -// to the tab width in the viewer displaying the result) -// flags formatting control -func (b *Writer) Init(output io.Writer, minwidth, tabwidth, padding int, padchar byte, flags uint) *Writer { - if minwidth < 0 || tabwidth < 0 || padding < 0 { - panic("negative minwidth, tabwidth, or padding") - } - b.output = output - b.minwidth = minwidth - b.tabwidth = tabwidth - b.padding = padding - for i := range b.padbytes { - b.padbytes[i] = padchar - } - if padchar == '\t' { - // tab padding enforces left-alignment - flags &^= AlignRight - } - b.flags = flags - - b.reset() - - return b -} - -// debugging support (keep code around) -func (b *Writer) dump() { - pos := 0 - for i, line := range b.lines { - print("(", i, ") ") - for _, c := range line { - print("[", string(b.buf[pos:pos+c.size]), "]") - pos += c.size - } - print("\n") - } - print("\n") -} - -// local error wrapper so we can distinguish errors we want to return -// as errors from genuine panics (which we don't want to return as errors) -type osError struct { - err error -} - -func (b *Writer) write0(buf []byte) { - n, err := b.output.Write(buf) - if n != len(buf) && err == nil { - err = io.ErrShortWrite - } - if err != nil { - panic(osError{err}) - } -} - -func (b *Writer) writeN(src []byte, n int) { - for n > len(src) { - b.write0(src) - n -= len(src) - } - b.write0(src[0:n]) -} - -var ( - newline = []byte{'\n'} - tabs = []byte("\t\t\t\t\t\t\t\t") -) - -func (b *Writer) writePadding(textw, cellw int, useTabs bool) { - if b.padbytes[0] == '\t' || useTabs { - // padding is done with tabs - if b.tabwidth == 0 { - return // tabs have no width - can't do any padding - } - // make cellw the smallest multiple of b.tabwidth - cellw = (cellw + b.tabwidth - 1) / b.tabwidth * b.tabwidth - n := cellw - textw // amount of padding - if n < 0 { - panic("internal error") - } - b.writeN(tabs, (n+b.tabwidth-1)/b.tabwidth) - return - } - - // padding is done with non-tab characters - b.writeN(b.padbytes[0:], cellw-textw) -} - -var vbar = []byte{'|'} - -func (b *Writer) writeLines(pos0 int, line0, line1 int) (pos int) { - pos = pos0 - for i := line0; i < line1; i++ { - line := b.lines[i] - - // if TabIndent is set, use tabs to pad leading empty cells - useTabs := b.flags&TabIndent != 0 - - for j, c := range line { - if j > 0 && b.flags&Debug != 0 { - // indicate column break - b.write0(vbar) - } - - if c.size == 0 { - // empty cell - if j < len(b.widths) { - b.writePadding(c.width, b.widths[j], useTabs) - } - } else { - // non-empty cell - useTabs = false - if b.flags&AlignRight == 0 { // align left - b.write0(b.buf[pos : pos+c.size]) - pos += c.size - if j < len(b.widths) { - b.writePadding(c.width, b.widths[j], false) - } - } else { // align right - if j < len(b.widths) { - b.writePadding(c.width, b.widths[j], false) - } - b.write0(b.buf[pos : pos+c.size]) - pos += c.size - } - } - } - - if i+1 == len(b.lines) { - // last buffered line - we don't have a newline, so just write - // any outstanding buffered data - b.write0(b.buf[pos : pos+b.cell.size]) - pos += b.cell.size - } else { - // not the last line - write newline - b.write0(newline) - } - } - return -} - -// Format the text between line0 and line1 (excluding line1); pos -// is the buffer position corresponding to the beginning of line0. -// Returns the buffer position corresponding to the beginning of -// line1 and an error, if any. -func (b *Writer) format(pos0 int, line0, line1 int) (pos int) { - pos = pos0 - column := len(b.widths) - for this := line0; this < line1; this++ { - line := b.lines[this] - - if column >= len(line)-1 { - continue - } - // cell exists in this column => this line - // has more cells than the previous line - // (the last cell per line is ignored because cells are - // tab-terminated; the last cell per line describes the - // text before the newline/formfeed and does not belong - // to a column) - - // print unprinted lines until beginning of block - pos = b.writeLines(pos, line0, this) - line0 = this - - // column block begin - width := b.minwidth // minimal column width - discardable := true // true if all cells in this column are empty and "soft" - for ; this < line1; this++ { - line = b.lines[this] - if column >= len(line)-1 { - break - } - // cell exists in this column - c := line[column] - // update width - if w := c.width + b.padding; w > width { - width = w - } - // update discardable - if c.width > 0 || c.htab { - discardable = false - } - } - // column block end - - // discard empty columns if necessary - if discardable && b.flags&DiscardEmptyColumns != 0 { - width = 0 - } - - // format and print all columns to the right of this column - // (we know the widths of this column and all columns to the left) - b.widths = append(b.widths, width) // push width - pos = b.format(pos, line0, this) - b.widths = b.widths[0 : len(b.widths)-1] // pop width - line0 = this - } - - // print unprinted lines until end - return b.writeLines(pos, line0, line1) -} - -// Append text to current cell. -func (b *Writer) append(text []byte) { - b.buf = append(b.buf, text...) - b.cell.size += len(text) -} - -// Update the cell width. -func (b *Writer) updateWidth() { - b.cell.width += runewidth.StringWidth(string(b.buf[b.pos:])) - b.pos = len(b.buf) -} - -// To escape a text segment, bracket it with Escape characters. -// For instance, the tab in this string "Ignore this tab: \xff\t\xff" -// does not terminate a cell and constitutes a single character of -// width one for formatting purposes. -// -// The value 0xff was chosen because it cannot appear in a valid UTF-8 sequence. -const Escape = '\xff' - -// Start escaped mode. -func (b *Writer) startEscape(ch byte) { - switch ch { - case Escape: - b.endChar = Escape - case '<': - b.endChar = '>' - case '&': - b.endChar = ';' - } -} - -// Terminate escaped mode. If the escaped text was an HTML tag, its width -// is assumed to be zero for formatting purposes; if it was an HTML entity, -// its width is assumed to be one. In all other cases, the width is the -// unicode width of the text. -func (b *Writer) endEscape() { - switch b.endChar { - case Escape: - b.updateWidth() - if b.flags&StripEscape == 0 { - b.cell.width -= 2 // don't count the Escape chars - } - case '>': // tag of zero width - case ';': - b.cell.width++ // entity, count as one rune - } - b.pos = len(b.buf) - b.endChar = 0 -} - -// Terminate the current cell by adding it to the list of cells of the -// current line. Returns the number of cells in that line. -func (b *Writer) terminateCell(htab bool) int { - b.cell.htab = htab - line := &b.lines[len(b.lines)-1] - *line = append(*line, b.cell) - b.cell = cell{} - return len(*line) -} - -func (b *Writer) handlePanic(err *error, op string) { - if e := recover(); e != nil { - if op == "Flush" { - // If Flush ran into a panic, we still need to reset. - b.reset() - } - if nerr, ok := e.(osError); ok { - *err = nerr.err - return - } - panic("tabwriter: panic during " + op) - } -} - -// Flush should be called after the last call to Write to ensure -// that any data buffered in the Writer is written to output. Any -// incomplete escape sequence at the end is considered -// complete for formatting purposes. -func (b *Writer) Flush() error { - return b.flush() -} - -// flush is the internal version of Flush, with a named return value which we -// don't want to expose. -func (b *Writer) flush() (err error) { - defer b.handlePanic(&err, "Flush") - b.flushNoDefers() - return nil -} - -// flushNoDefers is like flush, but without a deferred handlePanic call. This -// can be called from other methods which already have their own deferred -// handlePanic calls, such as Write, and avoid the extra defer work. -func (b *Writer) flushNoDefers() { - // add current cell if not empty - if b.cell.size > 0 { - if b.endChar != 0 { - // inside escape - terminate it even if incomplete - b.endEscape() - } - b.terminateCell(false) - } - - // format contents of buffer - b.format(0, 0, len(b.lines)) - b.reset() -} - -var hbar = []byte("---\n") - -// Write writes buf to the writer b. -// The only errors returned are ones encountered -// while writing to the underlying output stream. -func (b *Writer) Write(buf []byte) (n int, err error) { - defer b.handlePanic(&err, "Write") - - // split text into cells - n = 0 - for i, ch := range buf { - if b.endChar == 0 { - // outside escape - switch ch { - case '\t', '\v', '\n', '\f': - // end of cell - b.append(buf[n:i]) - b.updateWidth() - n = i + 1 // ch consumed - ncells := b.terminateCell(ch == '\t') - if ch == '\n' || ch == '\f' { - // terminate line - b.addLine(ch == '\f') - if ch == '\f' || ncells == 1 { - // A '\f' always forces a flush. Otherwise, if the previous - // line has only one cell which does not have an impact on - // the formatting of the following lines (the last cell per - // line is ignored by format()), thus we can flush the - // Writer contents. - b.flushNoDefers() - if ch == '\f' && b.flags&Debug != 0 { - // indicate section break - b.write0(hbar) - } - } - } - - case Escape: - // start of escaped sequence - b.append(buf[n:i]) - b.updateWidth() - n = i - if b.flags&StripEscape != 0 { - n++ // strip Escape - } - b.startEscape(Escape) - - case '<', '&': - // possibly an html tag/entity - if b.flags&FilterHTML != 0 { - // begin of tag/entity - b.append(buf[n:i]) - b.updateWidth() - n = i - b.startEscape(ch) - } - } - } else { - // inside escape - if ch == b.endChar { - // end of tag/entity - j := i + 1 - if ch == Escape && b.flags&StripEscape != 0 { - j = i // strip Escape - } - b.append(buf[n:j]) - n = i + 1 // ch consumed - b.endEscape() - } - } - } - - // append leftover text - b.append(buf[n:]) - n = len(buf) - return -} - -// NewWriter allocates and initializes a new tabwriter.Writer. -// The parameters are the same as for the Init function. -func NewWriter(output io.Writer, minwidth, tabwidth, padding int, padchar byte, flags uint) *Writer { - return new(Writer).Init(output, minwidth, tabwidth, padding, padchar, flags) -} diff --git a/vendor/github.com/docker/cli/cli/command/formatter/volume.go b/vendor/github.com/docker/cli/cli/command/formatter/volume.go deleted file mode 100644 index fa8ef7f23..000000000 --- a/vendor/github.com/docker/cli/cli/command/formatter/volume.go +++ /dev/null @@ -1,165 +0,0 @@ -package formatter - -import ( - "fmt" - "strconv" - "strings" - - "github.com/docker/docker/api/types/volume" - units "github.com/docker/go-units" -) - -const ( - defaultVolumeQuietFormat = "{{.Name}}" - defaultVolumeTableFormat = "table {{.Driver}}\t{{.Name}}" - - idHeader = "ID" - volumeNameHeader = "VOLUME NAME" - mountpointHeader = "MOUNTPOINT" - linksHeader = "LINKS" - groupHeader = "GROUP" - availabilityHeader = "AVAILABILITY" - statusHeader = "STATUS" -) - -// NewVolumeFormat returns a format for use with a volume Context -func NewVolumeFormat(source string, quiet bool) Format { - switch source { - case TableFormatKey: - if quiet { - return defaultVolumeQuietFormat - } - return defaultVolumeTableFormat - case RawFormatKey: - if quiet { - return `name: {{.Name}}` - } - return `name: {{.Name}}\ndriver: {{.Driver}}\n` - } - return Format(source) -} - -// VolumeWrite writes formatted volumes using the Context -func VolumeWrite(ctx Context, volumes []*volume.Volume) error { - render := func(format func(subContext SubContext) error) error { - for _, vol := range volumes { - if err := format(&volumeContext{v: *vol}); err != nil { - return err - } - } - return nil - } - return ctx.Write(newVolumeContext(), render) -} - -type volumeContext struct { - HeaderContext - v volume.Volume -} - -func newVolumeContext() *volumeContext { - volumeCtx := volumeContext{} - volumeCtx.Header = SubHeaderContext{ - "ID": idHeader, - "Name": volumeNameHeader, - "Group": groupHeader, - "Driver": DriverHeader, - "Scope": ScopeHeader, - "Availability": availabilityHeader, - "Mountpoint": mountpointHeader, - "Labels": LabelsHeader, - "Links": linksHeader, - "Size": SizeHeader, - "Status": statusHeader, - } - return &volumeCtx -} - -func (c *volumeContext) MarshalJSON() ([]byte, error) { - return MarshalJSON(c) -} - -func (c *volumeContext) Name() string { - return c.v.Name -} - -func (c *volumeContext) Driver() string { - return c.v.Driver -} - -func (c *volumeContext) Scope() string { - return c.v.Scope -} - -func (c *volumeContext) Mountpoint() string { - return c.v.Mountpoint -} - -func (c *volumeContext) Labels() string { - if c.v.Labels == nil { - return "" - } - - var joinLabels []string - for k, v := range c.v.Labels { - joinLabels = append(joinLabels, k+"="+v) - } - return strings.Join(joinLabels, ",") -} - -func (c *volumeContext) Label(name string) string { - if c.v.Labels == nil { - return "" - } - return c.v.Labels[name] -} - -func (c *volumeContext) Links() string { - if c.v.UsageData == nil { - return "N/A" - } - return strconv.FormatInt(c.v.UsageData.RefCount, 10) -} - -func (c *volumeContext) Size() string { - if c.v.UsageData == nil { - return "N/A" - } - return units.HumanSize(float64(c.v.UsageData.Size)) -} - -func (c *volumeContext) Group() string { - if c.v.ClusterVolume == nil { - return "N/A" - } - - return c.v.ClusterVolume.Spec.Group -} - -func (c *volumeContext) Availability() string { - if c.v.ClusterVolume == nil { - return "N/A" - } - - return string(c.v.ClusterVolume.Spec.Availability) -} - -func (c *volumeContext) Status() string { - if c.v.ClusterVolume == nil { - return "N/A" - } - - if c.v.ClusterVolume.Info == nil || c.v.ClusterVolume.Info.VolumeID == "" { - return "pending creation" - } - - l := len(c.v.ClusterVolume.PublishStatus) - switch l { - case 0: - return "created" - case 1: - return "in use (1 node)" - default: - return fmt.Sprintf("in use (%d nodes)", l) - } -} diff --git a/vendor/github.com/docker/cli/cli/command/image/build.go b/vendor/github.com/docker/cli/cli/command/image/build.go deleted file mode 100644 index 2c69a23b9..000000000 --- a/vendor/github.com/docker/cli/cli/command/image/build.go +++ /dev/null @@ -1,564 +0,0 @@ -package image - -import ( - "archive/tar" - "bufio" - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "os" - "path/filepath" - "regexp" - "runtime" - "strings" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/image/build" - "github.com/docker/cli/opts" - "github.com/docker/distribution/reference" - "github.com/docker/docker/api" - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/container" - registrytypes "github.com/docker/docker/api/types/registry" - "github.com/docker/docker/builder/remotecontext/urlutil" - "github.com/docker/docker/pkg/archive" - "github.com/docker/docker/pkg/idtools" - "github.com/docker/docker/pkg/jsonmessage" - "github.com/docker/docker/pkg/progress" - "github.com/docker/docker/pkg/streamformatter" - units "github.com/docker/go-units" - "github.com/pkg/errors" - "github.com/spf13/cobra" -) - -var errStdinConflict = errors.New("invalid argument: can't use stdin for both build context and dockerfile") - -type buildOptions struct { - context string - dockerfileName string - tags opts.ListOpts - labels opts.ListOpts - buildArgs opts.ListOpts - extraHosts opts.ListOpts - ulimits *opts.UlimitOpt - memory opts.MemBytes - memorySwap opts.MemSwapBytes - shmSize opts.MemBytes - cpuShares int64 - cpuPeriod int64 - cpuQuota int64 - cpuSetCpus string - cpuSetMems string - cgroupParent string - isolation string - quiet bool - noCache bool - rm bool - forceRm bool - pull bool - cacheFrom []string - compress bool - securityOpt []string - networkMode string - squash bool - target string - imageIDFile string - platform string - untrusted bool -} - -// dockerfileFromStdin returns true when the user specified that the Dockerfile -// should be read from stdin instead of a file -func (o buildOptions) dockerfileFromStdin() bool { - return o.dockerfileName == "-" -} - -// contextFromStdin returns true when the user specified that the build context -// should be read from stdin -func (o buildOptions) contextFromStdin() bool { - return o.context == "-" -} - -func newBuildOptions() buildOptions { - ulimits := make(map[string]*units.Ulimit) - return buildOptions{ - tags: opts.NewListOpts(validateTag), - buildArgs: opts.NewListOpts(opts.ValidateEnv), - ulimits: opts.NewUlimitOpt(&ulimits), - labels: opts.NewListOpts(opts.ValidateLabel), - extraHosts: opts.NewListOpts(opts.ValidateExtraHost), - } -} - -// NewBuildCommand creates a new `docker build` command -func NewBuildCommand(dockerCli command.Cli) *cobra.Command { - options := newBuildOptions() - - cmd := &cobra.Command{ - Use: "build [OPTIONS] PATH | URL | -", - Short: "Build an image from a Dockerfile", - Args: cli.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - options.context = args[0] - return runBuild(dockerCli, options) - }, - Annotations: map[string]string{ - "category-top": "4", - "aliases": "docker image build, docker build, docker buildx build, docker builder build", - }, - ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return nil, cobra.ShellCompDirectiveFilterDirs - }, - } - - flags := cmd.Flags() - - flags.VarP(&options.tags, "tag", "t", `Name and optionally a tag in the "name:tag" format`) - flags.Var(&options.buildArgs, "build-arg", "Set build-time variables") - flags.Var(options.ulimits, "ulimit", "Ulimit options") - flags.StringVarP(&options.dockerfileName, "file", "f", "", `Name of the Dockerfile (Default is "PATH/Dockerfile")`) - flags.VarP(&options.memory, "memory", "m", "Memory limit") - flags.Var(&options.memorySwap, "memory-swap", `Swap limit equal to memory plus swap: -1 to enable unlimited swap`) - flags.Var(&options.shmSize, "shm-size", `Size of "/dev/shm"`) - flags.Int64VarP(&options.cpuShares, "cpu-shares", "c", 0, "CPU shares (relative weight)") - flags.Int64Var(&options.cpuPeriod, "cpu-period", 0, "Limit the CPU CFS (Completely Fair Scheduler) period") - flags.Int64Var(&options.cpuQuota, "cpu-quota", 0, "Limit the CPU CFS (Completely Fair Scheduler) quota") - flags.StringVar(&options.cpuSetCpus, "cpuset-cpus", "", "CPUs in which to allow execution (0-3, 0,1)") - flags.StringVar(&options.cpuSetMems, "cpuset-mems", "", "MEMs in which to allow execution (0-3, 0,1)") - flags.StringVar(&options.cgroupParent, "cgroup-parent", "", `Set the parent cgroup for the "RUN" instructions during build`) - flags.StringVar(&options.isolation, "isolation", "", "Container isolation technology") - flags.Var(&options.labels, "label", "Set metadata for an image") - flags.BoolVar(&options.noCache, "no-cache", false, "Do not use cache when building the image") - flags.BoolVar(&options.rm, "rm", true, "Remove intermediate containers after a successful build") - flags.BoolVar(&options.forceRm, "force-rm", false, "Always remove intermediate containers") - flags.BoolVarP(&options.quiet, "quiet", "q", false, "Suppress the build output and print image ID on success") - flags.BoolVar(&options.pull, "pull", false, "Always attempt to pull a newer version of the image") - flags.StringSliceVar(&options.cacheFrom, "cache-from", []string{}, "Images to consider as cache sources") - flags.BoolVar(&options.compress, "compress", false, "Compress the build context using gzip") - flags.StringSliceVar(&options.securityOpt, "security-opt", []string{}, "Security options") - flags.StringVar(&options.networkMode, "network", "default", "Set the networking mode for the RUN instructions during build") - flags.SetAnnotation("network", "version", []string{"1.25"}) - flags.Var(&options.extraHosts, "add-host", `Add a custom host-to-IP mapping ("host:ip")`) - flags.StringVar(&options.target, "target", "", "Set the target build stage to build.") - flags.StringVar(&options.imageIDFile, "iidfile", "", "Write the image ID to the file") - - command.AddTrustVerificationFlags(flags, &options.untrusted, dockerCli.ContentTrustEnabled()) - - flags.StringVar(&options.platform, "platform", os.Getenv("DOCKER_DEFAULT_PLATFORM"), "Set platform if server is multi-platform capable") - flags.SetAnnotation("platform", "version", []string{"1.38"}) - - flags.BoolVar(&options.squash, "squash", false, "Squash newly built layers into a single new layer") - flags.SetAnnotation("squash", "experimental", nil) - flags.SetAnnotation("squash", "version", []string{"1.25"}) - - return cmd -} - -// lastProgressOutput is the same as progress.Output except -// that it only output with the last update. It is used in -// non terminal scenarios to suppress verbose messages -type lastProgressOutput struct { - output progress.Output -} - -// WriteProgress formats progress information from a ProgressReader. -func (out *lastProgressOutput) WriteProgress(prog progress.Progress) error { - if !prog.LastUpdate { - return nil - } - - return out.output.WriteProgress(prog) -} - -//nolint:gocyclo -func runBuild(dockerCli command.Cli, options buildOptions) error { - var ( - err error - buildCtx io.ReadCloser - dockerfileCtx io.ReadCloser - contextDir string - tempDir string - relDockerfile string - progBuff io.Writer - buildBuff io.Writer - remote string - ) - - if options.dockerfileFromStdin() { - if options.contextFromStdin() { - return errStdinConflict - } - dockerfileCtx = dockerCli.In() - } - - specifiedContext := options.context - progBuff = dockerCli.Out() - buildBuff = dockerCli.Out() - if options.quiet { - progBuff = bytes.NewBuffer(nil) - buildBuff = bytes.NewBuffer(nil) - } - if options.imageIDFile != "" { - // Avoid leaving a stale file if we eventually fail - if err := os.Remove(options.imageIDFile); err != nil && !os.IsNotExist(err) { - return errors.Wrap(err, "Removing image ID file") - } - } - - switch { - case options.contextFromStdin(): - // buildCtx is tar archive. if stdin was dockerfile then it is wrapped - buildCtx, relDockerfile, err = build.GetContextFromReader(dockerCli.In(), options.dockerfileName) - case isLocalDir(specifiedContext): - contextDir, relDockerfile, err = build.GetContextFromLocalDir(specifiedContext, options.dockerfileName) - if err == nil && strings.HasPrefix(relDockerfile, ".."+string(filepath.Separator)) { - // Dockerfile is outside of build-context; read the Dockerfile and pass it as dockerfileCtx - dockerfileCtx, err = os.Open(options.dockerfileName) - if err != nil { - return errors.Errorf("unable to open Dockerfile: %v", err) - } - defer dockerfileCtx.Close() - } - case urlutil.IsGitURL(specifiedContext): - tempDir, relDockerfile, err = build.GetContextFromGitURL(specifiedContext, options.dockerfileName) - case urlutil.IsURL(specifiedContext): - buildCtx, relDockerfile, err = build.GetContextFromURL(progBuff, specifiedContext, options.dockerfileName) - default: - return errors.Errorf("unable to prepare context: path %q not found", specifiedContext) - } - - if err != nil { - if options.quiet && urlutil.IsURL(specifiedContext) { - fmt.Fprintln(dockerCli.Err(), progBuff) - } - return errors.Errorf("unable to prepare context: %s", err) - } - - if tempDir != "" { - defer os.RemoveAll(tempDir) - contextDir = tempDir - } - - // read from a directory into tar archive - if buildCtx == nil { - excludes, err := build.ReadDockerignore(contextDir) - if err != nil { - return err - } - - if err := build.ValidateContextDirectory(contextDir, excludes); err != nil { - return errors.Wrap(err, "error checking context") - } - - // And canonicalize dockerfile name to a platform-independent one - relDockerfile = filepath.ToSlash(relDockerfile) - - excludes = build.TrimBuildFilesFromExcludes(excludes, relDockerfile, options.dockerfileFromStdin()) - buildCtx, err = archive.TarWithOptions(contextDir, &archive.TarOptions{ - ExcludePatterns: excludes, - ChownOpts: &idtools.Identity{UID: 0, GID: 0}, - }) - if err != nil { - return err - } - } - - // replace Dockerfile if it was added from stdin or a file outside the build-context, and there is archive context - if dockerfileCtx != nil && buildCtx != nil { - buildCtx, relDockerfile, err = build.AddDockerfileToBuildContext(dockerfileCtx, buildCtx) - if err != nil { - return err - } - } - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - var resolvedTags []*resolvedTag - if !options.untrusted { - translator := func(ctx context.Context, ref reference.NamedTagged) (reference.Canonical, error) { - return TrustedReference(ctx, dockerCli, ref) - } - // if there is a tar wrapper, the dockerfile needs to be replaced inside it - if buildCtx != nil { - // Wrap the tar archive to replace the Dockerfile entry with the rewritten - // Dockerfile which uses trusted pulls. - buildCtx = replaceDockerfileForContentTrust(ctx, buildCtx, relDockerfile, translator, &resolvedTags) - } else if dockerfileCtx != nil { - // if there was not archive context still do the possible replacements in Dockerfile - newDockerfile, _, err := rewriteDockerfileFromForContentTrust(ctx, dockerfileCtx, translator) - if err != nil { - return err - } - dockerfileCtx = io.NopCloser(bytes.NewBuffer(newDockerfile)) - } - } - - if options.compress { - buildCtx, err = build.Compress(buildCtx) - if err != nil { - return err - } - } - - // Setup an upload progress bar - progressOutput := streamformatter.NewProgressOutput(progBuff) - if !dockerCli.Out().IsTerminal() { - progressOutput = &lastProgressOutput{output: progressOutput} - } - - // if up to this point nothing has set the context then we must have another - // way for sending it(streaming) and set the context to the Dockerfile - if dockerfileCtx != nil && buildCtx == nil { - buildCtx = dockerfileCtx - } - - var body io.Reader - if buildCtx != nil { - body = progress.NewProgressReader(buildCtx, progressOutput, 0, "", "Sending build context to Docker daemon") - } - - configFile := dockerCli.ConfigFile() - creds, _ := configFile.GetAllCredentials() - authConfigs := make(map[string]registrytypes.AuthConfig, len(creds)) - for k, auth := range creds { - authConfigs[k] = registrytypes.AuthConfig(auth) - } - buildOptions := imageBuildOptions(dockerCli, options) - buildOptions.Version = types.BuilderV1 - buildOptions.Dockerfile = relDockerfile - buildOptions.AuthConfigs = authConfigs - buildOptions.RemoteContext = remote - - response, err := dockerCli.Client().ImageBuild(ctx, body, buildOptions) - if err != nil { - if options.quiet { - fmt.Fprintf(dockerCli.Err(), "%s", progBuff) - } - cancel() - return err - } - defer response.Body.Close() - - imageID := "" - aux := func(msg jsonmessage.JSONMessage) { - var result types.BuildResult - if err := json.Unmarshal(*msg.Aux, &result); err != nil { - fmt.Fprintf(dockerCli.Err(), "Failed to parse aux message: %s", err) - } else { - imageID = result.ID - } - } - - err = jsonmessage.DisplayJSONMessagesStream(response.Body, buildBuff, dockerCli.Out().FD(), dockerCli.Out().IsTerminal(), aux) - if err != nil { - if jerr, ok := err.(*jsonmessage.JSONError); ok { - // If no error code is set, default to 1 - if jerr.Code == 0 { - jerr.Code = 1 - } - if options.quiet { - fmt.Fprintf(dockerCli.Err(), "%s%s", progBuff, buildBuff) - } - return cli.StatusError{Status: jerr.Message, StatusCode: jerr.Code} - } - return err - } - - // Windows: show error message about modified file permissions if the - // daemon isn't running Windows. - if response.OSType != "windows" && runtime.GOOS == "windows" && !options.quiet { - fmt.Fprintln(dockerCli.Out(), "SECURITY WARNING: You are building a Docker "+ - "image from Windows against a non-Windows Docker host. All files and "+ - "directories added to build context will have '-rwxr-xr-x' permissions. "+ - "It is recommended to double check and reset permissions for sensitive "+ - "files and directories.") - } - - // Everything worked so if -q was provided the output from the daemon - // should be just the image ID and we'll print that to stdout. - if options.quiet { - imageID = fmt.Sprintf("%s", buildBuff) - _, _ = fmt.Fprint(dockerCli.Out(), imageID) - } - - if options.imageIDFile != "" { - if imageID == "" { - return errors.Errorf("Server did not provide an image ID. Cannot write %s", options.imageIDFile) - } - if err := os.WriteFile(options.imageIDFile, []byte(imageID), 0o666); err != nil { - return err - } - } - if !options.untrusted { - // Since the build was successful, now we must tag any of the resolved - // images from the above Dockerfile rewrite. - for _, resolved := range resolvedTags { - if err := TagTrusted(ctx, dockerCli, resolved.digestRef, resolved.tagRef); err != nil { - return err - } - } - } - - return nil -} - -func isLocalDir(c string) bool { - _, err := os.Stat(c) - return err == nil -} - -type translatorFunc func(context.Context, reference.NamedTagged) (reference.Canonical, error) - -// validateTag checks if the given image name can be resolved. -func validateTag(rawRepo string) (string, error) { - _, err := reference.ParseNormalizedNamed(rawRepo) - if err != nil { - return "", err - } - - return rawRepo, nil -} - -var dockerfileFromLinePattern = regexp.MustCompile(`(?i)^[\s]*FROM[ \f\r\t\v]+(?P[^ \f\r\t\v\n#]+)`) - -// resolvedTag records the repository, tag, and resolved digest reference -// from a Dockerfile rewrite. -type resolvedTag struct { - digestRef reference.Canonical - tagRef reference.NamedTagged -} - -// rewriteDockerfileFromForContentTrust rewrites the given Dockerfile by resolving images in -// "FROM " instructions to a digest reference. `translator` is a -// function that takes a repository name and tag reference and returns a -// trusted digest reference. -// This should be called *only* when content trust is enabled -func rewriteDockerfileFromForContentTrust(ctx context.Context, dockerfile io.Reader, translator translatorFunc) (newDockerfile []byte, resolvedTags []*resolvedTag, err error) { - scanner := bufio.NewScanner(dockerfile) - buf := bytes.NewBuffer(nil) - - // Scan the lines of the Dockerfile, looking for a "FROM" line. - for scanner.Scan() { - line := scanner.Text() - - matches := dockerfileFromLinePattern.FindStringSubmatch(line) - if matches != nil && matches[1] != api.NoBaseImageSpecifier { - // Replace the line with a resolved "FROM repo@digest" - var ref reference.Named - ref, err = reference.ParseNormalizedNamed(matches[1]) - if err != nil { - return nil, nil, err - } - ref = reference.TagNameOnly(ref) - if ref, ok := ref.(reference.NamedTagged); ok { - trustedRef, err := translator(ctx, ref) - if err != nil { - return nil, nil, err - } - - line = dockerfileFromLinePattern.ReplaceAllLiteralString(line, fmt.Sprintf("FROM %s", reference.FamiliarString(trustedRef))) - resolvedTags = append(resolvedTags, &resolvedTag{ - digestRef: trustedRef, - tagRef: ref, - }) - } - } - - _, err := fmt.Fprintln(buf, line) - if err != nil { - return nil, nil, err - } - } - - return buf.Bytes(), resolvedTags, scanner.Err() -} - -// replaceDockerfileForContentTrust wraps the given input tar archive stream and -// uses the translator to replace the Dockerfile which uses a trusted reference. -// Returns a new tar archive stream with the replaced Dockerfile. -func replaceDockerfileForContentTrust(ctx context.Context, inputTarStream io.ReadCloser, dockerfileName string, translator translatorFunc, resolvedTags *[]*resolvedTag) io.ReadCloser { - pipeReader, pipeWriter := io.Pipe() - go func() { - tarReader := tar.NewReader(inputTarStream) - tarWriter := tar.NewWriter(pipeWriter) - - defer inputTarStream.Close() - - for { - hdr, err := tarReader.Next() - if err == io.EOF { - // Signals end of archive. - tarWriter.Close() - pipeWriter.Close() - return - } - if err != nil { - pipeWriter.CloseWithError(err) - return - } - - content := io.Reader(tarReader) - if hdr.Name == dockerfileName { - // This entry is the Dockerfile. Since the tar archive was - // generated from a directory on the local filesystem, the - // Dockerfile will only appear once in the archive. - var newDockerfile []byte - newDockerfile, *resolvedTags, err = rewriteDockerfileFromForContentTrust(ctx, content, translator) - if err != nil { - pipeWriter.CloseWithError(err) - return - } - hdr.Size = int64(len(newDockerfile)) - content = bytes.NewBuffer(newDockerfile) - } - - if err := tarWriter.WriteHeader(hdr); err != nil { - pipeWriter.CloseWithError(err) - return - } - - if _, err := io.Copy(tarWriter, content); err != nil { - pipeWriter.CloseWithError(err) - return - } - } - }() - - return pipeReader -} - -func imageBuildOptions(dockerCli command.Cli, options buildOptions) types.ImageBuildOptions { - configFile := dockerCli.ConfigFile() - return types.ImageBuildOptions{ - Memory: options.memory.Value(), - MemorySwap: options.memorySwap.Value(), - Tags: options.tags.GetAll(), - SuppressOutput: options.quiet, - NoCache: options.noCache, - Remove: options.rm, - ForceRemove: options.forceRm, - PullParent: options.pull, - Isolation: container.Isolation(options.isolation), - CPUSetCPUs: options.cpuSetCpus, - CPUSetMems: options.cpuSetMems, - CPUShares: options.cpuShares, - CPUQuota: options.cpuQuota, - CPUPeriod: options.cpuPeriod, - CgroupParent: options.cgroupParent, - ShmSize: options.shmSize.Value(), - Ulimits: options.ulimits.GetList(), - BuildArgs: configFile.ParseProxyConfig(dockerCli.Client().DaemonHost(), opts.ConvertKVStringsToMapWithNil(options.buildArgs.GetAll())), - Labels: opts.ConvertKVStringsToMap(options.labels.GetAll()), - CacheFrom: options.cacheFrom, - SecurityOpt: options.securityOpt, - NetworkMode: options.networkMode, - Squash: options.squash, - ExtraHosts: options.extraHosts.GetAll(), - Target: options.target, - Platform: options.platform, - } -} diff --git a/vendor/github.com/docker/cli/cli/command/image/cmd.go b/vendor/github.com/docker/cli/cli/command/image/cmd.go deleted file mode 100644 index c035da17f..000000000 --- a/vendor/github.com/docker/cli/cli/command/image/cmd.go +++ /dev/null @@ -1,32 +0,0 @@ -package image - -import ( - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/spf13/cobra" -) - -// NewImageCommand returns a cobra command for `image` subcommands -func NewImageCommand(dockerCli command.Cli) *cobra.Command { - cmd := &cobra.Command{ - Use: "image", - Short: "Manage images", - Args: cli.NoArgs, - RunE: command.ShowHelp(dockerCli.Err()), - } - cmd.AddCommand( - NewBuildCommand(dockerCli), - NewHistoryCommand(dockerCli), - NewImportCommand(dockerCli), - NewLoadCommand(dockerCli), - NewPullCommand(dockerCli), - NewPushCommand(dockerCli), - NewSaveCommand(dockerCli), - NewTagCommand(dockerCli), - newListCommand(dockerCli), - newRemoveCommand(dockerCli), - newInspectCommand(dockerCli), - NewPruneCommand(dockerCli), - ) - return cmd -} diff --git a/vendor/github.com/docker/cli/cli/command/image/formatter_history.go b/vendor/github.com/docker/cli/cli/command/image/formatter_history.go deleted file mode 100644 index 4e826cb64..000000000 --- a/vendor/github.com/docker/cli/cli/command/image/formatter_history.go +++ /dev/null @@ -1,116 +0,0 @@ -package image - -import ( - "strconv" - "strings" - "time" - - "github.com/docker/cli/cli/command/formatter" - "github.com/docker/docker/api/types/image" - "github.com/docker/docker/pkg/stringid" - units "github.com/docker/go-units" -) - -const ( - defaultHistoryTableFormat = "table {{.ID}}\t{{.CreatedSince}}\t{{.CreatedBy}}\t{{.Size}}\t{{.Comment}}" - nonHumanHistoryTableFormat = "table {{.ID}}\t{{.CreatedAt}}\t{{.CreatedBy}}\t{{.Size}}\t{{.Comment}}" - - historyIDHeader = "IMAGE" - createdByHeader = "CREATED BY" - commentHeader = "COMMENT" -) - -// NewHistoryFormat returns a format for rendering an HistoryContext -func NewHistoryFormat(source string, quiet bool, human bool) formatter.Format { - switch source { - case formatter.TableFormatKey: - switch { - case quiet: - return formatter.DefaultQuietFormat - case !human: - return nonHumanHistoryTableFormat - default: - return defaultHistoryTableFormat - } - } - - return formatter.Format(source) -} - -// HistoryWrite writes the context -func HistoryWrite(ctx formatter.Context, human bool, histories []image.HistoryResponseItem) error { - render := func(format func(subContext formatter.SubContext) error) error { - for _, history := range histories { - historyCtx := &historyContext{trunc: ctx.Trunc, h: history, human: human} - if err := format(historyCtx); err != nil { - return err - } - } - return nil - } - historyCtx := &historyContext{} - historyCtx.Header = formatter.SubHeaderContext{ - "ID": historyIDHeader, - "CreatedSince": formatter.CreatedSinceHeader, - "CreatedAt": formatter.CreatedAtHeader, - "CreatedBy": createdByHeader, - "Size": formatter.SizeHeader, - "Comment": commentHeader, - } - return ctx.Write(historyCtx, render) -} - -type historyContext struct { - formatter.HeaderContext - trunc bool - human bool - h image.HistoryResponseItem -} - -func (c *historyContext) MarshalJSON() ([]byte, error) { - return formatter.MarshalJSON(c) -} - -func (c *historyContext) ID() string { - if c.trunc { - return stringid.TruncateID(c.h.ID) - } - return c.h.ID -} - -func (c *historyContext) CreatedAt() string { - return time.Unix(c.h.Created, 0).Format(time.RFC3339) -} - -// epoch is the time before which created-at dates are not displayed with human units. -var epoch = time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC).Unix() - -func (c *historyContext) CreatedSince() string { - if !c.human { - return c.CreatedAt() - } - if c.h.Created <= epoch { - return "N/A" - } - created := units.HumanDuration(time.Now().UTC().Sub(time.Unix(c.h.Created, 0))) - return created + " ago" -} - -func (c *historyContext) CreatedBy() string { - createdBy := strings.Replace(c.h.CreatedBy, "\t", " ", -1) - if c.trunc { - return formatter.Ellipsis(createdBy, 45) - } - return createdBy -} - -func (c *historyContext) Size() string { - if c.human { - return units.HumanSizeWithPrecision(float64(c.h.Size), 3) - } - return strconv.FormatInt(c.h.Size, 10) -} - -func (c *historyContext) Comment() string { - return c.h.Comment -} diff --git a/vendor/github.com/docker/cli/cli/command/image/history.go b/vendor/github.com/docker/cli/cli/command/image/history.go deleted file mode 100644 index c302e1bd4..000000000 --- a/vendor/github.com/docker/cli/cli/command/image/history.go +++ /dev/null @@ -1,68 +0,0 @@ -package image - -import ( - "context" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/formatter" - flagsHelper "github.com/docker/cli/cli/flags" - "github.com/spf13/cobra" -) - -type historyOptions struct { - image string - - human bool - quiet bool - noTrunc bool - format string -} - -// NewHistoryCommand creates a new `docker history` command -func NewHistoryCommand(dockerCli command.Cli) *cobra.Command { - var opts historyOptions - - cmd := &cobra.Command{ - Use: "history [OPTIONS] IMAGE", - Short: "Show the history of an image", - Args: cli.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - opts.image = args[0] - return runHistory(dockerCli, opts) - }, - Annotations: map[string]string{ - "aliases": "docker image history, docker history", - }, - } - - flags := cmd.Flags() - - flags.BoolVarP(&opts.human, "human", "H", true, "Print sizes and dates in human readable format") - flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Only show image IDs") - flags.BoolVar(&opts.noTrunc, "no-trunc", false, "Don't truncate output") - flags.StringVar(&opts.format, "format", "", flagsHelper.FormatHelp) - - return cmd -} - -func runHistory(dockerCli command.Cli, opts historyOptions) error { - ctx := context.Background() - - history, err := dockerCli.Client().ImageHistory(ctx, opts.image) - if err != nil { - return err - } - - format := opts.format - if len(format) == 0 { - format = formatter.TableFormatKey - } - - historyCtx := formatter.Context{ - Output: dockerCli.Out(), - Format: NewHistoryFormat(format, opts.quiet, opts.human), - Trunc: !opts.noTrunc, - } - return HistoryWrite(historyCtx, opts.human, history) -} diff --git a/vendor/github.com/docker/cli/cli/command/image/import.go b/vendor/github.com/docker/cli/cli/command/image/import.go deleted file mode 100644 index 1923eded7..000000000 --- a/vendor/github.com/docker/cli/cli/command/image/import.go +++ /dev/null @@ -1,92 +0,0 @@ -package image - -import ( - "context" - "os" - "strings" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - dockeropts "github.com/docker/cli/opts" - "github.com/docker/docker/api/types" - "github.com/docker/docker/pkg/jsonmessage" - "github.com/spf13/cobra" -) - -type importOptions struct { - source string - reference string - changes dockeropts.ListOpts - message string - platform string -} - -// NewImportCommand creates a new `docker import` command -func NewImportCommand(dockerCli command.Cli) *cobra.Command { - var options importOptions - - cmd := &cobra.Command{ - Use: "import [OPTIONS] file|URL|- [REPOSITORY[:TAG]]", - Short: "Import the contents from a tarball to create a filesystem image", - Args: cli.RequiresMinArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - options.source = args[0] - if len(args) > 1 { - options.reference = args[1] - } - return runImport(dockerCli, options) - }, - Annotations: map[string]string{ - "aliases": "docker image import, docker import", - }, - } - - flags := cmd.Flags() - - options.changes = dockeropts.NewListOpts(nil) - flags.VarP(&options.changes, "change", "c", "Apply Dockerfile instruction to the created image") - flags.StringVarP(&options.message, "message", "m", "", "Set commit message for imported image") - command.AddPlatformFlag(flags, &options.platform) - - return cmd -} - -func runImport(dockerCli command.Cli, options importOptions) error { - var source types.ImageImportSource - switch { - case options.source == "-": - // import from STDIN - source = types.ImageImportSource{ - Source: dockerCli.In(), - SourceName: options.source, - } - case strings.HasPrefix(options.source, "https://"), strings.HasPrefix(options.source, "http://"): - // import from a remote source (handled by the daemon) - source = types.ImageImportSource{ - SourceName: options.source, - } - default: - // import from a local file - file, err := os.Open(options.source) - if err != nil { - return err - } - defer file.Close() - source = types.ImageImportSource{ - Source: file, - SourceName: "-", - } - } - - responseBody, err := dockerCli.Client().ImageImport(context.Background(), source, options.reference, types.ImageImportOptions{ - Message: options.message, - Changes: options.changes.GetAll(), - Platform: options.platform, - }) - if err != nil { - return err - } - defer responseBody.Close() - - return jsonmessage.DisplayJSONMessagesToStream(responseBody, dockerCli.Out(), nil) -} diff --git a/vendor/github.com/docker/cli/cli/command/image/inspect.go b/vendor/github.com/docker/cli/cli/command/image/inspect.go deleted file mode 100644 index 2e3d5bf08..000000000 --- a/vendor/github.com/docker/cli/cli/command/image/inspect.go +++ /dev/null @@ -1,45 +0,0 @@ -package image - -import ( - "context" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/inspect" - flagsHelper "github.com/docker/cli/cli/flags" - "github.com/spf13/cobra" -) - -type inspectOptions struct { - format string - refs []string -} - -// newInspectCommand creates a new cobra.Command for `docker image inspect` -func newInspectCommand(dockerCli command.Cli) *cobra.Command { - var opts inspectOptions - - cmd := &cobra.Command{ - Use: "inspect [OPTIONS] IMAGE [IMAGE...]", - Short: "Display detailed information on one or more images", - Args: cli.RequiresMinArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - opts.refs = args - return runInspect(dockerCli, opts) - }, - } - - flags := cmd.Flags() - flags.StringVarP(&opts.format, "format", "f", "", flagsHelper.InspectFormatHelp) - return cmd -} - -func runInspect(dockerCli command.Cli, opts inspectOptions) error { - client := dockerCli.Client() - ctx := context.Background() - - getRefFunc := func(ref string) (interface{}, []byte, error) { - return client.ImageInspectWithRaw(ctx, ref) - } - return inspect.Inspect(dockerCli.Out(), opts.refs, opts.format, getRefFunc) -} diff --git a/vendor/github.com/docker/cli/cli/command/image/list.go b/vendor/github.com/docker/cli/cli/command/image/list.go deleted file mode 100644 index 2dd062da2..000000000 --- a/vendor/github.com/docker/cli/cli/command/image/list.go +++ /dev/null @@ -1,101 +0,0 @@ -package image - -import ( - "context" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/formatter" - flagsHelper "github.com/docker/cli/cli/flags" - "github.com/docker/cli/opts" - "github.com/docker/docker/api/types" - "github.com/spf13/cobra" -) - -type imagesOptions struct { - matchName string - - quiet bool - all bool - noTrunc bool - showDigests bool - format string - filter opts.FilterOpt -} - -// NewImagesCommand creates a new `docker images` command -func NewImagesCommand(dockerCli command.Cli) *cobra.Command { - options := imagesOptions{filter: opts.NewFilterOpt()} - - cmd := &cobra.Command{ - Use: "images [OPTIONS] [REPOSITORY[:TAG]]", - Short: "List images", - Args: cli.RequiresMaxArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - if len(args) > 0 { - options.matchName = args[0] - } - return runImages(dockerCli, options) - }, - Annotations: map[string]string{ - "category-top": "7", - "aliases": "docker image ls, docker image list, docker images", - }, - } - - flags := cmd.Flags() - - flags.BoolVarP(&options.quiet, "quiet", "q", false, "Only show image IDs") - flags.BoolVarP(&options.all, "all", "a", false, "Show all images (default hides intermediate images)") - flags.BoolVar(&options.noTrunc, "no-trunc", false, "Don't truncate output") - flags.BoolVar(&options.showDigests, "digests", false, "Show digests") - flags.StringVar(&options.format, "format", "", flagsHelper.FormatHelp) - flags.VarP(&options.filter, "filter", "f", "Filter output based on conditions provided") - - return cmd -} - -func newListCommand(dockerCli command.Cli) *cobra.Command { - cmd := *NewImagesCommand(dockerCli) - cmd.Aliases = []string{"list"} - cmd.Use = "ls [OPTIONS] [REPOSITORY[:TAG]]" - return &cmd -} - -func runImages(dockerCli command.Cli, options imagesOptions) error { - ctx := context.Background() - - filters := options.filter.Value() - if options.matchName != "" { - filters.Add("reference", options.matchName) - } - - listOptions := types.ImageListOptions{ - All: options.all, - Filters: filters, - } - - images, err := dockerCli.Client().ImageList(ctx, listOptions) - if err != nil { - return err - } - - format := options.format - if len(format) == 0 { - if len(dockerCli.ConfigFile().ImagesFormat) > 0 && !options.quiet { - format = dockerCli.ConfigFile().ImagesFormat - } else { - format = formatter.TableFormatKey - } - } - - imageCtx := formatter.ImageContext{ - Context: formatter.Context{ - Output: dockerCli.Out(), - Format: formatter.NewImageFormat(format, options.quiet, options.showDigests), - Trunc: !options.noTrunc, - }, - Digest: options.showDigests, - } - return formatter.ImageWrite(imageCtx, images) -} diff --git a/vendor/github.com/docker/cli/cli/command/image/load.go b/vendor/github.com/docker/cli/cli/command/image/load.go deleted file mode 100644 index 517610ec0..000000000 --- a/vendor/github.com/docker/cli/cli/command/image/load.go +++ /dev/null @@ -1,80 +0,0 @@ -package image - -import ( - "context" - "io" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/docker/docker/pkg/jsonmessage" - "github.com/moby/sys/sequential" - "github.com/pkg/errors" - "github.com/spf13/cobra" -) - -type loadOptions struct { - input string - quiet bool -} - -// NewLoadCommand creates a new `docker load` command -func NewLoadCommand(dockerCli command.Cli) *cobra.Command { - var opts loadOptions - - cmd := &cobra.Command{ - Use: "load [OPTIONS]", - Short: "Load an image from a tar archive or STDIN", - Args: cli.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - return runLoad(dockerCli, opts) - }, - Annotations: map[string]string{ - "aliases": "docker image load, docker load", - }, - ValidArgsFunction: completion.NoComplete, - } - - flags := cmd.Flags() - - flags.StringVarP(&opts.input, "input", "i", "", "Read from tar archive file, instead of STDIN") - flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Suppress the load output") - - return cmd -} - -func runLoad(dockerCli command.Cli, opts loadOptions) error { - var input io.Reader = dockerCli.In() - if opts.input != "" { - // We use sequential.Open to use sequential file access on Windows, avoiding - // depleting the standby list un-necessarily. On Linux, this equates to a regular os.Open. - file, err := sequential.Open(opts.input) - if err != nil { - return err - } - defer file.Close() - input = file - } - - // To avoid getting stuck, verify that a tar file is given either in - // the input flag or through stdin and if not display an error message and exit. - if opts.input == "" && dockerCli.In().IsTerminal() { - return errors.Errorf("requested load from stdin, but stdin is empty") - } - - if !dockerCli.Out().IsTerminal() { - opts.quiet = true - } - response, err := dockerCli.Client().ImageLoad(context.Background(), input, opts.quiet) - if err != nil { - return err - } - defer response.Body.Close() - - if response.Body != nil && response.JSON { - return jsonmessage.DisplayJSONMessagesToStream(response.Body, dockerCli.Out(), nil) - } - - _, err = io.Copy(dockerCli.Out(), response.Body) - return err -} diff --git a/vendor/github.com/docker/cli/cli/command/image/prune.go b/vendor/github.com/docker/cli/cli/command/image/prune.go deleted file mode 100644 index c94c1be59..000000000 --- a/vendor/github.com/docker/cli/cli/command/image/prune.go +++ /dev/null @@ -1,103 +0,0 @@ -package image - -import ( - "context" - "fmt" - "strings" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/docker/cli/opts" - units "github.com/docker/go-units" - "github.com/spf13/cobra" -) - -type pruneOptions struct { - force bool - all bool - filter opts.FilterOpt -} - -// NewPruneCommand returns a new cobra prune command for images -func NewPruneCommand(dockerCli command.Cli) *cobra.Command { - options := pruneOptions{filter: opts.NewFilterOpt()} - - cmd := &cobra.Command{ - Use: "prune [OPTIONS]", - Short: "Remove unused images", - Args: cli.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - spaceReclaimed, output, err := runPrune(dockerCli, options) - if err != nil { - return err - } - if output != "" { - fmt.Fprintln(dockerCli.Out(), output) - } - fmt.Fprintln(dockerCli.Out(), "Total reclaimed space:", units.HumanSize(float64(spaceReclaimed))) - return nil - }, - Annotations: map[string]string{"version": "1.25"}, - ValidArgsFunction: completion.NoComplete, - } - - flags := cmd.Flags() - flags.BoolVarP(&options.force, "force", "f", false, "Do not prompt for confirmation") - flags.BoolVarP(&options.all, "all", "a", false, "Remove all unused images, not just dangling ones") - flags.Var(&options.filter, "filter", `Provide filter values (e.g. "until=")`) - - return cmd -} - -const ( - allImageWarning = `WARNING! This will remove all images without at least one container associated to them. -Are you sure you want to continue?` - danglingWarning = `WARNING! This will remove all dangling images. -Are you sure you want to continue?` -) - -func runPrune(dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint64, output string, err error) { - pruneFilters := options.filter.Value().Clone() - pruneFilters.Add("dangling", fmt.Sprintf("%v", !options.all)) - pruneFilters = command.PruneFilters(dockerCli, pruneFilters) - - warning := danglingWarning - if options.all { - warning = allImageWarning - } - if !options.force && !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), warning) { - return 0, "", nil - } - - report, err := dockerCli.Client().ImagesPrune(context.Background(), pruneFilters) - if err != nil { - return 0, "", err - } - - if len(report.ImagesDeleted) > 0 { - var sb strings.Builder - sb.WriteString("Deleted Images:\n") - for _, st := range report.ImagesDeleted { - if st.Untagged != "" { - sb.WriteString("untagged: ") - sb.WriteString(st.Untagged) - sb.WriteByte('\n') - } else { - sb.WriteString("deleted: ") - sb.WriteString(st.Deleted) - sb.WriteByte('\n') - } - } - output = sb.String() - spaceReclaimed = report.SpaceReclaimed - } - - return spaceReclaimed, output, nil -} - -// RunPrune calls the Image Prune API -// This returns the amount of space reclaimed and a detailed output string -func RunPrune(dockerCli command.Cli, all bool, filter opts.FilterOpt) (uint64, string, error) { - return runPrune(dockerCli, pruneOptions{force: true, all: all, filter: filter}) -} diff --git a/vendor/github.com/docker/cli/cli/command/image/pull.go b/vendor/github.com/docker/cli/cli/command/image/pull.go deleted file mode 100644 index bfb682f5d..000000000 --- a/vendor/github.com/docker/cli/cli/command/image/pull.go +++ /dev/null @@ -1,92 +0,0 @@ -package image - -import ( - "context" - "fmt" - "strings" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/docker/cli/cli/trust" - "github.com/docker/distribution/reference" - "github.com/pkg/errors" - "github.com/spf13/cobra" -) - -// PullOptions defines what and how to pull -type PullOptions struct { - remote string - all bool - platform string - quiet bool - untrusted bool -} - -// NewPullCommand creates a new `docker pull` command -func NewPullCommand(dockerCli command.Cli) *cobra.Command { - var opts PullOptions - - cmd := &cobra.Command{ - Use: "pull [OPTIONS] NAME[:TAG|@DIGEST]", - Short: "Download an image from a registry", - Args: cli.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - opts.remote = args[0] - return RunPull(dockerCli, opts) - }, - Annotations: map[string]string{ - "category-top": "5", - "aliases": "docker image pull, docker pull", - }, - ValidArgsFunction: completion.NoComplete, - } - - flags := cmd.Flags() - - flags.BoolVarP(&opts.all, "all-tags", "a", false, "Download all tagged images in the repository") - flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Suppress verbose output") - - command.AddPlatformFlag(flags, &opts.platform) - command.AddTrustVerificationFlags(flags, &opts.untrusted, dockerCli.ContentTrustEnabled()) - - return cmd -} - -// RunPull performs a pull against the engine based on the specified options -func RunPull(cli command.Cli, opts PullOptions) error { - distributionRef, err := reference.ParseNormalizedNamed(opts.remote) - switch { - case err != nil: - return err - case opts.all && !reference.IsNameOnly(distributionRef): - return errors.New("tag can't be used with --all-tags/-a") - case !opts.all && reference.IsNameOnly(distributionRef): - distributionRef = reference.TagNameOnly(distributionRef) - if tagged, ok := distributionRef.(reference.Tagged); ok && !opts.quiet { - fmt.Fprintf(cli.Out(), "Using default tag: %s\n", tagged.Tag()) - } - } - - ctx := context.Background() - imgRefAndAuth, err := trust.GetImageReferencesAndAuth(ctx, AuthResolver(cli), distributionRef.String()) - if err != nil { - return err - } - - // Check if reference has a digest - _, isCanonical := distributionRef.(reference.Canonical) - if !opts.untrusted && !isCanonical { - err = trustedPull(ctx, cli, imgRefAndAuth, opts) - } else { - err = imagePullPrivileged(ctx, cli, imgRefAndAuth, opts) - } - if err != nil { - if strings.Contains(err.Error(), "when fetching 'plugin'") { - return errors.New(err.Error() + " - Use `docker plugin install`") - } - return err - } - fmt.Fprintln(cli.Out(), imgRefAndAuth.Reference().String()) - return nil -} diff --git a/vendor/github.com/docker/cli/cli/command/image/push.go b/vendor/github.com/docker/cli/cli/command/image/push.go deleted file mode 100644 index f60a92c33..000000000 --- a/vendor/github.com/docker/cli/cli/command/image/push.go +++ /dev/null @@ -1,110 +0,0 @@ -package image - -import ( - "context" - "fmt" - "io" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/docker/cli/cli/streams" - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" - registrytypes "github.com/docker/docker/api/types/registry" - "github.com/docker/docker/pkg/jsonmessage" - "github.com/docker/docker/registry" - "github.com/pkg/errors" - "github.com/spf13/cobra" -) - -type pushOptions struct { - all bool - remote string - untrusted bool - quiet bool -} - -// NewPushCommand creates a new `docker push` command -func NewPushCommand(dockerCli command.Cli) *cobra.Command { - var opts pushOptions - - cmd := &cobra.Command{ - Use: "push [OPTIONS] NAME[:TAG]", - Short: "Upload an image to a registry", - Args: cli.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - opts.remote = args[0] - return RunPush(dockerCli, opts) - }, - Annotations: map[string]string{ - "category-top": "6", - "aliases": "docker image push, docker push", - }, - ValidArgsFunction: completion.ImageNames(dockerCli), - } - - flags := cmd.Flags() - flags.BoolVarP(&opts.all, "all-tags", "a", false, "Push all tags of an image to the repository") - flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Suppress verbose output") - command.AddTrustSigningFlags(flags, &opts.untrusted, dockerCli.ContentTrustEnabled()) - - return cmd -} - -// RunPush performs a push against the engine based on the specified options -func RunPush(dockerCli command.Cli, opts pushOptions) error { - ref, err := reference.ParseNormalizedNamed(opts.remote) - switch { - case err != nil: - return err - case opts.all && !reference.IsNameOnly(ref): - return errors.New("tag can't be used with --all-tags/-a") - case !opts.all && reference.IsNameOnly(ref): - ref = reference.TagNameOnly(ref) - if tagged, ok := ref.(reference.Tagged); ok && !opts.quiet { - _, _ = fmt.Fprintf(dockerCli.Out(), "Using default tag: %s\n", tagged.Tag()) - } - } - - // Resolve the Repository name from fqn to RepositoryInfo - repoInfo, err := registry.ParseRepositoryInfo(ref) - if err != nil { - return err - } - - ctx := context.Background() - - // Resolve the Auth config relevant for this server - authConfig := command.ResolveAuthConfig(ctx, dockerCli, repoInfo.Index) - encodedAuth, err := registrytypes.EncodeAuthConfig(authConfig) - if err != nil { - return err - } - requestPrivilege := command.RegistryAuthenticationPrivilegedFunc(dockerCli, repoInfo.Index, "push") - options := types.ImagePushOptions{ - All: opts.all, - RegistryAuth: encodedAuth, - PrivilegeFunc: requestPrivilege, - } - - responseBody, err := dockerCli.Client().ImagePush(ctx, reference.FamiliarString(ref), options) - if err != nil { - return err - } - - defer responseBody.Close() - if !opts.untrusted { - // TODO PushTrustedReference currently doesn't respect `--quiet` - return PushTrustedReference(dockerCli, repoInfo, ref, authConfig, responseBody) - } - - if opts.quiet { - err = jsonmessage.DisplayJSONMessagesToStream(responseBody, streams.NewOut(io.Discard), nil) - if err == nil { - fmt.Fprintln(dockerCli.Out(), ref.String()) - } - return err - } - return jsonmessage.DisplayJSONMessagesToStream(responseBody, dockerCli.Out(), nil) -} diff --git a/vendor/github.com/docker/cli/cli/command/image/remove.go b/vendor/github.com/docker/cli/cli/command/image/remove.go deleted file mode 100644 index e96195b6d..000000000 --- a/vendor/github.com/docker/cli/cli/command/image/remove.go +++ /dev/null @@ -1,89 +0,0 @@ -package image - -import ( - "context" - "fmt" - "strings" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/docker/api/types" - apiclient "github.com/docker/docker/client" - "github.com/pkg/errors" - "github.com/spf13/cobra" -) - -type removeOptions struct { - force bool - noPrune bool -} - -// NewRemoveCommand creates a new `docker remove` command -func NewRemoveCommand(dockerCli command.Cli) *cobra.Command { - var opts removeOptions - - cmd := &cobra.Command{ - Use: "rmi [OPTIONS] IMAGE [IMAGE...]", - Short: "Remove one or more images", - Args: cli.RequiresMinArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - return runRemove(dockerCli, opts, args) - }, - Annotations: map[string]string{ - "aliases": "docker image rm, docker image remove, docker rmi", - }, - } - - flags := cmd.Flags() - - flags.BoolVarP(&opts.force, "force", "f", false, "Force removal of the image") - flags.BoolVar(&opts.noPrune, "no-prune", false, "Do not delete untagged parents") - - return cmd -} - -func newRemoveCommand(dockerCli command.Cli) *cobra.Command { - cmd := *NewRemoveCommand(dockerCli) - cmd.Aliases = []string{"rmi", "remove"} - cmd.Use = "rm [OPTIONS] IMAGE [IMAGE...]" - return &cmd -} - -func runRemove(dockerCli command.Cli, opts removeOptions, images []string) error { - client := dockerCli.Client() - ctx := context.Background() - - options := types.ImageRemoveOptions{ - Force: opts.force, - PruneChildren: !opts.noPrune, - } - - var errs []string - fatalErr := false - for _, img := range images { - dels, err := client.ImageRemove(ctx, img, options) - if err != nil { - if !apiclient.IsErrNotFound(err) { - fatalErr = true - } - errs = append(errs, err.Error()) - } else { - for _, del := range dels { - if del.Deleted != "" { - fmt.Fprintf(dockerCli.Out(), "Deleted: %s\n", del.Deleted) - } else { - fmt.Fprintf(dockerCli.Out(), "Untagged: %s\n", del.Untagged) - } - } - } - } - - if len(errs) > 0 { - msg := strings.Join(errs, "\n") - if !opts.force || fatalErr { - return errors.New(msg) - } - fmt.Fprintln(dockerCli.Err(), msg) - } - return nil -} diff --git a/vendor/github.com/docker/cli/cli/command/image/save.go b/vendor/github.com/docker/cli/cli/command/image/save.go deleted file mode 100644 index 8063c0e78..000000000 --- a/vendor/github.com/docker/cli/cli/command/image/save.go +++ /dev/null @@ -1,66 +0,0 @@ -package image - -import ( - "context" - "io" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/pkg/errors" - "github.com/spf13/cobra" -) - -type saveOptions struct { - images []string - output string -} - -// NewSaveCommand creates a new `docker save` command -func NewSaveCommand(dockerCli command.Cli) *cobra.Command { - var opts saveOptions - - cmd := &cobra.Command{ - Use: "save [OPTIONS] IMAGE [IMAGE...]", - Short: "Save one or more images to a tar archive (streamed to STDOUT by default)", - Args: cli.RequiresMinArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - opts.images = args - return RunSave(dockerCli, opts) - }, - Annotations: map[string]string{ - "aliases": "docker image save, docker save", - }, - ValidArgsFunction: completion.ImageNames(dockerCli), - } - - flags := cmd.Flags() - - flags.StringVarP(&opts.output, "output", "o", "", "Write to a file, instead of STDOUT") - - return cmd -} - -// RunSave performs a save against the engine based on the specified options -func RunSave(dockerCli command.Cli, opts saveOptions) error { - if opts.output == "" && dockerCli.Out().IsTerminal() { - return errors.New("cowardly refusing to save to a terminal. Use the -o flag or redirect") - } - - if err := command.ValidateOutputPath(opts.output); err != nil { - return errors.Wrap(err, "failed to save image") - } - - responseBody, err := dockerCli.Client().ImageSave(context.Background(), opts.images) - if err != nil { - return err - } - defer responseBody.Close() - - if opts.output == "" { - _, err := io.Copy(dockerCli.Out(), responseBody) - return err - } - - return command.CopyToFile(opts.output, responseBody) -} diff --git a/vendor/github.com/docker/cli/cli/command/image/tag.go b/vendor/github.com/docker/cli/cli/command/image/tag.go deleted file mode 100644 index f63b328b5..000000000 --- a/vendor/github.com/docker/cli/cli/command/image/tag.go +++ /dev/null @@ -1,46 +0,0 @@ -package image - -import ( - "context" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/command/completion" - "github.com/spf13/cobra" -) - -type tagOptions struct { - image string - name string -} - -// NewTagCommand creates a new `docker tag` command -func NewTagCommand(dockerCli command.Cli) *cobra.Command { - var opts tagOptions - - cmd := &cobra.Command{ - Use: "tag SOURCE_IMAGE[:TAG] TARGET_IMAGE[:TAG]", - Short: "Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE", - Args: cli.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - opts.image = args[0] - opts.name = args[1] - return runTag(dockerCli, opts) - }, - Annotations: map[string]string{ - "aliases": "docker image tag, docker tag", - }, - ValidArgsFunction: completion.ImageNames(dockerCli), - } - - flags := cmd.Flags() - flags.SetInterspersed(false) - - return cmd -} - -func runTag(dockerCli command.Cli, opts tagOptions) error { - ctx := context.Background() - - return dockerCli.Client().ImageTag(ctx, opts.image, opts.name) -} diff --git a/vendor/github.com/docker/cli/cli/command/image/trust.go b/vendor/github.com/docker/cli/cli/command/image/trust.go deleted file mode 100644 index 3da1e8032..000000000 --- a/vendor/github.com/docker/cli/cli/command/image/trust.go +++ /dev/null @@ -1,344 +0,0 @@ -package image - -import ( - "context" - "encoding/hex" - "encoding/json" - "fmt" - "io" - "sort" - - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/streams" - "github.com/docker/cli/cli/trust" - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" - registrytypes "github.com/docker/docker/api/types/registry" - "github.com/docker/docker/pkg/jsonmessage" - "github.com/docker/docker/registry" - "github.com/opencontainers/go-digest" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" - "github.com/theupdateframework/notary/client" - "github.com/theupdateframework/notary/tuf/data" -) - -type target struct { - name string - digest digest.Digest - size int64 -} - -// TrustedPush handles content trust pushing of an image -func TrustedPush(ctx context.Context, cli command.Cli, repoInfo *registry.RepositoryInfo, ref reference.Named, authConfig registrytypes.AuthConfig, options types.ImagePushOptions) error { - responseBody, err := cli.Client().ImagePush(ctx, reference.FamiliarString(ref), options) - if err != nil { - return err - } - - defer responseBody.Close() - - return PushTrustedReference(cli, repoInfo, ref, authConfig, responseBody) -} - -// PushTrustedReference pushes a canonical reference to the trust server. -// -//nolint:gocyclo -func PushTrustedReference(streams command.Streams, repoInfo *registry.RepositoryInfo, ref reference.Named, authConfig registrytypes.AuthConfig, in io.Reader) error { - // If it is a trusted push we would like to find the target entry which match the - // tag provided in the function and then do an AddTarget later. - target := &client.Target{} - // Count the times of calling for handleTarget, - // if it is called more that once, that should be considered an error in a trusted push. - cnt := 0 - handleTarget := func(msg jsonmessage.JSONMessage) { - cnt++ - if cnt > 1 { - // handleTarget should only be called once. This will be treated as an error. - return - } - - var pushResult types.PushResult - err := json.Unmarshal(*msg.Aux, &pushResult) - if err == nil && pushResult.Tag != "" { - if dgst, err := digest.Parse(pushResult.Digest); err == nil { - h, err := hex.DecodeString(dgst.Hex()) - if err != nil { - target = nil - return - } - target.Name = pushResult.Tag - target.Hashes = data.Hashes{string(dgst.Algorithm()): h} - target.Length = int64(pushResult.Size) - } - } - } - - var tag string - switch x := ref.(type) { - case reference.Canonical: - return errors.New("cannot push a digest reference") - case reference.NamedTagged: - tag = x.Tag() - default: - // We want trust signatures to always take an explicit tag, - // otherwise it will act as an untrusted push. - if err := jsonmessage.DisplayJSONMessagesToStream(in, streams.Out(), nil); err != nil { - return err - } - fmt.Fprintln(streams.Err(), "No tag specified, skipping trust metadata push") - return nil - } - - if err := jsonmessage.DisplayJSONMessagesToStream(in, streams.Out(), handleTarget); err != nil { - return err - } - - if cnt > 1 { - return errors.Errorf("internal error: only one call to handleTarget expected") - } - - if target == nil { - return errors.Errorf("no targets found, please provide a specific tag in order to sign it") - } - - fmt.Fprintln(streams.Out(), "Signing and pushing trust metadata") - - repo, err := trust.GetNotaryRepository(streams.In(), streams.Out(), command.UserAgent(), repoInfo, &authConfig, "push", "pull") - if err != nil { - return errors.Wrap(err, "error establishing connection to trust repository") - } - - // get the latest repository metadata so we can figure out which roles to sign - _, err = repo.ListTargets() - - switch err.(type) { - case client.ErrRepoNotInitialized, client.ErrRepositoryNotExist: - keys := repo.GetCryptoService().ListKeys(data.CanonicalRootRole) - var rootKeyID string - // always select the first root key - if len(keys) > 0 { - sort.Strings(keys) - rootKeyID = keys[0] - } else { - rootPublicKey, err := repo.GetCryptoService().Create(data.CanonicalRootRole, "", data.ECDSAKey) - if err != nil { - return err - } - rootKeyID = rootPublicKey.ID() - } - - // Initialize the notary repository with a remotely managed snapshot key - if err := repo.Initialize([]string{rootKeyID}, data.CanonicalSnapshotRole); err != nil { - return trust.NotaryError(repoInfo.Name.Name(), err) - } - fmt.Fprintf(streams.Out(), "Finished initializing %q\n", repoInfo.Name.Name()) - err = repo.AddTarget(target, data.CanonicalTargetsRole) - case nil: - // already initialized and we have successfully downloaded the latest metadata - err = AddTargetToAllSignableRoles(repo, target) - default: - return trust.NotaryError(repoInfo.Name.Name(), err) - } - - if err == nil { - err = repo.Publish() - } - - if err != nil { - err = errors.Wrapf(err, "failed to sign %s:%s", repoInfo.Name.Name(), tag) - return trust.NotaryError(repoInfo.Name.Name(), err) - } - - fmt.Fprintf(streams.Out(), "Successfully signed %s:%s\n", repoInfo.Name.Name(), tag) - return nil -} - -// AddTargetToAllSignableRoles attempts to add the image target to all the top level delegation roles we can -// (based on whether we have the signing key and whether the role's path allows -// us to). -// If there are no delegation roles, we add to the targets role. -func AddTargetToAllSignableRoles(repo client.Repository, target *client.Target) error { - signableRoles, err := trust.GetSignableRoles(repo, target) - if err != nil { - return err - } - - return repo.AddTarget(target, signableRoles...) -} - -// trustedPull handles content trust pulling of an image -func trustedPull(ctx context.Context, cli command.Cli, imgRefAndAuth trust.ImageRefAndAuth, opts PullOptions) error { - refs, err := getTrustedPullTargets(cli, imgRefAndAuth) - if err != nil { - return err - } - - ref := imgRefAndAuth.Reference() - for i, r := range refs { - displayTag := r.name - if displayTag != "" { - displayTag = ":" + displayTag - } - fmt.Fprintf(cli.Out(), "Pull (%d of %d): %s%s@%s\n", i+1, len(refs), reference.FamiliarName(ref), displayTag, r.digest) - - trustedRef, err := reference.WithDigest(reference.TrimNamed(ref), r.digest) - if err != nil { - return err - } - updatedImgRefAndAuth, err := trust.GetImageReferencesAndAuth(ctx, AuthResolver(cli), trustedRef.String()) - if err != nil { - return err - } - if err := imagePullPrivileged(ctx, cli, updatedImgRefAndAuth, PullOptions{ - all: false, - platform: opts.platform, - quiet: opts.quiet, - remote: opts.remote, - }); err != nil { - return err - } - - tagged, err := reference.WithTag(reference.TrimNamed(ref), r.name) - if err != nil { - return err - } - - if err := TagTrusted(ctx, cli, trustedRef, tagged); err != nil { - return err - } - } - return nil -} - -func getTrustedPullTargets(cli command.Cli, imgRefAndAuth trust.ImageRefAndAuth) ([]target, error) { - notaryRepo, err := cli.NotaryClient(imgRefAndAuth, trust.ActionsPullOnly) - if err != nil { - return nil, errors.Wrap(err, "error establishing connection to trust repository") - } - - ref := imgRefAndAuth.Reference() - tagged, isTagged := ref.(reference.NamedTagged) - if !isTagged { - // List all targets - targets, err := notaryRepo.ListTargets(trust.ReleasesRole, data.CanonicalTargetsRole) - if err != nil { - return nil, trust.NotaryError(ref.Name(), err) - } - var refs []target - for _, tgt := range targets { - t, err := convertTarget(tgt.Target) - if err != nil { - fmt.Fprintf(cli.Err(), "Skipping target for %q\n", reference.FamiliarName(ref)) - continue - } - // Only list tags in the top level targets role or the releases delegation role - ignore - // all other delegation roles - if tgt.Role != trust.ReleasesRole && tgt.Role != data.CanonicalTargetsRole { - continue - } - refs = append(refs, t) - } - if len(refs) == 0 { - return nil, trust.NotaryError(ref.Name(), errors.Errorf("No trusted tags for %s", ref.Name())) - } - return refs, nil - } - - t, err := notaryRepo.GetTargetByName(tagged.Tag(), trust.ReleasesRole, data.CanonicalTargetsRole) - if err != nil { - return nil, trust.NotaryError(ref.Name(), err) - } - // Only get the tag if it's in the top level targets role or the releases delegation role - // ignore it if it's in any other delegation roles - if t.Role != trust.ReleasesRole && t.Role != data.CanonicalTargetsRole { - return nil, trust.NotaryError(ref.Name(), errors.Errorf("No trust data for %s", tagged.Tag())) - } - - logrus.Debugf("retrieving target for %s role", t.Role) - r, err := convertTarget(t.Target) - return []target{r}, err -} - -// imagePullPrivileged pulls the image and displays it to the output -func imagePullPrivileged(ctx context.Context, cli command.Cli, imgRefAndAuth trust.ImageRefAndAuth, opts PullOptions) error { - encodedAuth, err := registrytypes.EncodeAuthConfig(*imgRefAndAuth.AuthConfig()) - if err != nil { - return err - } - requestPrivilege := command.RegistryAuthenticationPrivilegedFunc(cli, imgRefAndAuth.RepoInfo().Index, "pull") - responseBody, err := cli.Client().ImagePull(ctx, reference.FamiliarString(imgRefAndAuth.Reference()), types.ImagePullOptions{ - RegistryAuth: encodedAuth, - PrivilegeFunc: requestPrivilege, - All: opts.all, - Platform: opts.platform, - }) - if err != nil { - return err - } - defer responseBody.Close() - - out := cli.Out() - if opts.quiet { - out = streams.NewOut(io.Discard) - } - return jsonmessage.DisplayJSONMessagesToStream(responseBody, out, nil) -} - -// TrustedReference returns the canonical trusted reference for an image reference -func TrustedReference(ctx context.Context, cli command.Cli, ref reference.NamedTagged) (reference.Canonical, error) { - imgRefAndAuth, err := trust.GetImageReferencesAndAuth(ctx, AuthResolver(cli), ref.String()) - if err != nil { - return nil, err - } - - notaryRepo, err := cli.NotaryClient(imgRefAndAuth, []string{"pull"}) - if err != nil { - return nil, errors.Wrap(err, "error establishing connection to trust repository") - } - - t, err := notaryRepo.GetTargetByName(ref.Tag(), trust.ReleasesRole, data.CanonicalTargetsRole) - if err != nil { - return nil, trust.NotaryError(imgRefAndAuth.RepoInfo().Name.Name(), err) - } - // Only list tags in the top level targets role or the releases delegation role - ignore - // all other delegation roles - if t.Role != trust.ReleasesRole && t.Role != data.CanonicalTargetsRole { - return nil, trust.NotaryError(imgRefAndAuth.RepoInfo().Name.Name(), client.ErrNoSuchTarget(ref.Tag())) - } - r, err := convertTarget(t.Target) - if err != nil { - return nil, err - } - return reference.WithDigest(reference.TrimNamed(ref), r.digest) -} - -func convertTarget(t client.Target) (target, error) { - h, ok := t.Hashes["sha256"] - if !ok { - return target{}, errors.New("no valid hash, expecting sha256") - } - return target{ - name: t.Name, - digest: digest.NewDigestFromHex("sha256", hex.EncodeToString(h)), - size: t.Length, - }, nil -} - -// TagTrusted tags a trusted ref -func TagTrusted(ctx context.Context, cli command.Cli, trustedRef reference.Canonical, ref reference.NamedTagged) error { - // Use familiar references when interacting with client and output - familiarRef := reference.FamiliarString(ref) - trustedFamiliarRef := reference.FamiliarString(trustedRef) - - fmt.Fprintf(cli.Err(), "Tagging %s as %s\n", trustedFamiliarRef, familiarRef) - - return cli.Client().ImageTag(ctx, trustedFamiliarRef, familiarRef) -} - -// AuthResolver returns an auth resolver function from a command.Cli -func AuthResolver(cli command.Cli) func(ctx context.Context, index *registrytypes.IndexInfo) registrytypes.AuthConfig { - return func(ctx context.Context, index *registrytypes.IndexInfo) registrytypes.AuthConfig { - return command.ResolveAuthConfig(ctx, cli, index) - } -} diff --git a/vendor/github.com/docker/cli/cli/command/inspect/inspector.go b/vendor/github.com/docker/cli/cli/command/inspect/inspector.go deleted file mode 100644 index 4a6f21080..000000000 --- a/vendor/github.com/docker/cli/cli/command/inspect/inspector.go +++ /dev/null @@ -1,221 +0,0 @@ -package inspect - -import ( - "bytes" - "encoding/json" - "io" - "strings" - "text/template" - - "github.com/docker/cli/cli" - "github.com/docker/cli/templates" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" -) - -// Inspector defines an interface to implement to process elements -type Inspector interface { - // Inspect writes the raw element in JSON format. - Inspect(typedElement interface{}, rawElement []byte) error - // Flush writes the result of inspecting all elements into the output stream. - Flush() error -} - -// TemplateInspector uses a text template to inspect elements. -type TemplateInspector struct { - outputStream io.Writer - buffer *bytes.Buffer - tmpl *template.Template -} - -// NewTemplateInspector creates a new inspector with a template. -func NewTemplateInspector(outputStream io.Writer, tmpl *template.Template) Inspector { - return &TemplateInspector{ - outputStream: outputStream, - buffer: new(bytes.Buffer), - tmpl: tmpl, - } -} - -// NewTemplateInspectorFromString creates a new TemplateInspector from a string -// which is compiled into a template. -func NewTemplateInspectorFromString(out io.Writer, tmplStr string) (Inspector, error) { - if tmplStr == "" { - return NewIndentedInspector(out), nil - } - - if tmplStr == "json" { - return NewJSONInspector(out), nil - } - - tmpl, err := templates.Parse(tmplStr) - if err != nil { - return nil, errors.Errorf("template parsing error: %s", err) - } - return NewTemplateInspector(out, tmpl), nil -} - -// GetRefFunc is a function which used by Inspect to fetch an object from a -// reference -type GetRefFunc func(ref string) (interface{}, []byte, error) - -// Inspect fetches objects by reference using GetRefFunc and writes the json -// representation to the output writer. -func Inspect(out io.Writer, references []string, tmplStr string, getRef GetRefFunc) error { - inspector, err := NewTemplateInspectorFromString(out, tmplStr) - if err != nil { - return cli.StatusError{StatusCode: 64, Status: err.Error()} - } - - var inspectErrs []string - for _, ref := range references { - element, raw, err := getRef(ref) - if err != nil { - inspectErrs = append(inspectErrs, err.Error()) - continue - } - - if err := inspector.Inspect(element, raw); err != nil { - inspectErrs = append(inspectErrs, err.Error()) - } - } - - if err := inspector.Flush(); err != nil { - logrus.Errorf("%s\n", err) - } - - if len(inspectErrs) != 0 { - return cli.StatusError{ - StatusCode: 1, - Status: strings.Join(inspectErrs, "\n"), - } - } - return nil -} - -// Inspect executes the inspect template. -// It decodes the raw element into a map if the initial execution fails. -// This allows docker cli to parse inspect structs injected with Swarm fields. -func (i *TemplateInspector) Inspect(typedElement interface{}, rawElement []byte) error { - buffer := new(bytes.Buffer) - if err := i.tmpl.Execute(buffer, typedElement); err != nil { - if rawElement == nil { - return errors.Errorf("template parsing error: %v", err) - } - return i.tryRawInspectFallback(rawElement) - } - i.buffer.Write(buffer.Bytes()) - i.buffer.WriteByte('\n') - return nil -} - -// tryRawInspectFallback executes the inspect template with a raw interface. -// This allows docker cli to parse inspect structs injected with Swarm fields. -func (i *TemplateInspector) tryRawInspectFallback(rawElement []byte) error { - var raw interface{} - buffer := new(bytes.Buffer) - rdr := bytes.NewReader(rawElement) - dec := json.NewDecoder(rdr) - dec.UseNumber() - - if rawErr := dec.Decode(&raw); rawErr != nil { - return errors.Errorf("unable to read inspect data: %v", rawErr) - } - - tmplMissingKey := i.tmpl.Option("missingkey=error") - if rawErr := tmplMissingKey.Execute(buffer, raw); rawErr != nil { - return errors.Errorf("template parsing error: %v", rawErr) - } - - i.buffer.Write(buffer.Bytes()) - i.buffer.WriteByte('\n') - return nil -} - -// Flush writes the result of inspecting all elements into the output stream. -func (i *TemplateInspector) Flush() error { - if i.buffer.Len() == 0 { - _, err := io.WriteString(i.outputStream, "\n") - return err - } - _, err := io.Copy(i.outputStream, i.buffer) - return err -} - -// NewIndentedInspector generates a new inspector with an indented representation -// of elements. -func NewIndentedInspector(outputStream io.Writer) Inspector { - return &elementsInspector{ - outputStream: outputStream, - raw: func(dst *bytes.Buffer, src []byte) error { - return json.Indent(dst, src, "", " ") - }, - el: func(v interface{}) ([]byte, error) { - return json.MarshalIndent(v, "", " ") - }, - } -} - -// NewJSONInspector generates a new inspector with a compact representation -// of elements. -func NewJSONInspector(outputStream io.Writer) Inspector { - return &elementsInspector{ - outputStream: outputStream, - raw: json.Compact, - el: json.Marshal, - } -} - -type elementsInspector struct { - outputStream io.Writer - elements []interface{} - rawElements [][]byte - raw func(dst *bytes.Buffer, src []byte) error - el func(v interface{}) ([]byte, error) -} - -func (e *elementsInspector) Inspect(typedElement interface{}, rawElement []byte) error { - if rawElement != nil { - e.rawElements = append(e.rawElements, rawElement) - } else { - e.elements = append(e.elements, typedElement) - } - return nil -} - -func (e *elementsInspector) Flush() error { - if len(e.elements) == 0 && len(e.rawElements) == 0 { - _, err := io.WriteString(e.outputStream, "[]\n") - return err - } - - var buffer io.Reader - if len(e.rawElements) > 0 { - bytesBuffer := new(bytes.Buffer) - bytesBuffer.WriteString("[") - for idx, r := range e.rawElements { - bytesBuffer.Write(r) - if idx < len(e.rawElements)-1 { - bytesBuffer.WriteString(",") - } - } - bytesBuffer.WriteString("]") - output := new(bytes.Buffer) - if err := e.raw(output, bytesBuffer.Bytes()); err != nil { - return err - } - buffer = output - } else { - b, err := e.el(e.elements) - if err != nil { - return err - } - buffer = bytes.NewReader(b) - } - - if _, err := io.Copy(e.outputStream, buffer); err != nil { - return err - } - _, err := io.WriteString(e.outputStream, "\n") - return err -} diff --git a/vendor/github.com/docker/cli/cli/command/registry.go b/vendor/github.com/docker/cli/cli/command/registry.go deleted file mode 100644 index 95c16d7dc..000000000 --- a/vendor/github.com/docker/cli/cli/command/registry.go +++ /dev/null @@ -1,215 +0,0 @@ -package command - -import ( - "bufio" - "context" - "fmt" - "io" - "os" - "runtime" - "strings" - - configtypes "github.com/docker/cli/cli/config/types" - "github.com/docker/cli/cli/hints" - "github.com/docker/cli/cli/streams" - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" - registrytypes "github.com/docker/docker/api/types/registry" - "github.com/docker/docker/registry" - "github.com/moby/term" - "github.com/pkg/errors" -) - -const patSuggest = "You can log in with your password or a Personal Access " + - "Token (PAT). Using a limited-scope PAT grants better security and is required " + - "for organizations using SSO. Learn more at https://docs.docker.com/go/access-tokens/" - -// EncodeAuthToBase64 serializes the auth configuration as JSON base64 payload. -// -// Deprecated: use [registrytypes.EncodeAuthConfig] instead. -func EncodeAuthToBase64(authConfig registrytypes.AuthConfig) (string, error) { - return registrytypes.EncodeAuthConfig(authConfig) -} - -// RegistryAuthenticationPrivilegedFunc returns a RequestPrivilegeFunc from the specified registry index info -// for the given command. -func RegistryAuthenticationPrivilegedFunc(cli Cli, index *registrytypes.IndexInfo, cmdName string) types.RequestPrivilegeFunc { - return func() (string, error) { - fmt.Fprintf(cli.Out(), "\nPlease login prior to %s:\n", cmdName) - indexServer := registry.GetAuthConfigKey(index) - isDefaultRegistry := indexServer == registry.IndexServer - authConfig, err := GetDefaultAuthConfig(cli, true, indexServer, isDefaultRegistry) - if err != nil { - fmt.Fprintf(cli.Err(), "Unable to retrieve stored credentials for %s, error: %s.\n", indexServer, err) - } - err = ConfigureAuth(cli, "", "", &authConfig, isDefaultRegistry) - if err != nil { - return "", err - } - return registrytypes.EncodeAuthConfig(authConfig) - } -} - -// ResolveAuthConfig returns auth-config for the given registry from the -// credential-store. It returns an empty AuthConfig if no credentials were -// found. -// -// It is similar to [registry.ResolveAuthConfig], but uses the credentials- -// store, instead of looking up credentials from a map. -func ResolveAuthConfig(_ context.Context, cli Cli, index *registrytypes.IndexInfo) registrytypes.AuthConfig { - configKey := index.Name - if index.Official { - configKey = registry.IndexServer - } - - a, _ := cli.ConfigFile().GetAuthConfig(configKey) - return registrytypes.AuthConfig(a) -} - -// GetDefaultAuthConfig gets the default auth config given a serverAddress -// If credentials for given serverAddress exists in the credential store, the configuration will be populated with values in it -func GetDefaultAuthConfig(cli Cli, checkCredStore bool, serverAddress string, isDefaultRegistry bool) (registrytypes.AuthConfig, error) { - if !isDefaultRegistry { - serverAddress = registry.ConvertToHostname(serverAddress) - } - authconfig := configtypes.AuthConfig{} - var err error - if checkCredStore { - authconfig, err = cli.ConfigFile().GetAuthConfig(serverAddress) - if err != nil { - return registrytypes.AuthConfig{ - ServerAddress: serverAddress, - }, err - } - } - authconfig.ServerAddress = serverAddress - authconfig.IdentityToken = "" - res := registrytypes.AuthConfig(authconfig) - return res, nil -} - -// ConfigureAuth handles prompting of user's username and password if needed -func ConfigureAuth(cli Cli, flUser, flPassword string, authconfig *registrytypes.AuthConfig, isDefaultRegistry bool) error { - // On Windows, force the use of the regular OS stdin stream. - // - // See: - // - https://github.com/moby/moby/issues/14336 - // - https://github.com/moby/moby/issues/14210 - // - https://github.com/moby/moby/pull/17738 - // - // TODO(thaJeztah): we need to confirm if this special handling is still needed, as we may not be doing this in other places. - if runtime.GOOS == "windows" { - cli.SetIn(streams.NewIn(os.Stdin)) - } - - // Some links documenting this: - // - https://code.google.com/archive/p/mintty/issues/56 - // - https://github.com/docker/docker/issues/15272 - // - https://mintty.github.io/ (compatibility) - // Linux will hit this if you attempt `cat | docker login`, and Windows - // will hit this if you attempt docker login from mintty where stdin - // is a pipe, not a character based console. - if flPassword == "" && !cli.In().IsTerminal() { - return errors.Errorf("Error: Cannot perform an interactive login from a non TTY device") - } - - authconfig.Username = strings.TrimSpace(authconfig.Username) - - if flUser = strings.TrimSpace(flUser); flUser == "" { - if isDefaultRegistry { - // if this is a default registry (docker hub), then display the following message. - fmt.Fprintln(cli.Out(), "Log in with your Docker ID or email address to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com/ to create one.") - if hints.Enabled() { - fmt.Fprintln(cli.Out(), patSuggest) - fmt.Fprintln(cli.Out()) - } - } - promptWithDefault(cli.Out(), "Username", authconfig.Username) - var err error - flUser, err = readInput(cli.In()) - if err != nil { - return err - } - if flUser == "" { - flUser = authconfig.Username - } - } - if flUser == "" { - return errors.Errorf("Error: Non-null Username Required") - } - if flPassword == "" { - oldState, err := term.SaveState(cli.In().FD()) - if err != nil { - return err - } - fmt.Fprintf(cli.Out(), "Password: ") - _ = term.DisableEcho(cli.In().FD(), oldState) - defer func() { - _ = term.RestoreTerminal(cli.In().FD(), oldState) - }() - flPassword, err = readInput(cli.In()) - if err != nil { - return err - } - fmt.Fprint(cli.Out(), "\n") - if flPassword == "" { - return errors.Errorf("Error: Password Required") - } - } - - authconfig.Username = flUser - authconfig.Password = flPassword - - return nil -} - -// readInput reads, and returns user input from in. It tries to return a -// single line, not including the end-of-line bytes, and trims leading -// and trailing whitespace. -func readInput(in io.Reader) (string, error) { - line, _, err := bufio.NewReader(in).ReadLine() - if err != nil { - return "", errors.Wrap(err, "error while reading input") - } - return strings.TrimSpace(string(line)), nil -} - -func promptWithDefault(out io.Writer, prompt string, configDefault string) { - if configDefault == "" { - fmt.Fprintf(out, "%s: ", prompt) - } else { - fmt.Fprintf(out, "%s (%s): ", prompt, configDefault) - } -} - -// RetrieveAuthTokenFromImage retrieves an encoded auth token given a complete -// image. The auth configuration is serialized as a base64url encoded RFC4648, -// section 5) JSON string for sending through the X-Registry-Auth header. -// -// For details on base64url encoding, see: -// - RFC4648, section 5: https://tools.ietf.org/html/rfc4648#section-5 -func RetrieveAuthTokenFromImage(ctx context.Context, cli Cli, image string) (string, error) { - // Retrieve encoded auth token from the image reference - authConfig, err := resolveAuthConfigFromImage(ctx, cli, image) - if err != nil { - return "", err - } - encodedAuth, err := registrytypes.EncodeAuthConfig(authConfig) - if err != nil { - return "", err - } - return encodedAuth, nil -} - -// resolveAuthConfigFromImage retrieves that AuthConfig using the image string -func resolveAuthConfigFromImage(ctx context.Context, cli Cli, image string) (registrytypes.AuthConfig, error) { - registryRef, err := reference.ParseNormalizedNamed(image) - if err != nil { - return registrytypes.AuthConfig{}, err - } - repoInfo, err := registry.ParseRepositoryInfo(registryRef) - if err != nil { - return registrytypes.AuthConfig{}, err - } - return ResolveAuthConfig(ctx, cli, repoInfo.Index), nil -} diff --git a/vendor/github.com/docker/cli/cli/command/trust.go b/vendor/github.com/docker/cli/cli/command/trust.go deleted file mode 100644 index 65f240858..000000000 --- a/vendor/github.com/docker/cli/cli/command/trust.go +++ /dev/null @@ -1,15 +0,0 @@ -package command - -import ( - "github.com/spf13/pflag" -) - -// AddTrustVerificationFlags adds content trust flags to the provided flagset -func AddTrustVerificationFlags(fs *pflag.FlagSet, v *bool, trusted bool) { - fs.BoolVar(v, "disable-content-trust", !trusted, "Skip image verification") -} - -// AddTrustSigningFlags adds "signing" flags to the provided flagset -func AddTrustSigningFlags(fs *pflag.FlagSet, v *bool, trusted bool) { - fs.BoolVar(v, "disable-content-trust", !trusted, "Skip image signing") -} diff --git a/vendor/github.com/docker/cli/cli/command/utils.go b/vendor/github.com/docker/cli/cli/command/utils.go deleted file mode 100644 index 753f428aa..000000000 --- a/vendor/github.com/docker/cli/cli/command/utils.go +++ /dev/null @@ -1,197 +0,0 @@ -package command - -import ( - "bufio" - "fmt" - "io" - "os" - "path/filepath" - "runtime" - "strings" - - "github.com/docker/cli/cli/streams" - "github.com/docker/docker/api/types/filters" - "github.com/moby/sys/sequential" - "github.com/pkg/errors" - "github.com/spf13/pflag" -) - -// CopyToFile writes the content of the reader to the specified file -func CopyToFile(outfile string, r io.Reader) error { - // We use sequential file access here to avoid depleting the standby list - // on Windows. On Linux, this is a call directly to os.CreateTemp - tmpFile, err := sequential.CreateTemp(filepath.Dir(outfile), ".docker_temp_") - if err != nil { - return err - } - - tmpPath := tmpFile.Name() - - _, err = io.Copy(tmpFile, r) - tmpFile.Close() - - if err != nil { - os.Remove(tmpPath) - return err - } - - if err = os.Rename(tmpPath, outfile); err != nil { - os.Remove(tmpPath) - return err - } - - return nil -} - -// capitalizeFirst capitalizes the first character of string -func capitalizeFirst(s string) string { - switch l := len(s); l { - case 0: - return s - case 1: - return strings.ToLower(s) - default: - return strings.ToUpper(string(s[0])) + strings.ToLower(s[1:]) - } -} - -// PrettyPrint outputs arbitrary data for human formatted output by uppercasing the first letter. -func PrettyPrint(i interface{}) string { - switch t := i.(type) { - case nil: - return "None" - case string: - return capitalizeFirst(t) - default: - return capitalizeFirst(fmt.Sprintf("%s", t)) - } -} - -// PromptForConfirmation requests and checks confirmation from user. -// This will display the provided message followed by ' [y/N] '. If -// the user input 'y' or 'Y' it returns true other false. If no -// message is provided "Are you sure you want to proceed? [y/N] " -// will be used instead. -func PromptForConfirmation(ins io.Reader, outs io.Writer, message string) bool { - if message == "" { - message = "Are you sure you want to proceed?" - } - message += " [y/N] " - - _, _ = fmt.Fprint(outs, message) - - // On Windows, force the use of the regular OS stdin stream. - if runtime.GOOS == "windows" { - ins = streams.NewIn(os.Stdin) - } - - reader := bufio.NewReader(ins) - answer, _, _ := reader.ReadLine() - return strings.ToLower(string(answer)) == "y" -} - -// PruneFilters returns consolidated prune filters obtained from config.json and cli -func PruneFilters(dockerCli Cli, pruneFilters filters.Args) filters.Args { - if dockerCli.ConfigFile() == nil { - return pruneFilters - } - for _, f := range dockerCli.ConfigFile().PruneFilters { - k, v, ok := strings.Cut(f, "=") - if !ok { - continue - } - if k == "label" { - // CLI label filter supersede config.json. - // If CLI label filter conflict with config.json, - // skip adding label! filter in config.json. - if pruneFilters.Contains("label!") && pruneFilters.ExactMatch("label!", v) { - continue - } - } else if k == "label!" { - // CLI label! filter supersede config.json. - // If CLI label! filter conflict with config.json, - // skip adding label filter in config.json. - if pruneFilters.Contains("label") && pruneFilters.ExactMatch("label", v) { - continue - } - } - pruneFilters.Add(k, v) - } - - return pruneFilters -} - -// AddPlatformFlag adds `platform` to a set of flags for API version 1.32 and later. -func AddPlatformFlag(flags *pflag.FlagSet, target *string) { - flags.StringVar(target, "platform", os.Getenv("DOCKER_DEFAULT_PLATFORM"), "Set platform if server is multi-platform capable") - flags.SetAnnotation("platform", "version", []string{"1.32"}) -} - -// ValidateOutputPath validates the output paths of the `export` and `save` commands. -func ValidateOutputPath(path string) error { - dir := filepath.Dir(filepath.Clean(path)) - if dir != "" && dir != "." { - if _, err := os.Stat(dir); os.IsNotExist(err) { - return errors.Errorf("invalid output path: directory %q does not exist", dir) - } - } - // check whether `path` points to a regular file - // (if the path exists and doesn't point to a directory) - if fileInfo, err := os.Stat(path); !os.IsNotExist(err) { - if err != nil { - return err - } - - if fileInfo.Mode().IsDir() || fileInfo.Mode().IsRegular() { - return nil - } - - if err := ValidateOutputPathFileMode(fileInfo.Mode()); err != nil { - return errors.Wrapf(err, fmt.Sprintf("invalid output path: %q must be a directory or a regular file", path)) - } - } - return nil -} - -// ValidateOutputPathFileMode validates the output paths of the `cp` command and serves as a -// helper to `ValidateOutputPath` -func ValidateOutputPathFileMode(fileMode os.FileMode) error { - switch { - case fileMode&os.ModeDevice != 0: - return errors.New("got a device") - case fileMode&os.ModeIrregular != 0: - return errors.New("got an irregular file") - } - return nil -} - -func stringSliceIndex(s, subs []string) int { - j := 0 - if len(subs) > 0 { - for i, x := range s { - if j < len(subs) && subs[j] == x { - j++ - } else { - j = 0 - } - if len(subs) == j { - return i + 1 - j - } - } - } - return -1 -} - -// StringSliceReplaceAt replaces the sub-slice old, with the sub-slice new, in the string -// slice s, returning a new slice and a boolean indicating if the replacement happened. -// requireIdx is the index at which old needs to be found at (or -1 to disregard that). -func StringSliceReplaceAt(s, old, new []string, requireIndex int) ([]string, bool) { - idx := stringSliceIndex(s, old) - if (requireIndex != -1 && requireIndex != idx) || idx == -1 { - return s, false - } - out := append([]string{}, s[:idx]...) - out = append(out, new...) - out = append(out, s[idx+len(old):]...) - return out, true -} diff --git a/vendor/github.com/docker/cli/cli/compose/interpolation/interpolation.go b/vendor/github.com/docker/cli/cli/compose/interpolation/interpolation.go deleted file mode 100644 index e84756dba..000000000 --- a/vendor/github.com/docker/cli/cli/compose/interpolation/interpolation.go +++ /dev/null @@ -1,161 +0,0 @@ -package interpolation - -import ( - "os" - "strings" - - "github.com/docker/cli/cli/compose/template" - "github.com/pkg/errors" -) - -// Options supported by Interpolate -type Options struct { - // LookupValue from a key - LookupValue LookupValue - // TypeCastMapping maps key paths to functions to cast to a type - TypeCastMapping map[Path]Cast - // Substitution function to use - Substitute func(string, template.Mapping) (string, error) -} - -// LookupValue is a function which maps from variable names to values. -// Returns the value as a string and a bool indicating whether -// the value is present, to distinguish between an empty string -// and the absence of a value. -type LookupValue func(key string) (string, bool) - -// Cast a value to a new type, or return an error if the value can't be cast -type Cast func(value string) (interface{}, error) - -// Interpolate replaces variables in a string with the values from a mapping -func Interpolate(config map[string]interface{}, opts Options) (map[string]interface{}, error) { - if opts.LookupValue == nil { - opts.LookupValue = os.LookupEnv - } - if opts.TypeCastMapping == nil { - opts.TypeCastMapping = make(map[Path]Cast) - } - if opts.Substitute == nil { - opts.Substitute = template.Substitute - } - - out := map[string]interface{}{} - - for key, value := range config { - interpolatedValue, err := recursiveInterpolate(value, NewPath(key), opts) - if err != nil { - return out, err - } - out[key] = interpolatedValue - } - - return out, nil -} - -func recursiveInterpolate(value interface{}, path Path, opts Options) (interface{}, error) { - switch value := value.(type) { - case string: - newValue, err := opts.Substitute(value, template.Mapping(opts.LookupValue)) - if err != nil || newValue == value { - return value, newPathError(path, err) - } - caster, ok := opts.getCasterForPath(path) - if !ok { - return newValue, nil - } - casted, err := caster(newValue) - return casted, newPathError(path, errors.Wrap(err, "failed to cast to expected type")) - - case map[string]interface{}: - out := map[string]interface{}{} - for key, elem := range value { - interpolatedElem, err := recursiveInterpolate(elem, path.Next(key), opts) - if err != nil { - return nil, err - } - out[key] = interpolatedElem - } - return out, nil - - case []interface{}: - out := make([]interface{}, len(value)) - for i, elem := range value { - interpolatedElem, err := recursiveInterpolate(elem, path.Next(PathMatchList), opts) - if err != nil { - return nil, err - } - out[i] = interpolatedElem - } - return out, nil - - default: - return value, nil - } -} - -func newPathError(path Path, err error) error { - switch err := err.(type) { - case nil: - return nil - case *template.InvalidTemplateError: - return errors.Errorf( - "invalid interpolation format for %s: %#v; you may need to escape any $ with another $", - path, err.Template) - default: - return errors.Wrapf(err, "error while interpolating %s", path) - } -} - -const pathSeparator = "." - -// PathMatchAll is a token used as part of a Path to match any key at that level -// in the nested structure -const PathMatchAll = "*" - -// PathMatchList is a token used as part of a Path to match items in a list -const PathMatchList = "[]" - -// Path is a dotted path of keys to a value in a nested mapping structure. A * -// section in a path will match any key in the mapping structure. -type Path string - -// NewPath returns a new Path -func NewPath(items ...string) Path { - return Path(strings.Join(items, pathSeparator)) -} - -// Next returns a new path by append part to the current path -func (p Path) Next(part string) Path { - return Path(string(p) + pathSeparator + part) -} - -func (p Path) parts() []string { - return strings.Split(string(p), pathSeparator) -} - -func (p Path) matches(pattern Path) bool { - patternParts := pattern.parts() - parts := p.parts() - - if len(patternParts) != len(parts) { - return false - } - for index, part := range parts { - switch patternParts[index] { - case PathMatchAll, part: - continue - default: - return false - } - } - return true -} - -func (o Options) getCasterForPath(path Path) (Cast, bool) { - for pattern, caster := range o.TypeCastMapping { - if path.matches(pattern) { - return caster, true - } - } - return nil, false -} diff --git a/vendor/github.com/docker/cli/cli/compose/loader/example1.env b/vendor/github.com/docker/cli/cli/compose/loader/example1.env deleted file mode 100644 index f19ec0df4..000000000 --- a/vendor/github.com/docker/cli/cli/compose/loader/example1.env +++ /dev/null @@ -1,8 +0,0 @@ -# passed through -FOO=foo_from_env_file - -# overridden in example2.env -BAR=bar_from_env_file - -# overridden in full-example.yml -BAZ=baz_from_env_file diff --git a/vendor/github.com/docker/cli/cli/compose/loader/example2.env b/vendor/github.com/docker/cli/cli/compose/loader/example2.env deleted file mode 100644 index f47d1e614..000000000 --- a/vendor/github.com/docker/cli/cli/compose/loader/example2.env +++ /dev/null @@ -1,4 +0,0 @@ -BAR=bar_from_env_file_2 - -# overridden in configDetails.Environment -QUX=quz_from_env_file_2 diff --git a/vendor/github.com/docker/cli/cli/compose/loader/full-example.yml b/vendor/github.com/docker/cli/cli/compose/loader/full-example.yml deleted file mode 100644 index bb3473c72..000000000 --- a/vendor/github.com/docker/cli/cli/compose/loader/full-example.yml +++ /dev/null @@ -1,448 +0,0 @@ -version: "3.10" - -services: - foo: - - build: - context: ./dir - dockerfile: Dockerfile - args: - foo: bar - target: foo - network: foo - cache_from: - - foo - - bar - extra_hosts: - - "ipv4.example.com:127.0.0.1" - - "ipv6.example.com:::1" - labels: [FOO=BAR] - - - cap_add: - - ALL - - cap_drop: - - NET_ADMIN - - SYS_ADMIN - - cgroup_parent: m-executor-abcd - - # String or list - command: bundle exec thin -p 3000 - # command: ["bundle", "exec", "thin", "-p", "3000"] - - configs: - - config1 - - source: config2 - target: /my_config - uid: '103' - gid: '103' - mode: 0440 - - container_name: my-web-container - - depends_on: - - db - - redis - - deploy: - mode: replicated - replicas: 6 - labels: [FOO=BAR] - rollback_config: - parallelism: 3 - delay: 10s - failure_action: continue - monitor: 60s - max_failure_ratio: 0.3 - order: start-first - update_config: - parallelism: 3 - delay: 10s - failure_action: continue - monitor: 60s - max_failure_ratio: 0.3 - order: start-first - resources: - limits: - cpus: '0.001' - memory: 50M - pids: 100 - reservations: - cpus: '0.0001' - memory: 20M - generic_resources: - - discrete_resource_spec: - kind: 'gpu' - value: 2 - - discrete_resource_spec: - kind: 'ssd' - value: 1 - restart_policy: - condition: on-failure - delay: 5s - max_attempts: 3 - window: 120s - placement: - constraints: [node=foo] - max_replicas_per_node: 5 - preferences: - - spread: node.labels.az - endpoint_mode: dnsrr - - devices: - - "/dev/ttyUSB0:/dev/ttyUSB0" - - # String or list - # dns: 8.8.8.8 - dns: - - 8.8.8.8 - - 9.9.9.9 - - # String or list - # dns_search: example.com - dns_search: - - dc1.example.com - - dc2.example.com - - domainname: foo.com - - # String or list - # entrypoint: /code/entrypoint.sh -p 3000 - entrypoint: ["/code/entrypoint.sh", "-p", "3000"] - - # String or list - # env_file: .env - env_file: - - ./example1.env - - ./example2.env - - # Mapping or list - # Mapping values can be strings, numbers or null - # Booleans are not allowed - must be quoted - environment: - BAZ: baz_from_service_def - QUX: - # environment: - # - RACK_ENV=development - # - SHOW=true - # - SESSION_SECRET - - # Items can be strings or numbers - expose: - - "3000" - - 8000 - - external_links: - - redis_1 - - project_db_1:mysql - - project_db_1:postgresql - - # Mapping or list - # Mapping values must be strings - # extra_hosts: - # somehost: "162.242.195.82" - # otherhost: "50.31.209.229" - # host.docker.internal: "host-gateway" - extra_hosts: - - "somehost:162.242.195.82" - - "otherhost:50.31.209.229" - - "host.docker.internal:host-gateway" - - hostname: foo - - healthcheck: - test: echo "hello world" - interval: 10s - timeout: 1s - retries: 5 - start_period: 15s - - # Any valid image reference - repo, tag, id, sha - image: redis - # image: ubuntu:14.04 - # image: tutum/influxdb - # image: example-registry.com:4000/postgresql - # image: a4bc65fd - # image: busybox@sha256:38a203e1986cf79639cfb9b2e1d6e773de84002feea2d4eb006b52004ee8502d - - ipc: host - - # Mapping or list - # Mapping values can be strings, numbers or null - labels: - com.example.description: "Accounting webapp" - com.example.number: 42 - com.example.empty-label: - # labels: - # - "com.example.description=Accounting webapp" - # - "com.example.number=42" - # - "com.example.empty-label" - - links: - - db - - db:database - - redis - - logging: - driver: syslog - options: - syslog-address: "tcp://192.168.0.42:123" - - mac_address: 02:42:ac:11:65:43 - - # network_mode: "bridge" - # network_mode: "host" - # network_mode: "none" - # Use the network mode of an arbitrary container from another service - # network_mode: "service:db" - # Use the network mode of another container, specified by name or id - # network_mode: "container:some-container" - network_mode: "container:0cfeab0f748b9a743dc3da582046357c6ef497631c1a016d28d2bf9b4f899f7b" - - networks: - some-network: - aliases: - - alias1 - - alias3 - other-network: - ipv4_address: 172.16.238.10 - ipv6_address: 2001:3984:3989::10 - other-other-network: - - pid: "host" - - ports: - - 3000 - - "3001-3005" - - "8000:8000" - - "9090-9091:8080-8081" - - "49100:22" - - "127.0.0.1:8001:8001" - - "127.0.0.1:5000-5010:5000-5010" - - privileged: true - - read_only: true - - restart: always - - secrets: - - secret1 - - source: secret2 - target: my_secret - uid: '103' - gid: '103' - mode: 0440 - - security_opt: - - label=level:s0:c100,c200 - - label=type:svirt_apache_t - - stdin_open: true - - stop_grace_period: 20s - - stop_signal: SIGUSR1 - - sysctls: - net.core.somaxconn: 1024 - net.ipv4.tcp_syncookies: 0 - - # String or list - # tmpfs: /run - tmpfs: - - /run - - /tmp - - tty: true - - ulimits: - # Single number or mapping with soft + hard limits - nproc: 65535 - nofile: - soft: 20000 - hard: 40000 - - user: someone - - volumes: - # Just specify a path and let the Engine create a volume - - /var/lib/mysql - # Specify an absolute path mapping - - /opt/data:/var/lib/mysql - # Path on the host, relative to the Compose file - - .:/code - - ./static:/var/www/html - # User-relative path - - ~/configs:/etc/configs/:ro - # Named volume - - datavolume:/var/lib/mysql - - type: bind - source: ./opt - target: /opt - consistency: cached - - type: tmpfs - target: /opt - tmpfs: - size: 10000 - - type: cluster - source: group:mygroup - target: /srv - - working_dir: /code - x-bar: baz - x-foo: bar - -networks: - # Entries can be null, which specifies simply that a network - # called "{project name}_some-network" should be created and - # use the default driver - some-network: - - other-network: - driver: overlay - - driver_opts: - # Values can be strings or numbers - foo: "bar" - baz: 1 - - ipam: - driver: overlay - # driver_opts: - # # Values can be strings or numbers - # com.docker.network.enable_ipv6: "true" - # com.docker.network.numeric_value: 1 - config: - - subnet: 172.16.238.0/24 - # gateway: 172.16.238.1 - - subnet: 2001:3984:3989::/64 - # gateway: 2001:3984:3989::1 - - labels: - foo: bar - - external-network: - # Specifies that a pre-existing network called "external-network" - # can be referred to within this file as "external-network" - external: true - - other-external-network: - # Specifies that a pre-existing network called "my-cool-network" - # can be referred to within this file as "other-external-network" - external: - name: my-cool-network - x-bar: baz - x-foo: bar - -volumes: - # Entries can be null, which specifies simply that a volume - # called "{project name}_some-volume" should be created and - # use the default driver - some-volume: - - other-volume: - driver: flocker - - driver_opts: - # Values can be strings or numbers - foo: "bar" - baz: 1 - labels: - foo: bar - - another-volume: - name: "user_specified_name" - driver: vsphere - - driver_opts: - # Values can be strings or numbers - foo: "bar" - baz: 1 - - external-volume: - # Specifies that a pre-existing volume called "external-volume" - # can be referred to within this file as "external-volume" - external: true - - other-external-volume: - # Specifies that a pre-existing volume called "my-cool-volume" - # can be referred to within this file as "other-external-volume" - # This example uses the deprecated "volume.external.name" (replaced by "volume.name") - external: - name: my-cool-volume - - external-volume3: - # Specifies that a pre-existing volume called "this-is-volume3" - # can be referred to within this file as "external-volume3" - name: this-is-volume3 - external: true - x-bar: baz - x-foo: bar - - cluster-volume: - driver: my-csi-driver - x-cluster-spec: - group: mygroup - access_mode: - scope: single - sharing: none - block_volume: {} - accessibility_requirements: - requisite: - - segments: - - region=R1 - - zone=Z1 - - segments: - region: R1 - zone: Z2 - preferred: - - segments: - region: R1 - zone: Z1 - capacity_range: - required_bytes: 1G - limit_bytes: 8G - secrets: - - key: mycsisecret - secret: secret1 - - key: mycsisecret2 - secret: secret4 - availability: active - -configs: - config1: - file: ./config_data - labels: - foo: bar - config2: - external: - name: my_config - config3: - external: true - config4: - name: foo - x-bar: baz - x-foo: bar - -secrets: - secret1: - file: ./secret_data - labels: - foo: bar - secret2: - external: - name: my_secret - secret3: - external: true - secret4: - name: bar - x-bar: baz - x-foo: bar -x-bar: baz -x-foo: bar -x-nested: - bar: baz - foo: bar diff --git a/vendor/github.com/docker/cli/cli/compose/loader/interpolate.go b/vendor/github.com/docker/cli/cli/compose/loader/interpolate.go deleted file mode 100644 index d25936be8..000000000 --- a/vendor/github.com/docker/cli/cli/compose/loader/interpolate.go +++ /dev/null @@ -1,72 +0,0 @@ -package loader - -import ( - "strconv" - "strings" - - interp "github.com/docker/cli/cli/compose/interpolation" - "github.com/pkg/errors" -) - -var interpolateTypeCastMapping = map[interp.Path]interp.Cast{ - servicePath("configs", interp.PathMatchList, "mode"): toInt, - servicePath("secrets", interp.PathMatchList, "mode"): toInt, - servicePath("healthcheck", "retries"): toInt, - servicePath("healthcheck", "disable"): toBoolean, - servicePath("deploy", "replicas"): toInt, - servicePath("deploy", "update_config", "parallelism"): toInt, - servicePath("deploy", "update_config", "max_failure_ratio"): toFloat, - servicePath("deploy", "rollback_config", "parallelism"): toInt, - servicePath("deploy", "rollback_config", "max_failure_ratio"): toFloat, - servicePath("deploy", "restart_policy", "max_attempts"): toInt, - servicePath("deploy", "placement", "max_replicas_per_node"): toInt, - servicePath("ports", interp.PathMatchList, "target"): toInt, - servicePath("ports", interp.PathMatchList, "published"): toInt, - servicePath("ulimits", interp.PathMatchAll): toInt, - servicePath("ulimits", interp.PathMatchAll, "hard"): toInt, - servicePath("ulimits", interp.PathMatchAll, "soft"): toInt, - servicePath("privileged"): toBoolean, - servicePath("read_only"): toBoolean, - servicePath("stdin_open"): toBoolean, - servicePath("tty"): toBoolean, - servicePath("volumes", interp.PathMatchList, "read_only"): toBoolean, - servicePath("volumes", interp.PathMatchList, "volume", "nocopy"): toBoolean, - iPath("networks", interp.PathMatchAll, "external"): toBoolean, - iPath("networks", interp.PathMatchAll, "internal"): toBoolean, - iPath("networks", interp.PathMatchAll, "attachable"): toBoolean, - iPath("volumes", interp.PathMatchAll, "external"): toBoolean, - iPath("secrets", interp.PathMatchAll, "external"): toBoolean, - iPath("configs", interp.PathMatchAll, "external"): toBoolean, -} - -func iPath(parts ...string) interp.Path { - return interp.NewPath(parts...) -} - -func servicePath(parts ...string) interp.Path { - return iPath(append([]string{"services", interp.PathMatchAll}, parts...)...) -} - -func toInt(value string) (interface{}, error) { - return strconv.Atoi(value) -} - -func toFloat(value string) (interface{}, error) { - return strconv.ParseFloat(value, 64) -} - -// should match http://yaml.org/type/bool.html -func toBoolean(value string) (interface{}, error) { - switch strings.ToLower(value) { - case "y", "yes", "true", "on": - return true, nil - case "n", "no", "false", "off": - return false, nil - default: - return nil, errors.Errorf("invalid boolean: %s", value) - } -} - -func interpolateConfig(configDict map[string]interface{}, opts interp.Options) (map[string]interface{}, error) { - return interp.Interpolate(configDict, opts) -} diff --git a/vendor/github.com/docker/cli/cli/compose/loader/loader.go b/vendor/github.com/docker/cli/cli/compose/loader/loader.go deleted file mode 100644 index a9b8f1f1f..000000000 --- a/vendor/github.com/docker/cli/cli/compose/loader/loader.go +++ /dev/null @@ -1,956 +0,0 @@ -package loader - -import ( - "fmt" - "path" - "path/filepath" - "reflect" - "sort" - "strings" - "time" - - interp "github.com/docker/cli/cli/compose/interpolation" - "github.com/docker/cli/cli/compose/schema" - "github.com/docker/cli/cli/compose/template" - "github.com/docker/cli/cli/compose/types" - "github.com/docker/cli/opts" - "github.com/docker/docker/api/types/versions" - "github.com/docker/go-connections/nat" - units "github.com/docker/go-units" - "github.com/google/shlex" - "github.com/mitchellh/mapstructure" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" - yaml "gopkg.in/yaml.v2" -) - -// Options supported by Load -type Options struct { - // Skip schema validation - SkipValidation bool - // Skip interpolation - SkipInterpolation bool - // Interpolation options - Interpolate *interp.Options - // Discard 'env_file' entries after resolving to 'environment' section - discardEnvFiles bool -} - -// WithDiscardEnvFiles sets the Options to discard the `env_file` section after resolving to -// the `environment` section -func WithDiscardEnvFiles(opts *Options) { - opts.discardEnvFiles = true -} - -// ParseYAML reads the bytes from a file, parses the bytes into a mapping -// structure, and returns it. -func ParseYAML(source []byte) (map[string]interface{}, error) { - var cfg interface{} - if err := yaml.Unmarshal(source, &cfg); err != nil { - return nil, err - } - cfgMap, ok := cfg.(map[interface{}]interface{}) - if !ok { - return nil, errors.Errorf("top-level object must be a mapping") - } - converted, err := convertToStringKeysRecursive(cfgMap, "") - if err != nil { - return nil, err - } - return converted.(map[string]interface{}), nil -} - -// Load reads a ConfigDetails and returns a fully loaded configuration -func Load(configDetails types.ConfigDetails, options ...func(*Options)) (*types.Config, error) { - if len(configDetails.ConfigFiles) < 1 { - return nil, errors.Errorf("No files specified") - } - - opts := &Options{ - Interpolate: &interp.Options{ - Substitute: template.Substitute, - LookupValue: configDetails.LookupEnv, - TypeCastMapping: interpolateTypeCastMapping, - }, - } - - for _, op := range options { - op(opts) - } - - configs := []*types.Config{} - var err error - - for _, file := range configDetails.ConfigFiles { - configDict := file.Config - version := schema.Version(configDict) - if configDetails.Version == "" { - configDetails.Version = version - } - if configDetails.Version != version { - return nil, errors.Errorf("version mismatched between two composefiles : %v and %v", configDetails.Version, version) - } - - if err := validateForbidden(configDict); err != nil { - return nil, err - } - - if !opts.SkipInterpolation { - configDict, err = interpolateConfig(configDict, *opts.Interpolate) - if err != nil { - return nil, err - } - } - - if !opts.SkipValidation { - if err := schema.Validate(configDict, configDetails.Version); err != nil { - return nil, err - } - } - - cfg, err := loadSections(configDict, configDetails) - if err != nil { - return nil, err - } - cfg.Filename = file.Filename - if opts.discardEnvFiles { - for i := range cfg.Services { - cfg.Services[i].EnvFile = nil - } - } - - configs = append(configs, cfg) - } - - return merge(configs) -} - -func validateForbidden(configDict map[string]interface{}) error { - servicesDict, ok := configDict["services"].(map[string]interface{}) - if !ok { - return nil - } - forbidden := getProperties(servicesDict, types.ForbiddenProperties) - if len(forbidden) > 0 { - return &ForbiddenPropertiesError{Properties: forbidden} - } - return nil -} - -func loadSections(config map[string]interface{}, configDetails types.ConfigDetails) (*types.Config, error) { - var err error - cfg := types.Config{ - Version: schema.Version(config), - } - - loaders := []struct { - key string - fnc func(config map[string]interface{}) error - }{ - { - key: "services", - fnc: func(config map[string]interface{}) error { - cfg.Services, err = LoadServices(config, configDetails.WorkingDir, configDetails.LookupEnv) - return err - }, - }, - { - key: "networks", - fnc: func(config map[string]interface{}) error { - cfg.Networks, err = LoadNetworks(config, configDetails.Version) - return err - }, - }, - { - key: "volumes", - fnc: func(config map[string]interface{}) error { - cfg.Volumes, err = LoadVolumes(config, configDetails.Version) - return err - }, - }, - { - key: "secrets", - fnc: func(config map[string]interface{}) error { - cfg.Secrets, err = LoadSecrets(config, configDetails) - return err - }, - }, - { - key: "configs", - fnc: func(config map[string]interface{}) error { - cfg.Configs, err = LoadConfigObjs(config, configDetails) - return err - }, - }, - } - for _, loader := range loaders { - if err := loader.fnc(getSection(config, loader.key)); err != nil { - return nil, err - } - } - cfg.Extras = getExtras(config) - return &cfg, nil -} - -func getSection(config map[string]interface{}, key string) map[string]interface{} { - section, ok := config[key] - if !ok { - return make(map[string]interface{}) - } - return section.(map[string]interface{}) -} - -// GetUnsupportedProperties returns the list of any unsupported properties that are -// used in the Compose files. -func GetUnsupportedProperties(configDicts ...map[string]interface{}) []string { - unsupported := map[string]bool{} - - for _, configDict := range configDicts { - for _, service := range getServices(configDict) { - serviceDict := service.(map[string]interface{}) - for _, property := range types.UnsupportedProperties { - if _, isSet := serviceDict[property]; isSet { - unsupported[property] = true - } - } - } - } - - return sortedKeys(unsupported) -} - -func sortedKeys(set map[string]bool) []string { - var keys []string - for key := range set { - keys = append(keys, key) - } - sort.Strings(keys) - return keys -} - -// GetDeprecatedProperties returns the list of any deprecated properties that -// are used in the compose files. -func GetDeprecatedProperties(configDicts ...map[string]interface{}) map[string]string { - deprecated := map[string]string{} - - for _, configDict := range configDicts { - deprecatedProperties := getProperties(getServices(configDict), types.DeprecatedProperties) - for key, value := range deprecatedProperties { - deprecated[key] = value - } - } - - return deprecated -} - -func getProperties(services map[string]interface{}, propertyMap map[string]string) map[string]string { - output := map[string]string{} - - for _, service := range services { - if serviceDict, ok := service.(map[string]interface{}); ok { - for property, description := range propertyMap { - if _, isSet := serviceDict[property]; isSet { - output[property] = description - } - } - } - } - - return output -} - -// ForbiddenPropertiesError is returned when there are properties in the Compose -// file that are forbidden. -type ForbiddenPropertiesError struct { - Properties map[string]string -} - -func (e *ForbiddenPropertiesError) Error() string { - return "Configuration contains forbidden properties" -} - -func getServices(configDict map[string]interface{}) map[string]interface{} { - if services, ok := configDict["services"]; ok { - if servicesDict, ok := services.(map[string]interface{}); ok { - return servicesDict - } - } - - return map[string]interface{}{} -} - -// Transform converts the source into the target struct with compose types transformer -// and the specified transformers if any. -func Transform(source interface{}, target interface{}, additionalTransformers ...Transformer) error { - data := mapstructure.Metadata{} - config := &mapstructure.DecoderConfig{ - DecodeHook: mapstructure.ComposeDecodeHookFunc( - createTransformHook(additionalTransformers...), - mapstructure.StringToTimeDurationHookFunc()), - Result: target, - Metadata: &data, - } - decoder, err := mapstructure.NewDecoder(config) - if err != nil { - return err - } - return decoder.Decode(source) -} - -// TransformerFunc defines a function to perform the actual transformation -type TransformerFunc func(interface{}) (interface{}, error) - -// Transformer defines a map to type transformer -type Transformer struct { - TypeOf reflect.Type - Func TransformerFunc -} - -func createTransformHook(additionalTransformers ...Transformer) mapstructure.DecodeHookFuncType { - transforms := map[reflect.Type]func(interface{}) (interface{}, error){ - reflect.TypeOf(types.External{}): transformExternal, - reflect.TypeOf(types.HealthCheckTest{}): transformHealthCheckTest, - reflect.TypeOf(types.ShellCommand{}): transformShellCommand, - reflect.TypeOf(types.StringList{}): transformStringList, - reflect.TypeOf(map[string]string{}): transformMapStringString, - reflect.TypeOf(types.UlimitsConfig{}): transformUlimits, - reflect.TypeOf(types.UnitBytes(0)): transformSize, - reflect.TypeOf([]types.ServicePortConfig{}): transformServicePort, - reflect.TypeOf(types.ServiceSecretConfig{}): transformStringSourceMap, - reflect.TypeOf(types.ServiceConfigObjConfig{}): transformStringSourceMap, - reflect.TypeOf(types.StringOrNumberList{}): transformStringOrNumberList, - reflect.TypeOf(map[string]*types.ServiceNetworkConfig{}): transformServiceNetworkMap, - reflect.TypeOf(types.Mapping{}): transformMappingOrListFunc("=", false), - reflect.TypeOf(types.MappingWithEquals{}): transformMappingOrListFunc("=", true), - reflect.TypeOf(types.Labels{}): transformMappingOrListFunc("=", false), - reflect.TypeOf(types.MappingWithColon{}): transformMappingOrListFunc(":", false), - reflect.TypeOf(types.HostsList{}): transformListOrMappingFunc(":", false), - reflect.TypeOf(types.ServiceVolumeConfig{}): transformServiceVolumeConfig, - reflect.TypeOf(types.BuildConfig{}): transformBuildConfig, - reflect.TypeOf(types.Duration(0)): transformStringToDuration, - } - - for _, transformer := range additionalTransformers { - transforms[transformer.TypeOf] = transformer.Func - } - - return func(_ reflect.Type, target reflect.Type, data interface{}) (interface{}, error) { - transform, ok := transforms[target] - if !ok { - return data, nil - } - return transform(data) - } -} - -// keys needs to be converted to strings for jsonschema -func convertToStringKeysRecursive(value interface{}, keyPrefix string) (interface{}, error) { - if mapping, ok := value.(map[interface{}]interface{}); ok { - dict := make(map[string]interface{}) - for key, entry := range mapping { - str, ok := key.(string) - if !ok { - return nil, formatInvalidKeyError(keyPrefix, key) - } - var newKeyPrefix string - if keyPrefix == "" { - newKeyPrefix = str - } else { - newKeyPrefix = fmt.Sprintf("%s.%s", keyPrefix, str) - } - convertedEntry, err := convertToStringKeysRecursive(entry, newKeyPrefix) - if err != nil { - return nil, err - } - dict[str] = convertedEntry - } - return dict, nil - } - if list, ok := value.([]interface{}); ok { - var convertedList []interface{} - for index, entry := range list { - newKeyPrefix := fmt.Sprintf("%s[%d]", keyPrefix, index) - convertedEntry, err := convertToStringKeysRecursive(entry, newKeyPrefix) - if err != nil { - return nil, err - } - convertedList = append(convertedList, convertedEntry) - } - return convertedList, nil - } - return value, nil -} - -func formatInvalidKeyError(keyPrefix string, key interface{}) error { - var location string - if keyPrefix == "" { - location = "at top level" - } else { - location = "in " + keyPrefix - } - return errors.Errorf("non-string key %s: %#v", location, key) -} - -// LoadServices produces a ServiceConfig map from a compose file Dict -// the servicesDict is not validated if directly used. Use Load() to enable validation -func LoadServices(servicesDict map[string]interface{}, workingDir string, lookupEnv template.Mapping) ([]types.ServiceConfig, error) { - var services []types.ServiceConfig - - for name, serviceDef := range servicesDict { - serviceConfig, err := LoadService(name, serviceDef.(map[string]interface{}), workingDir, lookupEnv) - if err != nil { - return nil, err - } - services = append(services, *serviceConfig) - } - - return services, nil -} - -// LoadService produces a single ServiceConfig from a compose file Dict -// the serviceDict is not validated if directly used. Use Load() to enable validation -func LoadService(name string, serviceDict map[string]interface{}, workingDir string, lookupEnv template.Mapping) (*types.ServiceConfig, error) { - serviceConfig := &types.ServiceConfig{} - if err := Transform(serviceDict, serviceConfig); err != nil { - return nil, err - } - serviceConfig.Name = name - - if err := resolveEnvironment(serviceConfig, workingDir, lookupEnv); err != nil { - return nil, err - } - - if err := resolveVolumePaths(serviceConfig.Volumes, workingDir, lookupEnv); err != nil { - return nil, err - } - - serviceConfig.Extras = getExtras(serviceDict) - - return serviceConfig, nil -} - -func loadExtras(name string, source map[string]interface{}) map[string]interface{} { - if dict, ok := source[name].(map[string]interface{}); ok { - return getExtras(dict) - } - return nil -} - -func getExtras(dict map[string]interface{}) map[string]interface{} { - extras := map[string]interface{}{} - for key, value := range dict { - if strings.HasPrefix(key, "x-") { - extras[key] = value - } - } - if len(extras) == 0 { - return nil - } - return extras -} - -func updateEnvironment(environment map[string]*string, vars map[string]*string, lookupEnv template.Mapping) { - for k, v := range vars { - interpolatedV, ok := lookupEnv(k) - if (v == nil || *v == "") && ok { - // lookupEnv is prioritized over vars - environment[k] = &interpolatedV - } else { - environment[k] = v - } - } -} - -func resolveEnvironment(serviceConfig *types.ServiceConfig, workingDir string, lookupEnv template.Mapping) error { - environment := make(map[string]*string) - - if len(serviceConfig.EnvFile) > 0 { - var envVars []string - - for _, file := range serviceConfig.EnvFile { - filePath := absPath(workingDir, file) - fileVars, err := opts.ParseEnvFile(filePath) - if err != nil { - return err - } - envVars = append(envVars, fileVars...) - } - updateEnvironment(environment, - opts.ConvertKVStringsToMapWithNil(envVars), lookupEnv) - } - - updateEnvironment(environment, serviceConfig.Environment, lookupEnv) - serviceConfig.Environment = environment - return nil -} - -func resolveVolumePaths(volumes []types.ServiceVolumeConfig, workingDir string, lookupEnv template.Mapping) error { - for i, volume := range volumes { - if volume.Type != "bind" { - continue - } - - if volume.Source == "" { - return errors.New(`invalid mount config for type "bind": field Source must not be empty`) - } - - filePath := expandUser(volume.Source, lookupEnv) - // Check if source is an absolute path (either Unix or Windows), to - // handle a Windows client with a Unix daemon or vice-versa. - // - // Note that this is not required for Docker for Windows when specifying - // a local Windows path, because Docker for Windows translates the Windows - // path into a valid path within the VM. - if !path.IsAbs(filePath) && !isAbs(filePath) { - filePath = absPath(workingDir, filePath) - } - volume.Source = filePath - volumes[i] = volume - } - return nil -} - -// TODO: make this more robust -func expandUser(path string, lookupEnv template.Mapping) string { - if strings.HasPrefix(path, "~") { - home, ok := lookupEnv("HOME") - if !ok { - logrus.Warn("cannot expand '~', because the environment lacks HOME") - return path - } - return strings.Replace(path, "~", home, 1) - } - return path -} - -func transformUlimits(data interface{}) (interface{}, error) { - switch value := data.(type) { - case int: - return types.UlimitsConfig{Single: value}, nil - case map[string]interface{}: - ulimit := types.UlimitsConfig{} - ulimit.Soft = value["soft"].(int) - ulimit.Hard = value["hard"].(int) - return ulimit, nil - default: - return data, errors.Errorf("invalid type %T for ulimits", value) - } -} - -// LoadNetworks produces a NetworkConfig map from a compose file Dict -// the source Dict is not validated if directly used. Use Load() to enable validation -func LoadNetworks(source map[string]interface{}, version string) (map[string]types.NetworkConfig, error) { - networks := make(map[string]types.NetworkConfig) - err := Transform(source, &networks) - if err != nil { - return networks, err - } - for name, network := range networks { - if !network.External.External { - continue - } - switch { - case network.External.Name != "": - if network.Name != "" { - return nil, errors.Errorf("network %s: network.external.name and network.name conflict; only use network.name", name) - } - if versions.GreaterThanOrEqualTo(version, "3.5") { - logrus.Warnf("network %s: network.external.name is deprecated in favor of network.name", name) - } - network.Name = network.External.Name - network.External.Name = "" - case network.Name == "": - network.Name = name - } - network.Extras = loadExtras(name, source) - networks[name] = network - } - return networks, nil -} - -func externalVolumeError(volume, key string) error { - return errors.Errorf( - "conflicting parameters \"external\" and %q specified for volume %q", - key, volume) -} - -// LoadVolumes produces a VolumeConfig map from a compose file Dict -// the source Dict is not validated if directly used. Use Load() to enable validation -func LoadVolumes(source map[string]interface{}, version string) (map[string]types.VolumeConfig, error) { - volumes := make(map[string]types.VolumeConfig) - if err := Transform(source, &volumes); err != nil { - return volumes, err - } - - for name, volume := range volumes { - if !volume.External.External { - continue - } - switch { - case volume.Driver != "": - return nil, externalVolumeError(name, "driver") - case len(volume.DriverOpts) > 0: - return nil, externalVolumeError(name, "driver_opts") - case len(volume.Labels) > 0: - return nil, externalVolumeError(name, "labels") - case volume.External.Name != "": - if volume.Name != "" { - return nil, errors.Errorf("volume %s: volume.external.name and volume.name conflict; only use volume.name", name) - } - if versions.GreaterThanOrEqualTo(version, "3.4") { - logrus.Warnf("volume %s: volume.external.name is deprecated in favor of volume.name", name) - } - volume.Name = volume.External.Name - volume.External.Name = "" - case volume.Name == "": - volume.Name = name - } - volume.Extras = loadExtras(name, source) - volumes[name] = volume - } - return volumes, nil -} - -// LoadSecrets produces a SecretConfig map from a compose file Dict -// the source Dict is not validated if directly used. Use Load() to enable validation -func LoadSecrets(source map[string]interface{}, details types.ConfigDetails) (map[string]types.SecretConfig, error) { - secrets := make(map[string]types.SecretConfig) - if err := Transform(source, &secrets); err != nil { - return secrets, err - } - for name, secret := range secrets { - obj, err := loadFileObjectConfig(name, "secret", types.FileObjectConfig(secret), details) - if err != nil { - return nil, err - } - secretConfig := types.SecretConfig(obj) - secretConfig.Extras = loadExtras(name, source) - secrets[name] = secretConfig - } - return secrets, nil -} - -// LoadConfigObjs produces a ConfigObjConfig map from a compose file Dict -// the source Dict is not validated if directly used. Use Load() to enable validation -func LoadConfigObjs(source map[string]interface{}, details types.ConfigDetails) (map[string]types.ConfigObjConfig, error) { - configs := make(map[string]types.ConfigObjConfig) - if err := Transform(source, &configs); err != nil { - return configs, err - } - for name, config := range configs { - obj, err := loadFileObjectConfig(name, "config", types.FileObjectConfig(config), details) - if err != nil { - return nil, err - } - configConfig := types.ConfigObjConfig(obj) - configConfig.Extras = loadExtras(name, source) - configs[name] = configConfig - } - return configs, nil -} - -func loadFileObjectConfig(name string, objType string, obj types.FileObjectConfig, details types.ConfigDetails) (types.FileObjectConfig, error) { - // if "external: true" - switch { - case obj.External.External: - // handle deprecated external.name - if obj.External.Name != "" { - if obj.Name != "" { - return obj, errors.Errorf("%[1]s %[2]s: %[1]s.external.name and %[1]s.name conflict; only use %[1]s.name", objType, name) - } - if versions.GreaterThanOrEqualTo(details.Version, "3.5") { - logrus.Warnf("%[1]s %[2]s: %[1]s.external.name is deprecated in favor of %[1]s.name", objType, name) - } - obj.Name = obj.External.Name - obj.External.Name = "" - } else { - if obj.Name == "" { - obj.Name = name - } - } - // if not "external: true" - case obj.Driver != "": - if obj.File != "" { - return obj, errors.Errorf("%[1]s %[2]s: %[1]s.driver and %[1]s.file conflict; only use %[1]s.driver", objType, name) - } - default: - obj.File = absPath(details.WorkingDir, obj.File) - } - - return obj, nil -} - -func absPath(workingDir string, filePath string) string { - if filepath.IsAbs(filePath) { - return filePath - } - return filepath.Join(workingDir, filePath) -} - -var transformMapStringString TransformerFunc = func(data interface{}) (interface{}, error) { - switch value := data.(type) { - case map[string]interface{}: - return toMapStringString(value, false), nil - case map[string]string: - return value, nil - default: - return data, errors.Errorf("invalid type %T for map[string]string", value) - } -} - -var transformExternal TransformerFunc = func(data interface{}) (interface{}, error) { - switch value := data.(type) { - case bool: - return map[string]interface{}{"external": value}, nil - case map[string]interface{}: - return map[string]interface{}{"external": true, "name": value["name"]}, nil - default: - return data, errors.Errorf("invalid type %T for external", value) - } -} - -var transformServicePort TransformerFunc = func(data interface{}) (interface{}, error) { - switch entries := data.(type) { - case []interface{}: - // We process the list instead of individual items here. - // The reason is that one entry might be mapped to multiple ServicePortConfig. - // Therefore we take an input of a list and return an output of a list. - ports := []interface{}{} - for _, entry := range entries { - switch value := entry.(type) { - case int: - v, err := toServicePortConfigs(fmt.Sprint(value)) - if err != nil { - return data, err - } - ports = append(ports, v...) - case string: - v, err := toServicePortConfigs(value) - if err != nil { - return data, err - } - ports = append(ports, v...) - case map[string]interface{}: - ports = append(ports, value) - default: - return data, errors.Errorf("invalid type %T for port", value) - } - } - return ports, nil - default: - return data, errors.Errorf("invalid type %T for port", entries) - } -} - -var transformStringSourceMap TransformerFunc = func(data interface{}) (interface{}, error) { - switch value := data.(type) { - case string: - return map[string]interface{}{"source": value}, nil - case map[string]interface{}: - return data, nil - default: - return data, errors.Errorf("invalid type %T for secret", value) - } -} - -var transformBuildConfig TransformerFunc = func(data interface{}) (interface{}, error) { - switch value := data.(type) { - case string: - return map[string]interface{}{"context": value}, nil - case map[string]interface{}: - return data, nil - default: - return data, errors.Errorf("invalid type %T for service build", value) - } -} - -var transformServiceVolumeConfig TransformerFunc = func(data interface{}) (interface{}, error) { - switch value := data.(type) { - case string: - return ParseVolume(value) - case map[string]interface{}: - return data, nil - default: - return data, errors.Errorf("invalid type %T for service volume", value) - } -} - -var transformServiceNetworkMap TransformerFunc = func(value interface{}) (interface{}, error) { - if list, ok := value.([]interface{}); ok { - mapValue := map[interface{}]interface{}{} - for _, name := range list { - mapValue[name] = nil - } - return mapValue, nil - } - return value, nil -} - -var transformStringOrNumberList TransformerFunc = func(value interface{}) (interface{}, error) { - list := value.([]interface{}) - result := make([]string, len(list)) - for i, item := range list { - result[i] = fmt.Sprint(item) - } - return result, nil -} - -var transformStringList TransformerFunc = func(data interface{}) (interface{}, error) { - switch value := data.(type) { - case string: - return []string{value}, nil - case []interface{}: - return value, nil - default: - return data, errors.Errorf("invalid type %T for string list", value) - } -} - -func transformMappingOrListFunc(sep string, allowNil bool) TransformerFunc { - return func(data interface{}) (interface{}, error) { - return transformMappingOrList(data, sep, allowNil), nil - } -} - -func transformListOrMappingFunc(sep string, allowNil bool) TransformerFunc { - return func(data interface{}) (interface{}, error) { - return transformListOrMapping(data, sep, allowNil), nil - } -} - -func transformListOrMapping(listOrMapping interface{}, sep string, allowNil bool) interface{} { - switch value := listOrMapping.(type) { - case map[string]interface{}: - return toStringList(value, sep, allowNil) - case []interface{}: - return listOrMapping - } - panic(errors.Errorf("expected a map or a list, got %T: %#v", listOrMapping, listOrMapping)) -} - -func transformMappingOrList(mappingOrList interface{}, sep string, allowNil bool) interface{} { - switch values := mappingOrList.(type) { - case map[string]interface{}: - return toMapStringString(values, allowNil) - case []interface{}: - result := make(map[string]interface{}) - for _, v := range values { - key, val, hasValue := strings.Cut(v.(string), sep) - switch { - case !hasValue && allowNil: - result[key] = nil - case !hasValue && !allowNil: - result[key] = "" - default: - result[key] = val - } - } - return result - } - panic(errors.Errorf("expected a map or a list, got %T: %#v", mappingOrList, mappingOrList)) -} - -var transformShellCommand TransformerFunc = func(value interface{}) (interface{}, error) { - if str, ok := value.(string); ok { - return shlex.Split(str) - } - return value, nil -} - -var transformHealthCheckTest TransformerFunc = func(data interface{}) (interface{}, error) { - switch value := data.(type) { - case string: - return append([]string{"CMD-SHELL"}, value), nil - case []interface{}: - return value, nil - default: - return value, errors.Errorf("invalid type %T for healthcheck.test", value) - } -} - -var transformSize TransformerFunc = func(value interface{}) (interface{}, error) { - switch value := value.(type) { - case int: - return int64(value), nil - case string: - return units.RAMInBytes(value) - } - panic(errors.Errorf("invalid type for size %T", value)) -} - -var transformStringToDuration TransformerFunc = func(value interface{}) (interface{}, error) { - switch value := value.(type) { - case string: - d, err := time.ParseDuration(value) - if err != nil { - return value, err - } - return types.Duration(d), nil - default: - return value, errors.Errorf("invalid type %T for duration", value) - } -} - -func toServicePortConfigs(value string) ([]interface{}, error) { - var portConfigs []interface{} - - ports, portBindings, err := nat.ParsePortSpecs([]string{value}) - if err != nil { - return nil, err - } - // We need to sort the key of the ports to make sure it is consistent - keys := []string{} - for port := range ports { - keys = append(keys, string(port)) - } - sort.Strings(keys) - - for _, key := range keys { - // Reuse ConvertPortToPortConfig so that it is consistent - portConfig, err := opts.ConvertPortToPortConfig(nat.Port(key), portBindings) - if err != nil { - return nil, err - } - for _, p := range portConfig { - portConfigs = append(portConfigs, types.ServicePortConfig{ - Protocol: string(p.Protocol), - Target: p.TargetPort, - Published: p.PublishedPort, - Mode: string(p.PublishMode), - }) - } - } - - return portConfigs, nil -} - -func toMapStringString(value map[string]interface{}, allowNil bool) map[string]interface{} { - output := make(map[string]interface{}) - for key, value := range value { - output[key] = toString(value, allowNil) - } - return output -} - -func toString(value interface{}, allowNil bool) interface{} { - switch { - case value != nil: - return fmt.Sprint(value) - case allowNil: - return nil - default: - return "" - } -} - -func toStringList(value map[string]interface{}, separator string, allowNil bool) []string { - output := []string{} - for key, value := range value { - if value == nil && !allowNil { - continue - } - output = append(output, fmt.Sprintf("%s%s%s", key, separator, value)) - } - sort.Strings(output) - return output -} diff --git a/vendor/github.com/docker/cli/cli/compose/loader/merge.go b/vendor/github.com/docker/cli/cli/compose/loader/merge.go deleted file mode 100644 index 57bc2296b..000000000 --- a/vendor/github.com/docker/cli/cli/compose/loader/merge.go +++ /dev/null @@ -1,301 +0,0 @@ -package loader - -import ( - "reflect" - "sort" - - "github.com/docker/cli/cli/compose/types" - "github.com/imdario/mergo" - "github.com/pkg/errors" -) - -type specials struct { - m map[reflect.Type]func(dst, src reflect.Value) error -} - -func (s *specials) Transformer(t reflect.Type) func(dst, src reflect.Value) error { - if fn, ok := s.m[t]; ok { - return fn - } - return nil -} - -func merge(configs []*types.Config) (*types.Config, error) { - base := configs[0] - for _, override := range configs[1:] { - var err error - base.Services, err = mergeServices(base.Services, override.Services) - if err != nil { - return base, errors.Wrapf(err, "cannot merge services from %s", override.Filename) - } - base.Volumes, err = mergeVolumes(base.Volumes, override.Volumes) - if err != nil { - return base, errors.Wrapf(err, "cannot merge volumes from %s", override.Filename) - } - base.Networks, err = mergeNetworks(base.Networks, override.Networks) - if err != nil { - return base, errors.Wrapf(err, "cannot merge networks from %s", override.Filename) - } - base.Secrets, err = mergeSecrets(base.Secrets, override.Secrets) - if err != nil { - return base, errors.Wrapf(err, "cannot merge secrets from %s", override.Filename) - } - base.Configs, err = mergeConfigs(base.Configs, override.Configs) - if err != nil { - return base, errors.Wrapf(err, "cannot merge configs from %s", override.Filename) - } - } - return base, nil -} - -func mergeServices(base, override []types.ServiceConfig) ([]types.ServiceConfig, error) { - baseServices := mapByName(base) - overrideServices := mapByName(override) - specials := &specials{ - m: map[reflect.Type]func(dst, src reflect.Value) error{ - reflect.TypeOf(&types.LoggingConfig{}): safelyMerge(mergeLoggingConfig), - reflect.TypeOf([]types.ServicePortConfig{}): mergeSlice(toServicePortConfigsMap, toServicePortConfigsSlice), - reflect.TypeOf([]types.ServiceSecretConfig{}): mergeSlice(toServiceSecretConfigsMap, toServiceSecretConfigsSlice), - reflect.TypeOf([]types.ServiceConfigObjConfig{}): mergeSlice(toServiceConfigObjConfigsMap, toSServiceConfigObjConfigsSlice), - reflect.TypeOf(&types.UlimitsConfig{}): mergeUlimitsConfig, - reflect.TypeOf([]types.ServiceVolumeConfig{}): mergeSlice(toServiceVolumeConfigsMap, toServiceVolumeConfigsSlice), - reflect.TypeOf(types.ShellCommand{}): mergeShellCommand, - reflect.TypeOf(&types.ServiceNetworkConfig{}): mergeServiceNetworkConfig, - reflect.PointerTo(reflect.TypeOf(uint64(1))): mergeUint64, - }, - } - for name, overrideService := range overrideServices { - overrideService := overrideService - if baseService, ok := baseServices[name]; ok { - if err := mergo.Merge(&baseService, &overrideService, mergo.WithAppendSlice, mergo.WithOverride, mergo.WithTransformers(specials)); err != nil { - return base, errors.Wrapf(err, "cannot merge service %s", name) - } - baseServices[name] = baseService - continue - } - baseServices[name] = overrideService - } - services := []types.ServiceConfig{} - for _, baseService := range baseServices { - services = append(services, baseService) - } - sort.Slice(services, func(i, j int) bool { return services[i].Name < services[j].Name }) - return services, nil -} - -func toServiceSecretConfigsMap(s interface{}) (map[interface{}]interface{}, error) { - secrets, ok := s.([]types.ServiceSecretConfig) - if !ok { - return nil, errors.Errorf("not a serviceSecretConfig: %v", s) - } - m := map[interface{}]interface{}{} - for _, secret := range secrets { - m[secret.Source] = secret - } - return m, nil -} - -func toServiceConfigObjConfigsMap(s interface{}) (map[interface{}]interface{}, error) { - secrets, ok := s.([]types.ServiceConfigObjConfig) - if !ok { - return nil, errors.Errorf("not a serviceSecretConfig: %v", s) - } - m := map[interface{}]interface{}{} - for _, secret := range secrets { - m[secret.Source] = secret - } - return m, nil -} - -func toServicePortConfigsMap(s interface{}) (map[interface{}]interface{}, error) { - ports, ok := s.([]types.ServicePortConfig) - if !ok { - return nil, errors.Errorf("not a servicePortConfig slice: %v", s) - } - m := map[interface{}]interface{}{} - for _, p := range ports { - m[p.Published] = p - } - return m, nil -} - -func toServiceVolumeConfigsMap(s interface{}) (map[interface{}]interface{}, error) { - volumes, ok := s.([]types.ServiceVolumeConfig) - if !ok { - return nil, errors.Errorf("not a serviceVolumeConfig slice: %v", s) - } - m := map[interface{}]interface{}{} - for _, v := range volumes { - m[v.Target] = v - } - return m, nil -} - -func toServiceSecretConfigsSlice(dst reflect.Value, m map[interface{}]interface{}) error { - s := []types.ServiceSecretConfig{} - for _, v := range m { - s = append(s, v.(types.ServiceSecretConfig)) - } - sort.Slice(s, func(i, j int) bool { return s[i].Source < s[j].Source }) - dst.Set(reflect.ValueOf(s)) - return nil -} - -func toSServiceConfigObjConfigsSlice(dst reflect.Value, m map[interface{}]interface{}) error { - s := []types.ServiceConfigObjConfig{} - for _, v := range m { - s = append(s, v.(types.ServiceConfigObjConfig)) - } - sort.Slice(s, func(i, j int) bool { return s[i].Source < s[j].Source }) - dst.Set(reflect.ValueOf(s)) - return nil -} - -func toServicePortConfigsSlice(dst reflect.Value, m map[interface{}]interface{}) error { - s := []types.ServicePortConfig{} - for _, v := range m { - s = append(s, v.(types.ServicePortConfig)) - } - sort.Slice(s, func(i, j int) bool { return s[i].Published < s[j].Published }) - dst.Set(reflect.ValueOf(s)) - return nil -} - -func toServiceVolumeConfigsSlice(dst reflect.Value, m map[interface{}]interface{}) error { - s := []types.ServiceVolumeConfig{} - for _, v := range m { - s = append(s, v.(types.ServiceVolumeConfig)) - } - sort.Slice(s, func(i, j int) bool { return s[i].Target < s[j].Target }) - dst.Set(reflect.ValueOf(s)) - return nil -} - -type ( - tomapFn func(s interface{}) (map[interface{}]interface{}, error) - writeValueFromMapFn func(reflect.Value, map[interface{}]interface{}) error -) - -func safelyMerge(mergeFn func(dst, src reflect.Value) error) func(dst, src reflect.Value) error { - return func(dst, src reflect.Value) error { - if src.IsNil() { - return nil - } - if dst.IsNil() { - dst.Set(src) - return nil - } - return mergeFn(dst, src) - } -} - -func mergeSlice(tomap tomapFn, writeValue writeValueFromMapFn) func(dst, src reflect.Value) error { - return func(dst, src reflect.Value) error { - dstMap, err := sliceToMap(tomap, dst) - if err != nil { - return err - } - srcMap, err := sliceToMap(tomap, src) - if err != nil { - return err - } - if err := mergo.Map(&dstMap, srcMap, mergo.WithOverride); err != nil { - return err - } - return writeValue(dst, dstMap) - } -} - -func sliceToMap(tomap tomapFn, v reflect.Value) (map[interface{}]interface{}, error) { - // check if valid - if !v.IsValid() { - return nil, errors.Errorf("invalid value : %+v", v) - } - return tomap(v.Interface()) -} - -func mergeLoggingConfig(dst, src reflect.Value) error { - // Same driver, merging options - if getLoggingDriver(dst.Elem()) == getLoggingDriver(src.Elem()) || - getLoggingDriver(dst.Elem()) == "" || getLoggingDriver(src.Elem()) == "" { - if getLoggingDriver(dst.Elem()) == "" { - dst.Elem().FieldByName("Driver").SetString(getLoggingDriver(src.Elem())) - } - dstOptions := dst.Elem().FieldByName("Options").Interface().(map[string]string) - srcOptions := src.Elem().FieldByName("Options").Interface().(map[string]string) - return mergo.Merge(&dstOptions, srcOptions, mergo.WithOverride) - } - // Different driver, override with src - dst.Set(src) - return nil -} - -//nolint:unparam -func mergeUlimitsConfig(dst, src reflect.Value) error { - if src.Interface() != reflect.Zero(reflect.TypeOf(src.Interface())).Interface() { - dst.Elem().Set(src.Elem()) - } - return nil -} - -//nolint:unparam -func mergeShellCommand(dst, src reflect.Value) error { - if src.Len() != 0 { - dst.Set(src) - } - return nil -} - -//nolint:unparam -func mergeServiceNetworkConfig(dst, src reflect.Value) error { - if src.Interface() != reflect.Zero(reflect.TypeOf(src.Interface())).Interface() { - dst.Elem().FieldByName("Aliases").Set(src.Elem().FieldByName("Aliases")) - if ipv4 := src.Elem().FieldByName("Ipv4Address").Interface().(string); ipv4 != "" { - dst.Elem().FieldByName("Ipv4Address").SetString(ipv4) - } - if ipv6 := src.Elem().FieldByName("Ipv6Address").Interface().(string); ipv6 != "" { - dst.Elem().FieldByName("Ipv6Address").SetString(ipv6) - } - } - return nil -} - -//nolint:unparam -func mergeUint64(dst, src reflect.Value) error { - if !src.IsNil() { - dst.Elem().Set(src.Elem()) - } - return nil -} - -func getLoggingDriver(v reflect.Value) string { - return v.FieldByName("Driver").String() -} - -func mapByName(services []types.ServiceConfig) map[string]types.ServiceConfig { - m := map[string]types.ServiceConfig{} - for _, service := range services { - m[service.Name] = service - } - return m -} - -func mergeVolumes(base, override map[string]types.VolumeConfig) (map[string]types.VolumeConfig, error) { - err := mergo.Map(&base, &override, mergo.WithOverride) - return base, err -} - -func mergeNetworks(base, override map[string]types.NetworkConfig) (map[string]types.NetworkConfig, error) { - err := mergo.Map(&base, &override, mergo.WithOverride) - return base, err -} - -func mergeSecrets(base, override map[string]types.SecretConfig) (map[string]types.SecretConfig, error) { - err := mergo.Map(&base, &override, mergo.WithOverride) - return base, err -} - -func mergeConfigs(base, override map[string]types.ConfigObjConfig) (map[string]types.ConfigObjConfig, error) { - err := mergo.Map(&base, &override, mergo.WithOverride) - return base, err -} diff --git a/vendor/github.com/docker/cli/cli/compose/loader/volume.go b/vendor/github.com/docker/cli/cli/compose/loader/volume.go deleted file mode 100644 index f043f4aa5..000000000 --- a/vendor/github.com/docker/cli/cli/compose/loader/volume.go +++ /dev/null @@ -1,125 +0,0 @@ -package loader - -import ( - "strings" - "unicode" - "unicode/utf8" - - "github.com/docker/cli/cli/compose/types" - "github.com/docker/docker/api/types/mount" - "github.com/pkg/errors" -) - -const endOfSpec = rune(0) - -// ParseVolume parses a volume spec without any knowledge of the target platform -func ParseVolume(spec string) (types.ServiceVolumeConfig, error) { - volume := types.ServiceVolumeConfig{} - - switch len(spec) { - case 0: - return volume, errors.New("invalid empty volume spec") - case 1, 2: - volume.Target = spec - volume.Type = string(mount.TypeVolume) - return volume, nil - } - - buffer := []rune{} - for _, char := range spec + string(endOfSpec) { - switch { - case isWindowsDrive(buffer, char): - buffer = append(buffer, char) - case char == ':' || char == endOfSpec: - if err := populateFieldFromBuffer(char, buffer, &volume); err != nil { - populateType(&volume) - return volume, errors.Wrapf(err, "invalid spec: %s", spec) - } - buffer = []rune{} - default: - buffer = append(buffer, char) - } - } - - populateType(&volume) - return volume, nil -} - -func isWindowsDrive(buffer []rune, char rune) bool { - return char == ':' && len(buffer) == 1 && unicode.IsLetter(buffer[0]) -} - -func populateFieldFromBuffer(char rune, buffer []rune, volume *types.ServiceVolumeConfig) error { - strBuffer := string(buffer) - switch { - case len(buffer) == 0: - return errors.New("empty section between colons") - // Anonymous volume - case volume.Source == "" && char == endOfSpec: - volume.Target = strBuffer - return nil - case volume.Source == "": - volume.Source = strBuffer - return nil - case volume.Target == "": - volume.Target = strBuffer - return nil - case char == ':': - return errors.New("too many colons") - } - for _, option := range strings.Split(strBuffer, ",") { - switch option { - case "ro": - volume.ReadOnly = true - case "rw": - volume.ReadOnly = false - case "nocopy": - volume.Volume = &types.ServiceVolumeVolume{NoCopy: true} - default: - if isBindOption(option) { - volume.Bind = &types.ServiceVolumeBind{Propagation: option} - } - // ignore unknown options - } - } - return nil -} - -func isBindOption(option string) bool { - for _, propagation := range mount.Propagations { - if mount.Propagation(option) == propagation { - return true - } - } - return false -} - -func populateType(volume *types.ServiceVolumeConfig) { - switch { - // Anonymous volume - case volume.Source == "": - volume.Type = string(mount.TypeVolume) - case isFilePath(volume.Source): - volume.Type = string(mount.TypeBind) - default: - volume.Type = string(mount.TypeVolume) - } -} - -func isFilePath(source string) bool { - switch source[0] { - case '.', '/', '~': - return true - } - if len([]rune(source)) == 1 { - return false - } - - // windows named pipes - if strings.HasPrefix(source, `\\`) { - return true - } - - first, nextIndex := utf8.DecodeRuneInString(source) - return isWindowsDrive([]rune{first}, rune(source[nextIndex])) -} diff --git a/vendor/github.com/docker/cli/cli/compose/loader/windows_path.go b/vendor/github.com/docker/cli/cli/compose/loader/windows_path.go deleted file mode 100644 index 3070bf884..000000000 --- a/vendor/github.com/docker/cli/cli/compose/loader/windows_path.go +++ /dev/null @@ -1,67 +0,0 @@ -package loader - -// 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. -// https://github.com/golang/go/blob/master/LICENSE - -// This file contains utilities to check for Windows absolute paths on Linux. -// The code in this file was largely copied from the Golang filepath package -// https://github.com/golang/go/blob/1d0e94b1e13d5e8a323a63cd1cc1ef95290c9c36/src/path/filepath/path_windows.go#L12-L65 - -func isSlash(c uint8) bool { - return c == '\\' || c == '/' -} - -// isAbs reports whether the path is a Windows absolute path. -func isAbs(path string) (b bool) { - l := volumeNameLen(path) - if l == 0 { - return false - } - path = path[l:] - if path == "" { - return false - } - return isSlash(path[0]) -} - -// volumeNameLen returns length of the leading volume name on Windows. -// It returns 0 elsewhere. -// -//nolint:gocyclo -func volumeNameLen(path string) int { - if len(path) < 2 { - return 0 - } - // with drive letter - c := path[0] - if path[1] == ':' && ('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z') { - return 2 - } - // is it UNC? https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx - if l := len(path); l >= 5 && isSlash(path[0]) && isSlash(path[1]) && - !isSlash(path[2]) && path[2] != '.' { - // first, leading `\\` and next shouldn't be `\`. its server name. - for n := 3; n < l-1; n++ { - // second, next '\' shouldn't be repeated. - if isSlash(path[n]) { - n++ - // third, following something characters. its share name. - if !isSlash(path[n]) { - if path[n] == '.' { - break - } - for ; n < l; n++ { - if isSlash(path[n]) { - break - } - } - return n - } - break - } - } - } - return 0 -} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.0.json b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.0.json deleted file mode 100644 index f39344cfb..000000000 --- a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.0.json +++ /dev/null @@ -1,384 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "id": "config_schema_v3.0.json", - "type": "object", - "required": ["version"], - - "properties": { - "version": { - "type": "string" - }, - - "services": { - "id": "#/properties/services", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/service" - } - }, - "additionalProperties": false - }, - - "networks": { - "id": "#/properties/networks", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/network" - } - } - }, - - "volumes": { - "id": "#/properties/volumes", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/volume" - } - }, - "additionalProperties": false - } - }, - - "additionalProperties": false, - - "definitions": { - - "service": { - "id": "#/definitions/service", - "type": "object", - - "properties": { - "deploy": {"$ref": "#/definitions/deployment"}, - "build": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "context": {"type": "string"}, - "dockerfile": {"type": "string"}, - "args": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - } - ] - }, - "cap_add": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "cap_drop": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "cgroup_parent": {"type": "string"}, - "command": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "container_name": {"type": "string"}, - "depends_on": {"$ref": "#/definitions/list_of_strings"}, - "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "dns": {"$ref": "#/definitions/string_or_list"}, - "dns_search": {"$ref": "#/definitions/string_or_list"}, - "domainname": {"type": "string"}, - "entrypoint": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "env_file": {"$ref": "#/definitions/string_or_list"}, - "environment": {"$ref": "#/definitions/list_or_dict"}, - - "expose": { - "type": "array", - "items": { - "type": ["string", "number"], - "format": "expose" - }, - "uniqueItems": true - }, - - "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, - "healthcheck": {"$ref": "#/definitions/healthcheck"}, - "hostname": {"type": "string"}, - "image": {"type": "string"}, - "ipc": {"type": "string"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - - "logging": { - "type": "object", - - "properties": { - "driver": {"type": "string"}, - "options": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number", "null"]} - } - } - }, - "additionalProperties": false - }, - - "mac_address": {"type": "string"}, - "network_mode": {"type": "string"}, - - "networks": { - "oneOf": [ - {"$ref": "#/definitions/list_of_strings"}, - { - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "oneOf": [ - { - "type": "object", - "properties": { - "aliases": {"$ref": "#/definitions/list_of_strings"}, - "ipv4_address": {"type": "string"}, - "ipv6_address": {"type": "string"} - }, - "additionalProperties": false - }, - {"type": "null"} - ] - } - }, - "additionalProperties": false - } - ] - }, - "pid": {"type": ["string", "null"]}, - - "ports": { - "type": "array", - "items": { - "type": ["string", "number"], - "format": "ports" - }, - "uniqueItems": true - }, - - "privileged": {"type": "boolean"}, - "read_only": {"type": "boolean"}, - "restart": {"type": "string"}, - "security_opt": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "shm_size": {"type": ["number", "string"]}, - "sysctls": {"$ref": "#/definitions/list_or_dict"}, - "stdin_open": {"type": "boolean"}, - "stop_grace_period": {"type": "string", "format": "duration"}, - "stop_signal": {"type": "string"}, - "tmpfs": {"$ref": "#/definitions/string_or_list"}, - "tty": {"type": "boolean"}, - "ulimits": { - "type": "object", - "patternProperties": { - "^[a-z]+$": { - "oneOf": [ - {"type": "integer"}, - { - "type":"object", - "properties": { - "hard": {"type": "integer"}, - "soft": {"type": "integer"} - }, - "required": ["soft", "hard"], - "additionalProperties": false - } - ] - } - } - }, - "user": {"type": "string"}, - "userns_mode": {"type": "string"}, - "volumes": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "working_dir": {"type": "string"} - }, - "additionalProperties": false - }, - - "healthcheck": { - "id": "#/definitions/healthcheck", - "type": "object", - "additionalProperties": false, - "properties": { - "disable": {"type": "boolean"}, - "interval": {"type": "string"}, - "retries": {"type": "number"}, - "test": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "timeout": {"type": "string"} - } - }, - "deployment": { - "id": "#/definitions/deployment", - "type": ["object", "null"], - "properties": { - "mode": {"type": "string"}, - "replicas": {"type": "integer"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "update_config": { - "type": "object", - "properties": { - "parallelism": {"type": "integer"}, - "delay": {"type": "string", "format": "duration"}, - "failure_action": {"type": "string"}, - "monitor": {"type": "string", "format": "duration"}, - "max_failure_ratio": {"type": "number"} - }, - "additionalProperties": false - }, - "resources": { - "type": "object", - "properties": { - "limits": {"$ref": "#/definitions/resource"}, - "reservations": {"$ref": "#/definitions/resource"} - }, - "additionalProperties": false - }, - "restart_policy": { - "type": "object", - "properties": { - "condition": {"type": "string"}, - "delay": {"type": "string", "format": "duration"}, - "max_attempts": {"type": "integer"}, - "window": {"type": "string", "format": "duration"} - }, - "additionalProperties": false - }, - "placement": { - "type": "object", - "properties": { - "constraints": {"type": "array", "items": {"type": "string"}} - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - - "resource": { - "id": "#/definitions/resource", - "type": "object", - "properties": { - "cpus": {"type": "string"}, - "memory": {"type": "string"} - }, - "additionalProperties": false - }, - - "network": { - "id": "#/definitions/network", - "type": ["object", "null"], - "properties": { - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "ipam": { - "type": "object", - "properties": { - "driver": {"type": "string"}, - "config": { - "type": "array", - "items": { - "type": "object", - "properties": { - "subnet": {"type": "string"} - }, - "additionalProperties": false - } - } - }, - "additionalProperties": false - }, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - }, - "additionalProperties": false - }, - "internal": {"type": "boolean"}, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - }, - - "volume": { - "id": "#/definitions/volume", - "type": ["object", "null"], - "properties": { - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - }, - "additionalProperties": false - }, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - }, - - "string_or_list": { - "oneOf": [ - {"type": "string"}, - {"$ref": "#/definitions/list_of_strings"} - ] - }, - - "list_of_strings": { - "type": "array", - "items": {"type": "string"}, - "uniqueItems": true - }, - - "list_or_dict": { - "oneOf": [ - { - "type": "object", - "patternProperties": { - ".+": { - "type": ["string", "number", "null"] - } - }, - "additionalProperties": false - }, - {"type": "array", "items": {"type": "string"}, "uniqueItems": true} - ] - }, - - "constraints": { - "service": { - "id": "#/definitions/constraints/service", - "anyOf": [ - {"required": ["build"]}, - {"required": ["image"]} - ], - "properties": { - "build": { - "required": ["context"] - } - } - } - } - } -} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.1.json b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.1.json deleted file mode 100644 index 719c0fa7a..000000000 --- a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.1.json +++ /dev/null @@ -1,429 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "id": "config_schema_v3.1.json", - "type": "object", - "required": ["version"], - - "properties": { - "version": { - "type": "string" - }, - - "services": { - "id": "#/properties/services", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/service" - } - }, - "additionalProperties": false - }, - - "networks": { - "id": "#/properties/networks", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/network" - } - } - }, - - "volumes": { - "id": "#/properties/volumes", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/volume" - } - }, - "additionalProperties": false - }, - - "secrets": { - "id": "#/properties/secrets", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/secret" - } - }, - "additionalProperties": false - } - }, - - "additionalProperties": false, - - "definitions": { - - "service": { - "id": "#/definitions/service", - "type": "object", - - "properties": { - "deploy": {"$ref": "#/definitions/deployment"}, - "build": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "context": {"type": "string"}, - "dockerfile": {"type": "string"}, - "args": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - } - ] - }, - "cap_add": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "cap_drop": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "cgroup_parent": {"type": "string"}, - "command": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "container_name": {"type": "string"}, - "depends_on": {"$ref": "#/definitions/list_of_strings"}, - "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "dns": {"$ref": "#/definitions/string_or_list"}, - "dns_search": {"$ref": "#/definitions/string_or_list"}, - "domainname": {"type": "string"}, - "entrypoint": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "env_file": {"$ref": "#/definitions/string_or_list"}, - "environment": {"$ref": "#/definitions/list_or_dict"}, - - "expose": { - "type": "array", - "items": { - "type": ["string", "number"], - "format": "expose" - }, - "uniqueItems": true - }, - - "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, - "healthcheck": {"$ref": "#/definitions/healthcheck"}, - "hostname": {"type": "string"}, - "image": {"type": "string"}, - "ipc": {"type": "string"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - - "logging": { - "type": "object", - - "properties": { - "driver": {"type": "string"}, - "options": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number", "null"]} - } - } - }, - "additionalProperties": false - }, - - "mac_address": {"type": "string"}, - "network_mode": {"type": "string"}, - - "networks": { - "oneOf": [ - {"$ref": "#/definitions/list_of_strings"}, - { - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "oneOf": [ - { - "type": "object", - "properties": { - "aliases": {"$ref": "#/definitions/list_of_strings"}, - "ipv4_address": {"type": "string"}, - "ipv6_address": {"type": "string"} - }, - "additionalProperties": false - }, - {"type": "null"} - ] - } - }, - "additionalProperties": false - } - ] - }, - "pid": {"type": ["string", "null"]}, - - "ports": { - "type": "array", - "items": { - "type": ["string", "number"], - "format": "ports" - }, - "uniqueItems": true - }, - - "privileged": {"type": "boolean"}, - "read_only": {"type": "boolean"}, - "restart": {"type": "string"}, - "security_opt": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "shm_size": {"type": ["number", "string"]}, - "secrets": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "source": {"type": "string"}, - "target": {"type": "string"}, - "uid": {"type": "string"}, - "gid": {"type": "string"}, - "mode": {"type": "number"} - } - } - ] - } - }, - "sysctls": {"$ref": "#/definitions/list_or_dict"}, - "stdin_open": {"type": "boolean"}, - "stop_grace_period": {"type": "string", "format": "duration"}, - "stop_signal": {"type": "string"}, - "tmpfs": {"$ref": "#/definitions/string_or_list"}, - "tty": {"type": "boolean"}, - "ulimits": { - "type": "object", - "patternProperties": { - "^[a-z]+$": { - "oneOf": [ - {"type": "integer"}, - { - "type":"object", - "properties": { - "hard": {"type": "integer"}, - "soft": {"type": "integer"} - }, - "required": ["soft", "hard"], - "additionalProperties": false - } - ] - } - } - }, - "user": {"type": "string"}, - "userns_mode": {"type": "string"}, - "volumes": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "working_dir": {"type": "string"} - }, - "additionalProperties": false - }, - - "healthcheck": { - "id": "#/definitions/healthcheck", - "type": "object", - "additionalProperties": false, - "properties": { - "disable": {"type": "boolean"}, - "interval": {"type": "string"}, - "retries": {"type": "number"}, - "test": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "timeout": {"type": "string"} - } - }, - "deployment": { - "id": "#/definitions/deployment", - "type": ["object", "null"], - "properties": { - "mode": {"type": "string"}, - "replicas": {"type": "integer"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "update_config": { - "type": "object", - "properties": { - "parallelism": {"type": "integer"}, - "delay": {"type": "string", "format": "duration"}, - "failure_action": {"type": "string"}, - "monitor": {"type": "string", "format": "duration"}, - "max_failure_ratio": {"type": "number"} - }, - "additionalProperties": false - }, - "resources": { - "type": "object", - "properties": { - "limits": {"$ref": "#/definitions/resource"}, - "reservations": {"$ref": "#/definitions/resource"} - }, - "additionalProperties": false - }, - "restart_policy": { - "type": "object", - "properties": { - "condition": {"type": "string"}, - "delay": {"type": "string", "format": "duration"}, - "max_attempts": {"type": "integer"}, - "window": {"type": "string", "format": "duration"} - }, - "additionalProperties": false - }, - "placement": { - "type": "object", - "properties": { - "constraints": {"type": "array", "items": {"type": "string"}} - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - - "resource": { - "id": "#/definitions/resource", - "type": "object", - "properties": { - "cpus": {"type": "string"}, - "memory": {"type": "string"} - }, - "additionalProperties": false - }, - - "network": { - "id": "#/definitions/network", - "type": ["object", "null"], - "properties": { - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "ipam": { - "type": "object", - "properties": { - "driver": {"type": "string"}, - "config": { - "type": "array", - "items": { - "type": "object", - "properties": { - "subnet": {"type": "string"} - }, - "additionalProperties": false - } - } - }, - "additionalProperties": false - }, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - }, - "additionalProperties": false - }, - "internal": {"type": "boolean"}, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - }, - - "volume": { - "id": "#/definitions/volume", - "type": ["object", "null"], - "properties": { - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - }, - "additionalProperties": false - }, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - }, - - "secret": { - "id": "#/definitions/secret", - "type": "object", - "properties": { - "file": {"type": "string"}, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - } - }, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - }, - - "string_or_list": { - "oneOf": [ - {"type": "string"}, - {"$ref": "#/definitions/list_of_strings"} - ] - }, - - "list_of_strings": { - "type": "array", - "items": {"type": "string"}, - "uniqueItems": true - }, - - "list_or_dict": { - "oneOf": [ - { - "type": "object", - "patternProperties": { - ".+": { - "type": ["string", "number", "null"] - } - }, - "additionalProperties": false - }, - {"type": "array", "items": {"type": "string"}, "uniqueItems": true} - ] - }, - - "constraints": { - "service": { - "id": "#/definitions/constraints/service", - "anyOf": [ - {"required": ["build"]}, - {"required": ["image"]} - ], - "properties": { - "build": { - "required": ["context"] - } - } - } - } - } -} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.10.json b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.10.json deleted file mode 100644 index 7c032cf54..000000000 --- a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.10.json +++ /dev/null @@ -1,672 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "id": "config_schema_v3.10.json", - "type": "object", - - "properties": { - "version": { - "type": "string", - "default": "3.10" - }, - - "services": { - "id": "#/properties/services", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/service" - } - }, - "additionalProperties": false - }, - - "networks": { - "id": "#/properties/networks", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/network" - } - } - }, - - "volumes": { - "id": "#/properties/volumes", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/volume" - } - }, - "additionalProperties": false - }, - - "secrets": { - "id": "#/properties/secrets", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/secret" - } - }, - "additionalProperties": false - }, - - "configs": { - "id": "#/properties/configs", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/config" - } - }, - "additionalProperties": false - } - }, - - "patternProperties": {"^x-": {}}, - "additionalProperties": false, - - "definitions": { - - "service": { - "id": "#/definitions/service", - "type": "object", - - "properties": { - "deploy": {"$ref": "#/definitions/deployment"}, - "build": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "context": {"type": "string"}, - "dockerfile": {"type": "string"}, - "args": {"$ref": "#/definitions/list_or_dict"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "cache_from": {"$ref": "#/definitions/list_of_strings"}, - "network": {"type": "string"}, - "target": {"type": "string"}, - "shm_size": {"type": ["integer", "string"]}, - "extra_hosts": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - } - ] - }, - "cap_add": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "cap_drop": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "cgroupns_mode": {"type": "string"}, - "cgroup_parent": {"type": "string"}, - "command": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "configs": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "source": {"type": "string"}, - "target": {"type": "string"}, - "uid": {"type": "string"}, - "gid": {"type": "string"}, - "mode": {"type": "number"} - } - } - ] - } - }, - "container_name": {"type": "string"}, - "credential_spec": { - "type": "object", - "properties": { - "config": {"type": "string"}, - "file": {"type": "string"}, - "registry": {"type": "string"} - }, - "additionalProperties": false - }, - "depends_on": {"$ref": "#/definitions/list_of_strings"}, - "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "dns": {"$ref": "#/definitions/string_or_list"}, - "dns_search": {"$ref": "#/definitions/string_or_list"}, - "domainname": {"type": "string"}, - "entrypoint": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "env_file": {"$ref": "#/definitions/string_or_list"}, - "environment": {"$ref": "#/definitions/list_or_dict"}, - - "expose": { - "type": "array", - "items": { - "type": ["string", "number"], - "format": "expose" - }, - "uniqueItems": true - }, - - "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, - "healthcheck": {"$ref": "#/definitions/healthcheck"}, - "hostname": {"type": "string"}, - "image": {"type": "string"}, - "init": {"type": "boolean"}, - "ipc": {"type": "string"}, - "isolation": {"type": "string"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - - "logging": { - "type": "object", - - "properties": { - "driver": {"type": "string"}, - "options": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number", "null"]} - } - } - }, - "additionalProperties": false - }, - - "mac_address": {"type": "string"}, - "network_mode": {"type": "string"}, - - "networks": { - "oneOf": [ - {"$ref": "#/definitions/list_of_strings"}, - { - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "oneOf": [ - { - "type": "object", - "properties": { - "aliases": {"$ref": "#/definitions/list_of_strings"}, - "ipv4_address": {"type": "string"}, - "ipv6_address": {"type": "string"} - }, - "additionalProperties": false - }, - {"type": "null"} - ] - } - }, - "additionalProperties": false - } - ] - }, - "pid": {"type": ["string", "null"]}, - - "ports": { - "type": "array", - "items": { - "oneOf": [ - {"type": "number", "format": "ports"}, - {"type": "string", "format": "ports"}, - { - "type": "object", - "properties": { - "mode": {"type": "string"}, - "target": {"type": "integer"}, - "published": {"type": "integer"}, - "protocol": {"type": "string"} - }, - "additionalProperties": false - } - ] - }, - "uniqueItems": true - }, - - "privileged": {"type": "boolean"}, - "read_only": {"type": "boolean"}, - "restart": {"type": "string"}, - "security_opt": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "shm_size": {"type": ["number", "string"]}, - "secrets": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "source": {"type": "string"}, - "target": {"type": "string"}, - "uid": {"type": "string"}, - "gid": {"type": "string"}, - "mode": {"type": "number"} - } - } - ] - } - }, - "sysctls": {"$ref": "#/definitions/list_or_dict"}, - "stdin_open": {"type": "boolean"}, - "stop_grace_period": {"type": "string", "format": "duration"}, - "stop_signal": {"type": "string"}, - "tmpfs": {"$ref": "#/definitions/string_or_list"}, - "tty": {"type": "boolean"}, - "ulimits": { - "type": "object", - "patternProperties": { - "^[a-z]+$": { - "oneOf": [ - {"type": "integer"}, - { - "type":"object", - "properties": { - "hard": {"type": "integer"}, - "soft": {"type": "integer"} - }, - "required": ["soft", "hard"], - "additionalProperties": false - } - ] - } - } - }, - "user": {"type": "string"}, - "userns_mode": {"type": "string"}, - "volumes": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "required": ["type"], - "properties": { - "type": {"type": "string"}, - "source": {"type": "string"}, - "target": {"type": "string"}, - "read_only": {"type": "boolean"}, - "consistency": {"type": "string"}, - "bind": { - "type": "object", - "properties": { - "propagation": {"type": "string"} - } - }, - "volume": { - "type": "object", - "properties": { - "nocopy": {"type": "boolean"} - } - }, - "tmpfs": { - "type": "object", - "properties": { - "size": { - "type": "integer", - "minimum": 0 - } - } - } - }, - "additionalProperties": false - } - ], - "uniqueItems": true - } - }, - "working_dir": {"type": "string"} - }, - "patternProperties": {"^x-": {}}, - "additionalProperties": false - }, - - "healthcheck": { - "id": "#/definitions/healthcheck", - "type": "object", - "additionalProperties": false, - "properties": { - "disable": {"type": "boolean"}, - "interval": {"type": "string", "format": "duration"}, - "retries": {"type": "number"}, - "test": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "timeout": {"type": "string", "format": "duration"}, - "start_period": {"type": "string", "format": "duration"} - } - }, - "deployment": { - "id": "#/definitions/deployment", - "type": ["object", "null"], - "properties": { - "mode": {"type": "string"}, - "endpoint_mode": {"type": "string"}, - "replicas": {"type": "integer"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "rollback_config": { - "type": "object", - "properties": { - "parallelism": {"type": "integer"}, - "delay": {"type": "string", "format": "duration"}, - "failure_action": {"type": "string"}, - "monitor": {"type": "string", "format": "duration"}, - "max_failure_ratio": {"type": "number"}, - "order": {"type": "string", "enum": [ - "start-first", "stop-first" - ]} - }, - "additionalProperties": false - }, - "update_config": { - "type": "object", - "properties": { - "parallelism": {"type": "integer"}, - "delay": {"type": "string", "format": "duration"}, - "failure_action": {"type": "string"}, - "monitor": {"type": "string", "format": "duration"}, - "max_failure_ratio": {"type": "number"}, - "order": {"type": "string", "enum": [ - "start-first", "stop-first" - ]} - }, - "additionalProperties": false - }, - "resources": { - "type": "object", - "properties": { - "limits": { - "type": "object", - "properties": { - "cpus": {"type": "string"}, - "memory": {"type": "string"}, - "pids": {"type": "integer"} - }, - "additionalProperties": false - }, - "reservations": { - "type": "object", - "properties": { - "cpus": {"type": "string"}, - "memory": {"type": "string"}, - "generic_resources": {"$ref": "#/definitions/generic_resources"} - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - "restart_policy": { - "type": "object", - "properties": { - "condition": {"type": "string"}, - "delay": {"type": "string", "format": "duration"}, - "max_attempts": {"type": "integer"}, - "window": {"type": "string", "format": "duration"} - }, - "additionalProperties": false - }, - "placement": { - "type": "object", - "properties": { - "constraints": {"type": "array", "items": {"type": "string"}}, - "preferences": { - "type": "array", - "items": { - "type": "object", - "properties": { - "spread": {"type": "string"} - }, - "additionalProperties": false - } - }, - "max_replicas_per_node": {"type": "integer"} - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - - "generic_resources": { - "id": "#/definitions/generic_resources", - "type": "array", - "items": { - "type": "object", - "properties": { - "discrete_resource_spec": { - "type": "object", - "properties": { - "kind": {"type": "string"}, - "value": {"type": "number"} - }, - "additionalProperties": false - } - }, - "additionalProperties": false - } - }, - - "network": { - "id": "#/definitions/network", - "type": ["object", "null"], - "properties": { - "name": {"type": "string"}, - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "ipam": { - "type": "object", - "properties": { - "driver": {"type": "string"}, - "config": { - "type": "array", - "items": { - "type": "object", - "properties": { - "subnet": {"type": "string"} - }, - "additionalProperties": false - } - } - }, - "additionalProperties": false - }, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - }, - "additionalProperties": false - }, - "internal": {"type": "boolean"}, - "attachable": {"type": "boolean"}, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "patternProperties": {"^x-": {}}, - "additionalProperties": false - }, - - "volume": { - "id": "#/definitions/volume", - "type": ["object", "null"], - "properties": { - "name": {"type": "string"}, - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - }, - "additionalProperties": false - }, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "x-cluster-spec": { - "type": "object", - "properties": { - "group": {"type": "string"}, - "access_mode": { - "type": "object", - "properties": { - "scope": {"type": "string"}, - "sharing": {"type": "string"}, - "block_volume": {"type": "object"}, - "mount_volume": { - "type": "object", - "properties": { - "fs_type": {"type": "string"}, - "mount_flags": {"type": "array", "items": {"type": "string"}} - } - } - } - }, - "accessibility_requirements": { - "type": "object", - "properties": { - "requisite": { - "type": "array", - "items": { - "type": "object", - "properties": { - "segments": {"$ref": "#/definitions/list_or_dict"} - } - } - }, - "preferred": { - "type": "array", - "items": { - "type": "object", - "properties": { - "segments": {"$ref": "#/definitions/list_or_dict"} - } - } - } - } - }, - "capacity_range": { - "type": "object", - "properties": { - "required_bytes": {"type": "string"}, - "limit_bytes": {"type": "string"} - } - }, - "availability": {"type": "string"} - } - } - }, - "patternProperties": {"^x-": {}}, - "additionalProperties": false - }, - - "secret": { - "id": "#/definitions/secret", - "type": "object", - "properties": { - "name": {"type": "string"}, - "file": {"type": "string"}, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - } - }, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "template_driver": {"type": "string"} - }, - "patternProperties": {"^x-": {}}, - "additionalProperties": false - }, - - "config": { - "id": "#/definitions/config", - "type": "object", - "properties": { - "name": {"type": "string"}, - "file": {"type": "string"}, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - } - }, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "template_driver": {"type": "string"} - }, - "patternProperties": {"^x-": {}}, - "additionalProperties": false - }, - - "string_or_list": { - "oneOf": [ - {"type": "string"}, - {"$ref": "#/definitions/list_of_strings"} - ] - }, - - "list_of_strings": { - "type": "array", - "items": {"type": "string"}, - "uniqueItems": true - }, - - "list_or_dict": { - "oneOf": [ - { - "type": "object", - "patternProperties": { - ".+": { - "type": ["string", "number", "null"] - } - }, - "additionalProperties": false - }, - {"type": "array", "items": {"type": "string"}, "uniqueItems": true} - ] - }, - - "constraints": { - "service": { - "id": "#/definitions/constraints/service", - "anyOf": [ - {"required": ["build"]}, - {"required": ["image"]} - ], - "properties": { - "build": { - "required": ["context"] - } - } - } - } - } -} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.11.json b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.11.json deleted file mode 100644 index fb2c9fd84..000000000 --- a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.11.json +++ /dev/null @@ -1,672 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "id": "config_schema_v3.11.json", - "type": "object", - - "properties": { - "version": { - "type": "string", - "default": "3.11" - }, - - "services": { - "id": "#/properties/services", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/service" - } - }, - "additionalProperties": false - }, - - "networks": { - "id": "#/properties/networks", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/network" - } - } - }, - - "volumes": { - "id": "#/properties/volumes", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/volume" - } - }, - "additionalProperties": false - }, - - "secrets": { - "id": "#/properties/secrets", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/secret" - } - }, - "additionalProperties": false - }, - - "configs": { - "id": "#/properties/configs", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/config" - } - }, - "additionalProperties": false - } - }, - - "patternProperties": {"^x-": {}}, - "additionalProperties": false, - - "definitions": { - - "service": { - "id": "#/definitions/service", - "type": "object", - - "properties": { - "deploy": {"$ref": "#/definitions/deployment"}, - "build": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "context": {"type": "string"}, - "dockerfile": {"type": "string"}, - "args": {"$ref": "#/definitions/list_or_dict"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "cache_from": {"$ref": "#/definitions/list_of_strings"}, - "network": {"type": "string"}, - "target": {"type": "string"}, - "shm_size": {"type": ["integer", "string"]}, - "extra_hosts": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": true - } - ] - }, - "cap_add": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "cap_drop": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "cgroupns_mode": {"type": "string"}, - "cgroup_parent": {"type": "string"}, - "command": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "configs": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "source": {"type": "string"}, - "target": {"type": "string"}, - "uid": {"type": "string"}, - "gid": {"type": "string"}, - "mode": {"type": "number"} - } - } - ] - } - }, - "container_name": {"type": "string"}, - "credential_spec": { - "type": "object", - "properties": { - "config": {"type": "string"}, - "file": {"type": "string"}, - "registry": {"type": "string"} - }, - "additionalProperties": false - }, - "depends_on": {"$ref": "#/definitions/list_of_strings"}, - "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "dns": {"$ref": "#/definitions/string_or_list"}, - "dns_search": {"$ref": "#/definitions/string_or_list"}, - "domainname": {"type": "string"}, - "entrypoint": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "env_file": {"$ref": "#/definitions/string_or_list"}, - "environment": {"$ref": "#/definitions/list_or_dict"}, - - "expose": { - "type": "array", - "items": { - "type": ["string", "number"], - "format": "expose" - }, - "uniqueItems": true - }, - - "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, - "healthcheck": {"$ref": "#/definitions/healthcheck"}, - "hostname": {"type": "string"}, - "image": {"type": "string"}, - "init": {"type": "boolean"}, - "ipc": {"type": "string"}, - "isolation": {"type": "string"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - - "logging": { - "type": "object", - - "properties": { - "driver": {"type": "string"}, - "options": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number", "null"]} - } - } - }, - "additionalProperties": false - }, - - "mac_address": {"type": "string"}, - "network_mode": {"type": "string"}, - - "networks": { - "oneOf": [ - {"$ref": "#/definitions/list_of_strings"}, - { - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "oneOf": [ - { - "type": "object", - "properties": { - "aliases": {"$ref": "#/definitions/list_of_strings"}, - "ipv4_address": {"type": "string"}, - "ipv6_address": {"type": "string"} - }, - "additionalProperties": false - }, - {"type": "null"} - ] - } - }, - "additionalProperties": false - } - ] - }, - "pid": {"type": ["string", "null"]}, - - "ports": { - "type": "array", - "items": { - "oneOf": [ - {"type": "number", "format": "ports"}, - {"type": "string", "format": "ports"}, - { - "type": "object", - "properties": { - "mode": {"type": "string"}, - "target": {"type": "integer"}, - "published": {"type": "integer"}, - "protocol": {"type": "string"} - }, - "additionalProperties": false - } - ] - }, - "uniqueItems": true - }, - - "privileged": {"type": "boolean"}, - "read_only": {"type": "boolean"}, - "restart": {"type": "string"}, - "security_opt": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "shm_size": {"type": ["number", "string"]}, - "secrets": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "source": {"type": "string"}, - "target": {"type": "string"}, - "uid": {"type": "string"}, - "gid": {"type": "string"}, - "mode": {"type": "number"} - } - } - ] - } - }, - "sysctls": {"$ref": "#/definitions/list_or_dict"}, - "stdin_open": {"type": "boolean"}, - "stop_grace_period": {"type": "string", "format": "duration"}, - "stop_signal": {"type": "string"}, - "tmpfs": {"$ref": "#/definitions/string_or_list"}, - "tty": {"type": "boolean"}, - "ulimits": { - "type": "object", - "patternProperties": { - "^[a-z]+$": { - "oneOf": [ - {"type": "integer"}, - { - "type":"object", - "properties": { - "hard": {"type": "integer"}, - "soft": {"type": "integer"} - }, - "required": ["soft", "hard"], - "additionalProperties": false - } - ] - } - } - }, - "user": {"type": "string"}, - "userns_mode": {"type": "string"}, - "volumes": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "required": ["type"], - "properties": { - "type": {"type": "string"}, - "source": {"type": "string"}, - "target": {"type": "string"}, - "read_only": {"type": "boolean"}, - "consistency": {"type": "string"}, - "bind": { - "type": "object", - "properties": { - "propagation": {"type": "string"} - } - }, - "volume": { - "type": "object", - "properties": { - "nocopy": {"type": "boolean"} - } - }, - "tmpfs": { - "type": "object", - "properties": { - "size": { - "type": "integer", - "minimum": 0 - } - } - } - }, - "additionalProperties": false - } - ], - "uniqueItems": true - } - }, - "working_dir": {"type": "string"} - }, - "patternProperties": {"^x-": {}}, - "additionalProperties": false - }, - - "healthcheck": { - "id": "#/definitions/healthcheck", - "type": "object", - "additionalProperties": false, - "properties": { - "disable": {"type": "boolean"}, - "interval": {"type": "string", "format": "duration"}, - "retries": {"type": "number"}, - "test": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "timeout": {"type": "string", "format": "duration"}, - "start_period": {"type": "string", "format": "duration"} - } - }, - "deployment": { - "id": "#/definitions/deployment", - "type": ["object", "null"], - "properties": { - "mode": {"type": "string"}, - "endpoint_mode": {"type": "string"}, - "replicas": {"type": "integer"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "rollback_config": { - "type": "object", - "properties": { - "parallelism": {"type": "integer"}, - "delay": {"type": "string", "format": "duration"}, - "failure_action": {"type": "string"}, - "monitor": {"type": "string", "format": "duration"}, - "max_failure_ratio": {"type": "number"}, - "order": {"type": "string", "enum": [ - "start-first", "stop-first" - ]} - }, - "additionalProperties": false - }, - "update_config": { - "type": "object", - "properties": { - "parallelism": {"type": "integer"}, - "delay": {"type": "string", "format": "duration"}, - "failure_action": {"type": "string"}, - "monitor": {"type": "string", "format": "duration"}, - "max_failure_ratio": {"type": "number"}, - "order": {"type": "string", "enum": [ - "start-first", "stop-first" - ]} - }, - "additionalProperties": false - }, - "resources": { - "type": "object", - "properties": { - "limits": { - "type": "object", - "properties": { - "cpus": {"type": "string"}, - "memory": {"type": "string"}, - "pids": {"type": "integer"} - }, - "additionalProperties": false - }, - "reservations": { - "type": "object", - "properties": { - "cpus": {"type": "string"}, - "memory": {"type": "string"}, - "generic_resources": {"$ref": "#/definitions/generic_resources"} - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - "restart_policy": { - "type": "object", - "properties": { - "condition": {"type": "string"}, - "delay": {"type": "string", "format": "duration"}, - "max_attempts": {"type": "integer"}, - "window": {"type": "string", "format": "duration"} - }, - "additionalProperties": false - }, - "placement": { - "type": "object", - "properties": { - "constraints": {"type": "array", "items": {"type": "string"}}, - "preferences": { - "type": "array", - "items": { - "type": "object", - "properties": { - "spread": {"type": "string"} - }, - "additionalProperties": false - } - }, - "max_replicas_per_node": {"type": "integer"} - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - - "generic_resources": { - "id": "#/definitions/generic_resources", - "type": "array", - "items": { - "type": "object", - "properties": { - "discrete_resource_spec": { - "type": "object", - "properties": { - "kind": {"type": "string"}, - "value": {"type": "number"} - }, - "additionalProperties": false - } - }, - "additionalProperties": false - } - }, - - "network": { - "id": "#/definitions/network", - "type": ["object", "null"], - "properties": { - "name": {"type": "string"}, - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "ipam": { - "type": "object", - "properties": { - "driver": {"type": "string"}, - "config": { - "type": "array", - "items": { - "type": "object", - "properties": { - "subnet": {"type": "string"} - }, - "additionalProperties": false - } - } - }, - "additionalProperties": false - }, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - }, - "additionalProperties": false - }, - "internal": {"type": "boolean"}, - "attachable": {"type": "boolean"}, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "patternProperties": {"^x-": {}}, - "additionalProperties": false - }, - - "volume": { - "id": "#/definitions/volume", - "type": ["object", "null"], - "properties": { - "name": {"type": "string"}, - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - }, - "additionalProperties": false - }, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "x-cluster-spec": { - "type": "object", - "properties": { - "group": {"type": "string"}, - "access_mode": { - "type": "object", - "properties": { - "scope": {"type": "string"}, - "sharing": {"type": "string"}, - "block_volume": {"type": "object"}, - "mount_volume": { - "type": "object", - "properties": { - "fs_type": {"type": "string"}, - "mount_flags": {"type": "array", "items": {"type": "string"}} - } - } - } - }, - "accessibility_requirements": { - "type": "object", - "properties": { - "requisite": { - "type": "array", - "items": { - "type": "object", - "properties": { - "segments": {"$ref": "#/definitions/list_or_dict"} - } - } - }, - "preferred": { - "type": "array", - "items": { - "type": "object", - "properties": { - "segments": {"$ref": "#/definitions/list_or_dict"} - } - } - } - } - }, - "capacity_range": { - "type": "object", - "properties": { - "required_bytes": {"type": "string"}, - "limit_bytes": {"type": "string"} - } - }, - "availability": {"type": "string"} - } - } - }, - "patternProperties": {"^x-": {}}, - "additionalProperties": false - }, - - "secret": { - "id": "#/definitions/secret", - "type": "object", - "properties": { - "name": {"type": "string"}, - "file": {"type": "string"}, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - } - }, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "template_driver": {"type": "string"} - }, - "patternProperties": {"^x-": {}}, - "additionalProperties": false - }, - - "config": { - "id": "#/definitions/config", - "type": "object", - "properties": { - "name": {"type": "string"}, - "file": {"type": "string"}, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - } - }, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "template_driver": {"type": "string"} - }, - "patternProperties": {"^x-": {}}, - "additionalProperties": false - }, - - "string_or_list": { - "oneOf": [ - {"type": "string"}, - {"$ref": "#/definitions/list_of_strings"} - ] - }, - - "list_of_strings": { - "type": "array", - "items": {"type": "string"}, - "uniqueItems": true - }, - - "list_or_dict": { - "oneOf": [ - { - "type": "object", - "patternProperties": { - ".+": { - "type": ["string", "number", "null"] - } - }, - "additionalProperties": false - }, - {"type": "array", "items": {"type": "string"}, "uniqueItems": true} - ] - }, - - "constraints": { - "service": { - "id": "#/definitions/constraints/service", - "anyOf": [ - {"required": ["build"]}, - {"required": ["image"]} - ], - "properties": { - "build": { - "required": ["context"] - } - } - } - } - } -} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.2.json b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.2.json deleted file mode 100644 index 6e0e0e747..000000000 --- a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.2.json +++ /dev/null @@ -1,476 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "id": "config_schema_v3.2.json", - "type": "object", - "required": ["version"], - - "properties": { - "version": { - "type": "string" - }, - - "services": { - "id": "#/properties/services", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/service" - } - }, - "additionalProperties": false - }, - - "networks": { - "id": "#/properties/networks", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/network" - } - } - }, - - "volumes": { - "id": "#/properties/volumes", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/volume" - } - }, - "additionalProperties": false - }, - - "secrets": { - "id": "#/properties/secrets", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/secret" - } - }, - "additionalProperties": false - } - }, - - "additionalProperties": false, - - "definitions": { - - "service": { - "id": "#/definitions/service", - "type": "object", - - "properties": { - "deploy": {"$ref": "#/definitions/deployment"}, - "build": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "context": {"type": "string"}, - "dockerfile": {"type": "string"}, - "args": {"$ref": "#/definitions/list_or_dict"}, - "cache_from": {"$ref": "#/definitions/list_of_strings"} - }, - "additionalProperties": false - } - ] - }, - "cap_add": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "cap_drop": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "cgroup_parent": {"type": "string"}, - "command": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "container_name": {"type": "string"}, - "depends_on": {"$ref": "#/definitions/list_of_strings"}, - "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "dns": {"$ref": "#/definitions/string_or_list"}, - "dns_search": {"$ref": "#/definitions/string_or_list"}, - "domainname": {"type": "string"}, - "entrypoint": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "env_file": {"$ref": "#/definitions/string_or_list"}, - "environment": {"$ref": "#/definitions/list_or_dict"}, - - "expose": { - "type": "array", - "items": { - "type": ["string", "number"], - "format": "expose" - }, - "uniqueItems": true - }, - - "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, - "healthcheck": {"$ref": "#/definitions/healthcheck"}, - "hostname": {"type": "string"}, - "image": {"type": "string"}, - "ipc": {"type": "string"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - - "logging": { - "type": "object", - - "properties": { - "driver": {"type": "string"}, - "options": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number", "null"]} - } - } - }, - "additionalProperties": false - }, - - "mac_address": {"type": "string"}, - "network_mode": {"type": "string"}, - - "networks": { - "oneOf": [ - {"$ref": "#/definitions/list_of_strings"}, - { - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "oneOf": [ - { - "type": "object", - "properties": { - "aliases": {"$ref": "#/definitions/list_of_strings"}, - "ipv4_address": {"type": "string"}, - "ipv6_address": {"type": "string"} - }, - "additionalProperties": false - }, - {"type": "null"} - ] - } - }, - "additionalProperties": false - } - ] - }, - "pid": {"type": ["string", "null"]}, - - "ports": { - "type": "array", - "items": { - "oneOf": [ - {"type": "number", "format": "ports"}, - {"type": "string", "format": "ports"}, - { - "type": "object", - "properties": { - "mode": {"type": "string"}, - "target": {"type": "integer"}, - "published": {"type": "integer"}, - "protocol": {"type": "string"} - }, - "additionalProperties": false - } - ] - }, - "uniqueItems": true - }, - - "privileged": {"type": "boolean"}, - "read_only": {"type": "boolean"}, - "restart": {"type": "string"}, - "security_opt": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "shm_size": {"type": ["number", "string"]}, - "secrets": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "source": {"type": "string"}, - "target": {"type": "string"}, - "uid": {"type": "string"}, - "gid": {"type": "string"}, - "mode": {"type": "number"} - } - } - ] - } - }, - "sysctls": {"$ref": "#/definitions/list_or_dict"}, - "stdin_open": {"type": "boolean"}, - "stop_grace_period": {"type": "string", "format": "duration"}, - "stop_signal": {"type": "string"}, - "tmpfs": {"$ref": "#/definitions/string_or_list"}, - "tty": {"type": "boolean"}, - "ulimits": { - "type": "object", - "patternProperties": { - "^[a-z]+$": { - "oneOf": [ - {"type": "integer"}, - { - "type":"object", - "properties": { - "hard": {"type": "integer"}, - "soft": {"type": "integer"} - }, - "required": ["soft", "hard"], - "additionalProperties": false - } - ] - } - } - }, - "user": {"type": "string"}, - "userns_mode": {"type": "string"}, - "volumes": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "required": ["type"], - "properties": { - "type": {"type": "string"}, - "source": {"type": "string"}, - "target": {"type": "string"}, - "read_only": {"type": "boolean"}, - "consistency": {"type": "string"}, - "bind": { - "type": "object", - "properties": { - "propagation": {"type": "string"} - } - }, - "volume": { - "type": "object", - "properties": { - "nocopy": {"type": "boolean"} - } - } - }, - "additionalProperties": false - } - ], - "uniqueItems": true - } - }, - "working_dir": {"type": "string"} - }, - "additionalProperties": false - }, - - "healthcheck": { - "id": "#/definitions/healthcheck", - "type": "object", - "additionalProperties": false, - "properties": { - "disable": {"type": "boolean"}, - "interval": {"type": "string"}, - "retries": {"type": "number"}, - "test": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "timeout": {"type": "string"} - } - }, - "deployment": { - "id": "#/definitions/deployment", - "type": ["object", "null"], - "properties": { - "mode": {"type": "string"}, - "endpoint_mode": {"type": "string"}, - "replicas": {"type": "integer"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "update_config": { - "type": "object", - "properties": { - "parallelism": {"type": "integer"}, - "delay": {"type": "string", "format": "duration"}, - "failure_action": {"type": "string"}, - "monitor": {"type": "string", "format": "duration"}, - "max_failure_ratio": {"type": "number"} - }, - "additionalProperties": false - }, - "resources": { - "type": "object", - "properties": { - "limits": {"$ref": "#/definitions/resource"}, - "reservations": {"$ref": "#/definitions/resource"} - }, - "additionalProperties": false - }, - "restart_policy": { - "type": "object", - "properties": { - "condition": {"type": "string"}, - "delay": {"type": "string", "format": "duration"}, - "max_attempts": {"type": "integer"}, - "window": {"type": "string", "format": "duration"} - }, - "additionalProperties": false - }, - "placement": { - "type": "object", - "properties": { - "constraints": {"type": "array", "items": {"type": "string"}} - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - - "resource": { - "id": "#/definitions/resource", - "type": "object", - "properties": { - "cpus": {"type": "string"}, - "memory": {"type": "string"} - }, - "additionalProperties": false - }, - - "network": { - "id": "#/definitions/network", - "type": ["object", "null"], - "properties": { - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "ipam": { - "type": "object", - "properties": { - "driver": {"type": "string"}, - "config": { - "type": "array", - "items": { - "type": "object", - "properties": { - "subnet": {"type": "string"} - }, - "additionalProperties": false - } - } - }, - "additionalProperties": false - }, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - }, - "additionalProperties": false - }, - "internal": {"type": "boolean"}, - "attachable": {"type": "boolean"}, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - }, - - "volume": { - "id": "#/definitions/volume", - "type": ["object", "null"], - "properties": { - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - }, - "additionalProperties": false - }, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - }, - - "secret": { - "id": "#/definitions/secret", - "type": "object", - "properties": { - "file": {"type": "string"}, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - } - }, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - }, - - "string_or_list": { - "oneOf": [ - {"type": "string"}, - {"$ref": "#/definitions/list_of_strings"} - ] - }, - - "list_of_strings": { - "type": "array", - "items": {"type": "string"}, - "uniqueItems": true - }, - - "list_or_dict": { - "oneOf": [ - { - "type": "object", - "patternProperties": { - ".+": { - "type": ["string", "number", "null"] - } - }, - "additionalProperties": false - }, - {"type": "array", "items": {"type": "string"}, "uniqueItems": true} - ] - }, - - "constraints": { - "service": { - "id": "#/definitions/constraints/service", - "anyOf": [ - {"required": ["build"]}, - {"required": ["image"]} - ], - "properties": { - "build": { - "required": ["context"] - } - } - } - } - } -} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.3.json b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.3.json deleted file mode 100644 index 13a58044d..000000000 --- a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.3.json +++ /dev/null @@ -1,540 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "id": "config_schema_v3.3.json", - "type": "object", - "required": ["version"], - - "properties": { - "version": { - "type": "string" - }, - - "services": { - "id": "#/properties/services", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/service" - } - }, - "additionalProperties": false - }, - - "networks": { - "id": "#/properties/networks", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/network" - } - } - }, - - "volumes": { - "id": "#/properties/volumes", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/volume" - } - }, - "additionalProperties": false - }, - - "secrets": { - "id": "#/properties/secrets", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/secret" - } - }, - "additionalProperties": false - }, - - "configs": { - "id": "#/properties/configs", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/config" - } - }, - "additionalProperties": false - } - }, - - "additionalProperties": false, - - "definitions": { - - "service": { - "id": "#/definitions/service", - "type": "object", - - "properties": { - "deploy": {"$ref": "#/definitions/deployment"}, - "build": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "context": {"type": "string"}, - "dockerfile": {"type": "string"}, - "args": {"$ref": "#/definitions/list_or_dict"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "cache_from": {"$ref": "#/definitions/list_of_strings"} - }, - "additionalProperties": false - } - ] - }, - "cap_add": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "cap_drop": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "cgroup_parent": {"type": "string"}, - "command": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "configs": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "source": {"type": "string"}, - "target": {"type": "string"}, - "uid": {"type": "string"}, - "gid": {"type": "string"}, - "mode": {"type": "number"} - } - } - ] - } - }, - "container_name": {"type": "string"}, - "credential_spec": { - "type": "object", - "properties": { - "file": {"type": "string"}, - "registry": {"type": "string"} - }, - "additionalProperties": false - }, - "depends_on": {"$ref": "#/definitions/list_of_strings"}, - "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "dns": {"$ref": "#/definitions/string_or_list"}, - "dns_search": {"$ref": "#/definitions/string_or_list"}, - "domainname": {"type": "string"}, - "entrypoint": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "env_file": {"$ref": "#/definitions/string_or_list"}, - "environment": {"$ref": "#/definitions/list_or_dict"}, - - "expose": { - "type": "array", - "items": { - "type": ["string", "number"], - "format": "expose" - }, - "uniqueItems": true - }, - - "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, - "healthcheck": {"$ref": "#/definitions/healthcheck"}, - "hostname": {"type": "string"}, - "image": {"type": "string"}, - "ipc": {"type": "string"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - - "logging": { - "type": "object", - - "properties": { - "driver": {"type": "string"}, - "options": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number", "null"]} - } - } - }, - "additionalProperties": false - }, - - "mac_address": {"type": "string"}, - "network_mode": {"type": "string"}, - - "networks": { - "oneOf": [ - {"$ref": "#/definitions/list_of_strings"}, - { - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "oneOf": [ - { - "type": "object", - "properties": { - "aliases": {"$ref": "#/definitions/list_of_strings"}, - "ipv4_address": {"type": "string"}, - "ipv6_address": {"type": "string"} - }, - "additionalProperties": false - }, - {"type": "null"} - ] - } - }, - "additionalProperties": false - } - ] - }, - "pid": {"type": ["string", "null"]}, - - "ports": { - "type": "array", - "items": { - "oneOf": [ - {"type": "number", "format": "ports"}, - {"type": "string", "format": "ports"}, - { - "type": "object", - "properties": { - "mode": {"type": "string"}, - "target": {"type": "integer"}, - "published": {"type": "integer"}, - "protocol": {"type": "string"} - }, - "additionalProperties": false - } - ] - }, - "uniqueItems": true - }, - - "privileged": {"type": "boolean"}, - "read_only": {"type": "boolean"}, - "restart": {"type": "string"}, - "security_opt": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "shm_size": {"type": ["number", "string"]}, - "secrets": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "source": {"type": "string"}, - "target": {"type": "string"}, - "uid": {"type": "string"}, - "gid": {"type": "string"}, - "mode": {"type": "number"} - } - } - ] - } - }, - "sysctls": {"$ref": "#/definitions/list_or_dict"}, - "stdin_open": {"type": "boolean"}, - "stop_grace_period": {"type": "string", "format": "duration"}, - "stop_signal": {"type": "string"}, - "tmpfs": {"$ref": "#/definitions/string_or_list"}, - "tty": {"type": "boolean"}, - "ulimits": { - "type": "object", - "patternProperties": { - "^[a-z]+$": { - "oneOf": [ - {"type": "integer"}, - { - "type":"object", - "properties": { - "hard": {"type": "integer"}, - "soft": {"type": "integer"} - }, - "required": ["soft", "hard"], - "additionalProperties": false - } - ] - } - } - }, - "user": {"type": "string"}, - "userns_mode": {"type": "string"}, - "volumes": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "required": ["type"], - "properties": { - "type": {"type": "string"}, - "source": {"type": "string"}, - "target": {"type": "string"}, - "read_only": {"type": "boolean"}, - "consistency": {"type": "string"}, - "bind": { - "type": "object", - "properties": { - "propagation": {"type": "string"} - } - }, - "volume": { - "type": "object", - "properties": { - "nocopy": {"type": "boolean"} - } - } - }, - "additionalProperties": false - } - ], - "uniqueItems": true - } - }, - "working_dir": {"type": "string"} - }, - "additionalProperties": false - }, - - "healthcheck": { - "id": "#/definitions/healthcheck", - "type": "object", - "additionalProperties": false, - "properties": { - "disable": {"type": "boolean"}, - "interval": {"type": "string"}, - "retries": {"type": "number"}, - "test": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "timeout": {"type": "string"} - } - }, - "deployment": { - "id": "#/definitions/deployment", - "type": ["object", "null"], - "properties": { - "mode": {"type": "string"}, - "endpoint_mode": {"type": "string"}, - "replicas": {"type": "integer"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "update_config": { - "type": "object", - "properties": { - "parallelism": {"type": "integer"}, - "delay": {"type": "string", "format": "duration"}, - "failure_action": {"type": "string"}, - "monitor": {"type": "string", "format": "duration"}, - "max_failure_ratio": {"type": "number"} - }, - "additionalProperties": false - }, - "resources": { - "type": "object", - "properties": { - "limits": {"$ref": "#/definitions/resource"}, - "reservations": {"$ref": "#/definitions/resource"} - }, - "additionalProperties": false - }, - "restart_policy": { - "type": "object", - "properties": { - "condition": {"type": "string"}, - "delay": {"type": "string", "format": "duration"}, - "max_attempts": {"type": "integer"}, - "window": {"type": "string", "format": "duration"} - }, - "additionalProperties": false - }, - "placement": { - "type": "object", - "properties": { - "constraints": {"type": "array", "items": {"type": "string"}}, - "preferences": { - "type": "array", - "items": { - "type": "object", - "properties": { - "spread": {"type": "string"} - }, - "additionalProperties": false - } - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - - "resource": { - "id": "#/definitions/resource", - "type": "object", - "properties": { - "cpus": {"type": "string"}, - "memory": {"type": "string"} - }, - "additionalProperties": false - }, - - "network": { - "id": "#/definitions/network", - "type": ["object", "null"], - "properties": { - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "ipam": { - "type": "object", - "properties": { - "driver": {"type": "string"}, - "config": { - "type": "array", - "items": { - "type": "object", - "properties": { - "subnet": {"type": "string"} - }, - "additionalProperties": false - } - } - }, - "additionalProperties": false - }, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - }, - "additionalProperties": false - }, - "internal": {"type": "boolean"}, - "attachable": {"type": "boolean"}, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - }, - - "volume": { - "id": "#/definitions/volume", - "type": ["object", "null"], - "properties": { - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - }, - "additionalProperties": false - }, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - }, - - "secret": { - "id": "#/definitions/secret", - "type": "object", - "properties": { - "file": {"type": "string"}, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - } - }, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - }, - - "config": { - "id": "#/definitions/config", - "type": "object", - "properties": { - "file": {"type": "string"}, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - } - }, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - }, - - "string_or_list": { - "oneOf": [ - {"type": "string"}, - {"$ref": "#/definitions/list_of_strings"} - ] - }, - - "list_of_strings": { - "type": "array", - "items": {"type": "string"}, - "uniqueItems": true - }, - - "list_or_dict": { - "oneOf": [ - { - "type": "object", - "patternProperties": { - ".+": { - "type": ["string", "number", "null"] - } - }, - "additionalProperties": false - }, - {"type": "array", "items": {"type": "string"}, "uniqueItems": true} - ] - }, - - "constraints": { - "service": { - "id": "#/definitions/constraints/service", - "anyOf": [ - {"required": ["build"]}, - {"required": ["image"]} - ], - "properties": { - "build": { - "required": ["context"] - } - } - } - } - } -} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.4.json b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.4.json deleted file mode 100644 index 8660c98da..000000000 --- a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.4.json +++ /dev/null @@ -1,548 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "id": "config_schema_v3.4.json", - "type": "object", - "required": ["version"], - - "properties": { - "version": { - "type": "string" - }, - - "services": { - "id": "#/properties/services", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/service" - } - }, - "additionalProperties": false - }, - - "networks": { - "id": "#/properties/networks", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/network" - } - } - }, - - "volumes": { - "id": "#/properties/volumes", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/volume" - } - }, - "additionalProperties": false - }, - - "secrets": { - "id": "#/properties/secrets", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/secret" - } - }, - "additionalProperties": false - }, - - "configs": { - "id": "#/properties/configs", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/config" - } - }, - "additionalProperties": false - } - }, - - "patternProperties": {"^x-": {}}, - "additionalProperties": false, - - "definitions": { - - "service": { - "id": "#/definitions/service", - "type": "object", - - "properties": { - "deploy": {"$ref": "#/definitions/deployment"}, - "build": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "context": {"type": "string"}, - "dockerfile": {"type": "string"}, - "args": {"$ref": "#/definitions/list_or_dict"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "cache_from": {"$ref": "#/definitions/list_of_strings"}, - "network": {"type": "string"}, - "target": {"type": "string"} - }, - "additionalProperties": false - } - ] - }, - "cap_add": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "cap_drop": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "cgroup_parent": {"type": "string"}, - "command": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "configs": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "source": {"type": "string"}, - "target": {"type": "string"}, - "uid": {"type": "string"}, - "gid": {"type": "string"}, - "mode": {"type": "number"} - } - } - ] - } - }, - "container_name": {"type": "string"}, - "credential_spec": { - "type": "object", - "properties": { - "file": {"type": "string"}, - "registry": {"type": "string"} - }, - "additionalProperties": false - }, - "depends_on": {"$ref": "#/definitions/list_of_strings"}, - "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "dns": {"$ref": "#/definitions/string_or_list"}, - "dns_search": {"$ref": "#/definitions/string_or_list"}, - "domainname": {"type": "string"}, - "entrypoint": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "env_file": {"$ref": "#/definitions/string_or_list"}, - "environment": {"$ref": "#/definitions/list_or_dict"}, - - "expose": { - "type": "array", - "items": { - "type": ["string", "number"], - "format": "expose" - }, - "uniqueItems": true - }, - - "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, - "healthcheck": {"$ref": "#/definitions/healthcheck"}, - "hostname": {"type": "string"}, - "image": {"type": "string"}, - "ipc": {"type": "string"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - - "logging": { - "type": "object", - - "properties": { - "driver": {"type": "string"}, - "options": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number", "null"]} - } - } - }, - "additionalProperties": false - }, - - "mac_address": {"type": "string"}, - "network_mode": {"type": "string"}, - - "networks": { - "oneOf": [ - {"$ref": "#/definitions/list_of_strings"}, - { - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "oneOf": [ - { - "type": "object", - "properties": { - "aliases": {"$ref": "#/definitions/list_of_strings"}, - "ipv4_address": {"type": "string"}, - "ipv6_address": {"type": "string"} - }, - "additionalProperties": false - }, - {"type": "null"} - ] - } - }, - "additionalProperties": false - } - ] - }, - "pid": {"type": ["string", "null"]}, - - "ports": { - "type": "array", - "items": { - "oneOf": [ - {"type": "number", "format": "ports"}, - {"type": "string", "format": "ports"}, - { - "type": "object", - "properties": { - "mode": {"type": "string"}, - "target": {"type": "integer"}, - "published": {"type": "integer"}, - "protocol": {"type": "string"} - }, - "additionalProperties": false - } - ] - }, - "uniqueItems": true - }, - - "privileged": {"type": "boolean"}, - "read_only": {"type": "boolean"}, - "restart": {"type": "string"}, - "security_opt": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "shm_size": {"type": ["number", "string"]}, - "secrets": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "source": {"type": "string"}, - "target": {"type": "string"}, - "uid": {"type": "string"}, - "gid": {"type": "string"}, - "mode": {"type": "number"} - } - } - ] - } - }, - "sysctls": {"$ref": "#/definitions/list_or_dict"}, - "stdin_open": {"type": "boolean"}, - "stop_grace_period": {"type": "string", "format": "duration"}, - "stop_signal": {"type": "string"}, - "tmpfs": {"$ref": "#/definitions/string_or_list"}, - "tty": {"type": "boolean"}, - "ulimits": { - "type": "object", - "patternProperties": { - "^[a-z]+$": { - "oneOf": [ - {"type": "integer"}, - { - "type":"object", - "properties": { - "hard": {"type": "integer"}, - "soft": {"type": "integer"} - }, - "required": ["soft", "hard"], - "additionalProperties": false - } - ] - } - } - }, - "user": {"type": "string"}, - "userns_mode": {"type": "string"}, - "volumes": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "required": ["type"], - "properties": { - "type": {"type": "string"}, - "source": {"type": "string"}, - "target": {"type": "string"}, - "read_only": {"type": "boolean"}, - "consistency": {"type": "string"}, - "bind": { - "type": "object", - "properties": { - "propagation": {"type": "string"} - } - }, - "volume": { - "type": "object", - "properties": { - "nocopy": {"type": "boolean"} - } - } - }, - "additionalProperties": false - } - ], - "uniqueItems": true - } - }, - "working_dir": {"type": "string"} - }, - "additionalProperties": false - }, - - "healthcheck": { - "id": "#/definitions/healthcheck", - "type": "object", - "additionalProperties": false, - "properties": { - "disable": {"type": "boolean"}, - "interval": {"type": "string", "format": "duration"}, - "retries": {"type": "number"}, - "test": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "timeout": {"type": "string", "format": "duration"}, - "start_period": {"type": "string", "format": "duration"} - } - }, - "deployment": { - "id": "#/definitions/deployment", - "type": ["object", "null"], - "properties": { - "mode": {"type": "string"}, - "endpoint_mode": {"type": "string"}, - "replicas": {"type": "integer"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "update_config": { - "type": "object", - "properties": { - "parallelism": {"type": "integer"}, - "delay": {"type": "string", "format": "duration"}, - "failure_action": {"type": "string"}, - "monitor": {"type": "string", "format": "duration"}, - "max_failure_ratio": {"type": "number"}, - "order": {"type": "string", "enum": [ - "start-first", "stop-first" - ]} - }, - "additionalProperties": false - }, - "resources": { - "type": "object", - "properties": { - "limits": {"$ref": "#/definitions/resource"}, - "reservations": {"$ref": "#/definitions/resource"} - }, - "additionalProperties": false - }, - "restart_policy": { - "type": "object", - "properties": { - "condition": {"type": "string"}, - "delay": {"type": "string", "format": "duration"}, - "max_attempts": {"type": "integer"}, - "window": {"type": "string", "format": "duration"} - }, - "additionalProperties": false - }, - "placement": { - "type": "object", - "properties": { - "constraints": {"type": "array", "items": {"type": "string"}}, - "preferences": { - "type": "array", - "items": { - "type": "object", - "properties": { - "spread": {"type": "string"} - }, - "additionalProperties": false - } - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - - "resource": { - "id": "#/definitions/resource", - "type": "object", - "properties": { - "cpus": {"type": "string"}, - "memory": {"type": "string"} - }, - "additionalProperties": false - }, - - "network": { - "id": "#/definitions/network", - "type": ["object", "null"], - "properties": { - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "ipam": { - "type": "object", - "properties": { - "driver": {"type": "string"}, - "config": { - "type": "array", - "items": { - "type": "object", - "properties": { - "subnet": {"type": "string"} - }, - "additionalProperties": false - } - } - }, - "additionalProperties": false - }, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - }, - "additionalProperties": false - }, - "internal": {"type": "boolean"}, - "attachable": {"type": "boolean"}, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - }, - - "volume": { - "id": "#/definitions/volume", - "type": ["object", "null"], - "properties": { - "name": {"type": "string"}, - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - }, - "additionalProperties": false - }, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - }, - - "secret": { - "id": "#/definitions/secret", - "type": "object", - "properties": { - "file": {"type": "string"}, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - } - }, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - }, - - "config": { - "id": "#/definitions/config", - "type": "object", - "properties": { - "file": {"type": "string"}, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - } - }, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - }, - - "string_or_list": { - "oneOf": [ - {"type": "string"}, - {"$ref": "#/definitions/list_of_strings"} - ] - }, - - "list_of_strings": { - "type": "array", - "items": {"type": "string"}, - "uniqueItems": true - }, - - "list_or_dict": { - "oneOf": [ - { - "type": "object", - "patternProperties": { - ".+": { - "type": ["string", "number", "null"] - } - }, - "additionalProperties": false - }, - {"type": "array", "items": {"type": "string"}, "uniqueItems": true} - ] - }, - - "constraints": { - "service": { - "id": "#/definitions/constraints/service", - "anyOf": [ - {"required": ["build"]}, - {"required": ["image"]} - ], - "properties": { - "build": { - "required": ["context"] - } - } - } - } - } -} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.5.json b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.5.json deleted file mode 100644 index bf9c56c02..000000000 --- a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.5.json +++ /dev/null @@ -1,577 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "id": "config_schema_v3.5.json", - "type": "object", - "required": ["version"], - - "properties": { - "version": { - "type": "string" - }, - - "services": { - "id": "#/properties/services", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/service" - } - }, - "additionalProperties": false - }, - - "networks": { - "id": "#/properties/networks", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/network" - } - } - }, - - "volumes": { - "id": "#/properties/volumes", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/volume" - } - }, - "additionalProperties": false - }, - - "secrets": { - "id": "#/properties/secrets", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/secret" - } - }, - "additionalProperties": false - }, - - "configs": { - "id": "#/properties/configs", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/config" - } - }, - "additionalProperties": false - } - }, - - "patternProperties": {"^x-": {}}, - "additionalProperties": false, - - "definitions": { - - "service": { - "id": "#/definitions/service", - "type": "object", - - "properties": { - "deploy": {"$ref": "#/definitions/deployment"}, - "build": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "context": {"type": "string"}, - "dockerfile": {"type": "string"}, - "args": {"$ref": "#/definitions/list_or_dict"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "cache_from": {"$ref": "#/definitions/list_of_strings"}, - "network": {"type": "string"}, - "target": {"type": "string"}, - "shm_size": {"type": ["integer", "string"]} - }, - "additionalProperties": false - } - ] - }, - "cap_add": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "cap_drop": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "cgroup_parent": {"type": "string"}, - "command": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "configs": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "source": {"type": "string"}, - "target": {"type": "string"}, - "uid": {"type": "string"}, - "gid": {"type": "string"}, - "mode": {"type": "number"} - } - } - ] - } - }, - "container_name": {"type": "string"}, - "credential_spec": { - "type": "object", - "properties": { - "file": {"type": "string"}, - "registry": {"type": "string"} - }, - "additionalProperties": false - }, - "depends_on": {"$ref": "#/definitions/list_of_strings"}, - "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "dns": {"$ref": "#/definitions/string_or_list"}, - "dns_search": {"$ref": "#/definitions/string_or_list"}, - "domainname": {"type": "string"}, - "entrypoint": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "env_file": {"$ref": "#/definitions/string_or_list"}, - "environment": {"$ref": "#/definitions/list_or_dict"}, - - "expose": { - "type": "array", - "items": { - "type": ["string", "number"], - "format": "expose" - }, - "uniqueItems": true - }, - - "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, - "healthcheck": {"$ref": "#/definitions/healthcheck"}, - "hostname": {"type": "string"}, - "image": {"type": "string"}, - "ipc": {"type": "string"}, - "isolation": {"type": "string"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - - "logging": { - "type": "object", - - "properties": { - "driver": {"type": "string"}, - "options": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number", "null"]} - } - } - }, - "additionalProperties": false - }, - - "mac_address": {"type": "string"}, - "network_mode": {"type": "string"}, - - "networks": { - "oneOf": [ - {"$ref": "#/definitions/list_of_strings"}, - { - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "oneOf": [ - { - "type": "object", - "properties": { - "aliases": {"$ref": "#/definitions/list_of_strings"}, - "ipv4_address": {"type": "string"}, - "ipv6_address": {"type": "string"} - }, - "additionalProperties": false - }, - {"type": "null"} - ] - } - }, - "additionalProperties": false - } - ] - }, - "pid": {"type": ["string", "null"]}, - - "ports": { - "type": "array", - "items": { - "oneOf": [ - {"type": "number", "format": "ports"}, - {"type": "string", "format": "ports"}, - { - "type": "object", - "properties": { - "mode": {"type": "string"}, - "target": {"type": "integer"}, - "published": {"type": "integer"}, - "protocol": {"type": "string"} - }, - "additionalProperties": false - } - ] - }, - "uniqueItems": true - }, - - "privileged": {"type": "boolean"}, - "read_only": {"type": "boolean"}, - "restart": {"type": "string"}, - "security_opt": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "shm_size": {"type": ["number", "string"]}, - "secrets": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "source": {"type": "string"}, - "target": {"type": "string"}, - "uid": {"type": "string"}, - "gid": {"type": "string"}, - "mode": {"type": "number"} - } - } - ] - } - }, - "sysctls": {"$ref": "#/definitions/list_or_dict"}, - "stdin_open": {"type": "boolean"}, - "stop_grace_period": {"type": "string", "format": "duration"}, - "stop_signal": {"type": "string"}, - "tmpfs": {"$ref": "#/definitions/string_or_list"}, - "tty": {"type": "boolean"}, - "ulimits": { - "type": "object", - "patternProperties": { - "^[a-z]+$": { - "oneOf": [ - {"type": "integer"}, - { - "type":"object", - "properties": { - "hard": {"type": "integer"}, - "soft": {"type": "integer"} - }, - "required": ["soft", "hard"], - "additionalProperties": false - } - ] - } - } - }, - "user": {"type": "string"}, - "userns_mode": {"type": "string"}, - "volumes": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "required": ["type"], - "properties": { - "type": {"type": "string"}, - "source": {"type": "string"}, - "target": {"type": "string"}, - "read_only": {"type": "boolean"}, - "consistency": {"type": "string"}, - "bind": { - "type": "object", - "properties": { - "propagation": {"type": "string"} - } - }, - "volume": { - "type": "object", - "properties": { - "nocopy": {"type": "boolean"} - } - } - }, - "additionalProperties": false - } - ], - "uniqueItems": true - } - }, - "working_dir": {"type": "string"} - }, - "additionalProperties": false - }, - - "healthcheck": { - "id": "#/definitions/healthcheck", - "type": "object", - "additionalProperties": false, - "properties": { - "disable": {"type": "boolean"}, - "interval": {"type": "string", "format": "duration"}, - "retries": {"type": "number"}, - "test": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "timeout": {"type": "string", "format": "duration"}, - "start_period": {"type": "string", "format": "duration"} - } - }, - "deployment": { - "id": "#/definitions/deployment", - "type": ["object", "null"], - "properties": { - "mode": {"type": "string"}, - "endpoint_mode": {"type": "string"}, - "replicas": {"type": "integer"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "update_config": { - "type": "object", - "properties": { - "parallelism": {"type": "integer"}, - "delay": {"type": "string", "format": "duration"}, - "failure_action": {"type": "string"}, - "monitor": {"type": "string", "format": "duration"}, - "max_failure_ratio": {"type": "number"}, - "order": {"type": "string", "enum": [ - "start-first", "stop-first" - ]} - }, - "additionalProperties": false - }, - "resources": { - "type": "object", - "properties": { - "limits": { - "type": "object", - "properties": { - "cpus": {"type": "string"}, - "memory": {"type": "string"} - }, - "additionalProperties": false - }, - "reservations": { - "type": "object", - "properties": { - "cpus": {"type": "string"}, - "memory": {"type": "string"}, - "generic_resources": {"$ref": "#/definitions/generic_resources"} - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - "restart_policy": { - "type": "object", - "properties": { - "condition": {"type": "string"}, - "delay": {"type": "string", "format": "duration"}, - "max_attempts": {"type": "integer"}, - "window": {"type": "string", "format": "duration"} - }, - "additionalProperties": false - }, - "placement": { - "type": "object", - "properties": { - "constraints": {"type": "array", "items": {"type": "string"}}, - "preferences": { - "type": "array", - "items": { - "type": "object", - "properties": { - "spread": {"type": "string"} - }, - "additionalProperties": false - } - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - - "generic_resources": { - "id": "#/definitions/generic_resources", - "type": "array", - "items": { - "type": "object", - "properties": { - "discrete_resource_spec": { - "type": "object", - "properties": { - "kind": {"type": "string"}, - "value": {"type": "number"} - }, - "additionalProperties": false - } - }, - "additionalProperties": false - } - }, - - "network": { - "id": "#/definitions/network", - "type": ["object", "null"], - "properties": { - "name": {"type": "string"}, - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "ipam": { - "type": "object", - "properties": { - "driver": {"type": "string"}, - "config": { - "type": "array", - "items": { - "type": "object", - "properties": { - "subnet": {"type": "string"} - }, - "additionalProperties": false - } - } - }, - "additionalProperties": false - }, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - }, - "additionalProperties": false - }, - "internal": {"type": "boolean"}, - "attachable": {"type": "boolean"}, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - }, - - "volume": { - "id": "#/definitions/volume", - "type": ["object", "null"], - "properties": { - "name": {"type": "string"}, - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - }, - "additionalProperties": false - }, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - }, - - "secret": { - "id": "#/definitions/secret", - "type": "object", - "properties": { - "name": {"type": "string"}, - "file": {"type": "string"}, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - } - }, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - }, - - "config": { - "id": "#/definitions/config", - "type": "object", - "properties": { - "name": {"type": "string"}, - "file": {"type": "string"}, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - } - }, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - }, - - "string_or_list": { - "oneOf": [ - {"type": "string"}, - {"$ref": "#/definitions/list_of_strings"} - ] - }, - - "list_of_strings": { - "type": "array", - "items": {"type": "string"}, - "uniqueItems": true - }, - - "list_or_dict": { - "oneOf": [ - { - "type": "object", - "patternProperties": { - ".+": { - "type": ["string", "number", "null"] - } - }, - "additionalProperties": false - }, - {"type": "array", "items": {"type": "string"}, "uniqueItems": true} - ] - }, - - "constraints": { - "service": { - "id": "#/definitions/constraints/service", - "anyOf": [ - {"required": ["build"]}, - {"required": ["image"]} - ], - "properties": { - "build": { - "required": ["context"] - } - } - } - } - } -} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.6.json b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.6.json deleted file mode 100644 index cd6a638ce..000000000 --- a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.6.json +++ /dev/null @@ -1,586 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "id": "config_schema_v3.6.json", - "type": "object", - "required": ["version"], - - "properties": { - "version": { - "type": "string" - }, - - "services": { - "id": "#/properties/services", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/service" - } - }, - "additionalProperties": false - }, - - "networks": { - "id": "#/properties/networks", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/network" - } - } - }, - - "volumes": { - "id": "#/properties/volumes", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/volume" - } - }, - "additionalProperties": false - }, - - "secrets": { - "id": "#/properties/secrets", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/secret" - } - }, - "additionalProperties": false - }, - - "configs": { - "id": "#/properties/configs", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/config" - } - }, - "additionalProperties": false - } - }, - - "patternProperties": {"^x-": {}}, - "additionalProperties": false, - - "definitions": { - - "service": { - "id": "#/definitions/service", - "type": "object", - - "properties": { - "deploy": {"$ref": "#/definitions/deployment"}, - "build": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "context": {"type": "string"}, - "dockerfile": {"type": "string"}, - "args": {"$ref": "#/definitions/list_or_dict"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "cache_from": {"$ref": "#/definitions/list_of_strings"}, - "network": {"type": "string"}, - "target": {"type": "string"}, - "shm_size": {"type": ["integer", "string"]} - }, - "additionalProperties": false - } - ] - }, - "cap_add": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "cap_drop": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "cgroup_parent": {"type": "string"}, - "command": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "configs": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "source": {"type": "string"}, - "target": {"type": "string"}, - "uid": {"type": "string"}, - "gid": {"type": "string"}, - "mode": {"type": "number"} - } - } - ] - } - }, - "container_name": {"type": "string"}, - "credential_spec": { - "type": "object", - "properties": { - "file": {"type": "string"}, - "registry": {"type": "string"} - }, - "additionalProperties": false - }, - "depends_on": {"$ref": "#/definitions/list_of_strings"}, - "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "dns": {"$ref": "#/definitions/string_or_list"}, - "dns_search": {"$ref": "#/definitions/string_or_list"}, - "domainname": {"type": "string"}, - "entrypoint": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "env_file": {"$ref": "#/definitions/string_or_list"}, - "environment": {"$ref": "#/definitions/list_or_dict"}, - - "expose": { - "type": "array", - "items": { - "type": ["string", "number"], - "format": "expose" - }, - "uniqueItems": true - }, - - "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, - "healthcheck": {"$ref": "#/definitions/healthcheck"}, - "hostname": {"type": "string"}, - "image": {"type": "string"}, - "ipc": {"type": "string"}, - "isolation": {"type": "string"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - - "logging": { - "type": "object", - - "properties": { - "driver": {"type": "string"}, - "options": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number", "null"]} - } - } - }, - "additionalProperties": false - }, - - "mac_address": {"type": "string"}, - "network_mode": {"type": "string"}, - - "networks": { - "oneOf": [ - {"$ref": "#/definitions/list_of_strings"}, - { - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "oneOf": [ - { - "type": "object", - "properties": { - "aliases": {"$ref": "#/definitions/list_of_strings"}, - "ipv4_address": {"type": "string"}, - "ipv6_address": {"type": "string"} - }, - "additionalProperties": false - }, - {"type": "null"} - ] - } - }, - "additionalProperties": false - } - ] - }, - "pid": {"type": ["string", "null"]}, - - "ports": { - "type": "array", - "items": { - "oneOf": [ - {"type": "number", "format": "ports"}, - {"type": "string", "format": "ports"}, - { - "type": "object", - "properties": { - "mode": {"type": "string"}, - "target": {"type": "integer"}, - "published": {"type": "integer"}, - "protocol": {"type": "string"} - }, - "additionalProperties": false - } - ] - }, - "uniqueItems": true - }, - - "privileged": {"type": "boolean"}, - "read_only": {"type": "boolean"}, - "restart": {"type": "string"}, - "security_opt": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "shm_size": {"type": ["number", "string"]}, - "secrets": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "source": {"type": "string"}, - "target": {"type": "string"}, - "uid": {"type": "string"}, - "gid": {"type": "string"}, - "mode": {"type": "number"} - } - } - ] - } - }, - "sysctls": {"$ref": "#/definitions/list_or_dict"}, - "stdin_open": {"type": "boolean"}, - "stop_grace_period": {"type": "string", "format": "duration"}, - "stop_signal": {"type": "string"}, - "tmpfs": {"$ref": "#/definitions/string_or_list"}, - "tty": {"type": "boolean"}, - "ulimits": { - "type": "object", - "patternProperties": { - "^[a-z]+$": { - "oneOf": [ - {"type": "integer"}, - { - "type":"object", - "properties": { - "hard": {"type": "integer"}, - "soft": {"type": "integer"} - }, - "required": ["soft", "hard"], - "additionalProperties": false - } - ] - } - } - }, - "user": {"type": "string"}, - "userns_mode": {"type": "string"}, - "volumes": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "required": ["type"], - "properties": { - "type": {"type": "string"}, - "source": {"type": "string"}, - "target": {"type": "string"}, - "read_only": {"type": "boolean"}, - "consistency": {"type": "string"}, - "bind": { - "type": "object", - "properties": { - "propagation": {"type": "string"} - } - }, - "volume": { - "type": "object", - "properties": { - "nocopy": {"type": "boolean"} - } - }, - "tmpfs": { - "type": "object", - "properties": { - "size": { - "type": "integer", - "minimum": 0 - } - } - } - }, - "additionalProperties": false - } - ], - "uniqueItems": true - } - }, - "working_dir": {"type": "string"} - }, - "additionalProperties": false - }, - - "healthcheck": { - "id": "#/definitions/healthcheck", - "type": "object", - "additionalProperties": false, - "properties": { - "disable": {"type": "boolean"}, - "interval": {"type": "string", "format": "duration"}, - "retries": {"type": "number"}, - "test": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "timeout": {"type": "string", "format": "duration"}, - "start_period": {"type": "string", "format": "duration"} - } - }, - "deployment": { - "id": "#/definitions/deployment", - "type": ["object", "null"], - "properties": { - "mode": {"type": "string"}, - "endpoint_mode": {"type": "string"}, - "replicas": {"type": "integer"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "update_config": { - "type": "object", - "properties": { - "parallelism": {"type": "integer"}, - "delay": {"type": "string", "format": "duration"}, - "failure_action": {"type": "string"}, - "monitor": {"type": "string", "format": "duration"}, - "max_failure_ratio": {"type": "number"}, - "order": {"type": "string", "enum": [ - "start-first", "stop-first" - ]} - }, - "additionalProperties": false - }, - "resources": { - "type": "object", - "properties": { - "limits": { - "type": "object", - "properties": { - "cpus": {"type": "string"}, - "memory": {"type": "string"} - }, - "additionalProperties": false - }, - "reservations": { - "type": "object", - "properties": { - "cpus": {"type": "string"}, - "memory": {"type": "string"}, - "generic_resources": {"$ref": "#/definitions/generic_resources"} - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - "restart_policy": { - "type": "object", - "properties": { - "condition": {"type": "string"}, - "delay": {"type": "string", "format": "duration"}, - "max_attempts": {"type": "integer"}, - "window": {"type": "string", "format": "duration"} - }, - "additionalProperties": false - }, - "placement": { - "type": "object", - "properties": { - "constraints": {"type": "array", "items": {"type": "string"}}, - "preferences": { - "type": "array", - "items": { - "type": "object", - "properties": { - "spread": {"type": "string"} - }, - "additionalProperties": false - } - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - - "generic_resources": { - "id": "#/definitions/generic_resources", - "type": "array", - "items": { - "type": "object", - "properties": { - "discrete_resource_spec": { - "type": "object", - "properties": { - "kind": {"type": "string"}, - "value": {"type": "number"} - }, - "additionalProperties": false - } - }, - "additionalProperties": false - } - }, - - "network": { - "id": "#/definitions/network", - "type": ["object", "null"], - "properties": { - "name": {"type": "string"}, - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "ipam": { - "type": "object", - "properties": { - "driver": {"type": "string"}, - "config": { - "type": "array", - "items": { - "type": "object", - "properties": { - "subnet": {"type": "string"} - }, - "additionalProperties": false - } - } - }, - "additionalProperties": false - }, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - }, - "additionalProperties": false - }, - "internal": {"type": "boolean"}, - "attachable": {"type": "boolean"}, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - }, - - "volume": { - "id": "#/definitions/volume", - "type": ["object", "null"], - "properties": { - "name": {"type": "string"}, - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - }, - "additionalProperties": false - }, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - }, - - "secret": { - "id": "#/definitions/secret", - "type": "object", - "properties": { - "name": {"type": "string"}, - "file": {"type": "string"}, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - } - }, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - }, - - "config": { - "id": "#/definitions/config", - "type": "object", - "properties": { - "name": {"type": "string"}, - "file": {"type": "string"}, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - } - }, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - }, - - "string_or_list": { - "oneOf": [ - {"type": "string"}, - {"$ref": "#/definitions/list_of_strings"} - ] - }, - - "list_of_strings": { - "type": "array", - "items": {"type": "string"}, - "uniqueItems": true - }, - - "list_or_dict": { - "oneOf": [ - { - "type": "object", - "patternProperties": { - ".+": { - "type": ["string", "number", "null"] - } - }, - "additionalProperties": false - }, - {"type": "array", "items": {"type": "string"}, "uniqueItems": true} - ] - }, - - "constraints": { - "service": { - "id": "#/definitions/constraints/service", - "anyOf": [ - {"required": ["build"]}, - {"required": ["image"]} - ], - "properties": { - "build": { - "required": ["context"] - } - } - } - } - } -} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.7.json b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.7.json deleted file mode 100644 index 69d5c52f8..000000000 --- a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.7.json +++ /dev/null @@ -1,606 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "id": "config_schema_v3.7.json", - "type": "object", - "required": ["version"], - - "properties": { - "version": { - "type": "string" - }, - - "services": { - "id": "#/properties/services", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/service" - } - }, - "additionalProperties": false - }, - - "networks": { - "id": "#/properties/networks", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/network" - } - } - }, - - "volumes": { - "id": "#/properties/volumes", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/volume" - } - }, - "additionalProperties": false - }, - - "secrets": { - "id": "#/properties/secrets", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/secret" - } - }, - "additionalProperties": false - }, - - "configs": { - "id": "#/properties/configs", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/config" - } - }, - "additionalProperties": false - } - }, - - "patternProperties": {"^x-": {}}, - "additionalProperties": false, - - "definitions": { - - "service": { - "id": "#/definitions/service", - "type": "object", - - "properties": { - "deploy": {"$ref": "#/definitions/deployment"}, - "build": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "context": {"type": "string"}, - "dockerfile": {"type": "string"}, - "args": {"$ref": "#/definitions/list_or_dict"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "cache_from": {"$ref": "#/definitions/list_of_strings"}, - "network": {"type": "string"}, - "target": {"type": "string"}, - "shm_size": {"type": ["integer", "string"]} - }, - "additionalProperties": false - } - ] - }, - "cap_add": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "cap_drop": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "cgroup_parent": {"type": "string"}, - "command": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "configs": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "source": {"type": "string"}, - "target": {"type": "string"}, - "uid": {"type": "string"}, - "gid": {"type": "string"}, - "mode": {"type": "number"} - } - } - ] - } - }, - "container_name": {"type": "string"}, - "credential_spec": { - "type": "object", - "properties": { - "file": {"type": "string"}, - "registry": {"type": "string"} - }, - "additionalProperties": false - }, - "depends_on": {"$ref": "#/definitions/list_of_strings"}, - "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "dns": {"$ref": "#/definitions/string_or_list"}, - "dns_search": {"$ref": "#/definitions/string_or_list"}, - "domainname": {"type": "string"}, - "entrypoint": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "env_file": {"$ref": "#/definitions/string_or_list"}, - "environment": {"$ref": "#/definitions/list_or_dict"}, - - "expose": { - "type": "array", - "items": { - "type": ["string", "number"], - "format": "expose" - }, - "uniqueItems": true - }, - - "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, - "healthcheck": {"$ref": "#/definitions/healthcheck"}, - "hostname": {"type": "string"}, - "image": {"type": "string"}, - "init": {"type": "boolean"}, - "ipc": {"type": "string"}, - "isolation": {"type": "string"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - - "logging": { - "type": "object", - - "properties": { - "driver": {"type": "string"}, - "options": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number", "null"]} - } - } - }, - "additionalProperties": false - }, - - "mac_address": {"type": "string"}, - "network_mode": {"type": "string"}, - - "networks": { - "oneOf": [ - {"$ref": "#/definitions/list_of_strings"}, - { - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "oneOf": [ - { - "type": "object", - "properties": { - "aliases": {"$ref": "#/definitions/list_of_strings"}, - "ipv4_address": {"type": "string"}, - "ipv6_address": {"type": "string"} - }, - "additionalProperties": false - }, - {"type": "null"} - ] - } - }, - "additionalProperties": false - } - ] - }, - "pid": {"type": ["string", "null"]}, - - "ports": { - "type": "array", - "items": { - "oneOf": [ - {"type": "number", "format": "ports"}, - {"type": "string", "format": "ports"}, - { - "type": "object", - "properties": { - "mode": {"type": "string"}, - "target": {"type": "integer"}, - "published": {"type": "integer"}, - "protocol": {"type": "string"} - }, - "additionalProperties": false - } - ] - }, - "uniqueItems": true - }, - - "privileged": {"type": "boolean"}, - "read_only": {"type": "boolean"}, - "restart": {"type": "string"}, - "security_opt": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "shm_size": {"type": ["number", "string"]}, - "secrets": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "source": {"type": "string"}, - "target": {"type": "string"}, - "uid": {"type": "string"}, - "gid": {"type": "string"}, - "mode": {"type": "number"} - } - } - ] - } - }, - "sysctls": {"$ref": "#/definitions/list_or_dict"}, - "stdin_open": {"type": "boolean"}, - "stop_grace_period": {"type": "string", "format": "duration"}, - "stop_signal": {"type": "string"}, - "tmpfs": {"$ref": "#/definitions/string_or_list"}, - "tty": {"type": "boolean"}, - "ulimits": { - "type": "object", - "patternProperties": { - "^[a-z]+$": { - "oneOf": [ - {"type": "integer"}, - { - "type":"object", - "properties": { - "hard": {"type": "integer"}, - "soft": {"type": "integer"} - }, - "required": ["soft", "hard"], - "additionalProperties": false - } - ] - } - } - }, - "user": {"type": "string"}, - "userns_mode": {"type": "string"}, - "volumes": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "required": ["type"], - "properties": { - "type": {"type": "string"}, - "source": {"type": "string"}, - "target": {"type": "string"}, - "read_only": {"type": "boolean"}, - "consistency": {"type": "string"}, - "bind": { - "type": "object", - "properties": { - "propagation": {"type": "string"} - } - }, - "volume": { - "type": "object", - "properties": { - "nocopy": {"type": "boolean"} - } - }, - "tmpfs": { - "type": "object", - "properties": { - "size": { - "type": "integer", - "minimum": 0 - } - } - } - }, - "additionalProperties": false - } - ], - "uniqueItems": true - } - }, - "working_dir": {"type": "string"} - }, - "patternProperties": {"^x-": {}}, - "additionalProperties": false - }, - - "healthcheck": { - "id": "#/definitions/healthcheck", - "type": "object", - "additionalProperties": false, - "properties": { - "disable": {"type": "boolean"}, - "interval": {"type": "string", "format": "duration"}, - "retries": {"type": "number"}, - "test": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "timeout": {"type": "string", "format": "duration"}, - "start_period": {"type": "string", "format": "duration"} - } - }, - "deployment": { - "id": "#/definitions/deployment", - "type": ["object", "null"], - "properties": { - "mode": {"type": "string"}, - "endpoint_mode": {"type": "string"}, - "replicas": {"type": "integer"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "rollback_config": { - "type": "object", - "properties": { - "parallelism": {"type": "integer"}, - "delay": {"type": "string", "format": "duration"}, - "failure_action": {"type": "string"}, - "monitor": {"type": "string", "format": "duration"}, - "max_failure_ratio": {"type": "number"}, - "order": {"type": "string", "enum": [ - "start-first", "stop-first" - ]} - }, - "additionalProperties": false - }, - "update_config": { - "type": "object", - "properties": { - "parallelism": {"type": "integer"}, - "delay": {"type": "string", "format": "duration"}, - "failure_action": {"type": "string"}, - "monitor": {"type": "string", "format": "duration"}, - "max_failure_ratio": {"type": "number"}, - "order": {"type": "string", "enum": [ - "start-first", "stop-first" - ]} - }, - "additionalProperties": false - }, - "resources": { - "type": "object", - "properties": { - "limits": { - "type": "object", - "properties": { - "cpus": {"type": "string"}, - "memory": {"type": "string"} - }, - "additionalProperties": false - }, - "reservations": { - "type": "object", - "properties": { - "cpus": {"type": "string"}, - "memory": {"type": "string"}, - "generic_resources": {"$ref": "#/definitions/generic_resources"} - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - "restart_policy": { - "type": "object", - "properties": { - "condition": {"type": "string"}, - "delay": {"type": "string", "format": "duration"}, - "max_attempts": {"type": "integer"}, - "window": {"type": "string", "format": "duration"} - }, - "additionalProperties": false - }, - "placement": { - "type": "object", - "properties": { - "constraints": {"type": "array", "items": {"type": "string"}}, - "preferences": { - "type": "array", - "items": { - "type": "object", - "properties": { - "spread": {"type": "string"} - }, - "additionalProperties": false - } - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - - "generic_resources": { - "id": "#/definitions/generic_resources", - "type": "array", - "items": { - "type": "object", - "properties": { - "discrete_resource_spec": { - "type": "object", - "properties": { - "kind": {"type": "string"}, - "value": {"type": "number"} - }, - "additionalProperties": false - } - }, - "additionalProperties": false - } - }, - - "network": { - "id": "#/definitions/network", - "type": ["object", "null"], - "properties": { - "name": {"type": "string"}, - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "ipam": { - "type": "object", - "properties": { - "driver": {"type": "string"}, - "config": { - "type": "array", - "items": { - "type": "object", - "properties": { - "subnet": {"type": "string"} - }, - "additionalProperties": false - } - } - }, - "additionalProperties": false - }, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - }, - "additionalProperties": false - }, - "internal": {"type": "boolean"}, - "attachable": {"type": "boolean"}, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "patternProperties": {"^x-": {}}, - "additionalProperties": false - }, - - "volume": { - "id": "#/definitions/volume", - "type": ["object", "null"], - "properties": { - "name": {"type": "string"}, - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - }, - "additionalProperties": false - }, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "patternProperties": {"^x-": {}}, - "additionalProperties": false - }, - - "secret": { - "id": "#/definitions/secret", - "type": "object", - "properties": { - "name": {"type": "string"}, - "file": {"type": "string"}, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - } - }, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "patternProperties": {"^x-": {}}, - "additionalProperties": false - }, - - "config": { - "id": "#/definitions/config", - "type": "object", - "properties": { - "name": {"type": "string"}, - "file": {"type": "string"}, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - } - }, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "patternProperties": {"^x-": {}}, - "additionalProperties": false - }, - - "string_or_list": { - "oneOf": [ - {"type": "string"}, - {"$ref": "#/definitions/list_of_strings"} - ] - }, - - "list_of_strings": { - "type": "array", - "items": {"type": "string"}, - "uniqueItems": true - }, - - "list_or_dict": { - "oneOf": [ - { - "type": "object", - "patternProperties": { - ".+": { - "type": ["string", "number", "null"] - } - }, - "additionalProperties": false - }, - {"type": "array", "items": {"type": "string"}, "uniqueItems": true} - ] - }, - - "constraints": { - "service": { - "id": "#/definitions/constraints/service", - "anyOf": [ - {"required": ["build"]}, - {"required": ["image"]} - ], - "properties": { - "build": { - "required": ["context"] - } - } - } - } - } -} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.8.json b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.8.json deleted file mode 100644 index 059c0bcf7..000000000 --- a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.8.json +++ /dev/null @@ -1,617 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "id": "config_schema_v3.8.json", - "type": "object", - "required": ["version"], - - "properties": { - "version": { - "type": "string" - }, - - "services": { - "id": "#/properties/services", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/service" - } - }, - "additionalProperties": false - }, - - "networks": { - "id": "#/properties/networks", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/network" - } - } - }, - - "volumes": { - "id": "#/properties/volumes", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/volume" - } - }, - "additionalProperties": false - }, - - "secrets": { - "id": "#/properties/secrets", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/secret" - } - }, - "additionalProperties": false - }, - - "configs": { - "id": "#/properties/configs", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/config" - } - }, - "additionalProperties": false - } - }, - - "patternProperties": {"^x-": {}}, - "additionalProperties": false, - - "definitions": { - - "service": { - "id": "#/definitions/service", - "type": "object", - - "properties": { - "deploy": {"$ref": "#/definitions/deployment"}, - "build": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "context": {"type": "string"}, - "dockerfile": {"type": "string"}, - "args": {"$ref": "#/definitions/list_or_dict"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "cache_from": {"$ref": "#/definitions/list_of_strings"}, - "network": {"type": "string"}, - "target": {"type": "string"}, - "shm_size": {"type": ["integer", "string"]} - }, - "additionalProperties": false - } - ] - }, - "cap_add": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "cap_drop": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "cgroup_parent": {"type": "string"}, - "command": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "configs": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "source": {"type": "string"}, - "target": {"type": "string"}, - "uid": {"type": "string"}, - "gid": {"type": "string"}, - "mode": {"type": "number"} - } - } - ] - } - }, - "container_name": {"type": "string"}, - "credential_spec": { - "type": "object", - "properties": { - "config": {"type": "string"}, - "file": {"type": "string"}, - "registry": {"type": "string"} - }, - "additionalProperties": false - }, - "depends_on": {"$ref": "#/definitions/list_of_strings"}, - "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "dns": {"$ref": "#/definitions/string_or_list"}, - "dns_search": {"$ref": "#/definitions/string_or_list"}, - "domainname": {"type": "string"}, - "entrypoint": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "env_file": {"$ref": "#/definitions/string_or_list"}, - "environment": {"$ref": "#/definitions/list_or_dict"}, - - "expose": { - "type": "array", - "items": { - "type": ["string", "number"], - "format": "expose" - }, - "uniqueItems": true - }, - - "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, - "healthcheck": {"$ref": "#/definitions/healthcheck"}, - "hostname": {"type": "string"}, - "image": {"type": "string"}, - "init": {"type": "boolean"}, - "ipc": {"type": "string"}, - "isolation": {"type": "string"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - - "logging": { - "type": "object", - - "properties": { - "driver": {"type": "string"}, - "options": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number", "null"]} - } - } - }, - "additionalProperties": false - }, - - "mac_address": {"type": "string"}, - "network_mode": {"type": "string"}, - - "networks": { - "oneOf": [ - {"$ref": "#/definitions/list_of_strings"}, - { - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "oneOf": [ - { - "type": "object", - "properties": { - "aliases": {"$ref": "#/definitions/list_of_strings"}, - "ipv4_address": {"type": "string"}, - "ipv6_address": {"type": "string"} - }, - "additionalProperties": false - }, - {"type": "null"} - ] - } - }, - "additionalProperties": false - } - ] - }, - "pid": {"type": ["string", "null"]}, - - "ports": { - "type": "array", - "items": { - "oneOf": [ - {"type": "number", "format": "ports"}, - {"type": "string", "format": "ports"}, - { - "type": "object", - "properties": { - "mode": {"type": "string"}, - "target": {"type": "integer"}, - "published": {"type": "integer"}, - "protocol": {"type": "string"} - }, - "additionalProperties": false - } - ] - }, - "uniqueItems": true - }, - - "privileged": {"type": "boolean"}, - "read_only": {"type": "boolean"}, - "restart": {"type": "string"}, - "security_opt": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "shm_size": {"type": ["number", "string"]}, - "secrets": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "source": {"type": "string"}, - "target": {"type": "string"}, - "uid": {"type": "string"}, - "gid": {"type": "string"}, - "mode": {"type": "number"} - } - } - ] - } - }, - "sysctls": {"$ref": "#/definitions/list_or_dict"}, - "stdin_open": {"type": "boolean"}, - "stop_grace_period": {"type": "string", "format": "duration"}, - "stop_signal": {"type": "string"}, - "tmpfs": {"$ref": "#/definitions/string_or_list"}, - "tty": {"type": "boolean"}, - "ulimits": { - "type": "object", - "patternProperties": { - "^[a-z]+$": { - "oneOf": [ - {"type": "integer"}, - { - "type":"object", - "properties": { - "hard": {"type": "integer"}, - "soft": {"type": "integer"} - }, - "required": ["soft", "hard"], - "additionalProperties": false - } - ] - } - } - }, - "user": {"type": "string"}, - "userns_mode": {"type": "string"}, - "volumes": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "required": ["type"], - "properties": { - "type": {"type": "string"}, - "source": {"type": "string"}, - "target": {"type": "string"}, - "read_only": {"type": "boolean"}, - "consistency": {"type": "string"}, - "bind": { - "type": "object", - "properties": { - "propagation": {"type": "string"} - } - }, - "volume": { - "type": "object", - "properties": { - "nocopy": {"type": "boolean"} - } - }, - "tmpfs": { - "type": "object", - "properties": { - "size": { - "type": "integer", - "minimum": 0 - } - } - } - }, - "additionalProperties": false - } - ], - "uniqueItems": true - } - }, - "working_dir": {"type": "string"} - }, - "patternProperties": {"^x-": {}}, - "additionalProperties": false - }, - - "healthcheck": { - "id": "#/definitions/healthcheck", - "type": "object", - "additionalProperties": false, - "properties": { - "disable": {"type": "boolean"}, - "interval": {"type": "string", "format": "duration"}, - "retries": {"type": "number"}, - "test": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "timeout": {"type": "string", "format": "duration"}, - "start_period": {"type": "string", "format": "duration"} - } - }, - "deployment": { - "id": "#/definitions/deployment", - "type": ["object", "null"], - "properties": { - "mode": {"type": "string"}, - "endpoint_mode": {"type": "string"}, - "replicas": {"type": "integer"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "rollback_config": { - "type": "object", - "properties": { - "parallelism": {"type": "integer"}, - "delay": {"type": "string", "format": "duration"}, - "failure_action": {"type": "string"}, - "monitor": {"type": "string", "format": "duration"}, - "max_failure_ratio": {"type": "number"}, - "order": {"type": "string", "enum": [ - "start-first", "stop-first" - ]} - }, - "additionalProperties": false - }, - "update_config": { - "type": "object", - "properties": { - "parallelism": {"type": "integer"}, - "delay": {"type": "string", "format": "duration"}, - "failure_action": {"type": "string"}, - "monitor": {"type": "string", "format": "duration"}, - "max_failure_ratio": {"type": "number"}, - "order": {"type": "string", "enum": [ - "start-first", "stop-first" - ]} - }, - "additionalProperties": false - }, - "resources": { - "type": "object", - "properties": { - "limits": { - "type": "object", - "properties": { - "cpus": {"type": "string"}, - "memory": {"type": "string"} - }, - "additionalProperties": false - }, - "reservations": { - "type": "object", - "properties": { - "cpus": {"type": "string"}, - "memory": {"type": "string"}, - "generic_resources": {"$ref": "#/definitions/generic_resources"} - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - "restart_policy": { - "type": "object", - "properties": { - "condition": {"type": "string"}, - "delay": {"type": "string", "format": "duration"}, - "max_attempts": {"type": "integer"}, - "window": {"type": "string", "format": "duration"} - }, - "additionalProperties": false - }, - "placement": { - "type": "object", - "properties": { - "constraints": {"type": "array", "items": {"type": "string"}}, - "preferences": { - "type": "array", - "items": { - "type": "object", - "properties": { - "spread": {"type": "string"} - }, - "additionalProperties": false - } - }, - "max_replicas_per_node": {"type": "integer"} - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - - "generic_resources": { - "id": "#/definitions/generic_resources", - "type": "array", - "items": { - "type": "object", - "properties": { - "discrete_resource_spec": { - "type": "object", - "properties": { - "kind": {"type": "string"}, - "value": {"type": "number"} - }, - "additionalProperties": false - } - }, - "additionalProperties": false - } - }, - - "network": { - "id": "#/definitions/network", - "type": ["object", "null"], - "properties": { - "name": {"type": "string"}, - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "ipam": { - "type": "object", - "properties": { - "driver": {"type": "string"}, - "config": { - "type": "array", - "items": { - "type": "object", - "properties": { - "subnet": {"type": "string"} - }, - "additionalProperties": false - } - } - }, - "additionalProperties": false - }, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - }, - "additionalProperties": false - }, - "internal": {"type": "boolean"}, - "attachable": {"type": "boolean"}, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "patternProperties": {"^x-": {}}, - "additionalProperties": false - }, - - "volume": { - "id": "#/definitions/volume", - "type": ["object", "null"], - "properties": { - "name": {"type": "string"}, - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - }, - "additionalProperties": false - }, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "patternProperties": {"^x-": {}}, - "additionalProperties": false - }, - - "secret": { - "id": "#/definitions/secret", - "type": "object", - "properties": { - "name": {"type": "string"}, - "file": {"type": "string"}, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - } - }, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "template_driver": {"type": "string"} - }, - "patternProperties": {"^x-": {}}, - "additionalProperties": false - }, - - "config": { - "id": "#/definitions/config", - "type": "object", - "properties": { - "name": {"type": "string"}, - "file": {"type": "string"}, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - } - }, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "template_driver": {"type": "string"} - }, - "patternProperties": {"^x-": {}}, - "additionalProperties": false - }, - - "string_or_list": { - "oneOf": [ - {"type": "string"}, - {"$ref": "#/definitions/list_of_strings"} - ] - }, - - "list_of_strings": { - "type": "array", - "items": {"type": "string"}, - "uniqueItems": true - }, - - "list_or_dict": { - "oneOf": [ - { - "type": "object", - "patternProperties": { - ".+": { - "type": ["string", "number", "null"] - } - }, - "additionalProperties": false - }, - {"type": "array", "items": {"type": "string"}, "uniqueItems": true} - ] - }, - - "constraints": { - "service": { - "id": "#/definitions/constraints/service", - "anyOf": [ - {"required": ["build"]}, - {"required": ["image"]} - ], - "properties": { - "build": { - "required": ["context"] - } - } - } - } - } -} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.9.json b/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.9.json deleted file mode 100644 index c6f63fda4..000000000 --- a/vendor/github.com/docker/cli/cli/compose/schema/data/config_schema_v3.9.json +++ /dev/null @@ -1,620 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "id": "config_schema_v3.9.json", - "type": "object", - "required": ["version"], - - "properties": { - "version": { - "type": "string" - }, - - "services": { - "id": "#/properties/services", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/service" - } - }, - "additionalProperties": false - }, - - "networks": { - "id": "#/properties/networks", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/network" - } - } - }, - - "volumes": { - "id": "#/properties/volumes", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/volume" - } - }, - "additionalProperties": false - }, - - "secrets": { - "id": "#/properties/secrets", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/secret" - } - }, - "additionalProperties": false - }, - - "configs": { - "id": "#/properties/configs", - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/config" - } - }, - "additionalProperties": false - } - }, - - "patternProperties": {"^x-": {}}, - "additionalProperties": false, - - "definitions": { - - "service": { - "id": "#/definitions/service", - "type": "object", - - "properties": { - "deploy": {"$ref": "#/definitions/deployment"}, - "build": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "context": {"type": "string"}, - "dockerfile": {"type": "string"}, - "args": {"$ref": "#/definitions/list_or_dict"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "cache_from": {"$ref": "#/definitions/list_of_strings"}, - "network": {"type": "string"}, - "target": {"type": "string"}, - "shm_size": {"type": ["integer", "string"]}, - "extra_hosts": {"$ref": "#/definitions/list_or_dict"} - }, - "additionalProperties": false - } - ] - }, - "cap_add": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "cap_drop": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "cgroupns_mode": {"type": "string"}, - "cgroup_parent": {"type": "string"}, - "command": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "configs": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "source": {"type": "string"}, - "target": {"type": "string"}, - "uid": {"type": "string"}, - "gid": {"type": "string"}, - "mode": {"type": "number"} - } - } - ] - } - }, - "container_name": {"type": "string"}, - "credential_spec": { - "type": "object", - "properties": { - "config": {"type": "string"}, - "file": {"type": "string"}, - "registry": {"type": "string"} - }, - "additionalProperties": false - }, - "depends_on": {"$ref": "#/definitions/list_of_strings"}, - "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "dns": {"$ref": "#/definitions/string_or_list"}, - "dns_search": {"$ref": "#/definitions/string_or_list"}, - "domainname": {"type": "string"}, - "entrypoint": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "env_file": {"$ref": "#/definitions/string_or_list"}, - "environment": {"$ref": "#/definitions/list_or_dict"}, - - "expose": { - "type": "array", - "items": { - "type": ["string", "number"], - "format": "expose" - }, - "uniqueItems": true - }, - - "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, - "healthcheck": {"$ref": "#/definitions/healthcheck"}, - "hostname": {"type": "string"}, - "image": {"type": "string"}, - "init": {"type": "boolean"}, - "ipc": {"type": "string"}, - "isolation": {"type": "string"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - - "logging": { - "type": "object", - - "properties": { - "driver": {"type": "string"}, - "options": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number", "null"]} - } - } - }, - "additionalProperties": false - }, - - "mac_address": {"type": "string"}, - "network_mode": {"type": "string"}, - - "networks": { - "oneOf": [ - {"$ref": "#/definitions/list_of_strings"}, - { - "type": "object", - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "oneOf": [ - { - "type": "object", - "properties": { - "aliases": {"$ref": "#/definitions/list_of_strings"}, - "ipv4_address": {"type": "string"}, - "ipv6_address": {"type": "string"} - }, - "additionalProperties": false - }, - {"type": "null"} - ] - } - }, - "additionalProperties": false - } - ] - }, - "pid": {"type": ["string", "null"]}, - - "ports": { - "type": "array", - "items": { - "oneOf": [ - {"type": "number", "format": "ports"}, - {"type": "string", "format": "ports"}, - { - "type": "object", - "properties": { - "mode": {"type": "string"}, - "target": {"type": "integer"}, - "published": {"type": "integer"}, - "protocol": {"type": "string"} - }, - "additionalProperties": false - } - ] - }, - "uniqueItems": true - }, - - "privileged": {"type": "boolean"}, - "read_only": {"type": "boolean"}, - "restart": {"type": "string"}, - "security_opt": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "shm_size": {"type": ["number", "string"]}, - "secrets": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "properties": { - "source": {"type": "string"}, - "target": {"type": "string"}, - "uid": {"type": "string"}, - "gid": {"type": "string"}, - "mode": {"type": "number"} - } - } - ] - } - }, - "sysctls": {"$ref": "#/definitions/list_or_dict"}, - "stdin_open": {"type": "boolean"}, - "stop_grace_period": {"type": "string", "format": "duration"}, - "stop_signal": {"type": "string"}, - "tmpfs": {"$ref": "#/definitions/string_or_list"}, - "tty": {"type": "boolean"}, - "ulimits": { - "type": "object", - "patternProperties": { - "^[a-z]+$": { - "oneOf": [ - {"type": "integer"}, - { - "type":"object", - "properties": { - "hard": {"type": "integer"}, - "soft": {"type": "integer"} - }, - "required": ["soft", "hard"], - "additionalProperties": false - } - ] - } - } - }, - "user": {"type": "string"}, - "userns_mode": {"type": "string"}, - "volumes": { - "type": "array", - "items": { - "oneOf": [ - {"type": "string"}, - { - "type": "object", - "required": ["type"], - "properties": { - "type": {"type": "string"}, - "source": {"type": "string"}, - "target": {"type": "string"}, - "read_only": {"type": "boolean"}, - "consistency": {"type": "string"}, - "bind": { - "type": "object", - "properties": { - "propagation": {"type": "string"} - } - }, - "volume": { - "type": "object", - "properties": { - "nocopy": {"type": "boolean"} - } - }, - "tmpfs": { - "type": "object", - "properties": { - "size": { - "type": "integer", - "minimum": 0 - } - } - } - }, - "additionalProperties": false - } - ], - "uniqueItems": true - } - }, - "working_dir": {"type": "string"} - }, - "patternProperties": {"^x-": {}}, - "additionalProperties": false - }, - - "healthcheck": { - "id": "#/definitions/healthcheck", - "type": "object", - "additionalProperties": false, - "properties": { - "disable": {"type": "boolean"}, - "interval": {"type": "string", "format": "duration"}, - "retries": {"type": "number"}, - "test": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ] - }, - "timeout": {"type": "string", "format": "duration"}, - "start_period": {"type": "string", "format": "duration"} - } - }, - "deployment": { - "id": "#/definitions/deployment", - "type": ["object", "null"], - "properties": { - "mode": {"type": "string"}, - "endpoint_mode": {"type": "string"}, - "replicas": {"type": "integer"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "rollback_config": { - "type": "object", - "properties": { - "parallelism": {"type": "integer"}, - "delay": {"type": "string", "format": "duration"}, - "failure_action": {"type": "string"}, - "monitor": {"type": "string", "format": "duration"}, - "max_failure_ratio": {"type": "number"}, - "order": {"type": "string", "enum": [ - "start-first", "stop-first" - ]} - }, - "additionalProperties": false - }, - "update_config": { - "type": "object", - "properties": { - "parallelism": {"type": "integer"}, - "delay": {"type": "string", "format": "duration"}, - "failure_action": {"type": "string"}, - "monitor": {"type": "string", "format": "duration"}, - "max_failure_ratio": {"type": "number"}, - "order": {"type": "string", "enum": [ - "start-first", "stop-first" - ]} - }, - "additionalProperties": false - }, - "resources": { - "type": "object", - "properties": { - "limits": { - "type": "object", - "properties": { - "cpus": {"type": "string"}, - "memory": {"type": "string"}, - "pids": {"type": "integer"} - }, - "additionalProperties": false - }, - "reservations": { - "type": "object", - "properties": { - "cpus": {"type": "string"}, - "memory": {"type": "string"}, - "generic_resources": {"$ref": "#/definitions/generic_resources"} - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - "restart_policy": { - "type": "object", - "properties": { - "condition": {"type": "string"}, - "delay": {"type": "string", "format": "duration"}, - "max_attempts": {"type": "integer"}, - "window": {"type": "string", "format": "duration"} - }, - "additionalProperties": false - }, - "placement": { - "type": "object", - "properties": { - "constraints": {"type": "array", "items": {"type": "string"}}, - "preferences": { - "type": "array", - "items": { - "type": "object", - "properties": { - "spread": {"type": "string"} - }, - "additionalProperties": false - } - }, - "max_replicas_per_node": {"type": "integer"} - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - - "generic_resources": { - "id": "#/definitions/generic_resources", - "type": "array", - "items": { - "type": "object", - "properties": { - "discrete_resource_spec": { - "type": "object", - "properties": { - "kind": {"type": "string"}, - "value": {"type": "number"} - }, - "additionalProperties": false - } - }, - "additionalProperties": false - } - }, - - "network": { - "id": "#/definitions/network", - "type": ["object", "null"], - "properties": { - "name": {"type": "string"}, - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "ipam": { - "type": "object", - "properties": { - "driver": {"type": "string"}, - "config": { - "type": "array", - "items": { - "type": "object", - "properties": { - "subnet": {"type": "string"} - }, - "additionalProperties": false - } - } - }, - "additionalProperties": false - }, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - }, - "additionalProperties": false - }, - "internal": {"type": "boolean"}, - "attachable": {"type": "boolean"}, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "patternProperties": {"^x-": {}}, - "additionalProperties": false - }, - - "volume": { - "id": "#/definitions/volume", - "type": ["object", "null"], - "properties": { - "name": {"type": "string"}, - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - }, - "additionalProperties": false - }, - "labels": {"$ref": "#/definitions/list_or_dict"} - }, - "patternProperties": {"^x-": {}}, - "additionalProperties": false - }, - - "secret": { - "id": "#/definitions/secret", - "type": "object", - "properties": { - "name": {"type": "string"}, - "file": {"type": "string"}, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - } - }, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "template_driver": {"type": "string"} - }, - "patternProperties": {"^x-": {}}, - "additionalProperties": false - }, - - "config": { - "id": "#/definitions/config", - "type": "object", - "properties": { - "name": {"type": "string"}, - "file": {"type": "string"}, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - } - }, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "template_driver": {"type": "string"} - }, - "patternProperties": {"^x-": {}}, - "additionalProperties": false - }, - - "string_or_list": { - "oneOf": [ - {"type": "string"}, - {"$ref": "#/definitions/list_of_strings"} - ] - }, - - "list_of_strings": { - "type": "array", - "items": {"type": "string"}, - "uniqueItems": true - }, - - "list_or_dict": { - "oneOf": [ - { - "type": "object", - "patternProperties": { - ".+": { - "type": ["string", "number", "null"] - } - }, - "additionalProperties": false - }, - {"type": "array", "items": {"type": "string"}, "uniqueItems": true} - ] - }, - - "constraints": { - "service": { - "id": "#/definitions/constraints/service", - "anyOf": [ - {"required": ["build"]}, - {"required": ["image"]} - ], - "properties": { - "build": { - "required": ["context"] - } - } - } - } - } -} diff --git a/vendor/github.com/docker/cli/cli/compose/schema/schema.go b/vendor/github.com/docker/cli/cli/compose/schema/schema.go deleted file mode 100644 index 3481780c9..000000000 --- a/vendor/github.com/docker/cli/cli/compose/schema/schema.go +++ /dev/null @@ -1,177 +0,0 @@ -package schema - -import ( - "embed" - "fmt" - "strings" - "time" - - "github.com/pkg/errors" - "github.com/xeipuuv/gojsonschema" -) - -const ( - defaultVersion = "3.11" - versionField = "version" -) - -type portsFormatChecker struct{} - -func (checker portsFormatChecker) IsFormat(_ interface{}) bool { - // TODO: implement this - return true -} - -type durationFormatChecker struct{} - -func (checker durationFormatChecker) IsFormat(input interface{}) bool { - value, ok := input.(string) - if !ok { - return false - } - _, err := time.ParseDuration(value) - return err == nil -} - -func init() { - gojsonschema.FormatCheckers.Add("expose", portsFormatChecker{}) - gojsonschema.FormatCheckers.Add("ports", portsFormatChecker{}) - gojsonschema.FormatCheckers.Add("duration", durationFormatChecker{}) -} - -// Version returns the version of the config, defaulting to the latest "3.x" -// version (3.11). If only the major version "3" is specified, it is used as -// version "3.x" and returns the default version (latest 3.x). -func Version(config map[string]interface{}) string { - version, ok := config[versionField] - if !ok { - return defaultVersion - } - return normalizeVersion(fmt.Sprintf("%v", version)) -} - -func normalizeVersion(version string) string { - switch version { - case "", "3": - return defaultVersion - default: - return version - } -} - -//go:embed data/config_schema_v*.json -var schemas embed.FS - -// Validate uses the jsonschema to validate the configuration -func Validate(config map[string]interface{}, version string) error { - version = normalizeVersion(version) - schemaData, err := schemas.ReadFile("data/config_schema_v" + version + ".json") - if err != nil { - return errors.Errorf("unsupported Compose file version: %s", version) - } - - schemaLoader := gojsonschema.NewStringLoader(string(schemaData)) - dataLoader := gojsonschema.NewGoLoader(config) - - result, err := gojsonschema.Validate(schemaLoader, dataLoader) - if err != nil { - return err - } - - if !result.Valid() { - return toError(result) - } - - return nil -} - -func toError(result *gojsonschema.Result) error { - err := getMostSpecificError(result.Errors()) - return err -} - -const ( - jsonschemaOneOf = "number_one_of" - jsonschemaAnyOf = "number_any_of" -) - -func getDescription(err validationError) string { - switch err.parent.Type() { - case "invalid_type": - if expectedType, ok := err.parent.Details()["expected"].(string); ok { - return fmt.Sprintf("must be a %s", humanReadableType(expectedType)) - } - case jsonschemaOneOf, jsonschemaAnyOf: - if err.child == nil { - return err.parent.Description() - } - return err.child.Description() - } - return err.parent.Description() -} - -func humanReadableType(definition string) string { - if definition[0:1] == "[" { - allTypes := strings.Split(definition[1:len(definition)-1], ",") - for i, t := range allTypes { - allTypes[i] = humanReadableType(t) - } - return fmt.Sprintf( - "%s or %s", - strings.Join(allTypes[0:len(allTypes)-1], ", "), - allTypes[len(allTypes)-1], - ) - } - if definition == "object" { - return "mapping" - } - if definition == "array" { - return "list" - } - return definition -} - -type validationError struct { - parent gojsonschema.ResultError - child gojsonschema.ResultError -} - -func (err validationError) Error() string { - description := getDescription(err) - return fmt.Sprintf("%s %s", err.parent.Field(), description) -} - -func getMostSpecificError(errors []gojsonschema.ResultError) validationError { - mostSpecificError := 0 - for i, err := range errors { - if specificity(err) > specificity(errors[mostSpecificError]) { - mostSpecificError = i - continue - } - - if specificity(err) == specificity(errors[mostSpecificError]) { - // Invalid type errors win in a tie-breaker for most specific field name - if err.Type() == "invalid_type" && errors[mostSpecificError].Type() != "invalid_type" { - mostSpecificError = i - } - } - } - - if mostSpecificError+1 == len(errors) { - return validationError{parent: errors[mostSpecificError]} - } - - switch errors[mostSpecificError].Type() { - case "number_one_of", "number_any_of": - return validationError{ - parent: errors[mostSpecificError], - child: errors[mostSpecificError+1], - } - default: - return validationError{parent: errors[mostSpecificError]} - } -} - -func specificity(err gojsonschema.ResultError) int { - return len(strings.Split(err.Field(), ".")) -} diff --git a/vendor/github.com/docker/cli/cli/compose/template/template.go b/vendor/github.com/docker/cli/cli/compose/template/template.go deleted file mode 100644 index f8e507a90..000000000 --- a/vendor/github.com/docker/cli/cli/compose/template/template.go +++ /dev/null @@ -1,247 +0,0 @@ -package template - -import ( - "fmt" - "regexp" - "strings" -) - -var ( - delimiter = "\\$" - substitution = "[_a-z][_a-z0-9]*(?::?[-?][^}]*)?" -) - -var patternString = fmt.Sprintf( - "%s(?i:(?P%s)|(?P%s)|{(?P%s)}|(?P))", - delimiter, delimiter, substitution, substitution, -) - -var defaultPattern = regexp.MustCompile(patternString) - -// DefaultSubstituteFuncs contains the default SubstituteFunc used by the docker cli -var DefaultSubstituteFuncs = []SubstituteFunc{ - softDefault, - hardDefault, - requiredNonEmpty, - required, -} - -// InvalidTemplateError is returned when a variable template is not in a valid -// format -type InvalidTemplateError struct { - Template string -} - -func (e InvalidTemplateError) Error() string { - return fmt.Sprintf("Invalid template: %#v", e.Template) -} - -// Mapping is a user-supplied function which maps from variable names to values. -// Returns the value as a string and a bool indicating whether -// the value is present, to distinguish between an empty string -// and the absence of a value. -type Mapping func(string) (string, bool) - -// SubstituteFunc is a user-supplied function that apply substitution. -// Returns the value as a string, a bool indicating if the function could apply -// the substitution and an error. -type SubstituteFunc func(string, Mapping) (string, bool, error) - -// SubstituteWith subsitute variables in the string with their values. -// It accepts additional substitute function. -func SubstituteWith(template string, mapping Mapping, pattern *regexp.Regexp, subsFuncs ...SubstituteFunc) (string, error) { - var err error - result := pattern.ReplaceAllStringFunc(template, func(substring string) string { - matches := pattern.FindStringSubmatch(substring) - groups := matchGroups(matches, pattern) - if escaped := groups["escaped"]; escaped != "" { - return escaped - } - - substitution := groups["named"] - if substitution == "" { - substitution = groups["braced"] - } - - if substitution == "" { - err = &InvalidTemplateError{Template: template} - return "" - } - - for _, f := range subsFuncs { - var ( - value string - applied bool - ) - value, applied, err = f(substitution, mapping) - if err != nil { - return "" - } - if !applied { - continue - } - return value - } - - value, _ := mapping(substitution) - return value - }) - - return result, err -} - -// Substitute variables in the string with their values -func Substitute(template string, mapping Mapping) (string, error) { - return SubstituteWith(template, mapping, defaultPattern, DefaultSubstituteFuncs...) -} - -// ExtractVariables returns a map of all the variables defined in the specified -// composefile (dict representation) and their default value if any. -func ExtractVariables(configDict map[string]interface{}, pattern *regexp.Regexp) map[string]string { - if pattern == nil { - pattern = defaultPattern - } - return recurseExtract(configDict, pattern) -} - -func recurseExtract(value interface{}, pattern *regexp.Regexp) map[string]string { - m := map[string]string{} - - switch value := value.(type) { - case string: - if values, is := extractVariable(value, pattern); is { - for _, v := range values { - m[v.name] = v.value - } - } - case map[string]interface{}: - for _, elem := range value { - submap := recurseExtract(elem, pattern) - for key, value := range submap { - m[key] = value - } - } - - case []interface{}: - for _, elem := range value { - if values, is := extractVariable(elem, pattern); is { - for _, v := range values { - m[v.name] = v.value - } - } - } - } - - return m -} - -type extractedValue struct { - name string - value string -} - -func extractVariable(value interface{}, pattern *regexp.Regexp) ([]extractedValue, bool) { - sValue, ok := value.(string) - if !ok { - return []extractedValue{}, false - } - matches := pattern.FindAllStringSubmatch(sValue, -1) - if len(matches) == 0 { - return []extractedValue{}, false - } - values := []extractedValue{} - for _, match := range matches { - groups := matchGroups(match, pattern) - if escaped := groups["escaped"]; escaped != "" { - continue - } - val := groups["named"] - if val == "" { - val = groups["braced"] - } - name := val - var defaultValue string - switch { - case strings.Contains(val, ":?"): - name, _ = partition(val, ":?") - case strings.Contains(val, "?"): - name, _ = partition(val, "?") - case strings.Contains(val, ":-"): - name, defaultValue = partition(val, ":-") - case strings.Contains(val, "-"): - name, defaultValue = partition(val, "-") - } - values = append(values, extractedValue{name: name, value: defaultValue}) - } - return values, len(values) > 0 -} - -// Soft default (fall back if unset or empty) -func softDefault(substitution string, mapping Mapping) (string, bool, error) { - sep := ":-" - if !strings.Contains(substitution, sep) { - return "", false, nil - } - name, defaultValue := partition(substitution, sep) - value, ok := mapping(name) - if !ok || value == "" { - return defaultValue, true, nil - } - return value, true, nil -} - -// Hard default (fall back if-and-only-if empty) -func hardDefault(substitution string, mapping Mapping) (string, bool, error) { - sep := "-" - if !strings.Contains(substitution, sep) { - return "", false, nil - } - name, defaultValue := partition(substitution, sep) - value, ok := mapping(name) - if !ok { - return defaultValue, true, nil - } - return value, true, nil -} - -func requiredNonEmpty(substitution string, mapping Mapping) (string, bool, error) { - return withRequired(substitution, mapping, ":?", func(v string) bool { return v != "" }) -} - -func required(substitution string, mapping Mapping) (string, bool, error) { - return withRequired(substitution, mapping, "?", func(_ string) bool { return true }) -} - -func withRequired(substitution string, mapping Mapping, sep string, valid func(string) bool) (string, bool, error) { - if !strings.Contains(substitution, sep) { - return "", false, nil - } - name, errorMessage := partition(substitution, sep) - value, ok := mapping(name) - if !ok || !valid(value) { - return "", true, &InvalidTemplateError{ - Template: fmt.Sprintf("required variable %s is missing a value: %s", name, errorMessage), - } - } - return value, true, nil -} - -func matchGroups(matches []string, pattern *regexp.Regexp) map[string]string { - groups := make(map[string]string) - for i, name := range pattern.SubexpNames()[1:] { - groups[name] = matches[i+1] - } - return groups -} - -// Split the string at the first occurrence of sep, and return the part before the separator, -// and the part after the separator. -// -// If the separator is not found, return the string itself, followed by an empty string. -func partition(s, sep string) (string, string) { - k, v, ok := strings.Cut(s, sep) - if !ok { - return s, "" - } - return k, v -} diff --git a/vendor/github.com/docker/cli/cli/compose/types/types.go b/vendor/github.com/docker/cli/cli/compose/types/types.go deleted file mode 100644 index ed2e10e85..000000000 --- a/vendor/github.com/docker/cli/cli/compose/types/types.go +++ /dev/null @@ -1,595 +0,0 @@ -package types - -import ( - "encoding/json" - "fmt" - "time" -) - -// UnsupportedProperties not yet supported by this implementation of the compose file -var UnsupportedProperties = []string{ - "build", - "cgroupns_mode", - "cgroup_parent", - "devices", - "domainname", - "external_links", - "ipc", - "links", - "mac_address", - "network_mode", - "pid", - "privileged", - "restart", - "security_opt", - "shm_size", - "userns_mode", -} - -// DeprecatedProperties that were removed from the v3 format, but their -// use should not impact the behaviour of the application. -var DeprecatedProperties = map[string]string{ - "container_name": "Setting the container name is not supported.", - "expose": "Exposing ports is unnecessary - services on the same network can access each other's containers on any port.", -} - -// ForbiddenProperties that are not supported in this implementation of the -// compose file. -var ForbiddenProperties = map[string]string{ - "extends": "Support for `extends` is not implemented yet.", - "volume_driver": "Instead of setting the volume driver on the service, define a volume using the top-level `volumes` option and specify the driver there.", - "volumes_from": "To share a volume between services, define it using the top-level `volumes` option and reference it from each service that shares it using the service-level `volumes` option.", - "cpu_quota": "Set resource limits using deploy.resources", - "cpu_shares": "Set resource limits using deploy.resources", - "cpuset": "Set resource limits using deploy.resources", - "mem_limit": "Set resource limits using deploy.resources", - "memswap_limit": "Set resource limits using deploy.resources", -} - -// ConfigFile is a filename and the contents of the file as a Dict -type ConfigFile struct { - Filename string - Config map[string]interface{} -} - -// ConfigDetails are the details about a group of ConfigFiles -type ConfigDetails struct { - Version string - WorkingDir string - ConfigFiles []ConfigFile - Environment map[string]string -} - -// Duration is a thin wrapper around time.Duration with improved JSON marshalling -type Duration time.Duration - -func (d Duration) String() string { - return time.Duration(d).String() -} - -// ConvertDurationPtr converts a typedefined Duration pointer to a time.Duration pointer with the same value. -func ConvertDurationPtr(d *Duration) *time.Duration { - if d == nil { - return nil - } - res := time.Duration(*d) - return &res -} - -// MarshalJSON makes Duration implement json.Marshaler -func (d Duration) MarshalJSON() ([]byte, error) { - return json.Marshal(d.String()) -} - -// MarshalYAML makes Duration implement yaml.Marshaler -func (d Duration) MarshalYAML() (interface{}, error) { - return d.String(), nil -} - -// LookupEnv provides a lookup function for environment variables -func (cd ConfigDetails) LookupEnv(key string) (string, bool) { - v, ok := cd.Environment[key] - return v, ok -} - -// Config is a full compose file configuration -type Config struct { - Filename string `yaml:"-" json:"-"` - Version string `json:"version"` - Services Services `json:"services"` - Networks map[string]NetworkConfig `yaml:",omitempty" json:"networks,omitempty"` - Volumes map[string]VolumeConfig `yaml:",omitempty" json:"volumes,omitempty"` - Secrets map[string]SecretConfig `yaml:",omitempty" json:"secrets,omitempty"` - Configs map[string]ConfigObjConfig `yaml:",omitempty" json:"configs,omitempty"` - Extras map[string]interface{} `yaml:",inline" json:"-"` -} - -// MarshalJSON makes Config implement json.Marshaler -func (c Config) MarshalJSON() ([]byte, error) { - m := map[string]interface{}{ - "version": c.Version, - "services": c.Services, - } - - if len(c.Networks) > 0 { - m["networks"] = c.Networks - } - if len(c.Volumes) > 0 { - m["volumes"] = c.Volumes - } - if len(c.Secrets) > 0 { - m["secrets"] = c.Secrets - } - if len(c.Configs) > 0 { - m["configs"] = c.Configs - } - for k, v := range c.Extras { - m[k] = v - } - return json.Marshal(m) -} - -// Services is a list of ServiceConfig -type Services []ServiceConfig - -// MarshalYAML makes Services implement yaml.Marshaller -func (s Services) MarshalYAML() (interface{}, error) { - services := map[string]ServiceConfig{} - for _, service := range s { - services[service.Name] = service - } - return services, nil -} - -// MarshalJSON makes Services implement json.Marshaler -func (s Services) MarshalJSON() ([]byte, error) { - data, err := s.MarshalYAML() - if err != nil { - return nil, err - } - return json.MarshalIndent(data, "", " ") -} - -// ServiceConfig is the configuration of one service -type ServiceConfig struct { - Name string `yaml:"-" json:"-"` - - Build BuildConfig `yaml:",omitempty" json:"build,omitempty"` - CapAdd []string `mapstructure:"cap_add" yaml:"cap_add,omitempty" json:"cap_add,omitempty"` - CapDrop []string `mapstructure:"cap_drop" yaml:"cap_drop,omitempty" json:"cap_drop,omitempty"` - CgroupNSMode string `mapstructure:"cgroupns_mode" yaml:"cgroupns_mode,omitempty" json:"cgroupns_mode,omitempty"` - CgroupParent string `mapstructure:"cgroup_parent" yaml:"cgroup_parent,omitempty" json:"cgroup_parent,omitempty"` - Command ShellCommand `yaml:",omitempty" json:"command,omitempty"` - Configs []ServiceConfigObjConfig `yaml:",omitempty" json:"configs,omitempty"` - ContainerName string `mapstructure:"container_name" yaml:"container_name,omitempty" json:"container_name,omitempty"` - CredentialSpec CredentialSpecConfig `mapstructure:"credential_spec" yaml:"credential_spec,omitempty" json:"credential_spec,omitempty"` - DependsOn []string `mapstructure:"depends_on" yaml:"depends_on,omitempty" json:"depends_on,omitempty"` - Deploy DeployConfig `yaml:",omitempty" json:"deploy,omitempty"` - Devices []string `yaml:",omitempty" json:"devices,omitempty"` - DNS StringList `yaml:",omitempty" json:"dns,omitempty"` - DNSSearch StringList `mapstructure:"dns_search" yaml:"dns_search,omitempty" json:"dns_search,omitempty"` - DomainName string `mapstructure:"domainname" yaml:"domainname,omitempty" json:"domainname,omitempty"` - Entrypoint ShellCommand `yaml:",omitempty" json:"entrypoint,omitempty"` - Environment MappingWithEquals `yaml:",omitempty" json:"environment,omitempty"` - EnvFile StringList `mapstructure:"env_file" yaml:"env_file,omitempty" json:"env_file,omitempty"` - Expose StringOrNumberList `yaml:",omitempty" json:"expose,omitempty"` - ExternalLinks []string `mapstructure:"external_links" yaml:"external_links,omitempty" json:"external_links,omitempty"` - ExtraHosts HostsList `mapstructure:"extra_hosts" yaml:"extra_hosts,omitempty" json:"extra_hosts,omitempty"` - Hostname string `yaml:",omitempty" json:"hostname,omitempty"` - HealthCheck *HealthCheckConfig `yaml:",omitempty" json:"healthcheck,omitempty"` - Image string `yaml:",omitempty" json:"image,omitempty"` - Init *bool `yaml:",omitempty" json:"init,omitempty"` - Ipc string `yaml:",omitempty" json:"ipc,omitempty"` - Isolation string `mapstructure:"isolation" yaml:"isolation,omitempty" json:"isolation,omitempty"` - Labels Labels `yaml:",omitempty" json:"labels,omitempty"` - Links []string `yaml:",omitempty" json:"links,omitempty"` - Logging *LoggingConfig `yaml:",omitempty" json:"logging,omitempty"` - MacAddress string `mapstructure:"mac_address" yaml:"mac_address,omitempty" json:"mac_address,omitempty"` - NetworkMode string `mapstructure:"network_mode" yaml:"network_mode,omitempty" json:"network_mode,omitempty"` - Networks map[string]*ServiceNetworkConfig `yaml:",omitempty" json:"networks,omitempty"` - Pid string `yaml:",omitempty" json:"pid,omitempty"` - Ports []ServicePortConfig `yaml:",omitempty" json:"ports,omitempty"` - Privileged bool `yaml:",omitempty" json:"privileged,omitempty"` - ReadOnly bool `mapstructure:"read_only" yaml:"read_only,omitempty" json:"read_only,omitempty"` - Restart string `yaml:",omitempty" json:"restart,omitempty"` - Secrets []ServiceSecretConfig `yaml:",omitempty" json:"secrets,omitempty"` - SecurityOpt []string `mapstructure:"security_opt" yaml:"security_opt,omitempty" json:"security_opt,omitempty"` - ShmSize string `mapstructure:"shm_size" yaml:"shm_size,omitempty" json:"shm_size,omitempty"` - StdinOpen bool `mapstructure:"stdin_open" yaml:"stdin_open,omitempty" json:"stdin_open,omitempty"` - StopGracePeriod *Duration `mapstructure:"stop_grace_period" yaml:"stop_grace_period,omitempty" json:"stop_grace_period,omitempty"` - StopSignal string `mapstructure:"stop_signal" yaml:"stop_signal,omitempty" json:"stop_signal,omitempty"` - Sysctls Mapping `yaml:",omitempty" json:"sysctls,omitempty"` - Tmpfs StringList `yaml:",omitempty" json:"tmpfs,omitempty"` - Tty bool `mapstructure:"tty" yaml:"tty,omitempty" json:"tty,omitempty"` - Ulimits map[string]*UlimitsConfig `yaml:",omitempty" json:"ulimits,omitempty"` - User string `yaml:",omitempty" json:"user,omitempty"` - UserNSMode string `mapstructure:"userns_mode" yaml:"userns_mode,omitempty" json:"userns_mode,omitempty"` - Volumes []ServiceVolumeConfig `yaml:",omitempty" json:"volumes,omitempty"` - WorkingDir string `mapstructure:"working_dir" yaml:"working_dir,omitempty" json:"working_dir,omitempty"` - - Extras map[string]interface{} `yaml:",inline" json:"-"` -} - -// BuildConfig is a type for build -// using the same format at libcompose: https://github.com/docker/libcompose/blob/master/yaml/build.go#L12 -type BuildConfig struct { - Context string `yaml:",omitempty" json:"context,omitempty"` - Dockerfile string `yaml:",omitempty" json:"dockerfile,omitempty"` - Args MappingWithEquals `yaml:",omitempty" json:"args,omitempty"` - Labels Labels `yaml:",omitempty" json:"labels,omitempty"` - CacheFrom StringList `mapstructure:"cache_from" yaml:"cache_from,omitempty" json:"cache_from,omitempty"` - ExtraHosts HostsList `mapstructure:"extra_hosts" yaml:"extra_hosts,omitempty" json:"extra_hosts,omitempty"` - Network string `yaml:",omitempty" json:"network,omitempty"` - Target string `yaml:",omitempty" json:"target,omitempty"` -} - -// ShellCommand is a string or list of string args -type ShellCommand []string - -// StringList is a type for fields that can be a string or list of strings -type StringList []string - -// StringOrNumberList is a type for fields that can be a list of strings or -// numbers -type StringOrNumberList []string - -// MappingWithEquals is a mapping type that can be converted from a list of -// key[=value] strings. -// For the key with an empty value (`key=`), the mapped value is set to a pointer to `""`. -// For the key without value (`key`), the mapped value is set to nil. -type MappingWithEquals map[string]*string - -// Mapping is a mapping type that can be converted from a list of -// key[=value] strings. -// For the key with an empty value (`key=`), or key without value (`key`), the -// mapped value is set to an empty string `""`. -type Mapping map[string]string - -// Labels is a mapping type for labels -type Labels map[string]string - -// MappingWithColon is a mapping type that can be converted from a list of -// 'key: value' strings -type MappingWithColon map[string]string - -// HostsList is a list of colon-separated host-ip mappings -type HostsList []string - -// LoggingConfig the logging configuration for a service -type LoggingConfig struct { - Driver string `yaml:",omitempty" json:"driver,omitempty"` - Options map[string]string `yaml:",omitempty" json:"options,omitempty"` -} - -// DeployConfig the deployment configuration for a service -type DeployConfig struct { - Mode string `yaml:",omitempty" json:"mode,omitempty"` - Replicas *uint64 `yaml:",omitempty" json:"replicas,omitempty"` - Labels Labels `yaml:",omitempty" json:"labels,omitempty"` - UpdateConfig *UpdateConfig `mapstructure:"update_config" yaml:"update_config,omitempty" json:"update_config,omitempty"` - RollbackConfig *UpdateConfig `mapstructure:"rollback_config" yaml:"rollback_config,omitempty" json:"rollback_config,omitempty"` - Resources Resources `yaml:",omitempty" json:"resources,omitempty"` - RestartPolicy *RestartPolicy `mapstructure:"restart_policy" yaml:"restart_policy,omitempty" json:"restart_policy,omitempty"` - Placement Placement `yaml:",omitempty" json:"placement,omitempty"` - EndpointMode string `mapstructure:"endpoint_mode" yaml:"endpoint_mode,omitempty" json:"endpoint_mode,omitempty"` -} - -// HealthCheckConfig the healthcheck configuration for a service -type HealthCheckConfig struct { - Test HealthCheckTest `yaml:",omitempty" json:"test,omitempty"` - Timeout *Duration `yaml:",omitempty" json:"timeout,omitempty"` - Interval *Duration `yaml:",omitempty" json:"interval,omitempty"` - Retries *uint64 `yaml:",omitempty" json:"retries,omitempty"` - StartPeriod *Duration `mapstructure:"start_period" yaml:"start_period,omitempty" json:"start_period,omitempty"` - Disable bool `yaml:",omitempty" json:"disable,omitempty"` -} - -// HealthCheckTest is the command run to test the health of a service -type HealthCheckTest []string - -// UpdateConfig the service update configuration -type UpdateConfig struct { - Parallelism *uint64 `yaml:",omitempty" json:"parallelism,omitempty"` - Delay Duration `yaml:",omitempty" json:"delay,omitempty"` - FailureAction string `mapstructure:"failure_action" yaml:"failure_action,omitempty" json:"failure_action,omitempty"` - Monitor Duration `yaml:",omitempty" json:"monitor,omitempty"` - MaxFailureRatio float32 `mapstructure:"max_failure_ratio" yaml:"max_failure_ratio,omitempty" json:"max_failure_ratio,omitempty"` - Order string `yaml:",omitempty" json:"order,omitempty"` -} - -// Resources the resource limits and reservations -type Resources struct { - Limits *ResourceLimit `yaml:",omitempty" json:"limits,omitempty"` - Reservations *Resource `yaml:",omitempty" json:"reservations,omitempty"` -} - -// ResourceLimit is a resource to be limited -type ResourceLimit struct { - // TODO: types to convert from units and ratios - NanoCPUs string `mapstructure:"cpus" yaml:"cpus,omitempty" json:"cpus,omitempty"` - MemoryBytes UnitBytes `mapstructure:"memory" yaml:"memory,omitempty" json:"memory,omitempty"` - Pids int64 `mapstructure:"pids" yaml:"pids,omitempty" json:"pids,omitempty"` -} - -// Resource is a resource to be reserved -type Resource struct { - // TODO: types to convert from units and ratios - NanoCPUs string `mapstructure:"cpus" yaml:"cpus,omitempty" json:"cpus,omitempty"` - MemoryBytes UnitBytes `mapstructure:"memory" yaml:"memory,omitempty" json:"memory,omitempty"` - GenericResources []GenericResource `mapstructure:"generic_resources" yaml:"generic_resources,omitempty" json:"generic_resources,omitempty"` -} - -// GenericResource represents a "user defined" resource which can -// only be an integer (e.g: SSD=3) for a service -type GenericResource struct { - DiscreteResourceSpec *DiscreteGenericResource `mapstructure:"discrete_resource_spec" yaml:"discrete_resource_spec,omitempty" json:"discrete_resource_spec,omitempty"` -} - -// DiscreteGenericResource represents a "user defined" resource which is defined -// as an integer -// "Kind" is used to describe the Kind of a resource (e.g: "GPU", "FPGA", "SSD", ...) -// Value is used to count the resource (SSD=5, HDD=3, ...) -type DiscreteGenericResource struct { - Kind string `json:"kind"` - Value int64 `json:"value"` -} - -// UnitBytes is the bytes type -type UnitBytes int64 - -// MarshalYAML makes UnitBytes implement yaml.Marshaller -func (u UnitBytes) MarshalYAML() (interface{}, error) { - return fmt.Sprintf("%d", u), nil -} - -// MarshalJSON makes UnitBytes implement json.Marshaler -func (u UnitBytes) MarshalJSON() ([]byte, error) { - return []byte(fmt.Sprintf(`"%d"`, u)), nil -} - -// RestartPolicy the service restart policy -type RestartPolicy struct { - Condition string `yaml:",omitempty" json:"condition,omitempty"` - Delay *Duration `yaml:",omitempty" json:"delay,omitempty"` - MaxAttempts *uint64 `mapstructure:"max_attempts" yaml:"max_attempts,omitempty" json:"max_attempts,omitempty"` - Window *Duration `yaml:",omitempty" json:"window,omitempty"` -} - -// Placement constraints for the service -type Placement struct { - Constraints []string `yaml:",omitempty" json:"constraints,omitempty"` - Preferences []PlacementPreferences `yaml:",omitempty" json:"preferences,omitempty"` - MaxReplicas uint64 `mapstructure:"max_replicas_per_node" yaml:"max_replicas_per_node,omitempty" json:"max_replicas_per_node,omitempty"` -} - -// PlacementPreferences is the preferences for a service placement -type PlacementPreferences struct { - Spread string `yaml:",omitempty" json:"spread,omitempty"` -} - -// ServiceNetworkConfig is the network configuration for a service -type ServiceNetworkConfig struct { - Aliases []string `yaml:",omitempty" json:"aliases,omitempty"` - Ipv4Address string `mapstructure:"ipv4_address" yaml:"ipv4_address,omitempty" json:"ipv4_address,omitempty"` - Ipv6Address string `mapstructure:"ipv6_address" yaml:"ipv6_address,omitempty" json:"ipv6_address,omitempty"` -} - -// ServicePortConfig is the port configuration for a service -type ServicePortConfig struct { - Mode string `yaml:",omitempty" json:"mode,omitempty"` - Target uint32 `yaml:",omitempty" json:"target,omitempty"` - Published uint32 `yaml:",omitempty" json:"published,omitempty"` - Protocol string `yaml:",omitempty" json:"protocol,omitempty"` -} - -// ServiceVolumeConfig are references to a volume used by a service -type ServiceVolumeConfig struct { - Type string `yaml:",omitempty" json:"type,omitempty"` - Source string `yaml:",omitempty" json:"source,omitempty"` - Target string `yaml:",omitempty" json:"target,omitempty"` - ReadOnly bool `mapstructure:"read_only" yaml:"read_only,omitempty" json:"read_only,omitempty"` - Consistency string `yaml:",omitempty" json:"consistency,omitempty"` - Bind *ServiceVolumeBind `yaml:",omitempty" json:"bind,omitempty"` - Volume *ServiceVolumeVolume `yaml:",omitempty" json:"volume,omitempty"` - Tmpfs *ServiceVolumeTmpfs `yaml:",omitempty" json:"tmpfs,omitempty"` - Cluster *ServiceVolumeCluster `yaml:",omitempty" json:"cluster,omitempty"` -} - -// ServiceVolumeBind are options for a service volume of type bind -type ServiceVolumeBind struct { - Propagation string `yaml:",omitempty" json:"propagation,omitempty"` -} - -// ServiceVolumeVolume are options for a service volume of type volume -type ServiceVolumeVolume struct { - NoCopy bool `mapstructure:"nocopy" yaml:"nocopy,omitempty" json:"nocopy,omitempty"` -} - -// ServiceVolumeTmpfs are options for a service volume of type tmpfs -type ServiceVolumeTmpfs struct { - Size int64 `yaml:",omitempty" json:"size,omitempty"` -} - -// ServiceVolumeCluster are options for a service volume of type cluster. -// Deliberately left blank for future options, but unused now. -type ServiceVolumeCluster struct{} - -// FileReferenceConfig for a reference to a swarm file object -type FileReferenceConfig struct { - Source string `yaml:",omitempty" json:"source,omitempty"` - Target string `yaml:",omitempty" json:"target,omitempty"` - UID string `yaml:",omitempty" json:"uid,omitempty"` - GID string `yaml:",omitempty" json:"gid,omitempty"` - Mode *uint32 `yaml:",omitempty" json:"mode,omitempty"` -} - -// ServiceConfigObjConfig is the config obj configuration for a service -type ServiceConfigObjConfig FileReferenceConfig - -// ServiceSecretConfig is the secret configuration for a service -type ServiceSecretConfig FileReferenceConfig - -// UlimitsConfig the ulimit configuration -type UlimitsConfig struct { - Single int `yaml:",omitempty" json:"single,omitempty"` - Soft int `yaml:",omitempty" json:"soft,omitempty"` - Hard int `yaml:",omitempty" json:"hard,omitempty"` -} - -// MarshalYAML makes UlimitsConfig implement yaml.Marshaller -func (u *UlimitsConfig) MarshalYAML() (interface{}, error) { - if u.Single != 0 { - return u.Single, nil - } - // Return as a value to avoid re-entering this method and use the default implementation - return *u, nil -} - -// MarshalJSON makes UlimitsConfig implement json.Marshaller -func (u *UlimitsConfig) MarshalJSON() ([]byte, error) { - if u.Single != 0 { - return json.Marshal(u.Single) - } - // Pass as a value to avoid re-entering this method and use the default implementation - return json.Marshal(*u) -} - -// NetworkConfig for a network -type NetworkConfig struct { - Name string `yaml:",omitempty" json:"name,omitempty"` - Driver string `yaml:",omitempty" json:"driver,omitempty"` - DriverOpts map[string]string `mapstructure:"driver_opts" yaml:"driver_opts,omitempty" json:"driver_opts,omitempty"` - Ipam IPAMConfig `yaml:",omitempty" json:"ipam,omitempty"` - External External `yaml:",omitempty" json:"external,omitempty"` - Internal bool `yaml:",omitempty" json:"internal,omitempty"` - Attachable bool `yaml:",omitempty" json:"attachable,omitempty"` - Labels Labels `yaml:",omitempty" json:"labels,omitempty"` - Extras map[string]interface{} `yaml:",inline" json:"-"` -} - -// IPAMConfig for a network -type IPAMConfig struct { - Driver string `yaml:",omitempty" json:"driver,omitempty"` - Config []*IPAMPool `yaml:",omitempty" json:"config,omitempty"` -} - -// IPAMPool for a network -type IPAMPool struct { - Subnet string `yaml:",omitempty" json:"subnet,omitempty"` -} - -// VolumeConfig for a volume -type VolumeConfig struct { - Name string `yaml:",omitempty" json:"name,omitempty"` - Driver string `yaml:",omitempty" json:"driver,omitempty"` - DriverOpts map[string]string `mapstructure:"driver_opts" yaml:"driver_opts,omitempty" json:"driver_opts,omitempty"` - External External `yaml:",omitempty" json:"external,omitempty"` - Labels Labels `yaml:",omitempty" json:"labels,omitempty"` - Extras map[string]interface{} `yaml:",inline" json:"-"` - Spec *ClusterVolumeSpec `mapstructure:"x-cluster-spec" yaml:"x-cluster-spec,omitempty" json:"x-cluster-spec,omitempty"` -} - -// ClusterVolumeSpec defines all the configuration and options specific to a -// cluster (CSI) volume. -type ClusterVolumeSpec struct { - Group string `yaml:",omitempty" json:"group,omitempty"` - AccessMode *AccessMode `mapstructure:"access_mode" yaml:"access_mode,omitempty" json:"access_mode,omitempty"` - AccessibilityRequirements *TopologyRequirement `mapstructure:"accessibility_requirements" yaml:"accessibility_requirements,omitempty" json:"accessibility_requirements,omitempty"` - CapacityRange *CapacityRange `mapstructure:"capacity_range" yaml:"capacity_range,omitempty" json:"capacity_range,omitempty"` - - Secrets []VolumeSecret `yaml:",omitempty" json:"secrets,omitempty"` - - Availability string `yaml:",omitempty" json:"availability,omitempty"` -} - -// AccessMode defines the way a cluster volume is accessed by the tasks -type AccessMode struct { - Scope string `yaml:",omitempty" json:"scope,omitempty"` - Sharing string `yaml:",omitempty" json:"sharing,omitempty"` - - MountVolume *MountVolume `mapstructure:"mount_volume" yaml:"mount_volume,omitempty" json:"mount_volume,omitempty"` - BlockVolume *BlockVolume `mapstructure:"block_volume" yaml:"block_volume,omitempty" json:"block_volume,omitempty"` -} - -// MountVolume defines options for using a volume as a Mount -type MountVolume struct { - FsType string `mapstructure:"fs_type" yaml:"fs_type,omitempty" json:"fs_type,omitempty"` - MountFlags []string `mapstructure:"mount_flags" yaml:"mount_flags,omitempty" json:"mount_flags,omitempty"` -} - -// BlockVolume is deliberately empty -type BlockVolume struct{} - -// TopologyRequirement defines the requirements for volume placement in the -// cluster. -type TopologyRequirement struct { - Requisite []Topology `yaml:",omitempty" json:"requisite,omitempty"` - Preferred []Topology `yaml:",omitempty" json:"preferred,omitempty"` -} - -// Topology defines a particular topology group -type Topology struct { - Segments Mapping `yaml:",omitempty" json:"segments,omitempty"` -} - -// CapacityRange defines the minimum and maximum size of a volume. -type CapacityRange struct { - RequiredBytes UnitBytes `mapstructure:"required_bytes" yaml:"required_bytes,omitempty" json:"required_bytes,omitempty"` - LimitBytes UnitBytes `mapstructure:"limit_bytes" yaml:"limit_bytes,omitempty" json:"limit_bytes,omitempty"` -} - -// VolumeSecret defines a secret that needs to be passed to the CSI plugin when -// using the volume. -type VolumeSecret struct { - Key string `yaml:",omitempty" json:"key,omitempty"` - Secret string `yaml:",omitempty" json:"secret,omitempty"` -} - -// External identifies a Volume or Network as a reference to a resource that is -// not managed, and should already exist. -// External.name is deprecated and replaced by Volume.name -type External struct { - Name string `yaml:",omitempty" json:"name,omitempty"` - External bool `yaml:",omitempty" json:"external,omitempty"` -} - -// MarshalYAML makes External implement yaml.Marshaller -func (e External) MarshalYAML() (interface{}, error) { - if e.Name == "" { - return e.External, nil - } - return External{Name: e.Name}, nil -} - -// MarshalJSON makes External implement json.Marshaller -func (e External) MarshalJSON() ([]byte, error) { - if e.Name == "" { - return []byte(fmt.Sprintf("%v", e.External)), nil - } - return []byte(fmt.Sprintf(`{"name": %q}`, e.Name)), nil -} - -// CredentialSpecConfig for credential spec on Windows -type CredentialSpecConfig struct { - Config string `yaml:",omitempty" json:"config,omitempty"` // Config was added in API v1.40 - File string `yaml:",omitempty" json:"file,omitempty"` - Registry string `yaml:",omitempty" json:"registry,omitempty"` -} - -// FileObjectConfig is a config type for a file used by a service -type FileObjectConfig struct { - Name string `yaml:",omitempty" json:"name,omitempty"` - File string `yaml:",omitempty" json:"file,omitempty"` - External External `yaml:",omitempty" json:"external,omitempty"` - Labels Labels `yaml:",omitempty" json:"labels,omitempty"` - Extras map[string]interface{} `yaml:",inline" json:"-"` - Driver string `yaml:",omitempty" json:"driver,omitempty"` - DriverOpts map[string]string `mapstructure:"driver_opts" yaml:"driver_opts,omitempty" json:"driver_opts,omitempty"` - TemplateDriver string `mapstructure:"template_driver" yaml:"template_driver,omitempty" json:"template_driver,omitempty"` -} - -// SecretConfig for a secret -type SecretConfig FileObjectConfig - -// ConfigObjConfig is the config for the swarm "Config" object -type ConfigObjConfig FileObjectConfig diff --git a/vendor/github.com/docker/cli/cli/config/config.go b/vendor/github.com/docker/cli/cli/config/config.go deleted file mode 100644 index b7c05c3f8..000000000 --- a/vendor/github.com/docker/cli/cli/config/config.go +++ /dev/null @@ -1,153 +0,0 @@ -package config - -import ( - "fmt" - "io" - "os" - "path/filepath" - "strings" - "sync" - - "github.com/docker/cli/cli/config/configfile" - "github.com/docker/cli/cli/config/credentials" - "github.com/docker/cli/cli/config/types" - "github.com/docker/docker/pkg/homedir" - "github.com/pkg/errors" -) - -const ( - // ConfigFileName is the name of config file - ConfigFileName = "config.json" - configFileDir = ".docker" - oldConfigfile = ".dockercfg" // Deprecated: remove once we stop printing deprecation warning - contextsDir = "contexts" -) - -var ( - initConfigDir = new(sync.Once) - configDir string - homeDir string -) - -// resetHomeDir is used in testing to reset the "homeDir" package variable to -// force re-lookup of the home directory between tests. -func resetHomeDir() { - homeDir = "" -} - -func getHomeDir() string { - if homeDir == "" { - homeDir = homedir.Get() - } - return homeDir -} - -// resetConfigDir is used in testing to reset the "configDir" package variable -// and its sync.Once to force re-lookup between tests. -func resetConfigDir() { - configDir = "" - initConfigDir = new(sync.Once) -} - -func setConfigDir() { - if configDir != "" { - return - } - configDir = os.Getenv("DOCKER_CONFIG") - if configDir == "" { - configDir = filepath.Join(getHomeDir(), configFileDir) - } -} - -// Dir returns the directory the configuration file is stored in -func Dir() string { - initConfigDir.Do(setConfigDir) - return configDir -} - -// ContextStoreDir returns the directory the docker contexts are stored in -func ContextStoreDir() string { - return filepath.Join(Dir(), contextsDir) -} - -// SetDir sets the directory the configuration file is stored in -func SetDir(dir string) { - configDir = filepath.Clean(dir) -} - -// Path returns the path to a file relative to the config dir -func Path(p ...string) (string, error) { - path := filepath.Join(append([]string{Dir()}, p...)...) - if !strings.HasPrefix(path, Dir()+string(filepath.Separator)) { - return "", errors.Errorf("path %q is outside of root config directory %q", path, Dir()) - } - return path, nil -} - -// LoadFromReader is a convenience function that creates a ConfigFile object from -// a reader -func LoadFromReader(configData io.Reader) (*configfile.ConfigFile, error) { - configFile := configfile.ConfigFile{ - AuthConfigs: make(map[string]types.AuthConfig), - } - err := configFile.LoadFromReader(configData) - return &configFile, err -} - -// Load reads the configuration files in the given directory, and sets up -// the auth config information and returns values. -// FIXME: use the internal golang config parser -func Load(configDir string) (*configfile.ConfigFile, error) { - cfg, _, err := load(configDir) - return cfg, err -} - -// TODO remove this temporary hack, which is used to warn about the deprecated ~/.dockercfg file -// so we can remove the bool return value and collapse this back into `Load` -func load(configDir string) (*configfile.ConfigFile, bool, error) { - printLegacyFileWarning := false - - if configDir == "" { - configDir = Dir() - } - - filename := filepath.Join(configDir, ConfigFileName) - configFile := configfile.New(filename) - - // Try happy path first - latest config file - if file, err := os.Open(filename); err == nil { - defer file.Close() - err = configFile.LoadFromReader(file) - if err != nil { - err = errors.Wrap(err, filename) - } - return configFile, printLegacyFileWarning, err - } else if !os.IsNotExist(err) { - // if file is there but we can't stat it for any reason other - // than it doesn't exist then stop - return configFile, printLegacyFileWarning, errors.Wrap(err, filename) - } - - // Can't find latest config file so check for the old one - filename = filepath.Join(getHomeDir(), oldConfigfile) - if _, err := os.Stat(filename); err == nil { - printLegacyFileWarning = true - } - return configFile, printLegacyFileWarning, nil -} - -// LoadDefaultConfigFile attempts to load the default config file and returns -// an initialized ConfigFile struct if none is found. -func LoadDefaultConfigFile(stderr io.Writer) *configfile.ConfigFile { - configFile, printLegacyFileWarning, err := load(Dir()) - if err != nil { - fmt.Fprintf(stderr, "WARNING: Error loading config file: %v\n", err) - } - if printLegacyFileWarning { - _, _ = fmt.Fprintln(stderr, "WARNING: Support for the legacy ~/.dockercfg configuration file and file-format has been removed and the configuration file will be ignored") - } - if !configFile.ContainsAuth() { - configFile.CredentialsStore = credentials.DetectDefaultStore(configFile.CredentialsStore) - } - return configFile -} diff --git a/vendor/github.com/docker/cli/cli/config/configfile/file.go b/vendor/github.com/docker/cli/cli/config/configfile/file.go deleted file mode 100644 index 442c31110..000000000 --- a/vendor/github.com/docker/cli/cli/config/configfile/file.go +++ /dev/null @@ -1,352 +0,0 @@ -package configfile - -import ( - "encoding/base64" - "encoding/json" - "io" - "os" - "path/filepath" - "strings" - - "github.com/docker/cli/cli/config/credentials" - "github.com/docker/cli/cli/config/types" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" -) - -// ConfigFile ~/.docker/config.json file info -type ConfigFile struct { - AuthConfigs map[string]types.AuthConfig `json:"auths"` - HTTPHeaders map[string]string `json:"HttpHeaders,omitempty"` - PsFormat string `json:"psFormat,omitempty"` - ImagesFormat string `json:"imagesFormat,omitempty"` - NetworksFormat string `json:"networksFormat,omitempty"` - PluginsFormat string `json:"pluginsFormat,omitempty"` - VolumesFormat string `json:"volumesFormat,omitempty"` - StatsFormat string `json:"statsFormat,omitempty"` - DetachKeys string `json:"detachKeys,omitempty"` - CredentialsStore string `json:"credsStore,omitempty"` - CredentialHelpers map[string]string `json:"credHelpers,omitempty"` - Filename string `json:"-"` // Note: for internal use only - ServiceInspectFormat string `json:"serviceInspectFormat,omitempty"` - ServicesFormat string `json:"servicesFormat,omitempty"` - TasksFormat string `json:"tasksFormat,omitempty"` - SecretFormat string `json:"secretFormat,omitempty"` - ConfigFormat string `json:"configFormat,omitempty"` - NodesFormat string `json:"nodesFormat,omitempty"` - PruneFilters []string `json:"pruneFilters,omitempty"` - Proxies map[string]ProxyConfig `json:"proxies,omitempty"` - Experimental string `json:"experimental,omitempty"` - CurrentContext string `json:"currentContext,omitempty"` - CLIPluginsExtraDirs []string `json:"cliPluginsExtraDirs,omitempty"` - Plugins map[string]map[string]string `json:"plugins,omitempty"` - Aliases map[string]string `json:"aliases,omitempty"` -} - -// ProxyConfig contains proxy configuration settings -type ProxyConfig struct { - HTTPProxy string `json:"httpProxy,omitempty"` - HTTPSProxy string `json:"httpsProxy,omitempty"` - NoProxy string `json:"noProxy,omitempty"` - FTPProxy string `json:"ftpProxy,omitempty"` - AllProxy string `json:"allProxy,omitempty"` -} - -// New initializes an empty configuration file for the given filename 'fn' -func New(fn string) *ConfigFile { - return &ConfigFile{ - AuthConfigs: make(map[string]types.AuthConfig), - HTTPHeaders: make(map[string]string), - Filename: fn, - Plugins: make(map[string]map[string]string), - Aliases: make(map[string]string), - } -} - -// LoadFromReader reads the configuration data given and sets up the auth config -// information with given directory and populates the receiver object -func (configFile *ConfigFile) LoadFromReader(configData io.Reader) error { - if err := json.NewDecoder(configData).Decode(configFile); err != nil && !errors.Is(err, io.EOF) { - return err - } - var err error - for addr, ac := range configFile.AuthConfigs { - if ac.Auth != "" { - ac.Username, ac.Password, err = decodeAuth(ac.Auth) - if err != nil { - return err - } - } - ac.Auth = "" - ac.ServerAddress = addr - configFile.AuthConfigs[addr] = ac - } - return nil -} - -// ContainsAuth returns whether there is authentication configured -// in this file or not. -func (configFile *ConfigFile) ContainsAuth() bool { - return configFile.CredentialsStore != "" || - len(configFile.CredentialHelpers) > 0 || - len(configFile.AuthConfigs) > 0 -} - -// GetAuthConfigs returns the mapping of repo to auth configuration -func (configFile *ConfigFile) GetAuthConfigs() map[string]types.AuthConfig { - if configFile.AuthConfigs == nil { - configFile.AuthConfigs = make(map[string]types.AuthConfig) - } - return configFile.AuthConfigs -} - -// SaveToWriter encodes and writes out all the authorization information to -// the given writer -func (configFile *ConfigFile) SaveToWriter(writer io.Writer) error { - // Encode sensitive data into a new/temp struct - tmpAuthConfigs := make(map[string]types.AuthConfig, len(configFile.AuthConfigs)) - for k, authConfig := range configFile.AuthConfigs { - authCopy := authConfig - // encode and save the authstring, while blanking out the original fields - authCopy.Auth = encodeAuth(&authCopy) - authCopy.Username = "" - authCopy.Password = "" - authCopy.ServerAddress = "" - tmpAuthConfigs[k] = authCopy - } - - saveAuthConfigs := configFile.AuthConfigs - configFile.AuthConfigs = tmpAuthConfigs - defer func() { configFile.AuthConfigs = saveAuthConfigs }() - - // User-Agent header is automatically set, and should not be stored in the configuration - for v := range configFile.HTTPHeaders { - if strings.EqualFold(v, "User-Agent") { - delete(configFile.HTTPHeaders, v) - } - } - - data, err := json.MarshalIndent(configFile, "", "\t") - if err != nil { - return err - } - _, err = writer.Write(data) - return err -} - -// Save encodes and writes out all the authorization information -func (configFile *ConfigFile) Save() (retErr error) { - if configFile.Filename == "" { - return errors.Errorf("Can't save config with empty filename") - } - - dir := filepath.Dir(configFile.Filename) - if err := os.MkdirAll(dir, 0o700); err != nil { - return err - } - temp, err := os.CreateTemp(dir, filepath.Base(configFile.Filename)) - if err != nil { - return err - } - defer func() { - temp.Close() - if retErr != nil { - if err := os.Remove(temp.Name()); err != nil { - logrus.WithError(err).WithField("file", temp.Name()).Debug("Error cleaning up temp file") - } - } - }() - - err = configFile.SaveToWriter(temp) - if err != nil { - return err - } - - if err := temp.Close(); err != nil { - return errors.Wrap(err, "error closing temp file") - } - - // Handle situation where the configfile is a symlink - cfgFile := configFile.Filename - if f, err := os.Readlink(cfgFile); err == nil { - cfgFile = f - } - - // Try copying the current config file (if any) ownership and permissions - copyFilePermissions(cfgFile, temp.Name()) - return os.Rename(temp.Name(), cfgFile) -} - -// ParseProxyConfig computes proxy configuration by retrieving the config for the provided host and -// then checking this against any environment variables provided to the container -func (configFile *ConfigFile) ParseProxyConfig(host string, runOpts map[string]*string) map[string]*string { - var cfgKey string - - if _, ok := configFile.Proxies[host]; !ok { - cfgKey = "default" - } else { - cfgKey = host - } - - config := configFile.Proxies[cfgKey] - permitted := map[string]*string{ - "HTTP_PROXY": &config.HTTPProxy, - "HTTPS_PROXY": &config.HTTPSProxy, - "NO_PROXY": &config.NoProxy, - "FTP_PROXY": &config.FTPProxy, - "ALL_PROXY": &config.AllProxy, - } - m := runOpts - if m == nil { - m = make(map[string]*string) - } - for k := range permitted { - if *permitted[k] == "" { - continue - } - if _, ok := m[k]; !ok { - m[k] = permitted[k] - } - if _, ok := m[strings.ToLower(k)]; !ok { - m[strings.ToLower(k)] = permitted[k] - } - } - return m -} - -// encodeAuth creates a base64 encoded string to containing authorization information -func encodeAuth(authConfig *types.AuthConfig) string { - if authConfig.Username == "" && authConfig.Password == "" { - return "" - } - - authStr := authConfig.Username + ":" + authConfig.Password - msg := []byte(authStr) - encoded := make([]byte, base64.StdEncoding.EncodedLen(len(msg))) - base64.StdEncoding.Encode(encoded, msg) - return string(encoded) -} - -// decodeAuth decodes a base64 encoded string and returns username and password -func decodeAuth(authStr string) (string, string, error) { - if authStr == "" { - return "", "", nil - } - - decLen := base64.StdEncoding.DecodedLen(len(authStr)) - decoded := make([]byte, decLen) - authByte := []byte(authStr) - n, err := base64.StdEncoding.Decode(decoded, authByte) - if err != nil { - return "", "", err - } - if n > decLen { - return "", "", errors.Errorf("Something went wrong decoding auth config") - } - userName, password, ok := strings.Cut(string(decoded), ":") - if !ok || userName == "" { - return "", "", errors.Errorf("Invalid auth configuration file") - } - return userName, strings.Trim(password, "\x00"), nil -} - -// GetCredentialsStore returns a new credentials store from the settings in the -// configuration file -func (configFile *ConfigFile) GetCredentialsStore(registryHostname string) credentials.Store { - if helper := getConfiguredCredentialStore(configFile, registryHostname); helper != "" { - return newNativeStore(configFile, helper) - } - return credentials.NewFileStore(configFile) -} - -// var for unit testing. -var newNativeStore = func(configFile *ConfigFile, helperSuffix string) credentials.Store { - return credentials.NewNativeStore(configFile, helperSuffix) -} - -// GetAuthConfig for a repository from the credential store -func (configFile *ConfigFile) GetAuthConfig(registryHostname string) (types.AuthConfig, error) { - return configFile.GetCredentialsStore(registryHostname).Get(registryHostname) -} - -// getConfiguredCredentialStore returns the credential helper configured for the -// given registry, the default credsStore, or the empty string if neither are -// configured. -func getConfiguredCredentialStore(c *ConfigFile, registryHostname string) string { - if c.CredentialHelpers != nil && registryHostname != "" { - if helper, exists := c.CredentialHelpers[registryHostname]; exists { - return helper - } - } - return c.CredentialsStore -} - -// GetAllCredentials returns all of the credentials stored in all of the -// configured credential stores. -func (configFile *ConfigFile) GetAllCredentials() (map[string]types.AuthConfig, error) { - auths := make(map[string]types.AuthConfig) - addAll := func(from map[string]types.AuthConfig) { - for reg, ac := range from { - auths[reg] = ac - } - } - - defaultStore := configFile.GetCredentialsStore("") - newAuths, err := defaultStore.GetAll() - if err != nil { - return nil, err - } - addAll(newAuths) - - // Auth configs from a registry-specific helper should override those from the default store. - for registryHostname := range configFile.CredentialHelpers { - newAuth, err := configFile.GetAuthConfig(registryHostname) - if err != nil { - logrus.WithError(err).Warnf("Failed to get credentials for registry: %s", registryHostname) - continue - } - auths[registryHostname] = newAuth - } - return auths, nil -} - -// GetFilename returns the file name that this config file is based on. -func (configFile *ConfigFile) GetFilename() string { - return configFile.Filename -} - -// PluginConfig retrieves the requested option for the given plugin. -func (configFile *ConfigFile) PluginConfig(pluginname, option string) (string, bool) { - if configFile.Plugins == nil { - return "", false - } - pluginConfig, ok := configFile.Plugins[pluginname] - if !ok { - return "", false - } - value, ok := pluginConfig[option] - return value, ok -} - -// SetPluginConfig sets the option to the given value for the given -// plugin. Passing a value of "" will remove the option. If removing -// the final config item for a given plugin then also cleans up the -// overall plugin entry. -func (configFile *ConfigFile) SetPluginConfig(pluginname, option, value string) { - if configFile.Plugins == nil { - configFile.Plugins = make(map[string]map[string]string) - } - pluginConfig, ok := configFile.Plugins[pluginname] - if !ok { - pluginConfig = make(map[string]string) - configFile.Plugins[pluginname] = pluginConfig - } - if value != "" { - pluginConfig[option] = value - } else { - delete(pluginConfig, option) - } - if len(pluginConfig) == 0 { - delete(configFile.Plugins, pluginname) - } -} diff --git a/vendor/github.com/docker/cli/cli/config/configfile/file_unix.go b/vendor/github.com/docker/cli/cli/config/configfile/file_unix.go deleted file mode 100644 index 353887547..000000000 --- a/vendor/github.com/docker/cli/cli/config/configfile/file_unix.go +++ /dev/null @@ -1,36 +0,0 @@ -//go:build !windows -// +build !windows - -package configfile - -import ( - "os" - "syscall" -) - -// copyFilePermissions copies file ownership and permissions from "src" to "dst", -// ignoring any error during the process. -func copyFilePermissions(src, dst string) { - var ( - mode os.FileMode = 0o600 - uid, gid int - ) - - fi, err := os.Stat(src) - if err != nil { - return - } - if fi.Mode().IsRegular() { - mode = fi.Mode() - } - if err := os.Chmod(dst, mode); err != nil { - return - } - - uid = int(fi.Sys().(*syscall.Stat_t).Uid) - gid = int(fi.Sys().(*syscall.Stat_t).Gid) - - if uid > 0 && gid > 0 { - _ = os.Chown(dst, uid, gid) - } -} diff --git a/vendor/github.com/docker/cli/cli/config/configfile/file_windows.go b/vendor/github.com/docker/cli/cli/config/configfile/file_windows.go deleted file mode 100644 index 42fffc39a..000000000 --- a/vendor/github.com/docker/cli/cli/config/configfile/file_windows.go +++ /dev/null @@ -1,5 +0,0 @@ -package configfile - -func copyFilePermissions(src, dst string) { - // TODO implement for Windows -} diff --git a/vendor/github.com/docker/cli/cli/config/credentials/credentials.go b/vendor/github.com/docker/cli/cli/config/credentials/credentials.go deleted file mode 100644 index 28d58ec48..000000000 --- a/vendor/github.com/docker/cli/cli/config/credentials/credentials.go +++ /dev/null @@ -1,17 +0,0 @@ -package credentials - -import ( - "github.com/docker/cli/cli/config/types" -) - -// Store is the interface that any credentials store must implement. -type Store interface { - // Erase removes credentials from the store for a given server. - Erase(serverAddress string) error - // Get retrieves credentials from the store for a given server. - Get(serverAddress string) (types.AuthConfig, error) - // GetAll retrieves all the credentials from the store. - GetAll() (map[string]types.AuthConfig, error) - // Store saves credentials in the store. - Store(authConfig types.AuthConfig) error -} diff --git a/vendor/github.com/docker/cli/cli/config/credentials/default_store.go b/vendor/github.com/docker/cli/cli/config/credentials/default_store.go deleted file mode 100644 index 402235bff..000000000 --- a/vendor/github.com/docker/cli/cli/config/credentials/default_store.go +++ /dev/null @@ -1,21 +0,0 @@ -package credentials - -import ( - exec "golang.org/x/sys/execabs" -) - -// DetectDefaultStore return the default credentials store for the platform if -// the store executable is available. -func DetectDefaultStore(store string) string { - platformDefault := defaultCredentialsStore() - - // user defined or no default for platform - if store != "" || platformDefault == "" { - return store - } - - if _, err := exec.LookPath(remoteCredentialsPrefix + platformDefault); err == nil { - return platformDefault - } - return "" -} diff --git a/vendor/github.com/docker/cli/cli/config/credentials/default_store_darwin.go b/vendor/github.com/docker/cli/cli/config/credentials/default_store_darwin.go deleted file mode 100644 index 5d42dec62..000000000 --- a/vendor/github.com/docker/cli/cli/config/credentials/default_store_darwin.go +++ /dev/null @@ -1,5 +0,0 @@ -package credentials - -func defaultCredentialsStore() string { - return "osxkeychain" -} diff --git a/vendor/github.com/docker/cli/cli/config/credentials/default_store_linux.go b/vendor/github.com/docker/cli/cli/config/credentials/default_store_linux.go deleted file mode 100644 index a9012c6d4..000000000 --- a/vendor/github.com/docker/cli/cli/config/credentials/default_store_linux.go +++ /dev/null @@ -1,13 +0,0 @@ -package credentials - -import ( - "os/exec" -) - -func defaultCredentialsStore() string { - if _, err := exec.LookPath("pass"); err == nil { - return "pass" - } - - return "secretservice" -} diff --git a/vendor/github.com/docker/cli/cli/config/credentials/default_store_unsupported.go b/vendor/github.com/docker/cli/cli/config/credentials/default_store_unsupported.go deleted file mode 100644 index c9630ea51..000000000 --- a/vendor/github.com/docker/cli/cli/config/credentials/default_store_unsupported.go +++ /dev/null @@ -1,8 +0,0 @@ -//go:build !windows && !darwin && !linux -// +build !windows,!darwin,!linux - -package credentials - -func defaultCredentialsStore() string { - return "" -} diff --git a/vendor/github.com/docker/cli/cli/config/credentials/default_store_windows.go b/vendor/github.com/docker/cli/cli/config/credentials/default_store_windows.go deleted file mode 100644 index bb799ca61..000000000 --- a/vendor/github.com/docker/cli/cli/config/credentials/default_store_windows.go +++ /dev/null @@ -1,5 +0,0 @@ -package credentials - -func defaultCredentialsStore() string { - return "wincred" -} diff --git a/vendor/github.com/docker/cli/cli/config/credentials/file_store.go b/vendor/github.com/docker/cli/cli/config/credentials/file_store.go deleted file mode 100644 index ea30fc300..000000000 --- a/vendor/github.com/docker/cli/cli/config/credentials/file_store.go +++ /dev/null @@ -1,81 +0,0 @@ -package credentials - -import ( - "strings" - - "github.com/docker/cli/cli/config/types" -) - -type store interface { - Save() error - GetAuthConfigs() map[string]types.AuthConfig - GetFilename() string -} - -// fileStore implements a credentials store using -// the docker configuration file to keep the credentials in plain text. -type fileStore struct { - file store -} - -// NewFileStore creates a new file credentials store. -func NewFileStore(file store) Store { - return &fileStore{file: file} -} - -// Erase removes the given credentials from the file store. -func (c *fileStore) Erase(serverAddress string) error { - delete(c.file.GetAuthConfigs(), serverAddress) - return c.file.Save() -} - -// Get retrieves credentials for a specific server from the file store. -func (c *fileStore) Get(serverAddress string) (types.AuthConfig, error) { - authConfig, ok := c.file.GetAuthConfigs()[serverAddress] - if !ok { - // Maybe they have a legacy config file, we will iterate the keys converting - // them to the new format and testing - for r, ac := range c.file.GetAuthConfigs() { - if serverAddress == ConvertToHostname(r) { - return ac, nil - } - } - - authConfig = types.AuthConfig{} - } - return authConfig, nil -} - -func (c *fileStore) GetAll() (map[string]types.AuthConfig, error) { - return c.file.GetAuthConfigs(), nil -} - -// Store saves the given credentials in the file store. -func (c *fileStore) Store(authConfig types.AuthConfig) error { - authConfigs := c.file.GetAuthConfigs() - authConfigs[authConfig.ServerAddress] = authConfig - return c.file.Save() -} - -func (c *fileStore) GetFilename() string { - return c.file.GetFilename() -} - -func (c *fileStore) IsFileStore() bool { - return true -} - -// ConvertToHostname converts a registry url which has http|https prepended -// to just an hostname. -// Copied from github.com/docker/docker/registry.ConvertToHostname to reduce dependencies. -func ConvertToHostname(url string) string { - stripped := url - if strings.HasPrefix(url, "http://") { - stripped = strings.TrimPrefix(url, "http://") - } else if strings.HasPrefix(url, "https://") { - stripped = strings.TrimPrefix(url, "https://") - } - - hostName, _, _ := strings.Cut(stripped, "/") - return hostName -} diff --git a/vendor/github.com/docker/cli/cli/config/credentials/native_store.go b/vendor/github.com/docker/cli/cli/config/credentials/native_store.go deleted file mode 100644 index f9619b038..000000000 --- a/vendor/github.com/docker/cli/cli/config/credentials/native_store.go +++ /dev/null @@ -1,143 +0,0 @@ -package credentials - -import ( - "github.com/docker/cli/cli/config/types" - "github.com/docker/docker-credential-helpers/client" - "github.com/docker/docker-credential-helpers/credentials" -) - -const ( - remoteCredentialsPrefix = "docker-credential-" //nolint:gosec // ignore G101: Potential hardcoded credentials - tokenUsername = "" -) - -// nativeStore implements a credentials store -// using native keychain to keep credentials secure. -// It piggybacks into a file store to keep users' emails. -type nativeStore struct { - programFunc client.ProgramFunc - fileStore Store -} - -// NewNativeStore creates a new native store that -// uses a remote helper program to manage credentials. -func NewNativeStore(file store, helperSuffix string) Store { - name := remoteCredentialsPrefix + helperSuffix - return &nativeStore{ - programFunc: client.NewShellProgramFunc(name), - fileStore: NewFileStore(file), - } -} - -// Erase removes the given credentials from the native store. -func (c *nativeStore) Erase(serverAddress string) error { - if err := client.Erase(c.programFunc, serverAddress); err != nil { - return err - } - - // Fallback to plain text store to remove email - return c.fileStore.Erase(serverAddress) -} - -// Get retrieves credentials for a specific server from the native store. -func (c *nativeStore) Get(serverAddress string) (types.AuthConfig, error) { - // load user email if it exist or an empty auth config. - auth, _ := c.fileStore.Get(serverAddress) - - creds, err := c.getCredentialsFromStore(serverAddress) - if err != nil { - return auth, err - } - auth.Username = creds.Username - auth.IdentityToken = creds.IdentityToken - auth.Password = creds.Password - - return auth, nil -} - -// GetAll retrieves all the credentials from the native store. -func (c *nativeStore) GetAll() (map[string]types.AuthConfig, error) { - auths, err := c.listCredentialsInStore() - if err != nil { - return nil, err - } - - // Emails are only stored in the file store. - // This call can be safely eliminated when emails are removed. - fileConfigs, _ := c.fileStore.GetAll() - - authConfigs := make(map[string]types.AuthConfig) - for registry := range auths { - creds, err := c.getCredentialsFromStore(registry) - if err != nil { - return nil, err - } - ac := fileConfigs[registry] // might contain Email - ac.Username = creds.Username - ac.Password = creds.Password - ac.IdentityToken = creds.IdentityToken - authConfigs[registry] = ac - } - - return authConfigs, nil -} - -// Store saves the given credentials in the file store. -func (c *nativeStore) Store(authConfig types.AuthConfig) error { - if err := c.storeCredentialsInStore(authConfig); err != nil { - return err - } - authConfig.Username = "" - authConfig.Password = "" - authConfig.IdentityToken = "" - - // Fallback to old credential in plain text to save only the email - return c.fileStore.Store(authConfig) -} - -// storeCredentialsInStore executes the command to store the credentials in the native store. -func (c *nativeStore) storeCredentialsInStore(config types.AuthConfig) error { - creds := &credentials.Credentials{ - ServerURL: config.ServerAddress, - Username: config.Username, - Secret: config.Password, - } - - if config.IdentityToken != "" { - creds.Username = tokenUsername - creds.Secret = config.IdentityToken - } - - return client.Store(c.programFunc, creds) -} - -// getCredentialsFromStore executes the command to get the credentials from the native store. -func (c *nativeStore) getCredentialsFromStore(serverAddress string) (types.AuthConfig, error) { - var ret types.AuthConfig - - creds, err := client.Get(c.programFunc, serverAddress) - if err != nil { - if credentials.IsErrCredentialsNotFound(err) { - // do not return an error if the credentials are not - // in the keychain. Let docker ask for new credentials. - return ret, nil - } - return ret, err - } - - if creds.Username == tokenUsername { - ret.IdentityToken = creds.Secret - } else { - ret.Password = creds.Secret - ret.Username = creds.Username - } - - ret.ServerAddress = serverAddress - return ret, nil -} - -// listCredentialsInStore returns a listing of stored credentials as a map of -// URL -> username. -func (c *nativeStore) listCredentialsInStore() (map[string]string, error) { - return client.List(c.programFunc) -} diff --git a/vendor/github.com/docker/cli/cli/config/types/authconfig.go b/vendor/github.com/docker/cli/cli/config/types/authconfig.go deleted file mode 100644 index 056af6b84..000000000 --- a/vendor/github.com/docker/cli/cli/config/types/authconfig.go +++ /dev/null @@ -1,22 +0,0 @@ -package types - -// AuthConfig contains authorization information for connecting to a Registry -type AuthConfig struct { - Username string `json:"username,omitempty"` - Password string `json:"password,omitempty"` - Auth string `json:"auth,omitempty"` - - // Email is an optional value associated with the username. - // This field is deprecated and will be removed in a later - // version of docker. - Email string `json:"email,omitempty"` - - ServerAddress string `json:"serveraddress,omitempty"` - - // IdentityToken is used to authenticate the user and get - // an access token for the registry. - IdentityToken string `json:"identitytoken,omitempty"` - - // RegistryToken is a bearer token to be sent to a registry - RegistryToken string `json:"registrytoken,omitempty"` -} diff --git a/vendor/github.com/docker/cli/cli/connhelper/commandconn/commandconn.go b/vendor/github.com/docker/cli/cli/connhelper/commandconn/commandconn.go deleted file mode 100644 index 835c4c48d..000000000 --- a/vendor/github.com/docker/cli/cli/connhelper/commandconn/commandconn.go +++ /dev/null @@ -1,289 +0,0 @@ -// Package commandconn provides a net.Conn implementation that can be used for -// proxying (or emulating) stream via a custom command. -// -// For example, to provide an http.Client that can connect to a Docker daemon -// running in a Docker container ("DIND"): -// -// httpClient := &http.Client{ -// Transport: &http.Transport{ -// DialContext: func(ctx context.Context, _network, _addr string) (net.Conn, error) { -// return commandconn.New(ctx, "docker", "exec", "-it", containerID, "docker", "system", "dial-stdio") -// }, -// }, -// } -package commandconn - -import ( - "bytes" - "context" - "fmt" - "io" - "net" - "os" - "runtime" - "strings" - "sync" - "sync/atomic" - "syscall" - "time" - - "github.com/pkg/errors" - "github.com/sirupsen/logrus" - exec "golang.org/x/sys/execabs" -) - -// New returns net.Conn -func New(_ context.Context, cmd string, args ...string) (net.Conn, error) { - var ( - c commandConn - err error - ) - c.cmd = exec.Command(cmd, args...) - // we assume that args never contains sensitive information - logrus.Debugf("commandconn: starting %s with %v", cmd, args) - c.cmd.Env = os.Environ() - c.cmd.SysProcAttr = &syscall.SysProcAttr{} - setPdeathsig(c.cmd) - createSession(c.cmd) - c.stdin, err = c.cmd.StdinPipe() - if err != nil { - return nil, err - } - c.stdout, err = c.cmd.StdoutPipe() - if err != nil { - return nil, err - } - c.cmd.Stderr = &stderrWriter{ - stderrMu: &c.stderrMu, - stderr: &c.stderr, - debugPrefix: fmt.Sprintf("commandconn (%s):", cmd), - } - c.localAddr = dummyAddr{network: "dummy", s: "dummy-0"} - c.remoteAddr = dummyAddr{network: "dummy", s: "dummy-1"} - return &c, c.cmd.Start() -} - -// commandConn implements net.Conn -type commandConn struct { - cmdMutex sync.Mutex // for cmd, cmdWaitErr - cmd *exec.Cmd - cmdWaitErr error - cmdExited atomic.Bool - stdin io.WriteCloser - stdout io.ReadCloser - stderrMu sync.Mutex // for stderr - stderr bytes.Buffer - stdinClosed atomic.Bool - stdoutClosed atomic.Bool - closing atomic.Bool - localAddr net.Addr - remoteAddr net.Addr -} - -// kill terminates the process. On Windows it kills the process directly, -// whereas on other platforms, a SIGTERM is sent, before forcefully terminating -// the process after 3 seconds. -func (c *commandConn) kill() { - if c.cmdExited.Load() { - return - } - c.cmdMutex.Lock() - var werr error - if runtime.GOOS != "windows" { - werrCh := make(chan error) - go func() { werrCh <- c.cmd.Wait() }() - _ = c.cmd.Process.Signal(syscall.SIGTERM) - select { - case werr = <-werrCh: - case <-time.After(3 * time.Second): - _ = c.cmd.Process.Kill() - werr = <-werrCh - } - } else { - _ = c.cmd.Process.Kill() - werr = c.cmd.Wait() - } - c.cmdWaitErr = werr - c.cmdMutex.Unlock() - c.cmdExited.Store(true) -} - -// handleEOF handles io.EOF errors while reading or writing from the underlying -// command pipes. -// -// When we've received an EOF we expect that the command will -// be terminated soon. As such, we call Wait() on the command -// and return EOF or the error depending on whether the command -// exited with an error. -// -// If Wait() does not return within 10s, an error is returned -func (c *commandConn) handleEOF(err error) error { - if err != io.EOF { - return err - } - - c.cmdMutex.Lock() - defer c.cmdMutex.Unlock() - - var werr error - if c.cmdExited.Load() { - werr = c.cmdWaitErr - } else { - werrCh := make(chan error) - go func() { werrCh <- c.cmd.Wait() }() - select { - case werr = <-werrCh: - c.cmdWaitErr = werr - c.cmdExited.Store(true) - case <-time.After(10 * time.Second): - c.stderrMu.Lock() - stderr := c.stderr.String() - c.stderrMu.Unlock() - return errors.Errorf("command %v did not exit after %v: stderr=%q", c.cmd.Args, err, stderr) - } - } - - if werr == nil { - return err - } - c.stderrMu.Lock() - stderr := c.stderr.String() - c.stderrMu.Unlock() - return errors.Errorf("command %v has exited with %v, please make sure the URL is valid, and Docker 18.09 or later is installed on the remote host: stderr=%s", c.cmd.Args, werr, stderr) -} - -func ignorableCloseError(err error) bool { - return strings.Contains(err.Error(), os.ErrClosed.Error()) -} - -func (c *commandConn) Read(p []byte) (int, error) { - n, err := c.stdout.Read(p) - // check after the call to Read, since - // it is blocking, and while waiting on it - // Close might get called - if c.closing.Load() { - // If we're currently closing the connection - // we don't want to call onEOF - return n, err - } - - return n, c.handleEOF(err) -} - -func (c *commandConn) Write(p []byte) (int, error) { - n, err := c.stdin.Write(p) - // check after the call to Write, since - // it is blocking, and while waiting on it - // Close might get called - if c.closing.Load() { - // If we're currently closing the connection - // we don't want to call onEOF - return n, err - } - - return n, c.handleEOF(err) -} - -// CloseRead allows commandConn to implement halfCloser -func (c *commandConn) CloseRead() error { - // NOTE: maybe already closed here - if err := c.stdout.Close(); err != nil && !ignorableCloseError(err) { - return err - } - c.stdoutClosed.Store(true) - - if c.stdinClosed.Load() { - c.kill() - } - - return nil -} - -// CloseWrite allows commandConn to implement halfCloser -func (c *commandConn) CloseWrite() error { - // NOTE: maybe already closed here - if err := c.stdin.Close(); err != nil && !ignorableCloseError(err) { - return err - } - c.stdinClosed.Store(true) - - if c.stdoutClosed.Load() { - c.kill() - } - return nil -} - -// Close is the net.Conn func that gets called -// by the transport when a dial is cancelled -// due to it's context timing out. Any blocked -// Read or Write calls will be unblocked and -// return errors. It will block until the underlying -// command has terminated. -func (c *commandConn) Close() error { - c.closing.Store(true) - defer c.closing.Store(false) - - if err := c.CloseRead(); err != nil { - logrus.Warnf("commandConn.Close: CloseRead: %v", err) - return err - } - if err := c.CloseWrite(); err != nil { - logrus.Warnf("commandConn.Close: CloseWrite: %v", err) - return err - } - - return nil -} - -func (c *commandConn) LocalAddr() net.Addr { - return c.localAddr -} - -func (c *commandConn) RemoteAddr() net.Addr { - return c.remoteAddr -} - -func (c *commandConn) SetDeadline(t time.Time) error { - logrus.Debugf("unimplemented call: SetDeadline(%v)", t) - return nil -} - -func (c *commandConn) SetReadDeadline(t time.Time) error { - logrus.Debugf("unimplemented call: SetReadDeadline(%v)", t) - return nil -} - -func (c *commandConn) SetWriteDeadline(t time.Time) error { - logrus.Debugf("unimplemented call: SetWriteDeadline(%v)", t) - return nil -} - -type dummyAddr struct { - network string - s string -} - -func (d dummyAddr) Network() string { - return d.network -} - -func (d dummyAddr) String() string { - return d.s -} - -type stderrWriter struct { - stderrMu *sync.Mutex - stderr *bytes.Buffer - debugPrefix string -} - -func (w *stderrWriter) Write(p []byte) (int, error) { - logrus.Debugf("%s%s", w.debugPrefix, string(p)) - w.stderrMu.Lock() - if w.stderr.Len() > 4096 { - w.stderr.Reset() - } - n, err := w.stderr.Write(p) - w.stderrMu.Unlock() - return n, err -} diff --git a/vendor/github.com/docker/cli/cli/connhelper/commandconn/pdeathsig_linux.go b/vendor/github.com/docker/cli/cli/connhelper/commandconn/pdeathsig_linux.go deleted file mode 100644 index 1cdd788cc..000000000 --- a/vendor/github.com/docker/cli/cli/connhelper/commandconn/pdeathsig_linux.go +++ /dev/null @@ -1,10 +0,0 @@ -package commandconn - -import ( - "os/exec" - "syscall" -) - -func setPdeathsig(cmd *exec.Cmd) { - cmd.SysProcAttr.Pdeathsig = syscall.SIGKILL -} diff --git a/vendor/github.com/docker/cli/cli/connhelper/commandconn/pdeathsig_nolinux.go b/vendor/github.com/docker/cli/cli/connhelper/commandconn/pdeathsig_nolinux.go deleted file mode 100644 index 2adcf0816..000000000 --- a/vendor/github.com/docker/cli/cli/connhelper/commandconn/pdeathsig_nolinux.go +++ /dev/null @@ -1,11 +0,0 @@ -//go:build !linux -// +build !linux - -package commandconn - -import ( - "os/exec" -) - -func setPdeathsig(cmd *exec.Cmd) { -} diff --git a/vendor/github.com/docker/cli/cli/connhelper/commandconn/session_unix.go b/vendor/github.com/docker/cli/cli/connhelper/commandconn/session_unix.go deleted file mode 100644 index 57bdecec0..000000000 --- a/vendor/github.com/docker/cli/cli/connhelper/commandconn/session_unix.go +++ /dev/null @@ -1,14 +0,0 @@ -//go:build !windows -// +build !windows - -package commandconn - -import ( - "os/exec" -) - -func createSession(cmd *exec.Cmd) { - // for supporting ssh connection helper with ProxyCommand - // https://github.com/docker/cli/issues/1707 - cmd.SysProcAttr.Setsid = true -} diff --git a/vendor/github.com/docker/cli/cli/connhelper/commandconn/session_windows.go b/vendor/github.com/docker/cli/cli/connhelper/commandconn/session_windows.go deleted file mode 100644 index b92607450..000000000 --- a/vendor/github.com/docker/cli/cli/connhelper/commandconn/session_windows.go +++ /dev/null @@ -1,8 +0,0 @@ -package commandconn - -import ( - "os/exec" -) - -func createSession(cmd *exec.Cmd) { -} diff --git a/vendor/github.com/docker/cli/cli/connhelper/connhelper.go b/vendor/github.com/docker/cli/cli/connhelper/connhelper.go deleted file mode 100644 index b98d97c25..000000000 --- a/vendor/github.com/docker/cli/cli/connhelper/connhelper.go +++ /dev/null @@ -1,82 +0,0 @@ -// Package connhelper provides helpers for connecting to a remote daemon host with custom logic. -package connhelper - -import ( - "context" - "net" - "net/url" - "strings" - - "github.com/docker/cli/cli/connhelper/commandconn" - "github.com/docker/cli/cli/connhelper/ssh" - "github.com/pkg/errors" -) - -// ConnectionHelper allows to connect to a remote host with custom stream provider binary. -type ConnectionHelper struct { - Dialer func(ctx context.Context, network, addr string) (net.Conn, error) - Host string // dummy URL used for HTTP requests. e.g. "http://docker" -} - -// GetConnectionHelper returns Docker-specific connection helper for the given URL. -// GetConnectionHelper returns nil without error when no helper is registered for the scheme. -// -// ssh://@ URL requires Docker 18.09 or later on the remote host. -func GetConnectionHelper(daemonURL string) (*ConnectionHelper, error) { - return getConnectionHelper(daemonURL, nil) -} - -// GetConnectionHelperWithSSHOpts returns Docker-specific connection helper for -// the given URL, and accepts additional options for ssh connections. It returns -// nil without error when no helper is registered for the scheme. -// -// Requires Docker 18.09 or later on the remote host. -func GetConnectionHelperWithSSHOpts(daemonURL string, sshFlags []string) (*ConnectionHelper, error) { - return getConnectionHelper(daemonURL, sshFlags) -} - -func getConnectionHelper(daemonURL string, sshFlags []string) (*ConnectionHelper, error) { - u, err := url.Parse(daemonURL) - if err != nil { - return nil, err - } - switch scheme := u.Scheme; scheme { - case "ssh": - sp, err := ssh.ParseURL(daemonURL) - if err != nil { - return nil, errors.Wrap(err, "ssh host connection is not valid") - } - return &ConnectionHelper{ - Dialer: func(ctx context.Context, network, addr string) (net.Conn, error) { - args := []string{"docker"} - if sp.Path != "" { - args = append(args, "--host", "unix://"+sp.Path) - } - sshFlags = addSSHTimeout(sshFlags) - args = append(args, "system", "dial-stdio") - return commandconn.New(ctx, "ssh", append(sshFlags, sp.Args(args...)...)...) - }, - Host: "http://docker.example.com", - }, nil - } - // Future version may support plugins via ~/.docker/config.json. e.g. "dind" - // See docker/cli#889 for the previous discussion. - return nil, err -} - -// GetCommandConnectionHelper returns Docker-specific connection helper constructed from an arbitrary command. -func GetCommandConnectionHelper(cmd string, flags ...string) (*ConnectionHelper, error) { - return &ConnectionHelper{ - Dialer: func(ctx context.Context, network, addr string) (net.Conn, error) { - return commandconn.New(ctx, cmd, flags...) - }, - Host: "http://docker.example.com", - }, nil -} - -func addSSHTimeout(sshFlags []string) []string { - if !strings.Contains(strings.Join(sshFlags, ""), "ConnectTimeout") { - sshFlags = append(sshFlags, "-o ConnectTimeout=30") - } - return sshFlags -} diff --git a/vendor/github.com/docker/cli/cli/connhelper/ssh/ssh.go b/vendor/github.com/docker/cli/cli/connhelper/ssh/ssh.go deleted file mode 100644 index fb4c91110..000000000 --- a/vendor/github.com/docker/cli/cli/connhelper/ssh/ssh.go +++ /dev/null @@ -1,63 +0,0 @@ -// Package ssh provides the connection helper for ssh:// URL. -package ssh - -import ( - "net/url" - - "github.com/pkg/errors" -) - -// ParseURL parses URL -func ParseURL(daemonURL string) (*Spec, error) { - u, err := url.Parse(daemonURL) - if err != nil { - return nil, err - } - if u.Scheme != "ssh" { - return nil, errors.Errorf("expected scheme ssh, got %q", u.Scheme) - } - - var sp Spec - - if u.User != nil { - sp.User = u.User.Username() - if _, ok := u.User.Password(); ok { - return nil, errors.New("plain-text password is not supported") - } - } - sp.Host = u.Hostname() - if sp.Host == "" { - return nil, errors.Errorf("no host specified") - } - sp.Port = u.Port() - sp.Path = u.Path - if u.RawQuery != "" { - return nil, errors.Errorf("extra query after the host: %q", u.RawQuery) - } - if u.Fragment != "" { - return nil, errors.Errorf("extra fragment after the host: %q", u.Fragment) - } - return &sp, err -} - -// Spec of SSH URL -type Spec struct { - User string - Host string - Port string - Path string -} - -// Args returns args except "ssh" itself combined with optional additional command args -func (sp *Spec) Args(add ...string) []string { - var args []string - if sp.User != "" { - args = append(args, "-l", sp.User) - } - if sp.Port != "" { - args = append(args, "-p", sp.Port) - } - args = append(args, "--", sp.Host) - args = append(args, add...) - return args -} diff --git a/vendor/github.com/docker/cli/cli/context/docker/constants.go b/vendor/github.com/docker/cli/cli/context/docker/constants.go deleted file mode 100644 index 1db5556d5..000000000 --- a/vendor/github.com/docker/cli/cli/context/docker/constants.go +++ /dev/null @@ -1,6 +0,0 @@ -package docker - -const ( - // DockerEndpoint is the name of the docker endpoint in a stored context - DockerEndpoint = "docker" -) diff --git a/vendor/github.com/docker/cli/cli/context/docker/load.go b/vendor/github.com/docker/cli/cli/context/docker/load.go deleted file mode 100644 index 76f6eaf30..000000000 --- a/vendor/github.com/docker/cli/cli/context/docker/load.go +++ /dev/null @@ -1,154 +0,0 @@ -package docker - -import ( - "crypto/tls" - "crypto/x509" - "encoding/pem" - "net" - "net/http" - "time" - - "github.com/docker/cli/cli/connhelper" - "github.com/docker/cli/cli/context" - "github.com/docker/cli/cli/context/store" - "github.com/docker/docker/client" - "github.com/docker/go-connections/tlsconfig" - "github.com/pkg/errors" -) - -// EndpointMeta is a typed wrapper around a context-store generic endpoint describing -// a Docker Engine endpoint, without its tls config -type EndpointMeta = context.EndpointMetaBase - -// Endpoint is a typed wrapper around a context-store generic endpoint describing -// a Docker Engine endpoint, with its tls data -type Endpoint struct { - EndpointMeta - TLSData *context.TLSData -} - -// WithTLSData loads TLS materials for the endpoint -func WithTLSData(s store.Reader, contextName string, m EndpointMeta) (Endpoint, error) { - tlsData, err := context.LoadTLSData(s, contextName, DockerEndpoint) - if err != nil { - return Endpoint{}, err - } - return Endpoint{ - EndpointMeta: m, - TLSData: tlsData, - }, nil -} - -// tlsConfig extracts a context docker endpoint TLS config -func (c *Endpoint) tlsConfig() (*tls.Config, error) { - if c.TLSData == nil && !c.SkipTLSVerify { - // there is no specific tls config - return nil, nil - } - var tlsOpts []func(*tls.Config) - if c.TLSData != nil && c.TLSData.CA != nil { - certPool := x509.NewCertPool() - if !certPool.AppendCertsFromPEM(c.TLSData.CA) { - return nil, errors.New("failed to retrieve context tls info: ca.pem seems invalid") - } - tlsOpts = append(tlsOpts, func(cfg *tls.Config) { - cfg.RootCAs = certPool - }) - } - if c.TLSData != nil && c.TLSData.Key != nil && c.TLSData.Cert != nil { - keyBytes := c.TLSData.Key - pemBlock, _ := pem.Decode(keyBytes) - if pemBlock == nil { - return nil, errors.New("no valid private key found") - } - if x509.IsEncryptedPEMBlock(pemBlock) { //nolint:staticcheck // SA1019: x509.IsEncryptedPEMBlock is deprecated, and insecure by design - return nil, errors.New("private key is encrypted - support for encrypted private keys has been removed, see https://docs.docker.com/go/deprecated/") - } - - x509cert, err := tls.X509KeyPair(c.TLSData.Cert, keyBytes) - if err != nil { - return nil, errors.Wrap(err, "failed to retrieve context tls info") - } - tlsOpts = append(tlsOpts, func(cfg *tls.Config) { - cfg.Certificates = []tls.Certificate{x509cert} - }) - } - if c.SkipTLSVerify { - tlsOpts = append(tlsOpts, func(cfg *tls.Config) { - cfg.InsecureSkipVerify = true - }) - } - return tlsconfig.ClientDefault(tlsOpts...), nil -} - -// ClientOpts returns a slice of Client options to configure an API client with this endpoint -func (c *Endpoint) ClientOpts() ([]client.Opt, error) { - var result []client.Opt - if c.Host != "" { - helper, err := connhelper.GetConnectionHelper(c.Host) - if err != nil { - return nil, err - } - if helper == nil { - tlsConfig, err := c.tlsConfig() - if err != nil { - return nil, err - } - result = append(result, - withHTTPClient(tlsConfig), - client.WithHost(c.Host), - ) - - } else { - httpClient := &http.Client{ - // No tls - // No proxy - Transport: &http.Transport{ - DialContext: helper.Dialer, - }, - } - result = append(result, - client.WithHTTPClient(httpClient), - client.WithHost(helper.Host), - client.WithDialContext(helper.Dialer), - ) - } - } - - result = append(result, client.WithVersionFromEnv(), client.WithAPIVersionNegotiation()) - return result, nil -} - -func withHTTPClient(tlsConfig *tls.Config) func(*client.Client) error { - return func(c *client.Client) error { - if tlsConfig == nil { - // Use the default HTTPClient - return nil - } - - httpClient := &http.Client{ - Transport: &http.Transport{ - TLSClientConfig: tlsConfig, - DialContext: (&net.Dialer{ - KeepAlive: 30 * time.Second, - Timeout: 30 * time.Second, - }).DialContext, - }, - CheckRedirect: client.CheckRedirect, - } - return client.WithHTTPClient(httpClient)(c) - } -} - -// EndpointFromContext parses a context docker endpoint metadata into a typed EndpointMeta structure -func EndpointFromContext(metadata store.Metadata) (EndpointMeta, error) { - ep, ok := metadata.Endpoints[DockerEndpoint] - if !ok { - return EndpointMeta{}, errors.New("cannot find docker endpoint in context") - } - typed, ok := ep.(EndpointMeta) - if !ok { - return EndpointMeta{}, errors.Errorf("endpoint %q is not of type EndpointMeta", DockerEndpoint) - } - return typed, nil -} diff --git a/vendor/github.com/docker/cli/cli/context/endpoint.go b/vendor/github.com/docker/cli/cli/context/endpoint.go deleted file mode 100644 index f2735246e..000000000 --- a/vendor/github.com/docker/cli/cli/context/endpoint.go +++ /dev/null @@ -1,7 +0,0 @@ -package context - -// EndpointMetaBase contains fields we expect to be common for most context endpoints -type EndpointMetaBase struct { - Host string `json:",omitempty"` - SkipTLSVerify bool -} diff --git a/vendor/github.com/docker/cli/cli/context/store/doc.go b/vendor/github.com/docker/cli/cli/context/store/doc.go deleted file mode 100644 index 705982ae4..000000000 --- a/vendor/github.com/docker/cli/cli/context/store/doc.go +++ /dev/null @@ -1,32 +0,0 @@ -// Package store provides a generic way to store credentials to connect to -// virtually any kind of remote system. -// The term `context` comes from the similar feature in Kubernetes kubectl -// config files. -// -// Conceptually, a context is a set of metadata and TLS data, that can be used -// to connect to various endpoints of a remote system. TLS data and metadata -// are stored separately, so that in the future, we will be able to store -// sensitive information in a more secure way, depending on the os we are running -// on (e.g.: on Windows we could use the user Certificate Store, on macOS the -// user Keychain...). -// -// Current implementation is purely file based with the following structure: -// -// ${CONTEXT_ROOT} -// meta/ -// /meta.json: contains context medata (key/value pairs) as -// well as a list of endpoints (themselves containing -// key/value pair metadata). -// tls/ -// /endpoint1/: directory containing TLS data for the endpoint1 -// in the corresponding context. -// -// The context store itself has absolutely no knowledge about what a docker -// endpoint should contain in term of metadata or TLS config. Client code is -// responsible for generating and parsing endpoint metadata and TLS files. The -// multi-endpoints approach of this package allows to combine many different -// endpoints in the same "context". -// -// Context IDs are actually SHA256 hashes of the context name, and are there -// only to avoid dealing with special characters in context names. -package store diff --git a/vendor/github.com/docker/cli/cli/context/store/io_utils.go b/vendor/github.com/docker/cli/cli/context/store/io_utils.go deleted file mode 100644 index 6f854c8e5..000000000 --- a/vendor/github.com/docker/cli/cli/context/store/io_utils.go +++ /dev/null @@ -1,29 +0,0 @@ -package store - -import ( - "errors" - "io" -) - -// LimitedReader is a fork of io.LimitedReader to override Read. -type LimitedReader struct { - R io.Reader - N int64 // max bytes remaining -} - -// Read is a fork of io.LimitedReader.Read that returns an error when limit exceeded. -func (l *LimitedReader) Read(p []byte) (n int, err error) { - if l.N < 0 { - return 0, errors.New("read exceeds the defined limit") - } - if l.N == 0 { - return 0, io.EOF - } - // have to cap N + 1 otherwise we won't hit limit err - if int64(len(p)) > l.N+1 { - p = p[0 : l.N+1] - } - n, err = l.R.Read(p) - l.N -= int64(n) - return n, err -} diff --git a/vendor/github.com/docker/cli/cli/context/store/metadatastore.go b/vendor/github.com/docker/cli/cli/context/store/metadatastore.go deleted file mode 100644 index 62c3f82a6..000000000 --- a/vendor/github.com/docker/cli/cli/context/store/metadatastore.go +++ /dev/null @@ -1,164 +0,0 @@ -package store - -import ( - "encoding/json" - "fmt" - "os" - "path/filepath" - "reflect" - "sort" - - "github.com/docker/docker/errdefs" - "github.com/docker/docker/pkg/ioutils" - "github.com/fvbommel/sortorder" - "github.com/pkg/errors" -) - -const ( - metadataDir = "meta" - metaFile = "meta.json" -) - -type metadataStore struct { - root string - config Config -} - -func (s *metadataStore) contextDir(id contextdir) string { - return filepath.Join(s.root, string(id)) -} - -func (s *metadataStore) createOrUpdate(meta Metadata) error { - contextDir := s.contextDir(contextdirOf(meta.Name)) - if err := os.MkdirAll(contextDir, 0o755); err != nil { - return err - } - bytes, err := json.Marshal(&meta) - if err != nil { - return err - } - return ioutils.AtomicWriteFile(filepath.Join(contextDir, metaFile), bytes, 0o644) -} - -func parseTypedOrMap(payload []byte, getter TypeGetter) (interface{}, error) { - if len(payload) == 0 || string(payload) == "null" { - return nil, nil - } - if getter == nil { - var res map[string]interface{} - if err := json.Unmarshal(payload, &res); err != nil { - return nil, err - } - return res, nil - } - typed := getter() - if err := json.Unmarshal(payload, typed); err != nil { - return nil, err - } - return reflect.ValueOf(typed).Elem().Interface(), nil -} - -func (s *metadataStore) get(name string) (Metadata, error) { - m, err := s.getByID(contextdirOf(name)) - if err != nil { - return m, errors.Wrapf(err, "context %q", name) - } - return m, nil -} - -func (s *metadataStore) getByID(id contextdir) (Metadata, error) { - fileName := filepath.Join(s.contextDir(id), metaFile) - bytes, err := os.ReadFile(fileName) - if err != nil { - if errors.Is(err, os.ErrNotExist) { - return Metadata{}, errdefs.NotFound(errors.Wrap(err, "context not found")) - } - return Metadata{}, err - } - var untyped untypedContextMetadata - r := Metadata{ - Endpoints: make(map[string]interface{}), - } - if err := json.Unmarshal(bytes, &untyped); err != nil { - return Metadata{}, fmt.Errorf("parsing %s: %v", fileName, err) - } - r.Name = untyped.Name - if r.Metadata, err = parseTypedOrMap(untyped.Metadata, s.config.contextType); err != nil { - return Metadata{}, fmt.Errorf("parsing %s: %v", fileName, err) - } - for k, v := range untyped.Endpoints { - if r.Endpoints[k], err = parseTypedOrMap(v, s.config.endpointTypes[k]); err != nil { - return Metadata{}, fmt.Errorf("parsing %s: %v", fileName, err) - } - } - return r, err -} - -func (s *metadataStore) remove(name string) error { - if err := os.RemoveAll(s.contextDir(contextdirOf(name))); err != nil { - return errors.Wrapf(err, "failed to remove metadata") - } - return nil -} - -func (s *metadataStore) list() ([]Metadata, error) { - ctxDirs, err := listRecursivelyMetadataDirs(s.root) - if err != nil { - if errors.Is(err, os.ErrNotExist) { - return nil, nil - } - return nil, err - } - var res []Metadata - for _, dir := range ctxDirs { - c, err := s.getByID(contextdir(dir)) - if err != nil { - if errors.Is(err, os.ErrNotExist) { - continue - } - return nil, errors.Wrap(err, "failed to read metadata") - } - res = append(res, c) - } - sort.Slice(res, func(i, j int) bool { - return sortorder.NaturalLess(res[i].Name, res[j].Name) - }) - return res, nil -} - -func isContextDir(path string) bool { - s, err := os.Stat(filepath.Join(path, metaFile)) - if err != nil { - return false - } - return !s.IsDir() -} - -func listRecursivelyMetadataDirs(root string) ([]string, error) { - fis, err := os.ReadDir(root) - if err != nil { - return nil, err - } - var result []string - for _, fi := range fis { - if fi.IsDir() { - if isContextDir(filepath.Join(root, fi.Name())) { - result = append(result, fi.Name()) - } - subs, err := listRecursivelyMetadataDirs(filepath.Join(root, fi.Name())) - if err != nil { - return nil, err - } - for _, s := range subs { - result = append(result, filepath.Join(fi.Name(), s)) - } - } - } - return result, nil -} - -type untypedContextMetadata struct { - Metadata json.RawMessage `json:"metadata,omitempty"` - Endpoints map[string]json.RawMessage `json:"endpoints,omitempty"` - Name string `json:"name,omitempty"` -} diff --git a/vendor/github.com/docker/cli/cli/context/store/store.go b/vendor/github.com/docker/cli/cli/context/store/store.go deleted file mode 100644 index 710125230..000000000 --- a/vendor/github.com/docker/cli/cli/context/store/store.go +++ /dev/null @@ -1,501 +0,0 @@ -package store - -import ( - "archive/tar" - "archive/zip" - "bufio" - "bytes" - _ "crypto/sha256" // ensure ids can be computed - "encoding/json" - "io" - "net/http" - "path" - "path/filepath" - "regexp" - "strings" - - "github.com/docker/docker/errdefs" - "github.com/opencontainers/go-digest" - "github.com/pkg/errors" -) - -const restrictedNamePattern = "^[a-zA-Z0-9][a-zA-Z0-9_.+-]+$" - -var restrictedNameRegEx = regexp.MustCompile(restrictedNamePattern) - -// Store provides a context store for easily remembering endpoints configuration -type Store interface { - Reader - Lister - Writer - StorageInfoProvider -} - -// Reader provides read-only (without list) access to context data -type Reader interface { - GetMetadata(name string) (Metadata, error) - ListTLSFiles(name string) (map[string]EndpointFiles, error) - GetTLSData(contextName, endpointName, fileName string) ([]byte, error) -} - -// Lister provides listing of contexts -type Lister interface { - List() ([]Metadata, error) -} - -// ReaderLister combines Reader and Lister interfaces -type ReaderLister interface { - Reader - Lister -} - -// StorageInfoProvider provides more information about storage details of contexts -type StorageInfoProvider interface { - GetStorageInfo(contextName string) StorageInfo -} - -// Writer provides write access to context data -type Writer interface { - CreateOrUpdate(meta Metadata) error - Remove(name string) error - ResetTLSMaterial(name string, data *ContextTLSData) error - ResetEndpointTLSMaterial(contextName string, endpointName string, data *EndpointTLSData) error -} - -// ReaderWriter combines Reader and Writer interfaces -type ReaderWriter interface { - Reader - Writer -} - -// Metadata contains metadata about a context and its endpoints -type Metadata struct { - Name string `json:",omitempty"` - Metadata interface{} `json:",omitempty"` - Endpoints map[string]interface{} `json:",omitempty"` -} - -// StorageInfo contains data about where a given context is stored -type StorageInfo struct { - MetadataPath string - TLSPath string -} - -// EndpointTLSData represents tls data for a given endpoint -type EndpointTLSData struct { - Files map[string][]byte -} - -// ContextTLSData represents tls data for a whole context -type ContextTLSData struct { - Endpoints map[string]EndpointTLSData -} - -// New creates a store from a given directory. -// If the directory does not exist or is empty, initialize it -func New(dir string, cfg Config) *ContextStore { - metaRoot := filepath.Join(dir, metadataDir) - tlsRoot := filepath.Join(dir, tlsDir) - - return &ContextStore{ - meta: &metadataStore{ - root: metaRoot, - config: cfg, - }, - tls: &tlsStore{ - root: tlsRoot, - }, - } -} - -// ContextStore implements Store. -type ContextStore struct { - meta *metadataStore - tls *tlsStore -} - -// List return all contexts. -func (s *ContextStore) List() ([]Metadata, error) { - return s.meta.list() -} - -// Names return Metadata names for a Lister -func Names(s Lister) ([]string, error) { - list, err := s.List() - if err != nil { - return nil, err - } - var names []string - for _, item := range list { - names = append(names, item.Name) - } - return names, nil -} - -// CreateOrUpdate creates or updates metadata for the context. -func (s *ContextStore) CreateOrUpdate(meta Metadata) error { - return s.meta.createOrUpdate(meta) -} - -// Remove deletes the context with the given name, if found. -func (s *ContextStore) Remove(name string) error { - if err := s.meta.remove(name); err != nil { - return errors.Wrapf(err, "failed to remove context %s", name) - } - if err := s.tls.remove(name); err != nil { - return errors.Wrapf(err, "failed to remove context %s", name) - } - return nil -} - -// GetMetadata returns the metadata for the context with the given name. -// It returns an errdefs.ErrNotFound if the context was not found. -func (s *ContextStore) GetMetadata(name string) (Metadata, error) { - return s.meta.get(name) -} - -// ResetTLSMaterial removes TLS data for all endpoints in the context and replaces -// it with the new data. -func (s *ContextStore) ResetTLSMaterial(name string, data *ContextTLSData) error { - if err := s.tls.remove(name); err != nil { - return err - } - if data == nil { - return nil - } - for ep, files := range data.Endpoints { - for fileName, data := range files.Files { - if err := s.tls.createOrUpdate(name, ep, fileName, data); err != nil { - return err - } - } - } - return nil -} - -// ResetEndpointTLSMaterial removes TLS data for the given context and endpoint, -// and replaces it with the new data. -func (s *ContextStore) ResetEndpointTLSMaterial(contextName string, endpointName string, data *EndpointTLSData) error { - if err := s.tls.removeEndpoint(contextName, endpointName); err != nil { - return err - } - if data == nil { - return nil - } - for fileName, data := range data.Files { - if err := s.tls.createOrUpdate(contextName, endpointName, fileName, data); err != nil { - return err - } - } - return nil -} - -// ListTLSFiles returns the list of TLS files present for each endpoint in the -// context. -func (s *ContextStore) ListTLSFiles(name string) (map[string]EndpointFiles, error) { - return s.tls.listContextData(name) -} - -// GetTLSData reads, and returns the content of the given fileName for an endpoint. -// It returns an errdefs.ErrNotFound if the file was not found. -func (s *ContextStore) GetTLSData(contextName, endpointName, fileName string) ([]byte, error) { - return s.tls.getData(contextName, endpointName, fileName) -} - -// GetStorageInfo returns the paths where the Metadata and TLS data are stored -// for the context. -func (s *ContextStore) GetStorageInfo(contextName string) StorageInfo { - return StorageInfo{ - MetadataPath: s.meta.contextDir(contextdirOf(contextName)), - TLSPath: s.tls.contextDir(contextName), - } -} - -// ValidateContextName checks a context name is valid. -func ValidateContextName(name string) error { - if name == "" { - return errors.New("context name cannot be empty") - } - if name == "default" { - return errors.New(`"default" is a reserved context name`) - } - if !restrictedNameRegEx.MatchString(name) { - return errors.Errorf("context name %q is invalid, names are validated against regexp %q", name, restrictedNamePattern) - } - return nil -} - -// Export exports an existing namespace into an opaque data stream -// This stream is actually a tarball containing context metadata and TLS materials, but it does -// not map 1:1 the layout of the context store (don't try to restore it manually without calling store.Import) -func Export(name string, s Reader) io.ReadCloser { - reader, writer := io.Pipe() - go func() { - tw := tar.NewWriter(writer) - defer tw.Close() - defer writer.Close() - meta, err := s.GetMetadata(name) - if err != nil { - writer.CloseWithError(err) - return - } - metaBytes, err := json.Marshal(&meta) - if err != nil { - writer.CloseWithError(err) - return - } - if err = tw.WriteHeader(&tar.Header{ - Name: metaFile, - Mode: 0o644, - Size: int64(len(metaBytes)), - }); err != nil { - writer.CloseWithError(err) - return - } - if _, err = tw.Write(metaBytes); err != nil { - writer.CloseWithError(err) - return - } - tlsFiles, err := s.ListTLSFiles(name) - if err != nil { - writer.CloseWithError(err) - return - } - if err = tw.WriteHeader(&tar.Header{ - Name: "tls", - Mode: 0o700, - Size: 0, - Typeflag: tar.TypeDir, - }); err != nil { - writer.CloseWithError(err) - return - } - for endpointName, endpointFiles := range tlsFiles { - if err = tw.WriteHeader(&tar.Header{ - Name: path.Join("tls", endpointName), - Mode: 0o700, - Size: 0, - Typeflag: tar.TypeDir, - }); err != nil { - writer.CloseWithError(err) - return - } - for _, fileName := range endpointFiles { - data, err := s.GetTLSData(name, endpointName, fileName) - if err != nil { - writer.CloseWithError(err) - return - } - if err = tw.WriteHeader(&tar.Header{ - Name: path.Join("tls", endpointName, fileName), - Mode: 0o600, - Size: int64(len(data)), - }); err != nil { - writer.CloseWithError(err) - return - } - if _, err = tw.Write(data); err != nil { - writer.CloseWithError(err) - return - } - } - } - }() - return reader -} - -const ( - maxAllowedFileSizeToImport int64 = 10 << 20 - zipType string = "application/zip" -) - -func getImportContentType(r *bufio.Reader) (string, error) { - head, err := r.Peek(512) - if err != nil && err != io.EOF { - return "", err - } - - return http.DetectContentType(head), nil -} - -// Import imports an exported context into a store -func Import(name string, s Writer, reader io.Reader) error { - // Buffered reader will not advance the buffer, needed to determine content type - r := bufio.NewReader(reader) - - importContentType, err := getImportContentType(r) - if err != nil { - return err - } - switch importContentType { - case zipType: - return importZip(name, s, r) - default: - // Assume it's a TAR (TAR does not have a "magic number") - return importTar(name, s, r) - } -} - -func isValidFilePath(p string) error { - if p != metaFile && !strings.HasPrefix(p, "tls/") { - return errors.New("unexpected context file") - } - if path.Clean(p) != p { - return errors.New("unexpected path format") - } - if strings.Contains(p, `\`) { - return errors.New(`unexpected '\' in path`) - } - return nil -} - -func importTar(name string, s Writer, reader io.Reader) error { - tr := tar.NewReader(&LimitedReader{R: reader, N: maxAllowedFileSizeToImport}) - tlsData := ContextTLSData{ - Endpoints: map[string]EndpointTLSData{}, - } - var importedMetaFile bool - for { - hdr, err := tr.Next() - if err == io.EOF { - break - } - if err != nil { - return err - } - if hdr.Typeflag != tar.TypeReg { - // skip this entry, only taking files into account - continue - } - if err := isValidFilePath(hdr.Name); err != nil { - return errors.Wrap(err, hdr.Name) - } - if hdr.Name == metaFile { - data, err := io.ReadAll(tr) - if err != nil { - return err - } - meta, err := parseMetadata(data, name) - if err != nil { - return err - } - if err := s.CreateOrUpdate(meta); err != nil { - return err - } - importedMetaFile = true - } else if strings.HasPrefix(hdr.Name, "tls/") { - data, err := io.ReadAll(tr) - if err != nil { - return err - } - if err := importEndpointTLS(&tlsData, hdr.Name, data); err != nil { - return err - } - } - } - if !importedMetaFile { - return errdefs.InvalidParameter(errors.New("invalid context: no metadata found")) - } - return s.ResetTLSMaterial(name, &tlsData) -} - -func importZip(name string, s Writer, reader io.Reader) error { - body, err := io.ReadAll(&LimitedReader{R: reader, N: maxAllowedFileSizeToImport}) - if err != nil { - return err - } - zr, err := zip.NewReader(bytes.NewReader(body), int64(len(body))) - if err != nil { - return err - } - tlsData := ContextTLSData{ - Endpoints: map[string]EndpointTLSData{}, - } - - var importedMetaFile bool - for _, zf := range zr.File { - fi := zf.FileInfo() - if !fi.Mode().IsRegular() { - // skip this entry, only taking regular files into account - continue - } - if err := isValidFilePath(zf.Name); err != nil { - return errors.Wrap(err, zf.Name) - } - if zf.Name == metaFile { - f, err := zf.Open() - if err != nil { - return err - } - - data, err := io.ReadAll(&LimitedReader{R: f, N: maxAllowedFileSizeToImport}) - defer f.Close() - if err != nil { - return err - } - meta, err := parseMetadata(data, name) - if err != nil { - return err - } - if err := s.CreateOrUpdate(meta); err != nil { - return err - } - importedMetaFile = true - } else if strings.HasPrefix(zf.Name, "tls/") { - f, err := zf.Open() - if err != nil { - return err - } - data, err := io.ReadAll(f) - defer f.Close() - if err != nil { - return err - } - err = importEndpointTLS(&tlsData, zf.Name, data) - if err != nil { - return err - } - } - } - if !importedMetaFile { - return errdefs.InvalidParameter(errors.New("invalid context: no metadata found")) - } - return s.ResetTLSMaterial(name, &tlsData) -} - -func parseMetadata(data []byte, name string) (Metadata, error) { - var meta Metadata - if err := json.Unmarshal(data, &meta); err != nil { - return meta, err - } - if err := ValidateContextName(name); err != nil { - return Metadata{}, err - } - meta.Name = name - return meta, nil -} - -func importEndpointTLS(tlsData *ContextTLSData, path string, data []byte) error { - parts := strings.SplitN(strings.TrimPrefix(path, "tls/"), "/", 2) - if len(parts) != 2 { - // TLS endpoints require archived file directory with 2 layers - // i.e. tls/{endpointName}/{fileName} - return errors.New("archive format is invalid") - } - - epName := parts[0] - fileName := parts[1] - if _, ok := tlsData.Endpoints[epName]; !ok { - tlsData.Endpoints[epName] = EndpointTLSData{ - Files: map[string][]byte{}, - } - } - tlsData.Endpoints[epName].Files[fileName] = data - return nil -} - -type contextdir string - -func contextdirOf(name string) contextdir { - return contextdir(digest.FromString(name).Encoded()) -} diff --git a/vendor/github.com/docker/cli/cli/context/store/storeconfig.go b/vendor/github.com/docker/cli/cli/context/store/storeconfig.go deleted file mode 100644 index 9c93ecbab..000000000 --- a/vendor/github.com/docker/cli/cli/context/store/storeconfig.go +++ /dev/null @@ -1,53 +0,0 @@ -package store - -// TypeGetter is a func used to determine the concrete type of a context or -// endpoint metadata by returning a pointer to an instance of the object -// eg: for a context of type DockerContext, the corresponding TypeGetter should return new(DockerContext) -type TypeGetter func() interface{} - -// NamedTypeGetter is a TypeGetter associated with a name -type NamedTypeGetter struct { - name string - typeGetter TypeGetter -} - -// EndpointTypeGetter returns a NamedTypeGetter with the spcecified name and getter -func EndpointTypeGetter(name string, getter TypeGetter) NamedTypeGetter { - return NamedTypeGetter{ - name: name, - typeGetter: getter, - } -} - -// Config is used to configure the metadata marshaler of the context ContextStore -type Config struct { - contextType TypeGetter - endpointTypes map[string]TypeGetter -} - -// SetEndpoint set an endpoint typing information -func (c Config) SetEndpoint(name string, getter TypeGetter) { - c.endpointTypes[name] = getter -} - -// ForeachEndpointType calls cb on every endpoint type registered with the Config -func (c Config) ForeachEndpointType(cb func(string, TypeGetter) error) error { - for n, ep := range c.endpointTypes { - if err := cb(n, ep); err != nil { - return err - } - } - return nil -} - -// NewConfig creates a config object -func NewConfig(contextType TypeGetter, endpoints ...NamedTypeGetter) Config { - res := Config{ - contextType: contextType, - endpointTypes: make(map[string]TypeGetter), - } - for _, e := range endpoints { - res.endpointTypes[e.name] = e.typeGetter - } - return res -} diff --git a/vendor/github.com/docker/cli/cli/context/store/tlsstore.go b/vendor/github.com/docker/cli/cli/context/store/tlsstore.go deleted file mode 100644 index ffbbde7c0..000000000 --- a/vendor/github.com/docker/cli/cli/context/store/tlsstore.go +++ /dev/null @@ -1,96 +0,0 @@ -package store - -import ( - "os" - "path/filepath" - - "github.com/docker/docker/errdefs" - "github.com/docker/docker/pkg/ioutils" - "github.com/pkg/errors" -) - -const tlsDir = "tls" - -type tlsStore struct { - root string -} - -func (s *tlsStore) contextDir(name string) string { - return filepath.Join(s.root, string(contextdirOf(name))) -} - -func (s *tlsStore) endpointDir(name, endpointName string) string { - return filepath.Join(s.contextDir(name), endpointName) -} - -func (s *tlsStore) createOrUpdate(name, endpointName, filename string, data []byte) error { - parentOfRoot := filepath.Dir(s.root) - if err := os.MkdirAll(parentOfRoot, 0o755); err != nil { - return err - } - endpointDir := s.endpointDir(name, endpointName) - if err := os.MkdirAll(endpointDir, 0o700); err != nil { - return err - } - return ioutils.AtomicWriteFile(filepath.Join(endpointDir, filename), data, 0o600) -} - -func (s *tlsStore) getData(name, endpointName, filename string) ([]byte, error) { - data, err := os.ReadFile(filepath.Join(s.endpointDir(name, endpointName), filename)) - if err != nil { - if os.IsNotExist(err) { - return nil, errdefs.NotFound(errors.Errorf("TLS data for %s/%s/%s does not exist", name, endpointName, filename)) - } - return nil, errors.Wrapf(err, "failed to read TLS data for endpoint %s", endpointName) - } - return data, nil -} - -// remove deletes all TLS data for the given context. -func (s *tlsStore) remove(name string) error { - if err := os.RemoveAll(s.contextDir(name)); err != nil { - return errors.Wrapf(err, "failed to remove TLS data") - } - return nil -} - -func (s *tlsStore) removeEndpoint(name, endpointName string) error { - if err := os.RemoveAll(s.endpointDir(name, endpointName)); err != nil { - return errors.Wrapf(err, "failed to remove TLS data for endpoint %s", endpointName) - } - return nil -} - -func (s *tlsStore) listContextData(name string) (map[string]EndpointFiles, error) { - contextDir := s.contextDir(name) - epFSs, err := os.ReadDir(contextDir) - if err != nil { - if os.IsNotExist(err) { - return map[string]EndpointFiles{}, nil - } - return nil, errors.Wrapf(err, "failed to list TLS files for context %s", name) - } - r := make(map[string]EndpointFiles) - for _, epFS := range epFSs { - if epFS.IsDir() { - fss, err := os.ReadDir(filepath.Join(contextDir, epFS.Name())) - if os.IsNotExist(err) { - continue - } - if err != nil { - return nil, errors.Wrapf(err, "failed to list TLS files for endpoint %s", epFS.Name()) - } - var files EndpointFiles - for _, fs := range fss { - if !fs.IsDir() { - files = append(files, fs.Name()) - } - } - r[epFS.Name()] = files - } - } - return r, nil -} - -// EndpointFiles is a slice of strings representing file names -type EndpointFiles []string diff --git a/vendor/github.com/docker/cli/cli/context/tlsdata.go b/vendor/github.com/docker/cli/cli/context/tlsdata.go deleted file mode 100644 index c758612a1..000000000 --- a/vendor/github.com/docker/cli/cli/context/tlsdata.go +++ /dev/null @@ -1,98 +0,0 @@ -package context - -import ( - "os" - - "github.com/docker/cli/cli/context/store" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" -) - -const ( - caKey = "ca.pem" - certKey = "cert.pem" - keyKey = "key.pem" -) - -// TLSData holds ca/cert/key raw data -type TLSData struct { - CA []byte - Key []byte - Cert []byte -} - -// ToStoreTLSData converts TLSData to the store representation -func (data *TLSData) ToStoreTLSData() *store.EndpointTLSData { - if data == nil { - return nil - } - result := store.EndpointTLSData{ - Files: make(map[string][]byte), - } - if data.CA != nil { - result.Files[caKey] = data.CA - } - if data.Cert != nil { - result.Files[certKey] = data.Cert - } - if data.Key != nil { - result.Files[keyKey] = data.Key - } - return &result -} - -// LoadTLSData loads TLS data from the store -func LoadTLSData(s store.Reader, contextName, endpointName string) (*TLSData, error) { - tlsFiles, err := s.ListTLSFiles(contextName) - if err != nil { - return nil, errors.Wrapf(err, "failed to retrieve TLS files for context %q", contextName) - } - if epTLSFiles, ok := tlsFiles[endpointName]; ok { - var tlsData TLSData - for _, f := range epTLSFiles { - data, err := s.GetTLSData(contextName, endpointName, f) - if err != nil { - return nil, errors.Wrapf(err, "failed to retrieve TLS data (%s) for context %q", f, contextName) - } - switch f { - case caKey: - tlsData.CA = data - case certKey: - tlsData.Cert = data - case keyKey: - tlsData.Key = data - default: - logrus.Warnf("unknown file in context %s TLS bundle: %s", contextName, f) - } - } - return &tlsData, nil - } - return nil, nil -} - -// TLSDataFromFiles reads files into a TLSData struct (or returns nil if all paths are empty) -func TLSDataFromFiles(caPath, certPath, keyPath string) (*TLSData, error) { - var ( - ca, cert, key []byte - err error - ) - if caPath != "" { - if ca, err = os.ReadFile(caPath); err != nil { - return nil, err - } - } - if certPath != "" { - if cert, err = os.ReadFile(certPath); err != nil { - return nil, err - } - } - if keyPath != "" { - if key, err = os.ReadFile(keyPath); err != nil { - return nil, err - } - } - if ca == nil && cert == nil && key == nil { - return nil, nil - } - return &TLSData{CA: ca, Cert: cert, Key: key}, nil -} diff --git a/vendor/github.com/docker/cli/cli/debug/debug.go b/vendor/github.com/docker/cli/cli/debug/debug.go deleted file mode 100644 index b00ea63ad..000000000 --- a/vendor/github.com/docker/cli/cli/debug/debug.go +++ /dev/null @@ -1,26 +0,0 @@ -package debug - -import ( - "os" - - "github.com/sirupsen/logrus" -) - -// Enable sets the DEBUG env var to true -// and makes the logger to log at debug level. -func Enable() { - os.Setenv("DEBUG", "1") - logrus.SetLevel(logrus.DebugLevel) -} - -// Disable sets the DEBUG env var to false -// and makes the logger to log at info level. -func Disable() { - os.Setenv("DEBUG", "") - logrus.SetLevel(logrus.InfoLevel) -} - -// IsEnabled checks whether the debug flag is set or not. -func IsEnabled() bool { - return os.Getenv("DEBUG") != "" -} diff --git a/vendor/github.com/docker/cli/cli/error.go b/vendor/github.com/docker/cli/cli/error.go deleted file mode 100644 index 62f62433b..000000000 --- a/vendor/github.com/docker/cli/cli/error.go +++ /dev/null @@ -1,33 +0,0 @@ -package cli - -import ( - "fmt" - "strings" -) - -// Errors is a list of errors. -// Useful in a loop if you don't want to return the error right away and you want to display after the loop, -// all the errors that happened during the loop. -type Errors []error - -func (errList Errors) Error() string { - if len(errList) < 1 { - return "" - } - - out := make([]string, len(errList)) - for i := range errList { - out[i] = errList[i].Error() - } - return strings.Join(out, ", ") -} - -// StatusError reports an unsuccessful exit by a command. -type StatusError struct { - Status string - StatusCode int -} - -func (e StatusError) Error() string { - return fmt.Sprintf("Status: %s, Code: %d", e.Status, e.StatusCode) -} diff --git a/vendor/github.com/docker/cli/cli/flags/options.go b/vendor/github.com/docker/cli/cli/flags/options.go deleted file mode 100644 index 03c1f2db2..000000000 --- a/vendor/github.com/docker/cli/cli/flags/options.go +++ /dev/null @@ -1,135 +0,0 @@ -package flags - -import ( - "fmt" - "os" - "path/filepath" - - "github.com/docker/cli/cli/config" - "github.com/docker/cli/opts" - "github.com/docker/docker/client" - "github.com/docker/go-connections/tlsconfig" - "github.com/sirupsen/logrus" - "github.com/spf13/pflag" -) - -const ( - // DefaultCaFile is the default filename for the CA pem file - DefaultCaFile = "ca.pem" - // DefaultKeyFile is the default filename for the key pem file - DefaultKeyFile = "key.pem" - // DefaultCertFile is the default filename for the cert pem file - DefaultCertFile = "cert.pem" - // FlagTLSVerify is the flag name for the TLS verification option - FlagTLSVerify = "tlsverify" - // FormatHelp describes the --format flag behavior for list commands - FormatHelp = `Format output using a custom template: -'table': Print output in table format with column headers (default) -'table TEMPLATE': Print output in table format using the given Go template -'json': Print in JSON format -'TEMPLATE': Print output using the given Go template. -Refer to https://docs.docker.com/go/formatting/ for more information about formatting output with templates` - // InspectFormatHelp describes the --format flag behavior for inspect commands - InspectFormatHelp = `Format output using a custom template: -'json': Print in JSON format -'TEMPLATE': Print output using the given Go template. -Refer to https://docs.docker.com/go/formatting/ for more information about formatting output with templates` -) - -var ( - dockerCertPath = os.Getenv(client.EnvOverrideCertPath) - dockerTLSVerify = os.Getenv(client.EnvTLSVerify) != "" - // TODO(thaJeztah) the 'DOCKER_TLS' environment variable is not documented, and does not have a const. - dockerTLS = os.Getenv("DOCKER_TLS") != "" -) - -// ClientOptions are the options used to configure the client cli. -type ClientOptions struct { - Debug bool - Hosts []string - LogLevel string - TLS bool - TLSVerify bool - TLSOptions *tlsconfig.Options - Context string - ConfigDir string -} - -// NewClientOptions returns a new ClientOptions. -func NewClientOptions() *ClientOptions { - return &ClientOptions{} -} - -// InstallFlags adds flags for the common options on the FlagSet -func (o *ClientOptions) InstallFlags(flags *pflag.FlagSet) { - if dockerCertPath == "" { - dockerCertPath = config.Dir() - } - - flags.BoolVarP(&o.Debug, "debug", "D", false, "Enable debug mode") - flags.StringVarP(&o.LogLevel, "log-level", "l", "info", `Set the logging level ("debug", "info", "warn", "error", "fatal")`) - flags.BoolVar(&o.TLS, "tls", dockerTLS, "Use TLS; implied by --tlsverify") - flags.BoolVar(&o.TLSVerify, FlagTLSVerify, dockerTLSVerify, "Use TLS and verify the remote") - - o.TLSOptions = &tlsconfig.Options{ - CAFile: filepath.Join(dockerCertPath, DefaultCaFile), - CertFile: filepath.Join(dockerCertPath, DefaultCertFile), - KeyFile: filepath.Join(dockerCertPath, DefaultKeyFile), - } - tlsOptions := o.TLSOptions - flags.Var(opts.NewQuotedString(&tlsOptions.CAFile), "tlscacert", "Trust certs signed only by this CA") - flags.Var(opts.NewQuotedString(&tlsOptions.CertFile), "tlscert", "Path to TLS certificate file") - flags.Var(opts.NewQuotedString(&tlsOptions.KeyFile), "tlskey", "Path to TLS key file") - - // opts.ValidateHost is not used here, so as to allow connection helpers - hostOpt := opts.NewNamedListOptsRef("hosts", &o.Hosts, nil) - flags.VarP(hostOpt, "host", "H", "Daemon socket to connect to") - flags.StringVarP(&o.Context, "context", "c", "", - `Name of the context to use to connect to the daemon (overrides `+client.EnvOverrideHost+` env var and default context set with "docker context use")`) -} - -// SetDefaultOptions sets default values for options after flag parsing is -// complete -func (o *ClientOptions) SetDefaultOptions(flags *pflag.FlagSet) { - // Regardless of whether the user sets it to true or false, if they - // specify --tlsverify at all then we need to turn on TLS - // TLSVerify can be true even if not set due to DOCKER_TLS_VERIFY env var, so we need - // to check that here as well - if flags.Changed(FlagTLSVerify) || o.TLSVerify { - o.TLS = true - } - - if !o.TLS { - o.TLSOptions = nil - } else { - tlsOptions := o.TLSOptions - tlsOptions.InsecureSkipVerify = !o.TLSVerify - - // Reset CertFile and KeyFile to empty string if the user did not specify - // the respective flags and the respective default files were not found. - if !flags.Changed("tlscert") { - if _, err := os.Stat(tlsOptions.CertFile); os.IsNotExist(err) { - tlsOptions.CertFile = "" - } - } - if !flags.Changed("tlskey") { - if _, err := os.Stat(tlsOptions.KeyFile); os.IsNotExist(err) { - tlsOptions.KeyFile = "" - } - } - } -} - -// SetLogLevel sets the logrus logging level -func SetLogLevel(logLevel string) { - if logLevel != "" { - lvl, err := logrus.ParseLevel(logLevel) - if err != nil { - fmt.Fprintf(os.Stderr, "Unable to parse logging level: %s\n", logLevel) - os.Exit(1) - } - logrus.SetLevel(lvl) - } else { - logrus.SetLevel(logrus.InfoLevel) - } -} diff --git a/vendor/github.com/docker/cli/cli/hints/hints.go b/vendor/github.com/docker/cli/cli/hints/hints.go deleted file mode 100644 index f99df8fda..000000000 --- a/vendor/github.com/docker/cli/cli/hints/hints.go +++ /dev/null @@ -1,18 +0,0 @@ -package hints - -import ( - "os" - "strconv" -) - -// Enabled returns whether cli hints are enabled or not -func Enabled() bool { - if v := os.Getenv("DOCKER_CLI_HINTS"); v != "" { - enabled, err := strconv.ParseBool(v) - if err != nil { - return true - } - return enabled - } - return true -} diff --git a/vendor/github.com/docker/cli/cli/manifest/store/store.go b/vendor/github.com/docker/cli/cli/manifest/store/store.go deleted file mode 100644 index 39e576f6b..000000000 --- a/vendor/github.com/docker/cli/cli/manifest/store/store.go +++ /dev/null @@ -1,179 +0,0 @@ -package store - -import ( - "encoding/json" - "fmt" - "os" - "path/filepath" - "strings" - - "github.com/docker/cli/cli/manifest/types" - "github.com/docker/distribution/manifest/manifestlist" - "github.com/docker/distribution/reference" - "github.com/opencontainers/go-digest" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" - "github.com/pkg/errors" -) - -// Store manages local storage of image distribution manifests -type Store interface { - Remove(listRef reference.Reference) error - Get(listRef reference.Reference, manifest reference.Reference) (types.ImageManifest, error) - GetList(listRef reference.Reference) ([]types.ImageManifest, error) - Save(listRef reference.Reference, manifest reference.Reference, image types.ImageManifest) error -} - -// fsStore manages manifest files stored on the local filesystem -type fsStore struct { - root string -} - -// NewStore returns a new store for a local file path -func NewStore(root string) Store { - return &fsStore{root: root} -} - -// Remove a manifest list from local storage -func (s *fsStore) Remove(listRef reference.Reference) error { - path := filepath.Join(s.root, makeFilesafeName(listRef.String())) - return os.RemoveAll(path) -} - -// Get returns the local manifest -func (s *fsStore) Get(listRef reference.Reference, manifest reference.Reference) (types.ImageManifest, error) { - filename := manifestToFilename(s.root, listRef.String(), manifest.String()) - return s.getFromFilename(manifest, filename) -} - -func (s *fsStore) getFromFilename(ref reference.Reference, filename string) (types.ImageManifest, error) { - bytes, err := os.ReadFile(filename) - switch { - case os.IsNotExist(err): - return types.ImageManifest{}, newNotFoundError(ref.String()) - case err != nil: - return types.ImageManifest{}, err - } - var manifestInfo struct { - types.ImageManifest - - // Deprecated Fields, replaced by Descriptor - Digest digest.Digest - Platform *manifestlist.PlatformSpec - } - - if err := json.Unmarshal(bytes, &manifestInfo); err != nil { - return types.ImageManifest{}, err - } - - // Compatibility with image manifests created before - // descriptor, newer versions omit Digest and Platform - if manifestInfo.Digest != "" { - mediaType, raw, err := manifestInfo.Payload() - if err != nil { - return types.ImageManifest{}, err - } - if dgst := digest.FromBytes(raw); dgst != manifestInfo.Digest { - return types.ImageManifest{}, errors.Errorf("invalid manifest file %v: image manifest digest mismatch (%v != %v)", filename, manifestInfo.Digest, dgst) - } - manifestInfo.ImageManifest.Descriptor = ocispec.Descriptor{ - Digest: manifestInfo.Digest, - Size: int64(len(raw)), - MediaType: mediaType, - Platform: types.OCIPlatform(manifestInfo.Platform), - } - } - - return manifestInfo.ImageManifest, nil -} - -// GetList returns all the local manifests for a transaction -func (s *fsStore) GetList(listRef reference.Reference) ([]types.ImageManifest, error) { - filenames, err := s.listManifests(listRef.String()) - switch { - case err != nil: - return nil, err - case filenames == nil: - return nil, newNotFoundError(listRef.String()) - } - - manifests := []types.ImageManifest{} - for _, filename := range filenames { - filename = filepath.Join(s.root, makeFilesafeName(listRef.String()), filename) - manifest, err := s.getFromFilename(listRef, filename) - if err != nil { - return nil, err - } - manifests = append(manifests, manifest) - } - return manifests, nil -} - -// listManifests stored in a transaction -func (s *fsStore) listManifests(transaction string) ([]string, error) { - transactionDir := filepath.Join(s.root, makeFilesafeName(transaction)) - fileInfos, err := os.ReadDir(transactionDir) - switch { - case os.IsNotExist(err): - return nil, nil - case err != nil: - return nil, err - } - - filenames := make([]string, 0, len(fileInfos)) - for _, info := range fileInfos { - filenames = append(filenames, info.Name()) - } - return filenames, nil -} - -// Save a manifest as part of a local manifest list -func (s *fsStore) Save(listRef reference.Reference, manifest reference.Reference, image types.ImageManifest) error { - if err := s.createManifestListDirectory(listRef.String()); err != nil { - return err - } - filename := manifestToFilename(s.root, listRef.String(), manifest.String()) - bytes, err := json.Marshal(image) - if err != nil { - return err - } - return os.WriteFile(filename, bytes, 0o644) -} - -func (s *fsStore) createManifestListDirectory(transaction string) error { - path := filepath.Join(s.root, makeFilesafeName(transaction)) - return os.MkdirAll(path, 0o755) -} - -func manifestToFilename(root, manifestList, manifest string) string { - return filepath.Join(root, makeFilesafeName(manifestList), makeFilesafeName(manifest)) -} - -func makeFilesafeName(ref string) string { - fileName := strings.Replace(ref, ":", "-", -1) - return strings.Replace(fileName, "/", "_", -1) -} - -type notFoundError struct { - object string -} - -func newNotFoundError(ref string) *notFoundError { - return ¬FoundError{object: ref} -} - -func (n *notFoundError) Error() string { - return fmt.Sprintf("No such manifest: %s", n.object) -} - -// NotFound interface -func (n *notFoundError) NotFound() {} - -// IsNotFound returns true if the error is a not found error -func IsNotFound(err error) bool { - _, ok := err.(notFound) - return ok -} - -type notFound interface { - NotFound() -} diff --git a/vendor/github.com/docker/cli/cli/manifest/types/types.go b/vendor/github.com/docker/cli/cli/manifest/types/types.go deleted file mode 100644 index ca2a3e786..000000000 --- a/vendor/github.com/docker/cli/cli/manifest/types/types.go +++ /dev/null @@ -1,150 +0,0 @@ -package types - -import ( - "encoding/json" - - "github.com/docker/distribution" - "github.com/docker/distribution/manifest/manifestlist" - "github.com/docker/distribution/manifest/ocischema" - "github.com/docker/distribution/manifest/schema2" - "github.com/docker/distribution/reference" - "github.com/opencontainers/go-digest" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" - "github.com/pkg/errors" -) - -// ImageManifest contains info to output for a manifest object. -type ImageManifest struct { - Ref *SerializableNamed - Descriptor ocispec.Descriptor - Raw []byte `json:",omitempty"` - - // SchemaV2Manifest is used for inspection - SchemaV2Manifest *schema2.DeserializedManifest `json:",omitempty"` - // OCIManifest is used for inspection - OCIManifest *ocischema.DeserializedManifest `json:",omitempty"` -} - -// OCIPlatform creates an OCI platform from a manifest list platform spec -func OCIPlatform(ps *manifestlist.PlatformSpec) *ocispec.Platform { - if ps == nil { - return nil - } - return &ocispec.Platform{ - Architecture: ps.Architecture, - OS: ps.OS, - OSVersion: ps.OSVersion, - OSFeatures: ps.OSFeatures, - Variant: ps.Variant, - } -} - -// PlatformSpecFromOCI creates a platform spec from OCI platform -func PlatformSpecFromOCI(p *ocispec.Platform) *manifestlist.PlatformSpec { - if p == nil { - return nil - } - return &manifestlist.PlatformSpec{ - Architecture: p.Architecture, - OS: p.OS, - OSVersion: p.OSVersion, - OSFeatures: p.OSFeatures, - Variant: p.Variant, - } -} - -// Blobs returns the digests for all the blobs referenced by this manifest -func (i ImageManifest) Blobs() []digest.Digest { - digests := []digest.Digest{} - switch { - case i.SchemaV2Manifest != nil: - for _, descriptor := range i.SchemaV2Manifest.References() { - digests = append(digests, descriptor.Digest) - } - case i.OCIManifest != nil: - for _, descriptor := range i.OCIManifest.References() { - digests = append(digests, descriptor.Digest) - } - } - return digests -} - -// Payload returns the media type and bytes for the manifest -func (i ImageManifest) Payload() (string, []byte, error) { - // TODO: If available, read content from a content store by digest - switch { - case i.SchemaV2Manifest != nil: - return i.SchemaV2Manifest.Payload() - case i.OCIManifest != nil: - return i.OCIManifest.Payload() - default: - return "", nil, errors.Errorf("%s has no payload", i.Ref) - } -} - -// References implements the distribution.Manifest interface. It delegates to -// the underlying manifest. -func (i ImageManifest) References() []distribution.Descriptor { - switch { - case i.SchemaV2Manifest != nil: - return i.SchemaV2Manifest.References() - case i.OCIManifest != nil: - return i.OCIManifest.References() - default: - return nil - } -} - -// NewImageManifest returns a new ImageManifest object. The values for Platform -// are initialized from those in the image -func NewImageManifest(ref reference.Named, desc ocispec.Descriptor, manifest *schema2.DeserializedManifest) ImageManifest { - raw, err := manifest.MarshalJSON() - if err != nil { - raw = nil - } - - return ImageManifest{ - Ref: &SerializableNamed{Named: ref}, - Descriptor: desc, - Raw: raw, - SchemaV2Manifest: manifest, - } -} - -// NewOCIImageManifest returns a new ImageManifest object. The values for -// Platform are initialized from those in the image -func NewOCIImageManifest(ref reference.Named, desc ocispec.Descriptor, manifest *ocischema.DeserializedManifest) ImageManifest { - raw, err := manifest.MarshalJSON() - if err != nil { - raw = nil - } - - return ImageManifest{ - Ref: &SerializableNamed{Named: ref}, - Descriptor: desc, - Raw: raw, - OCIManifest: manifest, - } -} - -// SerializableNamed is a reference.Named that can be serialized and deserialized -// from JSON -type SerializableNamed struct { - reference.Named -} - -// UnmarshalJSON loads the Named reference from JSON bytes -func (s *SerializableNamed) UnmarshalJSON(b []byte) error { - var raw string - if err := json.Unmarshal(b, &raw); err != nil { - return errors.Wrapf(err, "invalid named reference bytes: %s", b) - } - var err error - s.Named, err = reference.ParseNamed(raw) - return err -} - -// MarshalJSON returns the JSON bytes representation -func (s *SerializableNamed) MarshalJSON() ([]byte, error) { - return json.Marshal(s.String()) -} diff --git a/vendor/github.com/docker/cli/cli/registry/client/client.go b/vendor/github.com/docker/cli/cli/registry/client/client.go deleted file mode 100644 index 1c33a836f..000000000 --- a/vendor/github.com/docker/cli/cli/registry/client/client.go +++ /dev/null @@ -1,198 +0,0 @@ -package client - -import ( - "context" - "fmt" - "net/http" - "strings" - - manifesttypes "github.com/docker/cli/cli/manifest/types" - "github.com/docker/cli/cli/trust" - "github.com/docker/distribution" - "github.com/docker/distribution/reference" - distributionclient "github.com/docker/distribution/registry/client" - registrytypes "github.com/docker/docker/api/types/registry" - "github.com/opencontainers/go-digest" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" -) - -// RegistryClient is a client used to communicate with a Docker distribution -// registry -type RegistryClient interface { - GetManifest(ctx context.Context, ref reference.Named) (manifesttypes.ImageManifest, error) - GetManifestList(ctx context.Context, ref reference.Named) ([]manifesttypes.ImageManifest, error) - MountBlob(ctx context.Context, source reference.Canonical, target reference.Named) error - PutManifest(ctx context.Context, ref reference.Named, manifest distribution.Manifest) (digest.Digest, error) -} - -// NewRegistryClient returns a new RegistryClient with a resolver -func NewRegistryClient(resolver AuthConfigResolver, userAgent string, insecure bool) RegistryClient { - return &client{ - authConfigResolver: resolver, - insecureRegistry: insecure, - userAgent: userAgent, - } -} - -// AuthConfigResolver returns Auth Configuration for an index -type AuthConfigResolver func(ctx context.Context, index *registrytypes.IndexInfo) registrytypes.AuthConfig - -// PutManifestOptions is the data sent to push a manifest -type PutManifestOptions struct { - MediaType string - Payload []byte -} - -type client struct { - authConfigResolver AuthConfigResolver - insecureRegistry bool - userAgent string -} - -// ErrBlobCreated returned when a blob mount request was created -type ErrBlobCreated struct { - From reference.Named - Target reference.Named -} - -func (err ErrBlobCreated) Error() string { - return fmt.Sprintf("blob mounted from: %v to: %v", - err.From, err.Target) -} - -// ErrHTTPProto returned if attempting to use TLS with a non-TLS registry -type ErrHTTPProto struct { - OrigErr string -} - -func (err ErrHTTPProto) Error() string { - return err.OrigErr -} - -var _ RegistryClient = &client{} - -// MountBlob into the registry, so it can be referenced by a manifest -func (c *client) MountBlob(ctx context.Context, sourceRef reference.Canonical, targetRef reference.Named) error { - repoEndpoint, err := newDefaultRepositoryEndpoint(targetRef, c.insecureRegistry) - if err != nil { - return err - } - repoEndpoint.actions = trust.ActionsPushAndPull - repo, err := c.getRepositoryForReference(ctx, targetRef, repoEndpoint) - if err != nil { - return err - } - lu, err := repo.Blobs(ctx).Create(ctx, distributionclient.WithMountFrom(sourceRef)) - switch err.(type) { - case distribution.ErrBlobMounted: - logrus.Debugf("mount of blob %s succeeded", sourceRef) - return nil - case nil: - default: - return errors.Wrapf(err, "failed to mount blob %s to %s", sourceRef, targetRef) - } - lu.Cancel(ctx) - logrus.Debugf("mount of blob %s created", sourceRef) - return ErrBlobCreated{From: sourceRef, Target: targetRef} -} - -// PutManifest sends the manifest to a registry and returns the new digest -func (c *client) PutManifest(ctx context.Context, ref reference.Named, manifest distribution.Manifest) (digest.Digest, error) { - repoEndpoint, err := newDefaultRepositoryEndpoint(ref, c.insecureRegistry) - if err != nil { - return digest.Digest(""), err - } - - repoEndpoint.actions = trust.ActionsPushAndPull - repo, err := c.getRepositoryForReference(ctx, ref, repoEndpoint) - if err != nil { - return digest.Digest(""), err - } - - manifestService, err := repo.Manifests(ctx) - if err != nil { - return digest.Digest(""), err - } - - _, opts, err := getManifestOptionsFromReference(ref) - if err != nil { - return digest.Digest(""), err - } - - dgst, err := manifestService.Put(ctx, manifest, opts...) - return dgst, errors.Wrapf(err, "failed to put manifest %s", ref) -} - -func (c *client) getRepositoryForReference(ctx context.Context, ref reference.Named, repoEndpoint repositoryEndpoint) (distribution.Repository, error) { - repoName, err := reference.WithName(repoEndpoint.Name()) - if err != nil { - return nil, errors.Wrapf(err, "failed to parse repo name from %s", ref) - } - httpTransport, err := c.getHTTPTransportForRepoEndpoint(ctx, repoEndpoint) - if err != nil { - if !strings.Contains(err.Error(), "server gave HTTP response to HTTPS client") { - return nil, err - } - if !repoEndpoint.endpoint.TLSConfig.InsecureSkipVerify { - return nil, ErrHTTPProto{OrigErr: err.Error()} - } - // --insecure was set; fall back to plain HTTP - if url := repoEndpoint.endpoint.URL; url != nil && url.Scheme == "https" { - url.Scheme = "http" - httpTransport, err = c.getHTTPTransportForRepoEndpoint(ctx, repoEndpoint) - if err != nil { - return nil, err - } - } - } - return distributionclient.NewRepository(repoName, repoEndpoint.BaseURL(), httpTransport) -} - -func (c *client) getHTTPTransportForRepoEndpoint(ctx context.Context, repoEndpoint repositoryEndpoint) (http.RoundTripper, error) { - httpTransport, err := getHTTPTransport( - c.authConfigResolver(ctx, repoEndpoint.info.Index), - repoEndpoint.endpoint, - repoEndpoint.Name(), - c.userAgent, - repoEndpoint.actions, - ) - return httpTransport, errors.Wrap(err, "failed to configure transport") -} - -// GetManifest returns an ImageManifest for the reference -func (c *client) GetManifest(ctx context.Context, ref reference.Named) (manifesttypes.ImageManifest, error) { - var result manifesttypes.ImageManifest - fetch := func(ctx context.Context, repo distribution.Repository, ref reference.Named) (bool, error) { - var err error - result, err = fetchManifest(ctx, repo, ref) - return result.Ref != nil, err - } - - err := c.iterateEndpoints(ctx, ref, fetch) - return result, err -} - -// GetManifestList returns a list of ImageManifest for the reference -func (c *client) GetManifestList(ctx context.Context, ref reference.Named) ([]manifesttypes.ImageManifest, error) { - result := []manifesttypes.ImageManifest{} - fetch := func(ctx context.Context, repo distribution.Repository, ref reference.Named) (bool, error) { - var err error - result, err = fetchList(ctx, repo, ref) - return len(result) > 0, err - } - - err := c.iterateEndpoints(ctx, ref, fetch) - return result, err -} - -func getManifestOptionsFromReference(ref reference.Named) (digest.Digest, []distribution.ManifestServiceOption, error) { - if tagged, isTagged := ref.(reference.NamedTagged); isTagged { - tag := tagged.Tag() - return "", []distribution.ManifestServiceOption{distribution.WithTag(tag)}, nil - } - if digested, isDigested := ref.(reference.Canonical); isDigested { - return digested.Digest(), []distribution.ManifestServiceOption{}, nil - } - return "", nil, errors.Errorf("%s no tag or digest", ref) -} diff --git a/vendor/github.com/docker/cli/cli/registry/client/endpoint.go b/vendor/github.com/docker/cli/cli/registry/client/endpoint.go deleted file mode 100644 index 6d0e920c5..000000000 --- a/vendor/github.com/docker/cli/cli/registry/client/endpoint.go +++ /dev/null @@ -1,135 +0,0 @@ -package client - -import ( - "fmt" - "net" - "net/http" - "time" - - "github.com/docker/cli/cli/trust" - "github.com/docker/distribution/reference" - "github.com/docker/distribution/registry/client/auth" - "github.com/docker/distribution/registry/client/transport" - registrytypes "github.com/docker/docker/api/types/registry" - "github.com/docker/docker/registry" - "github.com/pkg/errors" -) - -type repositoryEndpoint struct { - info *registry.RepositoryInfo - endpoint registry.APIEndpoint - actions []string -} - -// Name returns the repository name -func (r repositoryEndpoint) Name() string { - repoName := r.info.Name.Name() - // If endpoint does not support CanonicalName, use the RemoteName instead - if r.endpoint.TrimHostname { - repoName = reference.Path(r.info.Name) - } - return repoName -} - -// BaseURL returns the endpoint url -func (r repositoryEndpoint) BaseURL() string { - return r.endpoint.URL.String() -} - -func newDefaultRepositoryEndpoint(ref reference.Named, insecure bool) (repositoryEndpoint, error) { - repoInfo, err := registry.ParseRepositoryInfo(ref) - if err != nil { - return repositoryEndpoint{}, err - } - endpoint, err := getDefaultEndpointFromRepoInfo(repoInfo) - if err != nil { - return repositoryEndpoint{}, err - } - if insecure { - endpoint.TLSConfig.InsecureSkipVerify = true - } - return repositoryEndpoint{info: repoInfo, endpoint: endpoint}, nil -} - -func getDefaultEndpointFromRepoInfo(repoInfo *registry.RepositoryInfo) (registry.APIEndpoint, error) { - var err error - - options := registry.ServiceOptions{} - registryService, err := registry.NewService(options) - if err != nil { - return registry.APIEndpoint{}, err - } - endpoints, err := registryService.LookupPushEndpoints(reference.Domain(repoInfo.Name)) - if err != nil { - return registry.APIEndpoint{}, err - } - // Default to the highest priority endpoint to return - endpoint := endpoints[0] - if !repoInfo.Index.Secure { - for _, ep := range endpoints { - if ep.URL.Scheme == "http" { - endpoint = ep - } - } - } - return endpoint, nil -} - -// getHTTPTransport builds a transport for use in communicating with a registry -func getHTTPTransport(authConfig registrytypes.AuthConfig, endpoint registry.APIEndpoint, repoName, userAgent string, actions []string) (http.RoundTripper, error) { - // get the http transport, this will be used in a client to upload manifest - base := &http.Transport{ - Proxy: http.ProxyFromEnvironment, - Dial: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - DualStack: true, - }).Dial, - TLSHandshakeTimeout: 10 * time.Second, - TLSClientConfig: endpoint.TLSConfig, - DisableKeepAlives: true, - } - - modifiers := registry.Headers(userAgent, http.Header{}) - authTransport := transport.NewTransport(base, modifiers...) - challengeManager, err := registry.PingV2Registry(endpoint.URL, authTransport) - if err != nil { - return nil, errors.Wrap(err, "error pinging v2 registry") - } - if authConfig.RegistryToken != "" { - passThruTokenHandler := &existingTokenHandler{token: authConfig.RegistryToken} - modifiers = append(modifiers, auth.NewAuthorizer(challengeManager, passThruTokenHandler)) - } else { - if len(actions) == 0 { - actions = trust.ActionsPullOnly - } - creds := registry.NewStaticCredentialStore(&authConfig) - tokenHandler := auth.NewTokenHandler(authTransport, creds, repoName, actions...) - basicHandler := auth.NewBasicHandler(creds) - modifiers = append(modifiers, auth.NewAuthorizer(challengeManager, tokenHandler, basicHandler)) - } - return transport.NewTransport(base, modifiers...), nil -} - -// RepoNameForReference returns the repository name from a reference -func RepoNameForReference(ref reference.Named) (string, error) { - // insecure is fine since this only returns the name - repo, err := newDefaultRepositoryEndpoint(ref, false) - if err != nil { - return "", err - } - return repo.Name(), nil -} - -type existingTokenHandler struct { - token string -} - -func (th *existingTokenHandler) AuthorizeRequest(req *http.Request, _ map[string]string) error { - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", th.token)) - return nil -} - -func (th *existingTokenHandler) Scheme() string { - return "bearer" -} diff --git a/vendor/github.com/docker/cli/cli/registry/client/fetcher.go b/vendor/github.com/docker/cli/cli/registry/client/fetcher.go deleted file mode 100644 index 3ce09d137..000000000 --- a/vendor/github.com/docker/cli/cli/registry/client/fetcher.go +++ /dev/null @@ -1,323 +0,0 @@ -package client - -import ( - "context" - "encoding/json" - - "github.com/docker/cli/cli/manifest/types" - "github.com/docker/distribution" - "github.com/docker/distribution/manifest/manifestlist" - "github.com/docker/distribution/manifest/ocischema" - "github.com/docker/distribution/manifest/schema2" - "github.com/docker/distribution/reference" - "github.com/docker/distribution/registry/api/errcode" - v2 "github.com/docker/distribution/registry/api/v2" - distclient "github.com/docker/distribution/registry/client" - "github.com/docker/docker/registry" - "github.com/opencontainers/go-digest" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" -) - -// fetchManifest pulls a manifest from a registry and returns it. An error -// is returned if no manifest is found matching namedRef. -func fetchManifest(ctx context.Context, repo distribution.Repository, ref reference.Named) (types.ImageManifest, error) { - manifest, err := getManifest(ctx, repo, ref) - if err != nil { - return types.ImageManifest{}, err - } - - switch v := manifest.(type) { - // Removed Schema 1 support - case *schema2.DeserializedManifest: - imageManifest, err := pullManifestSchemaV2(ctx, ref, repo, *v) - if err != nil { - return types.ImageManifest{}, err - } - return imageManifest, nil - case *ocischema.DeserializedManifest: - imageManifest, err := pullManifestOCISchema(ctx, ref, repo, *v) - if err != nil { - return types.ImageManifest{}, err - } - return imageManifest, nil - case *manifestlist.DeserializedManifestList: - return types.ImageManifest{}, errors.Errorf("%s is a manifest list", ref) - } - return types.ImageManifest{}, errors.Errorf("%s is not a manifest", ref) -} - -func fetchList(ctx context.Context, repo distribution.Repository, ref reference.Named) ([]types.ImageManifest, error) { - manifest, err := getManifest(ctx, repo, ref) - if err != nil { - return nil, err - } - - switch v := manifest.(type) { - case *manifestlist.DeserializedManifestList: - imageManifests, err := pullManifestList(ctx, ref, repo, *v) - if err != nil { - return nil, err - } - return imageManifests, nil - default: - return nil, errors.Errorf("unsupported manifest format: %v", v) - } -} - -func getManifest(ctx context.Context, repo distribution.Repository, ref reference.Named) (distribution.Manifest, error) { - manSvc, err := repo.Manifests(ctx) - if err != nil { - return nil, err - } - - dgst, opts, err := getManifestOptionsFromReference(ref) - if err != nil { - return nil, errors.Errorf("image manifest for %q does not exist", ref) - } - return manSvc.Get(ctx, dgst, opts...) -} - -func pullManifestSchemaV2(ctx context.Context, ref reference.Named, repo distribution.Repository, mfst schema2.DeserializedManifest) (types.ImageManifest, error) { - manifestDesc, err := validateManifestDigest(ref, mfst) - if err != nil { - return types.ImageManifest{}, err - } - configJSON, err := pullManifestSchemaV2ImageConfig(ctx, mfst.Target().Digest, repo) - if err != nil { - return types.ImageManifest{}, err - } - - if manifestDesc.Platform == nil { - manifestDesc.Platform = &ocispec.Platform{} - } - - // Fill in os and architecture fields from config JSON - if err := json.Unmarshal(configJSON, manifestDesc.Platform); err != nil { - return types.ImageManifest{}, err - } - - return types.NewImageManifest(ref, manifestDesc, &mfst), nil -} - -func pullManifestOCISchema(ctx context.Context, ref reference.Named, repo distribution.Repository, mfst ocischema.DeserializedManifest) (types.ImageManifest, error) { - manifestDesc, err := validateManifestDigest(ref, mfst) - if err != nil { - return types.ImageManifest{}, err - } - configJSON, err := pullManifestSchemaV2ImageConfig(ctx, mfst.Target().Digest, repo) - if err != nil { - return types.ImageManifest{}, err - } - - if manifestDesc.Platform == nil { - manifestDesc.Platform = &ocispec.Platform{} - } - - // Fill in os and architecture fields from config JSON - if err := json.Unmarshal(configJSON, manifestDesc.Platform); err != nil { - return types.ImageManifest{}, err - } - - return types.NewOCIImageManifest(ref, manifestDesc, &mfst), nil -} - -func pullManifestSchemaV2ImageConfig(ctx context.Context, dgst digest.Digest, repo distribution.Repository) ([]byte, error) { - blobs := repo.Blobs(ctx) - configJSON, err := blobs.Get(ctx, dgst) - if err != nil { - return nil, err - } - - verifier := dgst.Verifier() - if _, err := verifier.Write(configJSON); err != nil { - return nil, err - } - if !verifier.Verified() { - return nil, errors.Errorf("image config verification failed for digest %s", dgst) - } - return configJSON, nil -} - -// validateManifestDigest computes the manifest digest, and, if pulling by -// digest, ensures that it matches the requested digest. -func validateManifestDigest(ref reference.Named, mfst distribution.Manifest) (ocispec.Descriptor, error) { - mediaType, canonical, err := mfst.Payload() - if err != nil { - return ocispec.Descriptor{}, err - } - desc := ocispec.Descriptor{ - Digest: digest.FromBytes(canonical), - Size: int64(len(canonical)), - MediaType: mediaType, - } - - // If pull by digest, then verify the manifest digest. - if digested, isDigested := ref.(reference.Canonical); isDigested { - if digested.Digest() != desc.Digest { - err := errors.Errorf("manifest verification failed for digest %s", digested.Digest()) - return ocispec.Descriptor{}, err - } - } - - return desc, nil -} - -// pullManifestList handles "manifest lists" which point to various -// platform-specific manifests. -func pullManifestList(ctx context.Context, ref reference.Named, repo distribution.Repository, mfstList manifestlist.DeserializedManifestList) ([]types.ImageManifest, error) { - infos := []types.ImageManifest{} - - if _, err := validateManifestDigest(ref, mfstList); err != nil { - return nil, err - } - - for _, manifestDescriptor := range mfstList.Manifests { - manSvc, err := repo.Manifests(ctx) - if err != nil { - return nil, err - } - manifest, err := manSvc.Get(ctx, manifestDescriptor.Digest) - if err != nil { - return nil, err - } - - manifestRef, err := reference.WithDigest(ref, manifestDescriptor.Digest) - if err != nil { - return nil, err - } - - var imageManifest types.ImageManifest - switch v := manifest.(type) { - case *schema2.DeserializedManifest: - imageManifest, err = pullManifestSchemaV2(ctx, manifestRef, repo, *v) - case *ocischema.DeserializedManifest: - imageManifest, err = pullManifestOCISchema(ctx, manifestRef, repo, *v) - default: - err = errors.Errorf("unsupported manifest type: %T", manifest) - } - if err != nil { - return nil, err - } - - // Replace platform from config - p := manifestDescriptor.Platform - imageManifest.Descriptor.Platform = types.OCIPlatform(&p) - - infos = append(infos, imageManifest) - } - return infos, nil -} - -func continueOnError(err error) bool { - switch v := err.(type) { - case errcode.Errors: - if len(v) == 0 { - return true - } - return continueOnError(v[0]) - case errcode.Error: - e := err.(errcode.Error) - switch e.Code { - case errcode.ErrorCodeUnauthorized, v2.ErrorCodeManifestUnknown, v2.ErrorCodeNameUnknown: - return true - } - return false - case *distclient.UnexpectedHTTPResponseError: - return true - } - return false -} - -func (c *client) iterateEndpoints(ctx context.Context, namedRef reference.Named, each func(context.Context, distribution.Repository, reference.Named) (bool, error)) error { - endpoints, err := allEndpoints(namedRef, c.insecureRegistry) - if err != nil { - return err - } - - repoInfo, err := registry.ParseRepositoryInfo(namedRef) - if err != nil { - return err - } - - confirmedTLSRegistries := make(map[string]bool) - for _, endpoint := range endpoints { - if endpoint.URL.Scheme != "https" { - if _, confirmedTLS := confirmedTLSRegistries[endpoint.URL.Host]; confirmedTLS { - logrus.Debugf("skipping non-TLS endpoint %s for host/port that appears to use TLS", endpoint.URL) - continue - } - } - - if c.insecureRegistry { - endpoint.TLSConfig.InsecureSkipVerify = true - } - repoEndpoint := repositoryEndpoint{endpoint: endpoint, info: repoInfo} - repo, err := c.getRepositoryForReference(ctx, namedRef, repoEndpoint) - if err != nil { - logrus.Debugf("error %s with repo endpoint %+v", err, repoEndpoint) - if _, ok := err.(ErrHTTPProto); ok { - continue - } - return err - } - - if endpoint.URL.Scheme == "http" && !c.insecureRegistry { - logrus.Debugf("skipping non-tls registry endpoint: %s", endpoint.URL) - continue - } - done, err := each(ctx, repo, namedRef) - if err != nil { - if continueOnError(err) { - if endpoint.URL.Scheme == "https" { - confirmedTLSRegistries[endpoint.URL.Host] = true - } - logrus.Debugf("continuing on error (%T) %s", err, err) - continue - } - logrus.Debugf("not continuing on error (%T) %s", err, err) - return err - } - if done { - return nil - } - } - return newNotFoundError(namedRef.String()) -} - -// allEndpoints returns a list of endpoints ordered by priority (v2, https, v1). -func allEndpoints(namedRef reference.Named, insecure bool) ([]registry.APIEndpoint, error) { - repoInfo, err := registry.ParseRepositoryInfo(namedRef) - if err != nil { - return nil, err - } - - var serviceOpts registry.ServiceOptions - if insecure { - logrus.Debugf("allowing insecure registry for: %s", reference.Domain(namedRef)) - serviceOpts.InsecureRegistries = []string{reference.Domain(namedRef)} - } - registryService, err := registry.NewService(serviceOpts) - if err != nil { - return []registry.APIEndpoint{}, err - } - endpoints, err := registryService.LookupPullEndpoints(reference.Domain(repoInfo.Name)) - logrus.Debugf("endpoints for %s: %v", namedRef, endpoints) - return endpoints, err -} - -func newNotFoundError(ref string) *notFoundError { - return ¬FoundError{err: errors.New("no such manifest: " + ref)} -} - -type notFoundError struct { - err error -} - -func (n *notFoundError) Error() string { - return n.err.Error() -} - -// NotFound satisfies interface github.com/docker/docker/errdefs.ErrNotFound -func (n *notFoundError) NotFound() {} diff --git a/vendor/github.com/docker/cli/cli/required.go b/vendor/github.com/docker/cli/cli/required.go deleted file mode 100644 index 454e24761..000000000 --- a/vendor/github.com/docker/cli/cli/required.go +++ /dev/null @@ -1,108 +0,0 @@ -package cli - -import ( - "strings" - - "github.com/pkg/errors" - "github.com/spf13/cobra" -) - -// NoArgs validates args and returns an error if there are any args -func NoArgs(cmd *cobra.Command, args []string) error { - if len(args) == 0 { - return nil - } - - if cmd.HasSubCommands() { - return errors.Errorf("\n" + strings.TrimRight(cmd.UsageString(), "\n")) - } - - return errors.Errorf( - "%q accepts no arguments.\nSee '%s --help'.\n\nUsage: %s\n\n%s", - cmd.CommandPath(), - cmd.CommandPath(), - cmd.UseLine(), - cmd.Short, - ) -} - -// RequiresMinArgs returns an error if there is not at least min args -func RequiresMinArgs(min int) cobra.PositionalArgs { - return func(cmd *cobra.Command, args []string) error { - if len(args) >= min { - return nil - } - return errors.Errorf( - "%q requires at least %d %s.\nSee '%s --help'.\n\nUsage: %s\n\n%s", - cmd.CommandPath(), - min, - pluralize("argument", min), - cmd.CommandPath(), - cmd.UseLine(), - cmd.Short, - ) - } -} - -// RequiresMaxArgs returns an error if there is not at most max args -func RequiresMaxArgs(max int) cobra.PositionalArgs { - return func(cmd *cobra.Command, args []string) error { - if len(args) <= max { - return nil - } - return errors.Errorf( - "%q requires at most %d %s.\nSee '%s --help'.\n\nUsage: %s\n\n%s", - cmd.CommandPath(), - max, - pluralize("argument", max), - cmd.CommandPath(), - cmd.UseLine(), - cmd.Short, - ) - } -} - -// RequiresRangeArgs returns an error if there is not at least min args and at most max args -func RequiresRangeArgs(min int, max int) cobra.PositionalArgs { - return func(cmd *cobra.Command, args []string) error { - if len(args) >= min && len(args) <= max { - return nil - } - return errors.Errorf( - "%q requires at least %d and at most %d %s.\nSee '%s --help'.\n\nUsage: %s\n\n%s", - cmd.CommandPath(), - min, - max, - pluralize("argument", max), - cmd.CommandPath(), - cmd.UseLine(), - cmd.Short, - ) - } -} - -// ExactArgs returns an error if there is not the exact number of args -func ExactArgs(number int) cobra.PositionalArgs { - return func(cmd *cobra.Command, args []string) error { - if len(args) == number { - return nil - } - return errors.Errorf( - "%q requires exactly %d %s.\nSee '%s --help'.\n\nUsage: %s\n\n%s", - cmd.CommandPath(), - number, - pluralize("argument", number), - cmd.CommandPath(), - cmd.UseLine(), - cmd.Short, - ) - } -} - -//nolint:unparam -func pluralize(word string, number int) string { - if number == 1 { - return word - } - return word + "s" -} diff --git a/vendor/github.com/docker/cli/cli/streams/in.go b/vendor/github.com/docker/cli/cli/streams/in.go deleted file mode 100644 index 1a10f7c83..000000000 --- a/vendor/github.com/docker/cli/cli/streams/in.go +++ /dev/null @@ -1,61 +0,0 @@ -package streams - -import ( - "errors" - "io" - "os" - "runtime" - - "github.com/moby/term" -) - -// In is an input stream to read user input. It implements [io.ReadCloser] -// with additional utilities, such as putting the terminal in raw mode. -type In struct { - commonStream - in io.ReadCloser -} - -// Read implements the [io.Reader] interface. -func (i *In) Read(p []byte) (int, error) { - return i.in.Read(p) -} - -// Close implements the [io.Closer] interface. -func (i *In) Close() error { - return i.in.Close() -} - -// SetRawTerminal sets raw mode on the input terminal. It is a no-op if In -// is not a TTY, or if the "NORAW" environment variable is set to a non-empty -// value. -func (i *In) SetRawTerminal() (err error) { - if !i.isTerminal || os.Getenv("NORAW") != "" { - return nil - } - i.state, err = term.SetRawTerminal(i.fd) - return err -} - -// CheckTty checks if we are trying to attach to a container TTY -// from a non-TTY client input stream, and if so, returns an error. -func (i *In) CheckTty(attachStdin, ttyMode bool) error { - // In order to attach to a container tty, input stream for the client must - // be a tty itself: redirecting or piping the client standard input is - // incompatible with `docker run -t`, `docker exec -t` or `docker attach`. - if ttyMode && attachStdin && !i.isTerminal { - const eText = "the input device is not a TTY" - if runtime.GOOS == "windows" { - return errors.New(eText + ". If you are using mintty, try prefixing the command with 'winpty'") - } - return errors.New(eText) - } - return nil -} - -// NewIn returns a new [In] from an [io.ReadCloser]. -func NewIn(in io.ReadCloser) *In { - i := &In{in: in} - i.fd, i.isTerminal = term.GetFdInfo(in) - return i -} diff --git a/vendor/github.com/docker/cli/cli/streams/out.go b/vendor/github.com/docker/cli/cli/streams/out.go deleted file mode 100644 index 2383b0857..000000000 --- a/vendor/github.com/docker/cli/cli/streams/out.go +++ /dev/null @@ -1,58 +0,0 @@ -package streams - -import ( - "io" - "os" - - "github.com/moby/term" - "github.com/sirupsen/logrus" -) - -// Out is an output stream to write normal program output. It implements -// an [io.Writer], with additional utilities for detecting whether a terminal -// is connected, getting the TTY size, and putting the terminal in raw mode. -type Out struct { - commonStream - out io.Writer -} - -func (o *Out) Write(p []byte) (int, error) { - return o.out.Write(p) -} - -// SetRawTerminal puts the output of the terminal connected to the stream -// into raw mode. -// -// On UNIX, this does nothing. On Windows, it disables LF -> CRLF/ translation. -// It is a no-op if Out is not a TTY, or if the "NORAW" environment variable is -// set to a non-empty value. -func (o *Out) SetRawTerminal() (err error) { - if !o.isTerminal || os.Getenv("NORAW") != "" { - return nil - } - o.state, err = term.SetRawTerminalOutput(o.fd) - return err -} - -// GetTtySize returns the height and width in characters of the TTY, or -// zero for both if no TTY is connected. -func (o *Out) GetTtySize() (height uint, width uint) { - if !o.isTerminal { - return 0, 0 - } - ws, err := term.GetWinsize(o.fd) - if err != nil { - logrus.WithError(err).Debug("Error getting TTY size") - if ws == nil { - return 0, 0 - } - } - return uint(ws.Height), uint(ws.Width) -} - -// NewOut returns a new [Out] from an [io.Writer]. -func NewOut(out io.Writer) *Out { - o := &Out{out: out} - o.fd, o.isTerminal = term.GetFdInfo(out) - return o -} diff --git a/vendor/github.com/docker/cli/cli/streams/stream.go b/vendor/github.com/docker/cli/cli/streams/stream.go deleted file mode 100644 index 54c9cda0b..000000000 --- a/vendor/github.com/docker/cli/cli/streams/stream.go +++ /dev/null @@ -1,35 +0,0 @@ -package streams - -import ( - "github.com/moby/term" -) - -type commonStream struct { - fd uintptr - isTerminal bool - state *term.State -} - -// FD returns the file descriptor number for this stream. -func (s *commonStream) FD() uintptr { - return s.fd -} - -// IsTerminal returns true if this stream is connected to a terminal. -func (s *commonStream) IsTerminal() bool { - return s.isTerminal -} - -// RestoreTerminal restores normal mode to the terminal. -func (s *commonStream) RestoreTerminal() { - if s.state != nil { - _ = term.RestoreTerminal(s.fd, s.state) - } -} - -// SetIsTerminal overrides whether a terminal is connected. It is used to -// override this property in unit-tests, and should not be depended on for -// other purposes. -func (s *commonStream) SetIsTerminal(isTerminal bool) { - s.isTerminal = isTerminal -} diff --git a/vendor/github.com/docker/cli/cli/trust/trust.go b/vendor/github.com/docker/cli/cli/trust/trust.go deleted file mode 100644 index 5a862e7f0..000000000 --- a/vendor/github.com/docker/cli/cli/trust/trust.go +++ /dev/null @@ -1,378 +0,0 @@ -package trust - -import ( - "context" - "encoding/json" - "io" - "net" - "net/http" - "net/url" - "os" - "path" - "path/filepath" - "time" - - "github.com/docker/cli/cli/config" - "github.com/docker/distribution/reference" - "github.com/docker/distribution/registry/client/auth" - "github.com/docker/distribution/registry/client/auth/challenge" - "github.com/docker/distribution/registry/client/transport" - registrytypes "github.com/docker/docker/api/types/registry" - "github.com/docker/docker/registry" - "github.com/docker/go-connections/tlsconfig" - "github.com/opencontainers/go-digest" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" - "github.com/theupdateframework/notary" - "github.com/theupdateframework/notary/client" - "github.com/theupdateframework/notary/passphrase" - "github.com/theupdateframework/notary/storage" - "github.com/theupdateframework/notary/trustmanager" - "github.com/theupdateframework/notary/trustpinning" - "github.com/theupdateframework/notary/tuf/data" - "github.com/theupdateframework/notary/tuf/signed" -) - -var ( - // ReleasesRole is the role named "releases" - ReleasesRole = data.RoleName(path.Join(data.CanonicalTargetsRole.String(), "releases")) - // ActionsPullOnly defines the actions for read-only interactions with a Notary Repository - ActionsPullOnly = []string{"pull"} - // ActionsPushAndPull defines the actions for read-write interactions with a Notary Repository - ActionsPushAndPull = []string{"pull", "push"} - // NotaryServer is the endpoint serving the Notary trust server - NotaryServer = "https://notary.docker.io" -) - -// GetTrustDirectory returns the base trust directory name -func GetTrustDirectory() string { - return filepath.Join(config.Dir(), "trust") -} - -// certificateDirectory returns the directory containing -// TLS certificates for the given server. An error is -// returned if there was an error parsing the server string. -func certificateDirectory(server string) (string, error) { - u, err := url.Parse(server) - if err != nil { - return "", err - } - - return filepath.Join(config.Dir(), "tls", u.Host), nil -} - -// Server returns the base URL for the trust server. -func Server(index *registrytypes.IndexInfo) (string, error) { - if s := os.Getenv("DOCKER_CONTENT_TRUST_SERVER"); s != "" { - urlObj, err := url.Parse(s) - if err != nil || urlObj.Scheme != "https" { - return "", errors.Errorf("valid https URL required for trust server, got %s", s) - } - - return s, nil - } - if index.Official { - return NotaryServer, nil - } - return "https://" + index.Name, nil -} - -type simpleCredentialStore struct { - auth registrytypes.AuthConfig -} - -func (scs simpleCredentialStore) Basic(*url.URL) (string, string) { - return scs.auth.Username, scs.auth.Password -} - -func (scs simpleCredentialStore) RefreshToken(*url.URL, string) string { - return scs.auth.IdentityToken -} - -func (scs simpleCredentialStore) SetRefreshToken(*url.URL, string, string) {} - -// GetNotaryRepository returns a NotaryRepository which stores all the -// information needed to operate on a notary repository. -// It creates an HTTP transport providing authentication support. -func GetNotaryRepository(in io.Reader, out io.Writer, userAgent string, repoInfo *registry.RepositoryInfo, authConfig *registrytypes.AuthConfig, actions ...string) (client.Repository, error) { - server, err := Server(repoInfo.Index) - if err != nil { - return nil, err - } - - cfg := tlsconfig.ClientDefault() - cfg.InsecureSkipVerify = !repoInfo.Index.Secure - - // Get certificate base directory - certDir, err := certificateDirectory(server) - if err != nil { - return nil, err - } - logrus.Debugf("reading certificate directory: %s", certDir) - - if err := registry.ReadCertsDirectory(cfg, certDir); err != nil { - return nil, err - } - - base := &http.Transport{ - Proxy: http.ProxyFromEnvironment, - Dial: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - DualStack: true, - }).Dial, - TLSHandshakeTimeout: 10 * time.Second, - TLSClientConfig: cfg, - DisableKeepAlives: true, - } - - // Skip configuration headers since request is not going to Docker daemon - modifiers := registry.Headers(userAgent, http.Header{}) - authTransport := transport.NewTransport(base, modifiers...) - pingClient := &http.Client{ - Transport: authTransport, - Timeout: 5 * time.Second, - } - endpointStr := server + "/v2/" - req, err := http.NewRequest(http.MethodGet, endpointStr, nil) - if err != nil { - return nil, err - } - - challengeManager := challenge.NewSimpleManager() - - resp, err := pingClient.Do(req) - if err != nil { - // Ignore error on ping to operate in offline mode - logrus.Debugf("Error pinging notary server %q: %s", endpointStr, err) - } else { - defer resp.Body.Close() - - // Add response to the challenge manager to parse out - // authentication header and register authentication method - if err := challengeManager.AddResponse(resp); err != nil { - return nil, err - } - } - - scope := auth.RepositoryScope{ - Repository: repoInfo.Name.Name(), - Actions: actions, - Class: repoInfo.Class, // TODO(thaJeztah): Class is no longer needed for plugins and can likely be removed; see https://github.com/docker/cli/pull/4114#discussion_r1145430825 - } - creds := simpleCredentialStore{auth: *authConfig} - tokenHandlerOptions := auth.TokenHandlerOptions{ - Transport: authTransport, - Credentials: creds, - Scopes: []auth.Scope{scope}, - ClientID: registry.AuthClientID, - } - tokenHandler := auth.NewTokenHandlerWithOptions(tokenHandlerOptions) - basicHandler := auth.NewBasicHandler(creds) - modifiers = append(modifiers, auth.NewAuthorizer(challengeManager, tokenHandler, basicHandler)) - tr := transport.NewTransport(base, modifiers...) - - return client.NewFileCachedRepository( - GetTrustDirectory(), - data.GUN(repoInfo.Name.Name()), - server, - tr, - GetPassphraseRetriever(in, out), - trustpinning.TrustPinConfig{}) -} - -// GetPassphraseRetriever returns a passphrase retriever that utilizes Content Trust env vars -func GetPassphraseRetriever(in io.Reader, out io.Writer) notary.PassRetriever { - aliasMap := map[string]string{ - "root": "root", - "snapshot": "repository", - "targets": "repository", - "default": "repository", - } - baseRetriever := passphrase.PromptRetrieverWithInOut(in, out, aliasMap) - env := map[string]string{ - "root": os.Getenv("DOCKER_CONTENT_TRUST_ROOT_PASSPHRASE"), - "snapshot": os.Getenv("DOCKER_CONTENT_TRUST_REPOSITORY_PASSPHRASE"), - "targets": os.Getenv("DOCKER_CONTENT_TRUST_REPOSITORY_PASSPHRASE"), - "default": os.Getenv("DOCKER_CONTENT_TRUST_REPOSITORY_PASSPHRASE"), - } - - return func(keyName string, alias string, createNew bool, numAttempts int) (string, bool, error) { - if v := env[alias]; v != "" { - return v, numAttempts > 1, nil - } - // For non-root roles, we can also try the "default" alias if it is specified - if v := env["default"]; v != "" && alias != data.CanonicalRootRole.String() { - return v, numAttempts > 1, nil - } - return baseRetriever(keyName, alias, createNew, numAttempts) - } -} - -// NotaryError formats an error message received from the notary service -func NotaryError(repoName string, err error) error { - switch err.(type) { - case *json.SyntaxError: - logrus.Debugf("Notary syntax error: %s", err) - return errors.Errorf("Error: no trust data available for remote repository %s. Try running notary server and setting DOCKER_CONTENT_TRUST_SERVER to its HTTPS address?", repoName) - case signed.ErrExpired: - return errors.Errorf("Error: remote repository %s out-of-date: %v", repoName, err) - case trustmanager.ErrKeyNotFound: - return errors.Errorf("Error: signing keys for remote repository %s not found: %v", repoName, err) - case storage.NetworkError: - return errors.Errorf("Error: error contacting notary server: %v", err) - case storage.ErrMetaNotFound: - return errors.Errorf("Error: trust data missing for remote repository %s or remote repository not found: %v", repoName, err) - case trustpinning.ErrRootRotationFail, trustpinning.ErrValidationFail, signed.ErrInvalidKeyType: - return errors.Errorf("Warning: potential malicious behavior - trust data mismatch for remote repository %s: %v", repoName, err) - case signed.ErrNoKeys: - return errors.Errorf("Error: could not find signing keys for remote repository %s, or could not decrypt signing key: %v", repoName, err) - case signed.ErrLowVersion: - return errors.Errorf("Warning: potential malicious behavior - trust data version is lower than expected for remote repository %s: %v", repoName, err) - case signed.ErrRoleThreshold: - return errors.Errorf("Warning: potential malicious behavior - trust data has insufficient signatures for remote repository %s: %v", repoName, err) - case client.ErrRepositoryNotExist: - return errors.Errorf("Error: remote trust data does not exist for %s: %v", repoName, err) - case signed.ErrInsufficientSignatures: - return errors.Errorf("Error: could not produce valid signature for %s. If Yubikey was used, was touch input provided?: %v", repoName, err) - } - - return err -} - -// GetSignableRoles returns a list of roles for which we have valid signing -// keys, given a notary repository and a target -func GetSignableRoles(repo client.Repository, target *client.Target) ([]data.RoleName, error) { - var signableRoles []data.RoleName - - // translate the full key names, which includes the GUN, into just the key IDs - allCanonicalKeyIDs := make(map[string]struct{}) - for fullKeyID := range repo.GetCryptoService().ListAllKeys() { - allCanonicalKeyIDs[path.Base(fullKeyID)] = struct{}{} - } - - allDelegationRoles, err := repo.GetDelegationRoles() - if err != nil { - return signableRoles, err - } - - // if there are no delegation roles, then just try to sign it into the targets role - if len(allDelegationRoles) == 0 { - signableRoles = append(signableRoles, data.CanonicalTargetsRole) - return signableRoles, nil - } - - // there are delegation roles, find every delegation role we have a key for, and - // attempt to sign into into all those roles. - for _, delegationRole := range allDelegationRoles { - // We do not support signing any delegation role that isn't a direct child of the targets role. - // Also don't bother checking the keys if we can't add the target - // to this role due to path restrictions - if path.Dir(delegationRole.Name.String()) != data.CanonicalTargetsRole.String() || !delegationRole.CheckPaths(target.Name) { - continue - } - - for _, canonicalKeyID := range delegationRole.KeyIDs { - if _, ok := allCanonicalKeyIDs[canonicalKeyID]; ok { - signableRoles = append(signableRoles, delegationRole.Name) - break - } - } - } - - if len(signableRoles) == 0 { - return signableRoles, errors.Errorf("no valid signing keys for delegation roles") - } - - return signableRoles, nil -} - -// ImageRefAndAuth contains all reference information and the auth config for an image request -type ImageRefAndAuth struct { - original string - authConfig *registrytypes.AuthConfig - reference reference.Named - repoInfo *registry.RepositoryInfo - tag string - digest digest.Digest -} - -// GetImageReferencesAndAuth retrieves the necessary reference and auth information for an image name -// as an ImageRefAndAuth struct -func GetImageReferencesAndAuth(ctx context.Context, - authResolver func(ctx context.Context, index *registrytypes.IndexInfo) registrytypes.AuthConfig, - imgName string, -) (ImageRefAndAuth, error) { - ref, err := reference.ParseNormalizedNamed(imgName) - if err != nil { - return ImageRefAndAuth{}, err - } - - // Resolve the Repository name from fqn to RepositoryInfo - repoInfo, err := registry.ParseRepositoryInfo(ref) - if err != nil { - return ImageRefAndAuth{}, err - } - - authConfig := authResolver(ctx, repoInfo.Index) - return ImageRefAndAuth{ - original: imgName, - authConfig: &authConfig, - reference: ref, - repoInfo: repoInfo, - tag: getTag(ref), - digest: getDigest(ref), - }, nil -} - -func getTag(ref reference.Named) string { - switch x := ref.(type) { - case reference.Canonical, reference.Digested: - return "" - case reference.NamedTagged: - return x.Tag() - default: - return "" - } -} - -func getDigest(ref reference.Named) digest.Digest { - switch x := ref.(type) { - case reference.Canonical: - return x.Digest() - case reference.Digested: - return x.Digest() - default: - return digest.Digest("") - } -} - -// AuthConfig returns the auth information (username, etc) for a given ImageRefAndAuth -func (imgRefAuth *ImageRefAndAuth) AuthConfig() *registrytypes.AuthConfig { - return imgRefAuth.authConfig -} - -// Reference returns the Image reference for a given ImageRefAndAuth -func (imgRefAuth *ImageRefAndAuth) Reference() reference.Named { - return imgRefAuth.reference -} - -// RepoInfo returns the repository information for a given ImageRefAndAuth -func (imgRefAuth *ImageRefAndAuth) RepoInfo() *registry.RepositoryInfo { - return imgRefAuth.repoInfo -} - -// Tag returns the Image tag for a given ImageRefAndAuth -func (imgRefAuth *ImageRefAndAuth) Tag() string { - return imgRefAuth.tag -} - -// Digest returns the Image digest for a given ImageRefAndAuth -func (imgRefAuth *ImageRefAndAuth) Digest() digest.Digest { - return imgRefAuth.digest -} - -// Name returns the image name used to initialize the ImageRefAndAuth -func (imgRefAuth *ImageRefAndAuth) Name() string { - return imgRefAuth.original -} diff --git a/vendor/github.com/docker/cli/cli/version/version.go b/vendor/github.com/docker/cli/cli/version/version.go deleted file mode 100644 index a263b9a73..000000000 --- a/vendor/github.com/docker/cli/cli/version/version.go +++ /dev/null @@ -1,10 +0,0 @@ -package version - -// Default build-time variable. -// These values are overridden via ldflags -var ( - PlatformName = "" - Version = "unknown-version" - GitCommit = "unknown-commit" - BuildTime = "unknown-buildtime" -) diff --git a/vendor/github.com/docker/cli/opts/capabilities.go b/vendor/github.com/docker/cli/opts/capabilities.go deleted file mode 100644 index 82d071853..000000000 --- a/vendor/github.com/docker/cli/opts/capabilities.go +++ /dev/null @@ -1,89 +0,0 @@ -package opts - -import ( - "sort" - "strings" -) - -const ( - // AllCapabilities is a special value to add or drop all capabilities - AllCapabilities = "ALL" - - // ResetCapabilities is a special value to reset capabilities when updating. - // This value should only be used when updating, not used on "create". - ResetCapabilities = "RESET" -) - -// NormalizeCapability normalizes a capability by upper-casing, trimming white space -// and adding a CAP_ prefix (if not yet present). This function also accepts the -// "ALL" magic-value, as used by CapAdd/CapDrop. -// -// This function only handles rudimentary formatting; no validation is performed, -// as the list of available capabilities can be updated over time, thus should be -// handled by the daemon. -func NormalizeCapability(capability string) string { - capability = strings.ToUpper(strings.TrimSpace(capability)) - if capability == AllCapabilities || capability == ResetCapabilities { - return capability - } - if !strings.HasPrefix(capability, "CAP_") { - capability = "CAP_" + capability - } - return capability -} - -// CapabilitiesMap normalizes the given capabilities and converts them to a map. -func CapabilitiesMap(caps []string) map[string]bool { - normalized := make(map[string]bool) - for _, c := range caps { - normalized[NormalizeCapability(c)] = true - } - return normalized -} - -// EffectiveCapAddCapDrop normalizes and sorts capabilities to "add" and "drop", -// and returns the effective capabilities to include in both. -// -// "CapAdd" takes precedence over "CapDrop", so capabilities included in both -// lists are removed from the list of capabilities to drop. The special "ALL" -// capability is also taken into account. -// -// Note that the special "RESET" value is only used when updating an existing -// service, and will be ignored. -// -// Duplicates are removed, and the resulting lists are sorted. -func EffectiveCapAddCapDrop(add, drop []string) (capAdd, capDrop []string) { - var ( - addCaps = CapabilitiesMap(add) - dropCaps = CapabilitiesMap(drop) - ) - - if addCaps[AllCapabilities] { - // Special case: "ALL capabilities" trumps any other capability added. - addCaps = map[string]bool{AllCapabilities: true} - } - if dropCaps[AllCapabilities] { - // Special case: "ALL capabilities" trumps any other capability added. - dropCaps = map[string]bool{AllCapabilities: true} - } - for c := range dropCaps { - if addCaps[c] { - // Adding a capability takes precedence, so skip dropping - continue - } - if c != ResetCapabilities { - capDrop = append(capDrop, c) - } - } - - for c := range addCaps { - if c != ResetCapabilities { - capAdd = append(capAdd, c) - } - } - - sort.Strings(capAdd) - sort.Strings(capDrop) - - return capAdd, capDrop -} diff --git a/vendor/github.com/docker/cli/opts/config.go b/vendor/github.com/docker/cli/opts/config.go deleted file mode 100644 index 3be0fa93d..000000000 --- a/vendor/github.com/docker/cli/opts/config.go +++ /dev/null @@ -1,99 +0,0 @@ -package opts - -import ( - "encoding/csv" - "fmt" - "os" - "strconv" - "strings" - - swarmtypes "github.com/docker/docker/api/types/swarm" -) - -// ConfigOpt is a Value type for parsing configs -type ConfigOpt struct { - values []*swarmtypes.ConfigReference -} - -// Set a new config value -func (o *ConfigOpt) Set(value string) error { - csvReader := csv.NewReader(strings.NewReader(value)) - fields, err := csvReader.Read() - if err != nil { - return err - } - - options := &swarmtypes.ConfigReference{ - File: &swarmtypes.ConfigReferenceFileTarget{ - UID: "0", - GID: "0", - Mode: 0o444, - }, - } - - // support a simple syntax of --config foo - if len(fields) == 1 && !strings.Contains(fields[0], "=") { - options.File.Name = fields[0] - options.ConfigName = fields[0] - o.values = append(o.values, options) - return nil - } - - for _, field := range fields { - key, val, ok := strings.Cut(field, "=") - if !ok || key == "" { - return fmt.Errorf("invalid field '%s' must be a key=value pair", field) - } - - // TODO(thaJeztah): these options should not be case-insensitive. - switch strings.ToLower(key) { - case "source", "src": - options.ConfigName = val - case "target": - options.File.Name = val - case "uid": - options.File.UID = val - case "gid": - options.File.GID = val - case "mode": - m, err := strconv.ParseUint(val, 0, 32) - if err != nil { - return fmt.Errorf("invalid mode specified: %v", err) - } - - options.File.Mode = os.FileMode(m) - default: - return fmt.Errorf("invalid field in config request: %s", key) - } - } - - if options.ConfigName == "" { - return fmt.Errorf("source is required") - } - if options.File.Name == "" { - options.File.Name = options.ConfigName - } - - o.values = append(o.values, options) - return nil -} - -// Type returns the type of this option -func (o *ConfigOpt) Type() string { - return "config" -} - -// String returns a string repr of this option -func (o *ConfigOpt) String() string { - configs := []string{} - for _, config := range o.values { - repr := fmt.Sprintf("%s -> %s", config.ConfigName, config.File.Name) - configs = append(configs, repr) - } - return strings.Join(configs, ", ") -} - -// Value returns the config requests -func (o *ConfigOpt) Value() []*swarmtypes.ConfigReference { - return o.values -} diff --git a/vendor/github.com/docker/cli/opts/duration.go b/vendor/github.com/docker/cli/opts/duration.go deleted file mode 100644 index 5dc6eeaa7..000000000 --- a/vendor/github.com/docker/cli/opts/duration.go +++ /dev/null @@ -1,64 +0,0 @@ -package opts - -import ( - "time" - - "github.com/pkg/errors" -) - -// PositiveDurationOpt is an option type for time.Duration that uses a pointer. -// It behave similarly to DurationOpt but only allows positive duration values. -type PositiveDurationOpt struct { - DurationOpt -} - -// Set a new value on the option. Setting a negative duration value will cause -// an error to be returned. -func (d *PositiveDurationOpt) Set(s string) error { - err := d.DurationOpt.Set(s) - if err != nil { - return err - } - if *d.DurationOpt.value < 0 { - return errors.Errorf("duration cannot be negative") - } - return nil -} - -// DurationOpt is an option type for time.Duration that uses a pointer. This -// allows us to get nil values outside, instead of defaulting to 0 -type DurationOpt struct { - value *time.Duration -} - -// NewDurationOpt creates a DurationOpt with the specified duration -func NewDurationOpt(value *time.Duration) *DurationOpt { - return &DurationOpt{ - value: value, - } -} - -// Set a new value on the option -func (d *DurationOpt) Set(s string) error { - v, err := time.ParseDuration(s) - d.value = &v - return err -} - -// Type returns the type of this option, which will be displayed in `--help` output -func (d *DurationOpt) Type() string { - return "duration" -} - -// String returns a string repr of this option -func (d *DurationOpt) String() string { - if d.value != nil { - return d.value.String() - } - return "" -} - -// Value returns the time.Duration -func (d *DurationOpt) Value() *time.Duration { - return d.value -} diff --git a/vendor/github.com/docker/cli/opts/env.go b/vendor/github.com/docker/cli/opts/env.go deleted file mode 100644 index 214d6f440..000000000 --- a/vendor/github.com/docker/cli/opts/env.go +++ /dev/null @@ -1,31 +0,0 @@ -package opts - -import ( - "os" - "strings" - - "github.com/pkg/errors" -) - -// ValidateEnv validates an environment variable and returns it. -// If no value is specified, it obtains its value from the current environment -// -// As on ParseEnvFile and related to #16585, environment variable names -// are not validated, and it's up to the application inside the container -// to validate them or not. -// -// The only validation here is to check if name is empty, per #25099 -func ValidateEnv(val string) (string, error) { - k, _, hasValue := strings.Cut(val, "=") - if k == "" { - return "", errors.New("invalid environment variable: " + val) - } - if hasValue { - // val contains a "=" (but value may be an empty string) - return val, nil - } - if envVal, ok := os.LookupEnv(k); ok { - return k + "=" + envVal, nil - } - return val, nil -} diff --git a/vendor/github.com/docker/cli/opts/envfile.go b/vendor/github.com/docker/cli/opts/envfile.go deleted file mode 100644 index 26aa3c3a9..000000000 --- a/vendor/github.com/docker/cli/opts/envfile.go +++ /dev/null @@ -1,22 +0,0 @@ -package opts - -import ( - "os" -) - -// ParseEnvFile reads a file with environment variables enumerated by lines -// -// “Environment variable names used by the utilities in the Shell and -// Utilities volume of IEEE Std 1003.1-2001 consist solely of uppercase -// letters, digits, and the '_' (underscore) from the characters defined in -// Portable Character Set and do not begin with a digit. *But*, other -// characters may be permitted by an implementation; applications shall -// tolerate the presence of such names.” -// -- http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html -// -// As of #16585, it's up to application inside docker to validate or not -// environment variables, that's why we just strip leading whitespace and -// nothing more. -func ParseEnvFile(filename string) ([]string, error) { - return parseKeyValueFile(filename, os.LookupEnv) -} diff --git a/vendor/github.com/docker/cli/opts/file.go b/vendor/github.com/docker/cli/opts/file.go deleted file mode 100644 index 72b90e117..000000000 --- a/vendor/github.com/docker/cli/opts/file.go +++ /dev/null @@ -1,76 +0,0 @@ -package opts - -import ( - "bufio" - "bytes" - "fmt" - "os" - "strings" - "unicode" - "unicode/utf8" -) - -const whiteSpaces = " \t" - -// ErrBadKey typed error for bad environment variable -type ErrBadKey struct { - msg string -} - -func (e ErrBadKey) Error() string { - return fmt.Sprintf("poorly formatted environment: %s", e.msg) -} - -func parseKeyValueFile(filename string, emptyFn func(string) (string, bool)) ([]string, error) { - fh, err := os.Open(filename) - if err != nil { - return []string{}, err - } - defer fh.Close() - - lines := []string{} - scanner := bufio.NewScanner(fh) - currentLine := 0 - utf8bom := []byte{0xEF, 0xBB, 0xBF} - for scanner.Scan() { - scannedBytes := scanner.Bytes() - if !utf8.Valid(scannedBytes) { - return []string{}, fmt.Errorf("env file %s contains invalid utf8 bytes at line %d: %v", filename, currentLine+1, scannedBytes) - } - // We trim UTF8 BOM - if currentLine == 0 { - scannedBytes = bytes.TrimPrefix(scannedBytes, utf8bom) - } - // trim the line from all leading whitespace first - line := strings.TrimLeftFunc(string(scannedBytes), unicode.IsSpace) - currentLine++ - // line is not empty, and not starting with '#' - if len(line) > 0 && !strings.HasPrefix(line, "#") { - variable, value, hasValue := strings.Cut(line, "=") - - // trim the front of a variable, but nothing else - variable = strings.TrimLeft(variable, whiteSpaces) - if strings.ContainsAny(variable, whiteSpaces) { - return []string{}, ErrBadKey{fmt.Sprintf("variable '%s' contains whitespaces", variable)} - } - if len(variable) == 0 { - return []string{}, ErrBadKey{fmt.Sprintf("no variable name on line '%s'", line)} - } - - if hasValue { - // pass the value through, no trimming - lines = append(lines, variable+"="+value) - } else { - var present bool - if emptyFn != nil { - value, present = emptyFn(line) - } - if present { - // if only a pass-through variable is given, clean it up. - lines = append(lines, strings.TrimSpace(variable)+"="+value) - } - } - } - } - return lines, scanner.Err() -} diff --git a/vendor/github.com/docker/cli/opts/gpus.go b/vendor/github.com/docker/cli/opts/gpus.go deleted file mode 100644 index 93bf93978..000000000 --- a/vendor/github.com/docker/cli/opts/gpus.go +++ /dev/null @@ -1,111 +0,0 @@ -package opts - -import ( - "encoding/csv" - "fmt" - "strconv" - "strings" - - "github.com/docker/docker/api/types/container" - "github.com/pkg/errors" -) - -// GpuOpts is a Value type for parsing mounts -type GpuOpts struct { - values []container.DeviceRequest -} - -func parseCount(s string) (int, error) { - if s == "all" { - return -1, nil - } - i, err := strconv.Atoi(s) - return i, errors.Wrap(err, "count must be an integer") -} - -// Set a new mount value -// -//nolint:gocyclo -func (o *GpuOpts) Set(value string) error { - csvReader := csv.NewReader(strings.NewReader(value)) - fields, err := csvReader.Read() - if err != nil { - return err - } - - req := container.DeviceRequest{} - - seen := map[string]struct{}{} - // Set writable as the default - for _, field := range fields { - key, val, withValue := strings.Cut(field, "=") - if _, ok := seen[key]; ok { - return fmt.Errorf("gpu request key '%s' can be specified only once", key) - } - seen[key] = struct{}{} - - if !withValue { - seen["count"] = struct{}{} - req.Count, err = parseCount(key) - if err != nil { - return err - } - continue - } - - switch key { - case "driver": - req.Driver = val - case "count": - req.Count, err = parseCount(val) - if err != nil { - return err - } - case "device": - req.DeviceIDs = strings.Split(val, ",") - case "capabilities": - req.Capabilities = [][]string{append(strings.Split(val, ","), "gpu")} - case "options": - r := csv.NewReader(strings.NewReader(val)) - optFields, err := r.Read() - if err != nil { - return errors.Wrap(err, "failed to read gpu options") - } - req.Options = ConvertKVStringsToMap(optFields) - default: - return fmt.Errorf("unexpected key '%s' in '%s'", key, field) - } - } - - if _, ok := seen["count"]; !ok && req.DeviceIDs == nil { - req.Count = 1 - } - if req.Options == nil { - req.Options = make(map[string]string) - } - if req.Capabilities == nil { - req.Capabilities = [][]string{{"gpu"}} - } - - o.values = append(o.values, req) - return nil -} - -// Type returns the type of this option -func (o *GpuOpts) Type() string { - return "gpu-request" -} - -// String returns a string repr of this option -func (o *GpuOpts) String() string { - gpus := []string{} - for _, gpu := range o.values { - gpus = append(gpus, fmt.Sprintf("%v", gpu)) - } - return strings.Join(gpus, ", ") -} - -// Value returns the mounts -func (o *GpuOpts) Value() []container.DeviceRequest { - return o.values -} diff --git a/vendor/github.com/docker/cli/opts/hosts.go b/vendor/github.com/docker/cli/opts/hosts.go deleted file mode 100644 index 7cdd1218f..000000000 --- a/vendor/github.com/docker/cli/opts/hosts.go +++ /dev/null @@ -1,181 +0,0 @@ -package opts - -import ( - "fmt" - "net" - "net/url" - "strconv" - "strings" -) - -const ( - // defaultHTTPPort Default HTTP Port used if only the protocol is provided to -H flag e.g. dockerd -H tcp:// - // These are the IANA registered port numbers for use with Docker - // see http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml?search=docker - defaultHTTPPort = "2375" // Default HTTP Port - // defaultTLSHTTPPort Default HTTP Port used when TLS enabled - defaultTLSHTTPPort = "2376" // Default TLS encrypted HTTP Port - // defaultUnixSocket Path for the unix socket. - // Docker daemon by default always listens on the default unix socket - defaultUnixSocket = "/var/run/docker.sock" - // defaultTCPHost constant defines the default host string used by docker on Windows - defaultTCPHost = "tcp://" + defaultHTTPHost + ":" + defaultHTTPPort - // DefaultTLSHost constant defines the default host string used by docker for TLS sockets - defaultTLSHost = "tcp://" + defaultHTTPHost + ":" + defaultTLSHTTPPort - // DefaultNamedPipe defines the default named pipe used by docker on Windows - defaultNamedPipe = `//./pipe/docker_engine` - // hostGatewayName defines a special string which users can append to --add-host - // to add an extra entry in /etc/hosts that maps host.docker.internal to the host IP - // TODO Consider moving the hostGatewayName constant defined in docker at - // github.com/docker/docker/daemon/network/constants.go outside of the "daemon" - // package, so that the CLI can consume it. - hostGatewayName = "host-gateway" -) - -// ValidateHost validates that the specified string is a valid host and returns it. -// -// TODO(thaJeztah): ValidateHost appears to be unused; deprecate it. -func ValidateHost(val string) (string, error) { - host := strings.TrimSpace(val) - // The empty string means default and is not handled by parseDockerDaemonHost - if host != "" { - _, err := parseDockerDaemonHost(host) - if err != nil { - return val, err - } - } - // Note: unlike most flag validators, we don't return the mutated value here - // we need to know what the user entered later (using ParseHost) to adjust for TLS - return val, nil -} - -// ParseHost and set defaults for a Daemon host string -func ParseHost(defaultToTLS bool, val string) (string, error) { - host := strings.TrimSpace(val) - if host == "" { - if defaultToTLS { - host = defaultTLSHost - } else { - host = defaultHost - } - } else { - var err error - host, err = parseDockerDaemonHost(host) - if err != nil { - return val, err - } - } - return host, nil -} - -// parseDockerDaemonHost parses the specified address and returns an address that will be used as the host. -// Depending of the address specified, this may return one of the global Default* strings defined in hosts.go. -func parseDockerDaemonHost(addr string) (string, error) { - proto, host, hasProto := strings.Cut(addr, "://") - if !hasProto && proto != "" { - host = proto - proto = "tcp" - } - - switch proto { - case "tcp": - return ParseTCPAddr(host, defaultTCPHost) - case "unix": - return parseSimpleProtoAddr(proto, host, defaultUnixSocket) - case "npipe": - return parseSimpleProtoAddr(proto, host, defaultNamedPipe) - case "fd": - return addr, nil - case "ssh": - return addr, nil - default: - return "", fmt.Errorf("invalid bind address format: %s", addr) - } -} - -// parseSimpleProtoAddr parses and validates that the specified address is a valid -// socket address for simple protocols like unix and npipe. It returns a formatted -// socket address, either using the address parsed from addr, or the contents of -// defaultAddr if addr is a blank string. -func parseSimpleProtoAddr(proto, addr, defaultAddr string) (string, error) { - addr = strings.TrimPrefix(addr, proto+"://") - if strings.Contains(addr, "://") { - return "", fmt.Errorf("invalid proto, expected %s: %s", proto, addr) - } - if addr == "" { - addr = defaultAddr - } - return fmt.Sprintf("%s://%s", proto, addr), nil -} - -// ParseTCPAddr parses and validates that the specified address is a valid TCP -// address. It returns a formatted TCP address, either using the address parsed -// from tryAddr, or the contents of defaultAddr if tryAddr is a blank string. -// tryAddr is expected to have already been Trim()'d -// defaultAddr must be in the full `tcp://host:port` form -func ParseTCPAddr(tryAddr string, defaultAddr string) (string, error) { - if tryAddr == "" || tryAddr == "tcp://" { - return defaultAddr, nil - } - addr := strings.TrimPrefix(tryAddr, "tcp://") - if strings.Contains(addr, "://") || addr == "" { - return "", fmt.Errorf("invalid proto, expected tcp: %s", tryAddr) - } - - defaultAddr = strings.TrimPrefix(defaultAddr, "tcp://") - defaultHost, defaultPort, err := net.SplitHostPort(defaultAddr) - if err != nil { - return "", err - } - // url.Parse fails for trailing colon on IPv6 brackets on Go 1.5, but - // not 1.4. See https://github.com/golang/go/issues/12200 and - // https://github.com/golang/go/issues/6530. - if strings.HasSuffix(addr, "]:") { - addr += defaultPort - } - - u, err := url.Parse("tcp://" + addr) - if err != nil { - return "", err - } - host, port, err := net.SplitHostPort(u.Host) - if err != nil { - // try port addition once - host, port, err = net.SplitHostPort(net.JoinHostPort(u.Host, defaultPort)) - } - if err != nil { - return "", fmt.Errorf("invalid bind address format: %s", tryAddr) - } - - if host == "" { - host = defaultHost - } - if port == "" { - port = defaultPort - } - p, err := strconv.Atoi(port) - if err != nil && p == 0 { - return "", fmt.Errorf("invalid bind address format: %s", tryAddr) - } - - return fmt.Sprintf("tcp://%s%s", net.JoinHostPort(host, port), u.Path), nil -} - -// ValidateExtraHost validates that the specified string is a valid extrahost and returns it. -// ExtraHost is in the form of name:ip where the ip has to be a valid ip (IPv4 or IPv6). -// -// TODO(thaJeztah): remove client-side validation, and delegate to the API server. -func ValidateExtraHost(val string) (string, error) { - // allow for IPv6 addresses in extra hosts by only splitting on first ":" - k, v, ok := strings.Cut(val, ":") - if !ok || k == "" { - return "", fmt.Errorf("bad format for add-host: %q", val) - } - // Skip IPaddr validation for "host-gateway" string - if v != hostGatewayName { - if _, err := ValidateIPAddress(v); err != nil { - return "", fmt.Errorf("invalid IP address in add-host: %q", v) - } - } - return val, nil -} diff --git a/vendor/github.com/docker/cli/opts/hosts_unix.go b/vendor/github.com/docker/cli/opts/hosts_unix.go deleted file mode 100644 index 206834d4d..000000000 --- a/vendor/github.com/docker/cli/opts/hosts_unix.go +++ /dev/null @@ -1,10 +0,0 @@ -//go:build !windows -// +build !windows - -package opts - -// defaultHost constant defines the default host string used by docker on other hosts than Windows -const defaultHost = "unix://" + defaultUnixSocket - -// defaultHTTPHost Default HTTP Host used if only port is provided to -H flag e.g. dockerd -H tcp://:8080 -const defaultHTTPHost = "localhost" diff --git a/vendor/github.com/docker/cli/opts/hosts_windows.go b/vendor/github.com/docker/cli/opts/hosts_windows.go deleted file mode 100644 index 1e42a2d77..000000000 --- a/vendor/github.com/docker/cli/opts/hosts_windows.go +++ /dev/null @@ -1,59 +0,0 @@ -package opts - -// defaultHost constant defines the default host string used by docker on Windows -const defaultHost = "npipe://" + defaultNamedPipe - -// TODO Windows. Identify bug in GOLang 1.5.1+ and/or Windows Server 2016 TP5. -// @jhowardmsft, @swernli. -// -// On Windows, this mitigates a problem with the default options of running -// a docker client against a local docker daemon on TP5. -// -// What was found that if the default host is "localhost", even if the client -// (and daemon as this is local) is not physically on a network, and the DNS -// cache is flushed (ipconfig /flushdns), then the client will pause for -// exactly one second when connecting to the daemon for calls. For example -// using docker run windowsservercore cmd, the CLI will send a create followed -// by an attach. You see the delay between the attach finishing and the attach -// being seen by the daemon. -// -// Here's some daemon debug logs with additional debug spew put in. The -// AfterWriteJSON log is the very last thing the daemon does as part of the -// create call. The POST /attach is the second CLI call. Notice the second -// time gap. -// -// time="2015-11-06T13:38:37.259627400-08:00" level=debug msg="After createRootfs" -// time="2015-11-06T13:38:37.263626300-08:00" level=debug msg="After setHostConfig" -// time="2015-11-06T13:38:37.267631200-08:00" level=debug msg="before createContainerPl...." -// time="2015-11-06T13:38:37.271629500-08:00" level=debug msg=ToDiskLocking.... -// time="2015-11-06T13:38:37.275643200-08:00" level=debug msg="loggin event...." -// time="2015-11-06T13:38:37.277627600-08:00" level=debug msg="logged event...." -// time="2015-11-06T13:38:37.279631800-08:00" level=debug msg="In defer func" -// time="2015-11-06T13:38:37.282628100-08:00" level=debug msg="After daemon.create" -// time="2015-11-06T13:38:37.286651700-08:00" level=debug msg="return 2" -// time="2015-11-06T13:38:37.289629500-08:00" level=debug msg="Returned from daemon.ContainerCreate" -// time="2015-11-06T13:38:37.311629100-08:00" level=debug msg="After WriteJSON" -// ... 1 second gap here.... -// time="2015-11-06T13:38:38.317866200-08:00" level=debug msg="Calling POST /v1.22/containers/984758282b842f779e805664b2c95d563adc9a979c8a3973e68c807843ee4757/attach" -// time="2015-11-06T13:38:38.326882500-08:00" level=info msg="POST /v1.22/containers/984758282b842f779e805664b2c95d563adc9a979c8a3973e68c807843ee4757/attach?stderr=1&stdin=1&stdout=1&stream=1" -// -// We suspect this is either a bug introduced in GOLang 1.5.1, or that a change -// in GOLang 1.5.1 (from 1.4.3) is exposing a bug in Windows. In theory, -// the Windows networking stack is supposed to resolve "localhost" internally, -// without hitting DNS, or even reading the hosts file (which is why localhost -// is commented out in the hosts file on Windows). -// -// We have validated that working around this using the actual IPv4 localhost -// address does not cause the delay. -// -// This does not occur with the docker client built with 1.4.3 on the same -// Windows build, regardless of whether the daemon is built using 1.5.1 -// or 1.4.3. It does not occur on Linux. We also verified we see the same thing -// on a cross-compiled Windows binary (from Linux). -// -// Final note: This is a mitigation, not a 'real' fix. It is still susceptible -// to the delay if a user were to do 'docker run -H=tcp://localhost:2375...' -// explicitly. - -// defaultHTTPHost Default HTTP Host used if only port is provided to -H flag e.g. dockerd -H tcp://:8080 -const defaultHTTPHost = "127.0.0.1" diff --git a/vendor/github.com/docker/cli/opts/ip.go b/vendor/github.com/docker/cli/opts/ip.go deleted file mode 100644 index fb03b5011..000000000 --- a/vendor/github.com/docker/cli/opts/ip.go +++ /dev/null @@ -1,47 +0,0 @@ -package opts - -import ( - "fmt" - "net" -) - -// IPOpt holds an IP. It is used to store values from CLI flags. -type IPOpt struct { - *net.IP -} - -// NewIPOpt creates a new IPOpt from a reference net.IP and a -// string representation of an IP. If the string is not a valid -// IP it will fallback to the specified reference. -func NewIPOpt(ref *net.IP, defaultVal string) *IPOpt { - o := &IPOpt{ - IP: ref, - } - o.Set(defaultVal) - return o -} - -// Set sets an IPv4 or IPv6 address from a given string. If the given -// string is not parseable as an IP address it returns an error. -func (o *IPOpt) Set(val string) error { - ip := net.ParseIP(val) - if ip == nil { - return fmt.Errorf("%s is not an ip address", val) - } - *o.IP = ip - return nil -} - -// String returns the IP address stored in the IPOpt. If stored IP is a -// nil pointer, it returns an empty string. -func (o *IPOpt) String() string { - if *o.IP == nil { - return "" - } - return o.IP.String() -} - -// Type returns the type of the option -func (o *IPOpt) Type() string { - return "ip" -} diff --git a/vendor/github.com/docker/cli/opts/mount.go b/vendor/github.com/docker/cli/opts/mount.go deleted file mode 100644 index 2b531127e..000000000 --- a/vendor/github.com/docker/cli/opts/mount.go +++ /dev/null @@ -1,186 +0,0 @@ -package opts - -import ( - "encoding/csv" - "fmt" - "os" - "path/filepath" - "strconv" - "strings" - - mounttypes "github.com/docker/docker/api/types/mount" - "github.com/docker/go-units" -) - -// MountOpt is a Value type for parsing mounts -type MountOpt struct { - values []mounttypes.Mount -} - -// Set a new mount value -// -//nolint:gocyclo -func (m *MountOpt) Set(value string) error { - csvReader := csv.NewReader(strings.NewReader(value)) - fields, err := csvReader.Read() - if err != nil { - return err - } - - mount := mounttypes.Mount{} - - volumeOptions := func() *mounttypes.VolumeOptions { - if mount.VolumeOptions == nil { - mount.VolumeOptions = &mounttypes.VolumeOptions{ - Labels: make(map[string]string), - } - } - if mount.VolumeOptions.DriverConfig == nil { - mount.VolumeOptions.DriverConfig = &mounttypes.Driver{} - } - return mount.VolumeOptions - } - - bindOptions := func() *mounttypes.BindOptions { - if mount.BindOptions == nil { - mount.BindOptions = new(mounttypes.BindOptions) - } - return mount.BindOptions - } - - tmpfsOptions := func() *mounttypes.TmpfsOptions { - if mount.TmpfsOptions == nil { - mount.TmpfsOptions = new(mounttypes.TmpfsOptions) - } - return mount.TmpfsOptions - } - - setValueOnMap := func(target map[string]string, value string) { - k, v, _ := strings.Cut(value, "=") - if k != "" { - target[k] = v - } - } - - mount.Type = mounttypes.TypeVolume // default to volume mounts - // Set writable as the default - for _, field := range fields { - key, val, ok := strings.Cut(field, "=") - - // TODO(thaJeztah): these options should not be case-insensitive. - key = strings.ToLower(key) - - if !ok { - switch key { - case "readonly", "ro": - mount.ReadOnly = true - continue - case "volume-nocopy": - volumeOptions().NoCopy = true - continue - case "bind-nonrecursive": - bindOptions().NonRecursive = true - continue - default: - return fmt.Errorf("invalid field '%s' must be a key=value pair", field) - } - } - - switch key { - case "type": - mount.Type = mounttypes.Type(strings.ToLower(val)) - case "source", "src": - mount.Source = val - if strings.HasPrefix(val, "."+string(filepath.Separator)) || val == "." { - if abs, err := filepath.Abs(val); err == nil { - mount.Source = abs - } - } - case "target", "dst", "destination": - mount.Target = val - case "readonly", "ro": - mount.ReadOnly, err = strconv.ParseBool(val) - if err != nil { - return fmt.Errorf("invalid value for %s: %s", key, val) - } - case "consistency": - mount.Consistency = mounttypes.Consistency(strings.ToLower(val)) - case "bind-propagation": - bindOptions().Propagation = mounttypes.Propagation(strings.ToLower(val)) - case "bind-nonrecursive": - bindOptions().NonRecursive, err = strconv.ParseBool(val) - if err != nil { - return fmt.Errorf("invalid value for %s: %s", key, val) - } - case "volume-nocopy": - volumeOptions().NoCopy, err = strconv.ParseBool(val) - if err != nil { - return fmt.Errorf("invalid value for volume-nocopy: %s", val) - } - case "volume-label": - setValueOnMap(volumeOptions().Labels, val) - case "volume-driver": - volumeOptions().DriverConfig.Name = val - case "volume-opt": - if volumeOptions().DriverConfig.Options == nil { - volumeOptions().DriverConfig.Options = make(map[string]string) - } - setValueOnMap(volumeOptions().DriverConfig.Options, val) - case "tmpfs-size": - sizeBytes, err := units.RAMInBytes(val) - if err != nil { - return fmt.Errorf("invalid value for %s: %s", key, val) - } - tmpfsOptions().SizeBytes = sizeBytes - case "tmpfs-mode": - ui64, err := strconv.ParseUint(val, 8, 32) - if err != nil { - return fmt.Errorf("invalid value for %s: %s", key, val) - } - tmpfsOptions().Mode = os.FileMode(ui64) - default: - return fmt.Errorf("unexpected key '%s' in '%s'", key, field) - } - } - - if mount.Type == "" { - return fmt.Errorf("type is required") - } - - if mount.Target == "" { - return fmt.Errorf("target is required") - } - - if mount.VolumeOptions != nil && mount.Type != mounttypes.TypeVolume { - return fmt.Errorf("cannot mix 'volume-*' options with mount type '%s'", mount.Type) - } - if mount.BindOptions != nil && mount.Type != mounttypes.TypeBind { - return fmt.Errorf("cannot mix 'bind-*' options with mount type '%s'", mount.Type) - } - if mount.TmpfsOptions != nil && mount.Type != mounttypes.TypeTmpfs { - return fmt.Errorf("cannot mix 'tmpfs-*' options with mount type '%s'", mount.Type) - } - - m.values = append(m.values, mount) - return nil -} - -// Type returns the type of this option -func (m *MountOpt) Type() string { - return "mount" -} - -// String returns a string repr of this option -func (m *MountOpt) String() string { - mounts := []string{} - for _, mount := range m.values { - repr := fmt.Sprintf("%s %s %s", mount.Type, mount.Source, mount.Target) - mounts = append(mounts, repr) - } - return strings.Join(mounts, ", ") -} - -// Value returns the mounts -func (m *MountOpt) Value() []mounttypes.Mount { - return m.values -} diff --git a/vendor/github.com/docker/cli/opts/network.go b/vendor/github.com/docker/cli/opts/network.go deleted file mode 100644 index 12c3977b1..000000000 --- a/vendor/github.com/docker/cli/opts/network.go +++ /dev/null @@ -1,127 +0,0 @@ -package opts - -import ( - "encoding/csv" - "fmt" - "regexp" - "strings" -) - -const ( - networkOptName = "name" - networkOptAlias = "alias" - networkOptIPv4Address = "ip" - networkOptIPv6Address = "ip6" - driverOpt = "driver-opt" -) - -// NetworkAttachmentOpts represents the network options for endpoint creation -type NetworkAttachmentOpts struct { - Target string - Aliases []string - DriverOpts map[string]string - Links []string // TODO add support for links in the csv notation of `--network` - IPv4Address string - IPv6Address string - LinkLocalIPs []string // TODO add support for LinkLocalIPs in the csv notation of `--network` ? -} - -// NetworkOpt represents a network config in swarm mode. -type NetworkOpt struct { - options []NetworkAttachmentOpts -} - -// Set networkopts value -func (n *NetworkOpt) Set(value string) error { - longSyntax, err := regexp.MatchString(`\w+=\w+(,\w+=\w+)*`, value) - if err != nil { - return err - } - - var netOpt NetworkAttachmentOpts - if longSyntax { - csvReader := csv.NewReader(strings.NewReader(value)) - fields, err := csvReader.Read() - if err != nil { - return err - } - - netOpt.Aliases = []string{} - for _, field := range fields { - // TODO(thaJeztah): these options should not be case-insensitive. - key, val, ok := strings.Cut(strings.ToLower(field), "=") - if !ok || key == "" { - return fmt.Errorf("invalid field %s", field) - } - - key = strings.TrimSpace(key) - val = strings.TrimSpace(val) - - switch key { - case networkOptName: - netOpt.Target = val - case networkOptAlias: - netOpt.Aliases = append(netOpt.Aliases, val) - case networkOptIPv4Address: - netOpt.IPv4Address = val - case networkOptIPv6Address: - netOpt.IPv6Address = val - case driverOpt: - key, val, err = parseDriverOpt(val) - if err != nil { - return err - } - if netOpt.DriverOpts == nil { - netOpt.DriverOpts = make(map[string]string) - } - netOpt.DriverOpts[key] = val - default: - return fmt.Errorf("invalid field key %s", key) - } - } - if len(netOpt.Target) == 0 { - return fmt.Errorf("network name/id is not specified") - } - } else { - netOpt.Target = value - } - n.options = append(n.options, netOpt) - return nil -} - -// Type returns the type of this option -func (n *NetworkOpt) Type() string { - return "network" -} - -// Value returns the networkopts -func (n *NetworkOpt) Value() []NetworkAttachmentOpts { - return n.options -} - -// String returns the network opts as a string -func (n *NetworkOpt) String() string { - return "" -} - -// NetworkMode return the network mode for the network option -func (n *NetworkOpt) NetworkMode() string { - networkIDOrName := "default" - netOptVal := n.Value() - if len(netOptVal) > 0 { - networkIDOrName = netOptVal[0].Target - } - return networkIDOrName -} - -func parseDriverOpt(driverOpt string) (string, string, error) { - // TODO(thaJeztah): these options should not be case-insensitive. - // TODO(thaJeztah): should value be converted to lowercase as well, or only the key? - key, value, ok := strings.Cut(strings.ToLower(driverOpt), "=") - if !ok || key == "" { - return "", "", fmt.Errorf("invalid key value pair format in driver options") - } - key = strings.TrimSpace(key) - value = strings.TrimSpace(value) - return key, value, nil -} diff --git a/vendor/github.com/docker/cli/opts/opts.go b/vendor/github.com/docker/cli/opts/opts.go deleted file mode 100644 index 4e7790f0f..000000000 --- a/vendor/github.com/docker/cli/opts/opts.go +++ /dev/null @@ -1,513 +0,0 @@ -package opts - -import ( - "fmt" - "math/big" - "net" - "path" - "regexp" - "strings" - - "github.com/docker/docker/api/types/filters" - units "github.com/docker/go-units" - "github.com/pkg/errors" -) - -var ( - alphaRegexp = regexp.MustCompile(`[a-zA-Z]`) - domainRegexp = regexp.MustCompile(`^(:?(:?[a-zA-Z0-9]|(:?[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9]))(:?\.(:?[a-zA-Z0-9]|(:?[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])))*)\.?\s*$`) -) - -// ListOpts holds a list of values and a validation function. -type ListOpts struct { - values *[]string - validator ValidatorFctType -} - -// NewListOpts creates a new ListOpts with the specified validator. -func NewListOpts(validator ValidatorFctType) ListOpts { - var values []string - return *NewListOptsRef(&values, validator) -} - -// NewListOptsRef creates a new ListOpts with the specified values and validator. -func NewListOptsRef(values *[]string, validator ValidatorFctType) *ListOpts { - return &ListOpts{ - values: values, - validator: validator, - } -} - -func (opts *ListOpts) String() string { - if len(*opts.values) == 0 { - return "" - } - return fmt.Sprintf("%v", *opts.values) -} - -// Set validates if needed the input value and adds it to the -// internal slice. -func (opts *ListOpts) Set(value string) error { - if opts.validator != nil { - v, err := opts.validator(value) - if err != nil { - return err - } - value = v - } - *opts.values = append(*opts.values, value) - return nil -} - -// Delete removes the specified element from the slice. -func (opts *ListOpts) Delete(key string) { - for i, k := range *opts.values { - if k == key { - *opts.values = append((*opts.values)[:i], (*opts.values)[i+1:]...) - return - } - } -} - -// GetMap returns the content of values in a map in order to avoid -// duplicates. -func (opts *ListOpts) GetMap() map[string]struct{} { - ret := make(map[string]struct{}) - for _, k := range *opts.values { - ret[k] = struct{}{} - } - return ret -} - -// GetAll returns the values of slice. -func (opts *ListOpts) GetAll() []string { - return *opts.values -} - -// GetAllOrEmpty returns the values of the slice -// or an empty slice when there are no values. -func (opts *ListOpts) GetAllOrEmpty() []string { - v := *opts.values - if v == nil { - return make([]string, 0) - } - return v -} - -// Get checks the existence of the specified key. -func (opts *ListOpts) Get(key string) bool { - for _, k := range *opts.values { - if k == key { - return true - } - } - return false -} - -// Len returns the amount of element in the slice. -func (opts *ListOpts) Len() int { - return len(*opts.values) -} - -// Type returns a string name for this Option type -func (opts *ListOpts) Type() string { - return "list" -} - -// WithValidator returns the ListOpts with validator set. -func (opts *ListOpts) WithValidator(validator ValidatorFctType) *ListOpts { - opts.validator = validator - return opts -} - -// NamedOption is an interface that list and map options -// with names implement. -type NamedOption interface { - Name() string -} - -// NamedListOpts is a ListOpts with a configuration name. -// This struct is useful to keep reference to the assigned -// field name in the internal configuration struct. -type NamedListOpts struct { - name string - ListOpts -} - -var _ NamedOption = &NamedListOpts{} - -// NewNamedListOptsRef creates a reference to a new NamedListOpts struct. -func NewNamedListOptsRef(name string, values *[]string, validator ValidatorFctType) *NamedListOpts { - return &NamedListOpts{ - name: name, - ListOpts: *NewListOptsRef(values, validator), - } -} - -// Name returns the name of the NamedListOpts in the configuration. -func (o *NamedListOpts) Name() string { - return o.name -} - -// MapOpts holds a map of values and a validation function. -type MapOpts struct { - values map[string]string - validator ValidatorFctType -} - -// Set validates if needed the input value and add it to the -// internal map, by splitting on '='. -func (opts *MapOpts) Set(value string) error { - if opts.validator != nil { - v, err := opts.validator(value) - if err != nil { - return err - } - value = v - } - k, v, _ := strings.Cut(value, "=") - opts.values[k] = v - return nil -} - -// GetAll returns the values of MapOpts as a map. -func (opts *MapOpts) GetAll() map[string]string { - return opts.values -} - -func (opts *MapOpts) String() string { - return fmt.Sprintf("%v", opts.values) -} - -// Type returns a string name for this Option type -func (opts *MapOpts) Type() string { - return "map" -} - -// NewMapOpts creates a new MapOpts with the specified map of values and a validator. -func NewMapOpts(values map[string]string, validator ValidatorFctType) *MapOpts { - if values == nil { - values = make(map[string]string) - } - return &MapOpts{ - values: values, - validator: validator, - } -} - -// NamedMapOpts is a MapOpts struct with a configuration name. -// This struct is useful to keep reference to the assigned -// field name in the internal configuration struct. -type NamedMapOpts struct { - name string - MapOpts -} - -var _ NamedOption = &NamedMapOpts{} - -// NewNamedMapOpts creates a reference to a new NamedMapOpts struct. -func NewNamedMapOpts(name string, values map[string]string, validator ValidatorFctType) *NamedMapOpts { - return &NamedMapOpts{ - name: name, - MapOpts: *NewMapOpts(values, validator), - } -} - -// Name returns the name of the NamedMapOpts in the configuration. -func (o *NamedMapOpts) Name() string { - return o.name -} - -// ValidatorFctType defines a validator function that returns a validated string and/or an error. -type ValidatorFctType func(val string) (string, error) - -// ValidatorFctListType defines a validator function that returns a validated list of string and/or an error -type ValidatorFctListType func(val string) ([]string, error) - -// ValidateIPAddress validates an Ip address. -func ValidateIPAddress(val string) (string, error) { - ip := net.ParseIP(strings.TrimSpace(val)) - if ip != nil { - return ip.String(), nil - } - return "", fmt.Errorf("%s is not an ip address", val) -} - -// ValidateMACAddress validates a MAC address. -func ValidateMACAddress(val string) (string, error) { - _, err := net.ParseMAC(strings.TrimSpace(val)) - if err != nil { - return "", err - } - return val, nil -} - -// ValidateDNSSearch validates domain for resolvconf search configuration. -// A zero length domain is represented by a dot (.). -func ValidateDNSSearch(val string) (string, error) { - if val = strings.Trim(val, " "); val == "." { - return val, nil - } - return validateDomain(val) -} - -func validateDomain(val string) (string, error) { - if alphaRegexp.FindString(val) == "" { - return "", fmt.Errorf("%s is not a valid domain", val) - } - ns := domainRegexp.FindSubmatch([]byte(val)) - if len(ns) > 0 && len(ns[1]) < 255 { - return string(ns[1]), nil - } - return "", fmt.Errorf("%s is not a valid domain", val) -} - -// ValidateLabel validates that the specified string is a valid label, and returns it. -// -// Labels are in the form of key=value; key must be a non-empty string, and not -// contain whitespaces. A value is optional (defaults to an empty string if omitted). -// -// Leading whitespace is removed during validation but values are kept as-is -// otherwise, so any string value is accepted for both, which includes whitespace -// (for values) and quotes (surrounding, or embedded in key or value). -// -// TODO discuss if quotes (and other special characters) should be valid or invalid for keys -// TODO discuss if leading/trailing whitespace in keys should be preserved (and valid) -func ValidateLabel(value string) (string, error) { - key, _, _ := strings.Cut(value, "=") - key = strings.TrimLeft(key, whiteSpaces) - if key == "" { - return "", fmt.Errorf("invalid label '%s': empty name", value) - } - if strings.ContainsAny(key, whiteSpaces) { - return "", fmt.Errorf("label '%s' contains whitespaces", key) - } - return value, nil -} - -// ValidateSysctl validates a sysctl and returns it. -func ValidateSysctl(val string) (string, error) { - validSysctlMap := map[string]bool{ - "kernel.msgmax": true, - "kernel.msgmnb": true, - "kernel.msgmni": true, - "kernel.sem": true, - "kernel.shmall": true, - "kernel.shmmax": true, - "kernel.shmmni": true, - "kernel.shm_rmid_forced": true, - } - validSysctlPrefixes := []string{ - "net.", - "fs.mqueue.", - } - k, _, ok := strings.Cut(val, "=") - if !ok || k == "" { - return "", fmt.Errorf("sysctl '%s' is not allowed", val) - } - if validSysctlMap[k] { - return val, nil - } - for _, vp := range validSysctlPrefixes { - if strings.HasPrefix(k, vp) { - return val, nil - } - } - return "", fmt.Errorf("sysctl '%s' is not allowed", val) -} - -// FilterOpt is a flag type for validating filters -type FilterOpt struct { - filter filters.Args -} - -// NewFilterOpt returns a new FilterOpt -func NewFilterOpt() FilterOpt { - return FilterOpt{filter: filters.NewArgs()} -} - -func (o *FilterOpt) String() string { - repr, err := filters.ToJSON(o.filter) - if err != nil { - return "invalid filters" - } - return repr -} - -// Set sets the value of the opt by parsing the command line value -func (o *FilterOpt) Set(value string) error { - if value == "" { - return nil - } - if !strings.Contains(value, "=") { - return errors.New("bad format of filter (expected name=value)") - } - name, val, _ := strings.Cut(value, "=") - - // TODO(thaJeztah): these options should not be case-insensitive. - name = strings.ToLower(strings.TrimSpace(name)) - val = strings.TrimSpace(val) - o.filter.Add(name, val) - return nil -} - -// Type returns the option type -func (o *FilterOpt) Type() string { - return "filter" -} - -// Value returns the value of this option -func (o *FilterOpt) Value() filters.Args { - return o.filter -} - -// NanoCPUs is a type for fixed point fractional number. -type NanoCPUs int64 - -// String returns the string format of the number -func (c *NanoCPUs) String() string { - if *c == 0 { - return "" - } - return big.NewRat(c.Value(), 1e9).FloatString(3) -} - -// Set sets the value of the NanoCPU by passing a string -func (c *NanoCPUs) Set(value string) error { - cpus, err := ParseCPUs(value) - *c = NanoCPUs(cpus) - return err -} - -// Type returns the type -func (c *NanoCPUs) Type() string { - return "decimal" -} - -// Value returns the value in int64 -func (c *NanoCPUs) Value() int64 { - return int64(*c) -} - -// ParseCPUs takes a string ratio and returns an integer value of nano cpus -func ParseCPUs(value string) (int64, error) { - cpu, ok := new(big.Rat).SetString(value) - if !ok { - return 0, fmt.Errorf("failed to parse %v as a rational number", value) - } - nano := cpu.Mul(cpu, big.NewRat(1e9, 1)) - if !nano.IsInt() { - return 0, fmt.Errorf("value is too precise") - } - return nano.Num().Int64(), nil -} - -// ParseLink parses and validates the specified string as a link format (name:alias) -func ParseLink(val string) (string, string, error) { - if val == "" { - return "", "", fmt.Errorf("empty string specified for links") - } - // We expect two parts, but restrict to three to allow detecting invalid formats. - arr := strings.SplitN(val, ":", 3) - - // TODO(thaJeztah): clean up this logic!! - if len(arr) > 2 { - return "", "", fmt.Errorf("bad format for links: %s", val) - } - // TODO(thaJeztah): this should trim the "/" prefix as well?? - if len(arr) == 1 { - return val, val, nil - } - // This is kept because we can actually get a HostConfig with links - // from an already created container and the format is not `foo:bar` - // but `/foo:/c1/bar` - if strings.HasPrefix(arr[0], "/") { - // TODO(thaJeztah): clean up this logic!! - _, alias := path.Split(arr[1]) - return arr[0][1:], alias, nil - } - return arr[0], arr[1], nil -} - -// ValidateLink validates that the specified string has a valid link format (containerName:alias). -func ValidateLink(val string) (string, error) { - _, _, err := ParseLink(val) - return val, err -} - -// MemBytes is a type for human readable memory bytes (like 128M, 2g, etc) -type MemBytes int64 - -// String returns the string format of the human readable memory bytes -func (m *MemBytes) String() string { - // NOTE: In spf13/pflag/flag.go, "0" is considered as "zero value" while "0 B" is not. - // We return "0" in case value is 0 here so that the default value is hidden. - // (Sometimes "default 0 B" is actually misleading) - if m.Value() != 0 { - return units.BytesSize(float64(m.Value())) - } - return "0" -} - -// Set sets the value of the MemBytes by passing a string -func (m *MemBytes) Set(value string) error { - val, err := units.RAMInBytes(value) - *m = MemBytes(val) - return err -} - -// Type returns the type -func (m *MemBytes) Type() string { - return "bytes" -} - -// Value returns the value in int64 -func (m *MemBytes) Value() int64 { - return int64(*m) -} - -// UnmarshalJSON is the customized unmarshaler for MemBytes -func (m *MemBytes) UnmarshalJSON(s []byte) error { - if len(s) <= 2 || s[0] != '"' || s[len(s)-1] != '"' { - return fmt.Errorf("invalid size: %q", s) - } - val, err := units.RAMInBytes(string(s[1 : len(s)-1])) - *m = MemBytes(val) - return err -} - -// MemSwapBytes is a type for human readable memory bytes (like 128M, 2g, etc). -// It differs from MemBytes in that -1 is valid and the default. -type MemSwapBytes int64 - -// Set sets the value of the MemSwapBytes by passing a string -func (m *MemSwapBytes) Set(value string) error { - if value == "-1" { - *m = MemSwapBytes(-1) - return nil - } - val, err := units.RAMInBytes(value) - *m = MemSwapBytes(val) - return err -} - -// Type returns the type -func (m *MemSwapBytes) Type() string { - return "bytes" -} - -// Value returns the value in int64 -func (m *MemSwapBytes) Value() int64 { - return int64(*m) -} - -func (m *MemSwapBytes) String() string { - b := MemBytes(*m) - return b.String() -} - -// UnmarshalJSON is the customized unmarshaler for MemSwapBytes -func (m *MemSwapBytes) UnmarshalJSON(s []byte) error { - b := MemBytes(*m) - return b.UnmarshalJSON(s) -} diff --git a/vendor/github.com/docker/cli/opts/parse.go b/vendor/github.com/docker/cli/opts/parse.go deleted file mode 100644 index 017577e4b..000000000 --- a/vendor/github.com/docker/cli/opts/parse.go +++ /dev/null @@ -1,91 +0,0 @@ -package opts - -import ( - "fmt" - "os" - "strconv" - "strings" - - "github.com/docker/docker/api/types/container" -) - -// ReadKVStrings reads a file of line terminated key=value pairs, and overrides any keys -// present in the file with additional pairs specified in the override parameter -func ReadKVStrings(files []string, override []string) ([]string, error) { - return readKVStrings(files, override, nil) -} - -// ReadKVEnvStrings reads a file of line terminated key=value pairs, and overrides any keys -// present in the file with additional pairs specified in the override parameter. -// If a key has no value, it will get the value from the environment. -func ReadKVEnvStrings(files []string, override []string) ([]string, error) { - return readKVStrings(files, override, os.LookupEnv) -} - -func readKVStrings(files []string, override []string, emptyFn func(string) (string, bool)) ([]string, error) { - var variables []string - for _, ef := range files { - parsedVars, err := parseKeyValueFile(ef, emptyFn) - if err != nil { - return nil, err - } - variables = append(variables, parsedVars...) - } - // parse the '-e' and '--env' after, to allow override - variables = append(variables, override...) - - return variables, nil -} - -// ConvertKVStringsToMap converts ["key=value"] to {"key":"value"} -func ConvertKVStringsToMap(values []string) map[string]string { - result := make(map[string]string, len(values)) - for _, value := range values { - k, v, _ := strings.Cut(value, "=") - result[k] = v - } - - return result -} - -// ConvertKVStringsToMapWithNil converts ["key=value"] to {"key":"value"} -// but set unset keys to nil - meaning the ones with no "=" in them. -// We use this in cases where we need to distinguish between -// -// FOO= and FOO -// -// where the latter case just means FOO was mentioned but not given a value -func ConvertKVStringsToMapWithNil(values []string) map[string]*string { - result := make(map[string]*string, len(values)) - for _, value := range values { - k, v, ok := strings.Cut(value, "=") - if !ok { - result[k] = nil - } else { - result[k] = &v - } - } - - return result -} - -// ParseRestartPolicy returns the parsed policy or an error indicating what is incorrect -func ParseRestartPolicy(policy string) (container.RestartPolicy, error) { - p := container.RestartPolicy{} - - if policy == "" { - return p, nil - } - - k, v, _ := strings.Cut(policy, ":") - if v != "" { - count, err := strconv.Atoi(v) - if err != nil { - return p, fmt.Errorf("invalid restart policy format: maximum retry count must be an integer") - } - p.MaximumRetryCount = count - } - - p.Name = k - return p, nil -} diff --git a/vendor/github.com/docker/cli/opts/port.go b/vendor/github.com/docker/cli/opts/port.go deleted file mode 100644 index fe41cdd28..000000000 --- a/vendor/github.com/docker/cli/opts/port.go +++ /dev/null @@ -1,171 +0,0 @@ -package opts - -import ( - "encoding/csv" - "fmt" - "net" - "regexp" - "strconv" - "strings" - - "github.com/docker/docker/api/types/swarm" - "github.com/docker/go-connections/nat" - "github.com/sirupsen/logrus" -) - -const ( - portOptTargetPort = "target" - portOptPublishedPort = "published" - portOptProtocol = "protocol" - portOptMode = "mode" -) - -// PortOpt represents a port config in swarm mode. -type PortOpt struct { - ports []swarm.PortConfig -} - -// Set a new port value -// -//nolint:gocyclo -func (p *PortOpt) Set(value string) error { - longSyntax, err := regexp.MatchString(`\w+=\w+(,\w+=\w+)*`, value) - if err != nil { - return err - } - if longSyntax { - csvReader := csv.NewReader(strings.NewReader(value)) - fields, err := csvReader.Read() - if err != nil { - return err - } - - pConfig := swarm.PortConfig{} - for _, field := range fields { - // TODO(thaJeztah): these options should not be case-insensitive. - key, val, ok := strings.Cut(strings.ToLower(field), "=") - if !ok || key == "" { - return fmt.Errorf("invalid field %s", field) - } - switch key { - case portOptProtocol: - if val != string(swarm.PortConfigProtocolTCP) && val != string(swarm.PortConfigProtocolUDP) && val != string(swarm.PortConfigProtocolSCTP) { - return fmt.Errorf("invalid protocol value %s", val) - } - - pConfig.Protocol = swarm.PortConfigProtocol(val) - case portOptMode: - if val != string(swarm.PortConfigPublishModeIngress) && val != string(swarm.PortConfigPublishModeHost) { - return fmt.Errorf("invalid publish mode value %s", val) - } - - pConfig.PublishMode = swarm.PortConfigPublishMode(val) - case portOptTargetPort: - tPort, err := strconv.ParseUint(val, 10, 16) - if err != nil { - return err - } - - pConfig.TargetPort = uint32(tPort) - case portOptPublishedPort: - pPort, err := strconv.ParseUint(val, 10, 16) - if err != nil { - return err - } - - pConfig.PublishedPort = uint32(pPort) - default: - return fmt.Errorf("invalid field key %s", key) - } - } - - if pConfig.TargetPort == 0 { - return fmt.Errorf("missing mandatory field %q", portOptTargetPort) - } - - if pConfig.PublishMode == "" { - pConfig.PublishMode = swarm.PortConfigPublishModeIngress - } - - if pConfig.Protocol == "" { - pConfig.Protocol = swarm.PortConfigProtocolTCP - } - - p.ports = append(p.ports, pConfig) - } else { - // short syntax - portConfigs := []swarm.PortConfig{} - ports, portBindingMap, err := nat.ParsePortSpecs([]string{value}) - if err != nil { - return err - } - for _, portBindings := range portBindingMap { - for _, portBinding := range portBindings { - if portBinding.HostIP != "" { - return fmt.Errorf("hostip is not supported") - } - } - } - - for port := range ports { - portConfig, err := ConvertPortToPortConfig(port, portBindingMap) - if err != nil { - return err - } - portConfigs = append(portConfigs, portConfig...) - } - p.ports = append(p.ports, portConfigs...) - } - return nil -} - -// Type returns the type of this option -func (p *PortOpt) Type() string { - return "port" -} - -// String returns a string repr of this option -func (p *PortOpt) String() string { - ports := []string{} - for _, port := range p.ports { - repr := fmt.Sprintf("%v:%v/%s/%s", port.PublishedPort, port.TargetPort, port.Protocol, port.PublishMode) - ports = append(ports, repr) - } - return strings.Join(ports, ", ") -} - -// Value returns the ports -func (p *PortOpt) Value() []swarm.PortConfig { - return p.ports -} - -// ConvertPortToPortConfig converts ports to the swarm type -func ConvertPortToPortConfig( - port nat.Port, - portBindings map[nat.Port][]nat.PortBinding, -) ([]swarm.PortConfig, error) { - ports := []swarm.PortConfig{} - - for _, binding := range portBindings[port] { - if p := net.ParseIP(binding.HostIP); p != nil && !p.IsUnspecified() { - logrus.Warnf("ignoring IP-address (%s:%s) service will listen on '0.0.0.0'", net.JoinHostPort(binding.HostIP, binding.HostPort), port) - } - - startHostPort, endHostPort, err := nat.ParsePortRange(binding.HostPort) - - if err != nil && binding.HostPort != "" { - return nil, fmt.Errorf("invalid hostport binding (%s) for port (%s)", binding.HostPort, port.Port()) - } - - for i := startHostPort; i <= endHostPort; i++ { - ports = append(ports, swarm.PortConfig{ - // TODO Name: ? - Protocol: swarm.PortConfigProtocol(strings.ToLower(port.Proto())), - TargetPort: uint32(port.Int()), - PublishedPort: uint32(i), - PublishMode: swarm.PortConfigPublishModeIngress, - }) - } - } - return ports, nil -} diff --git a/vendor/github.com/docker/cli/opts/quotedstring.go b/vendor/github.com/docker/cli/opts/quotedstring.go deleted file mode 100644 index 741f450b1..000000000 --- a/vendor/github.com/docker/cli/opts/quotedstring.go +++ /dev/null @@ -1,40 +0,0 @@ -package opts - -// QuotedString is a string that may have extra quotes around the value. The -// quotes are stripped from the value. -type QuotedString struct { - value *string -} - -// Set sets a new value -func (s *QuotedString) Set(val string) error { - *s.value = trimQuotes(val) - return nil -} - -// Type returns the type of the value -func (s *QuotedString) Type() string { - return "string" -} - -func (s *QuotedString) String() string { - return *s.value -} - -func trimQuotes(value string) string { - if len(value) < 2 { - return value - } - lastIndex := len(value) - 1 - for _, char := range []byte{'\'', '"'} { - if value[0] == char && value[lastIndex] == char { - return value[1:lastIndex] - } - } - return value -} - -// NewQuotedString returns a new quoted string option -func NewQuotedString(value *string) *QuotedString { - return &QuotedString{value: value} -} diff --git a/vendor/github.com/docker/cli/opts/secret.go b/vendor/github.com/docker/cli/opts/secret.go deleted file mode 100644 index 750dbe4f3..000000000 --- a/vendor/github.com/docker/cli/opts/secret.go +++ /dev/null @@ -1,98 +0,0 @@ -package opts - -import ( - "encoding/csv" - "fmt" - "os" - "strconv" - "strings" - - swarmtypes "github.com/docker/docker/api/types/swarm" -) - -// SecretOpt is a Value type for parsing secrets -type SecretOpt struct { - values []*swarmtypes.SecretReference -} - -// Set a new secret value -func (o *SecretOpt) Set(value string) error { - csvReader := csv.NewReader(strings.NewReader(value)) - fields, err := csvReader.Read() - if err != nil { - return err - } - - options := &swarmtypes.SecretReference{ - File: &swarmtypes.SecretReferenceFileTarget{ - UID: "0", - GID: "0", - Mode: 0o444, - }, - } - - // support a simple syntax of --secret foo - if len(fields) == 1 && !strings.Contains(fields[0], "=") { - options.File.Name = fields[0] - options.SecretName = fields[0] - o.values = append(o.values, options) - return nil - } - - for _, field := range fields { - key, val, ok := strings.Cut(field, "=") - if !ok || key == "" { - return fmt.Errorf("invalid field '%s' must be a key=value pair", field) - } - // TODO(thaJeztah): these options should not be case-insensitive. - switch strings.ToLower(key) { - case "source", "src": - options.SecretName = val - case "target": - options.File.Name = val - case "uid": - options.File.UID = val - case "gid": - options.File.GID = val - case "mode": - m, err := strconv.ParseUint(val, 0, 32) - if err != nil { - return fmt.Errorf("invalid mode specified: %v", err) - } - - options.File.Mode = os.FileMode(m) - default: - return fmt.Errorf("invalid field in secret request: %s", key) - } - } - - if options.SecretName == "" { - return fmt.Errorf("source is required") - } - if options.File.Name == "" { - options.File.Name = options.SecretName - } - - o.values = append(o.values, options) - return nil -} - -// Type returns the type of this option -func (o *SecretOpt) Type() string { - return "secret" -} - -// String returns a string repr of this option -func (o *SecretOpt) String() string { - secrets := []string{} - for _, secret := range o.values { - repr := fmt.Sprintf("%s -> %s", secret.SecretName, secret.File.Name) - secrets = append(secrets, repr) - } - return strings.Join(secrets, ", ") -} - -// Value returns the secret requests -func (o *SecretOpt) Value() []*swarmtypes.SecretReference { - return o.values -} diff --git a/vendor/github.com/docker/cli/opts/throttledevice.go b/vendor/github.com/docker/cli/opts/throttledevice.go deleted file mode 100644 index 789acf60f..000000000 --- a/vendor/github.com/docker/cli/opts/throttledevice.go +++ /dev/null @@ -1,104 +0,0 @@ -package opts - -import ( - "fmt" - "strconv" - "strings" - - "github.com/docker/docker/api/types/blkiodev" - "github.com/docker/go-units" -) - -// ValidatorThrottleFctType defines a validator function that returns a validated struct and/or an error. -type ValidatorThrottleFctType func(val string) (*blkiodev.ThrottleDevice, error) - -// ValidateThrottleBpsDevice validates that the specified string has a valid device-rate format. -func ValidateThrottleBpsDevice(val string) (*blkiodev.ThrottleDevice, error) { - k, v, ok := strings.Cut(val, ":") - if !ok || k == "" { - return nil, fmt.Errorf("bad format: %s", val) - } - // TODO(thaJeztah): should we really validate this on the client? - if !strings.HasPrefix(k, "/dev/") { - return nil, fmt.Errorf("bad format for device path: %s", val) - } - rate, err := units.RAMInBytes(v) - if err != nil { - return nil, fmt.Errorf("invalid rate for device: %s. The correct format is :[]. Number must be a positive integer. Unit is optional and can be kb, mb, or gb", val) - } - if rate < 0 { - return nil, fmt.Errorf("invalid rate for device: %s. The correct format is :[]. Number must be a positive integer. Unit is optional and can be kb, mb, or gb", val) - } - - return &blkiodev.ThrottleDevice{ - Path: k, - Rate: uint64(rate), - }, nil -} - -// ValidateThrottleIOpsDevice validates that the specified string has a valid device-rate format. -func ValidateThrottleIOpsDevice(val string) (*blkiodev.ThrottleDevice, error) { - k, v, ok := strings.Cut(val, ":") - if !ok || k == "" { - return nil, fmt.Errorf("bad format: %s", val) - } - // TODO(thaJeztah): should we really validate this on the client? - if !strings.HasPrefix(k, "/dev/") { - return nil, fmt.Errorf("bad format for device path: %s", val) - } - rate, err := strconv.ParseUint(v, 10, 64) - if err != nil { - return nil, fmt.Errorf("invalid rate for device: %s. The correct format is :. Number must be a positive integer", val) - } - - return &blkiodev.ThrottleDevice{Path: k, Rate: rate}, nil -} - -// ThrottledeviceOpt defines a map of ThrottleDevices -type ThrottledeviceOpt struct { - values []*blkiodev.ThrottleDevice - validator ValidatorThrottleFctType -} - -// NewThrottledeviceOpt creates a new ThrottledeviceOpt -func NewThrottledeviceOpt(validator ValidatorThrottleFctType) ThrottledeviceOpt { - values := []*blkiodev.ThrottleDevice{} - return ThrottledeviceOpt{ - values: values, - validator: validator, - } -} - -// Set validates a ThrottleDevice and sets its name as a key in ThrottledeviceOpt -func (opt *ThrottledeviceOpt) Set(val string) error { - var value *blkiodev.ThrottleDevice - if opt.validator != nil { - v, err := opt.validator(val) - if err != nil { - return err - } - value = v - } - opt.values = append(opt.values, value) - return nil -} - -// String returns ThrottledeviceOpt values as a string. -func (opt *ThrottledeviceOpt) String() string { - var out []string - for _, v := range opt.values { - out = append(out, v.String()) - } - - return fmt.Sprintf("%v", out) -} - -// GetList returns a slice of pointers to ThrottleDevices. -func (opt *ThrottledeviceOpt) GetList() []*blkiodev.ThrottleDevice { - return append([]*blkiodev.ThrottleDevice{}, opt.values...) -} - -// Type returns the option type -func (opt *ThrottledeviceOpt) Type() string { - return "list" -} diff --git a/vendor/github.com/docker/cli/opts/ulimit.go b/vendor/github.com/docker/cli/opts/ulimit.go deleted file mode 100644 index 4667cc254..000000000 --- a/vendor/github.com/docker/cli/opts/ulimit.go +++ /dev/null @@ -1,60 +0,0 @@ -package opts - -import ( - "fmt" - "sort" - - "github.com/docker/go-units" -) - -// UlimitOpt defines a map of Ulimits -type UlimitOpt struct { - values *map[string]*units.Ulimit -} - -// NewUlimitOpt creates a new UlimitOpt. Ulimits are not validated. -func NewUlimitOpt(ref *map[string]*units.Ulimit) *UlimitOpt { - if ref == nil { - ref = &map[string]*units.Ulimit{} - } - return &UlimitOpt{ref} -} - -// Set validates a Ulimit and sets its name as a key in UlimitOpt -func (o *UlimitOpt) Set(val string) error { - l, err := units.ParseUlimit(val) - if err != nil { - return err - } - - (*o.values)[l.Name] = l - - return nil -} - -// String returns Ulimit values as a string. Values are sorted by name. -func (o *UlimitOpt) String() string { - var out []string - for _, v := range *o.values { - out = append(out, v.String()) - } - sort.Strings(out) - return fmt.Sprintf("%v", out) -} - -// GetList returns a slice of pointers to Ulimits. Values are sorted by name. -func (o *UlimitOpt) GetList() []*units.Ulimit { - var ulimits []*units.Ulimit - for _, v := range *o.values { - ulimits = append(ulimits, v) - } - sort.SliceStable(ulimits, func(i, j int) bool { - return ulimits[i].Name < ulimits[j].Name - }) - return ulimits -} - -// Type returns the option type -func (o *UlimitOpt) Type() string { - return "ulimit" -} diff --git a/vendor/github.com/docker/cli/opts/weightdevice.go b/vendor/github.com/docker/cli/opts/weightdevice.go deleted file mode 100644 index 3077e3da7..000000000 --- a/vendor/github.com/docker/cli/opts/weightdevice.go +++ /dev/null @@ -1,84 +0,0 @@ -package opts - -import ( - "fmt" - "strconv" - "strings" - - "github.com/docker/docker/api/types/blkiodev" -) - -// ValidatorWeightFctType defines a validator function that returns a validated struct and/or an error. -type ValidatorWeightFctType func(val string) (*blkiodev.WeightDevice, error) - -// ValidateWeightDevice validates that the specified string has a valid device-weight format. -func ValidateWeightDevice(val string) (*blkiodev.WeightDevice, error) { - k, v, ok := strings.Cut(val, ":") - if !ok || k == "" { - return nil, fmt.Errorf("bad format: %s", val) - } - // TODO(thaJeztah): should we really validate this on the client? - if !strings.HasPrefix(k, "/dev/") { - return nil, fmt.Errorf("bad format for device path: %s", val) - } - weight, err := strconv.ParseUint(v, 10, 16) - if err != nil { - return nil, fmt.Errorf("invalid weight for device: %s", val) - } - if weight > 0 && (weight < 10 || weight > 1000) { - return nil, fmt.Errorf("invalid weight for device: %s", val) - } - - return &blkiodev.WeightDevice{ - Path: k, - Weight: uint16(weight), - }, nil -} - -// WeightdeviceOpt defines a map of WeightDevices -type WeightdeviceOpt struct { - values []*blkiodev.WeightDevice - validator ValidatorWeightFctType -} - -// NewWeightdeviceOpt creates a new WeightdeviceOpt -func NewWeightdeviceOpt(validator ValidatorWeightFctType) WeightdeviceOpt { - return WeightdeviceOpt{ - values: []*blkiodev.WeightDevice{}, - validator: validator, - } -} - -// Set validates a WeightDevice and sets its name as a key in WeightdeviceOpt -func (opt *WeightdeviceOpt) Set(val string) error { - var value *blkiodev.WeightDevice - if opt.validator != nil { - v, err := opt.validator(val) - if err != nil { - return err - } - value = v - } - opt.values = append(opt.values, value) - return nil -} - -// String returns WeightdeviceOpt values as a string. -func (opt *WeightdeviceOpt) String() string { - var out []string - for _, v := range opt.values { - out = append(out, v.String()) - } - - return fmt.Sprintf("%v", out) -} - -// GetList returns a slice of pointers to WeightDevices. -func (opt *WeightdeviceOpt) GetList() []*blkiodev.WeightDevice { - return opt.values -} - -// Type returns the option type -func (opt *WeightdeviceOpt) Type() string { - return "list" -} diff --git a/vendor/github.com/docker/cli/templates/templates.go b/vendor/github.com/docker/cli/templates/templates.go deleted file mode 100644 index deb043299..000000000 --- a/vendor/github.com/docker/cli/templates/templates.go +++ /dev/null @@ -1,96 +0,0 @@ -package templates - -import ( - "bytes" - "encoding/json" - "strings" - "text/template" -) - -// basicFunctions are the set of initial -// functions provided to every template. -var basicFunctions = template.FuncMap{ - "json": func(v interface{}) string { - buf := &bytes.Buffer{} - enc := json.NewEncoder(buf) - enc.SetEscapeHTML(false) - enc.Encode(v) - // Remove the trailing new line added by the encoder - return strings.TrimSpace(buf.String()) - }, - "split": strings.Split, - "join": strings.Join, - "title": strings.Title, //nolint:staticcheck // strings.Title is deprecated, but we only use it for ASCII, so replacing with golang.org/x/text is out of scope - "lower": strings.ToLower, - "upper": strings.ToUpper, - "pad": padWithSpace, - "truncate": truncateWithLength, -} - -// HeaderFunctions are used to created headers of a table. -// This is a replacement of basicFunctions for header generation -// because we want the header to remain intact. -// Some functions like `pad` are not overridden (to preserve alignment -// with the columns). -var HeaderFunctions = template.FuncMap{ - "json": func(v string) string { - return v - }, - "split": func(v string, _ string) string { - // we want the table header to show the name of the column, and not - // split the table header itself. Using a different signature - // here, and return a string instead of []string - return v - }, - "join": func(v string, _ string) string { - // table headers are always a string, so use a different signature - // for the "join" function (string instead of []string) - return v - }, - "title": func(v string) string { - return v - }, - "lower": func(v string) string { - return v - }, - "upper": func(v string) string { - return v - }, - "truncate": func(v string, _ int) string { - return v - }, -} - -// Parse creates a new anonymous template with the basic functions -// and parses the given format. -func Parse(format string) (*template.Template, error) { - return NewParse("", format) -} - -// New creates a new empty template with the provided tag and built-in -// template functions. -func New(tag string) *template.Template { - return template.New(tag).Funcs(basicFunctions) -} - -// NewParse creates a new tagged template with the basic functions -// and parses the given format. -func NewParse(tag, format string) (*template.Template, error) { - return New(tag).Parse(format) -} - -// padWithSpace adds whitespace to the input if the input is non-empty -func padWithSpace(source string, prefix, suffix int) string { - if source == "" { - return source - } - return strings.Repeat(" ", prefix) + source + strings.Repeat(" ", suffix) -} - -// truncateWithLength truncates the source string up to the length provided by the input -func truncateWithLength(source string, length int) string { - if len(source) < length { - return source - } - return source[:length] -} diff --git a/vendor/github.com/docker/compose/v2/LICENSE b/vendor/github.com/docker/compose/v2/LICENSE deleted file mode 100644 index 7a4a3ea24..000000000 --- a/vendor/github.com/docker/compose/v2/LICENSE +++ /dev/null @@ -1,202 +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. \ No newline at end of file diff --git a/vendor/github.com/docker/compose/v2/NOTICE b/vendor/github.com/docker/compose/v2/NOTICE deleted file mode 100644 index dffae9187..000000000 --- a/vendor/github.com/docker/compose/v2/NOTICE +++ /dev/null @@ -1,4 +0,0 @@ -Docker Compose V2 -Copyright 2020 Docker Compose authors - -This product includes software developed at Docker, Inc. (https://www.docker.com). diff --git a/vendor/github.com/docker/compose/v2/internal/sync/docker_cp.go b/vendor/github.com/docker/compose/v2/internal/sync/docker_cp.go deleted file mode 100644 index ae5a77ad6..000000000 --- a/vendor/github.com/docker/compose/v2/internal/sync/docker_cp.go +++ /dev/null @@ -1,107 +0,0 @@ -/* - Copyright 2023 Docker Compose CLI 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 sync - -import ( - "context" - "errors" - "fmt" - "io" - "io/fs" - "os" - - "github.com/compose-spec/compose-go/types" - "github.com/docker/compose/v2/pkg/api" - "github.com/sirupsen/logrus" -) - -type ComposeClient interface { - Exec(ctx context.Context, projectName string, options api.RunOptions) (int, error) - - Copy(ctx context.Context, projectName string, options api.CopyOptions) error -} - -type DockerCopy struct { - client ComposeClient - - projectName string - - infoWriter io.Writer -} - -var _ Syncer = &DockerCopy{} - -func NewDockerCopy(projectName string, client ComposeClient, infoWriter io.Writer) *DockerCopy { - return &DockerCopy{ - projectName: projectName, - client: client, - infoWriter: infoWriter, - } -} - -func (d *DockerCopy) Sync(ctx context.Context, service types.ServiceConfig, paths []PathMapping) error { - var errs []error - for i := range paths { - if err := d.sync(ctx, service, paths[i]); err != nil { - errs = append(errs, err) - } - } - return errors.Join(errs...) -} - -func (d *DockerCopy) sync(ctx context.Context, service types.ServiceConfig, pathMapping PathMapping) error { - scale := 1 - if service.Deploy != nil && service.Deploy.Replicas != nil { - scale = int(*service.Deploy.Replicas) - } - - if fi, statErr := os.Stat(pathMapping.HostPath); statErr == nil { - if fi.IsDir() { - for i := 1; i <= scale; i++ { - _, err := d.client.Exec(ctx, d.projectName, api.RunOptions{ - Service: service.Name, - Command: []string{"mkdir", "-p", pathMapping.ContainerPath}, - Index: i, - }) - if err != nil { - logrus.Warnf("failed to create %q from %s: %v", pathMapping.ContainerPath, service.Name, err) - } - } - fmt.Fprintf(d.infoWriter, "%s created\n", pathMapping.ContainerPath) - } else { - err := d.client.Copy(ctx, d.projectName, api.CopyOptions{ - Source: pathMapping.HostPath, - Destination: fmt.Sprintf("%s:%s", service.Name, pathMapping.ContainerPath), - }) - if err != nil { - return err - } - fmt.Fprintf(d.infoWriter, "%s updated\n", pathMapping.ContainerPath) - } - } else if errors.Is(statErr, fs.ErrNotExist) { - for i := 1; i <= scale; i++ { - _, err := d.client.Exec(ctx, d.projectName, api.RunOptions{ - Service: service.Name, - Command: []string{"rm", "-rf", pathMapping.ContainerPath}, - Index: i, - }) - if err != nil { - logrus.Warnf("failed to delete %q from %s: %v", pathMapping.ContainerPath, service.Name, err) - } - } - fmt.Fprintf(d.infoWriter, "%s deleted from service\n", pathMapping.ContainerPath) - } - return nil -} diff --git a/vendor/github.com/docker/compose/v2/internal/sync/shared.go b/vendor/github.com/docker/compose/v2/internal/sync/shared.go deleted file mode 100644 index 2ff9b434c..000000000 --- a/vendor/github.com/docker/compose/v2/internal/sync/shared.go +++ /dev/null @@ -1,42 +0,0 @@ -/* - Copyright 2023 Docker Compose CLI 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 sync - -import ( - "context" - - "github.com/compose-spec/compose-go/types" -) - -// PathMapping contains the Compose service and modified host system path. -type PathMapping struct { - // HostPath that was created/modified/deleted outside the container. - // - // This is the path as seen from the user's perspective, e.g. - // - C:\Users\moby\Documents\hello-world\main.go (file on Windows) - // - /Users/moby/Documents/hello-world (directory on macOS) - HostPath string - // ContainerPath for the target file inside the container (only populated - // for sync events, not rebuild). - // - // This is the path as used in Docker CLI commands, e.g. - // - /workdir/main.go - // - /workdir/subdir - ContainerPath string -} - -type Syncer interface { - Sync(ctx context.Context, service types.ServiceConfig, paths []PathMapping) error -} diff --git a/vendor/github.com/docker/compose/v2/internal/sync/tar.go b/vendor/github.com/docker/compose/v2/internal/sync/tar.go deleted file mode 100644 index c16444c3b..000000000 --- a/vendor/github.com/docker/compose/v2/internal/sync/tar.go +++ /dev/null @@ -1,354 +0,0 @@ -/* - Copyright 2018 The Tilt Dev Authors - Copyright 2023 Docker Compose CLI 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 sync - -import ( - "archive/tar" - "bytes" - "context" - "fmt" - "io" - "io/fs" - "os" - "path" - "path/filepath" - "strings" - - "github.com/hashicorp/go-multierror" - "github.com/pkg/errors" - - "github.com/compose-spec/compose-go/types" - moby "github.com/docker/docker/api/types" - "github.com/docker/docker/pkg/archive" -) - -type archiveEntry struct { - path string - info os.FileInfo - header *tar.Header -} - -type LowLevelClient interface { - ContainersForService(ctx context.Context, projectName string, serviceName string) ([]moby.Container, error) - - Exec(ctx context.Context, containerID string, cmd []string, in io.Reader) error -} - -type Tar struct { - client LowLevelClient - - projectName string -} - -var _ Syncer = &Tar{} - -func NewTar(projectName string, client LowLevelClient) *Tar { - return &Tar{ - projectName: projectName, - client: client, - } -} - -func (t *Tar) Sync(ctx context.Context, service types.ServiceConfig, paths []PathMapping) error { - containers, err := t.client.ContainersForService(ctx, t.projectName, service.Name) - if err != nil { - return err - } - - var pathsToCopy []PathMapping - var pathsToDelete []string - for _, p := range paths { - if _, err := os.Stat(p.HostPath); err != nil && errors.Is(err, fs.ErrNotExist) { - pathsToDelete = append(pathsToDelete, p.ContainerPath) - } else { - pathsToCopy = append(pathsToCopy, p) - } - } - - var deleteCmd []string - if len(pathsToDelete) != 0 { - deleteCmd = append([]string{"rm", "-rf"}, pathsToDelete...) - } - copyCmd := []string{"tar", "-v", "-C", "/", "-x", "-f", "-"} - - var eg multierror.Group - writers := make([]*io.PipeWriter, len(containers)) - for i := range containers { - containerID := containers[i].ID - r, w := io.Pipe() - writers[i] = w - eg.Go(func() error { - if len(deleteCmd) != 0 { - if err := t.client.Exec(ctx, containerID, deleteCmd, nil); err != nil { - return fmt.Errorf("deleting paths in %s: %w", containerID, err) - } - } - if err := t.client.Exec(ctx, containerID, copyCmd, r); err != nil { - return fmt.Errorf("copying files to %s: %w", containerID, err) - } - return nil - }) - } - - multiWriter := newLossyMultiWriter(writers...) - tarReader := tarArchive(pathsToCopy) - defer func() { - _ = tarReader.Close() - multiWriter.Close() - }() - _, err = io.Copy(multiWriter, tarReader) - if err != nil { - return err - } - multiWriter.Close() - - return eg.Wait().ErrorOrNil() -} - -type ArchiveBuilder struct { - tw *tar.Writer - // A shared I/O buffer to help with file copying. - copyBuf *bytes.Buffer -} - -func NewArchiveBuilder(writer io.Writer) *ArchiveBuilder { - tw := tar.NewWriter(writer) - return &ArchiveBuilder{ - tw: tw, - copyBuf: &bytes.Buffer{}, - } -} - -func (a *ArchiveBuilder) Close() error { - return a.tw.Close() -} - -// ArchivePathsIfExist creates a tar archive of all local files in `paths`. It quietly skips any paths that don't exist. -func (a *ArchiveBuilder) ArchivePathsIfExist(paths []PathMapping) error { - // In order to handle overlapping syncs, we - // 1) collect all the entries, - // 2) de-dupe them, with last-one-wins semantics - // 3) write all the entries - // - // It's not obvious that this is the correct behavior. A better approach - // (that's more in-line with how syncs work) might ignore files in earlier - // path mappings when we know they're going to be "synced" over. - // There's a bunch of subtle product decisions about how overlapping path - // mappings work that we're not sure about. - var entries []archiveEntry - for _, p := range paths { - newEntries, err := a.entriesForPath(p.HostPath, p.ContainerPath) - if err != nil { - return fmt.Errorf("inspecting %q: %w", p.HostPath, err) - } - - entries = append(entries, newEntries...) - } - - entries = dedupeEntries(entries) - for _, entry := range entries { - err := a.writeEntry(entry) - if err != nil { - return fmt.Errorf("archiving %q: %w", entry.path, err) - } - } - return nil -} - -func (a *ArchiveBuilder) writeEntry(entry archiveEntry) error { - pathInTar := entry.path - header := entry.header - - if header.Typeflag != tar.TypeReg { - // anything other than a regular file (e.g. dir, symlink) just needs the header - if err := a.tw.WriteHeader(header); err != nil { - return fmt.Errorf("writing %q header: %w", pathInTar, err) - } - return nil - } - - file, err := os.Open(pathInTar) - if err != nil { - // In case the file has been deleted since we last looked at it. - if os.IsNotExist(err) { - return nil - } - return err - } - - defer func() { - _ = file.Close() - }() - - // The size header must match the number of contents bytes. - // - // There is room for a race condition here if something writes to the file - // after we've read the file size. - // - // For small files, we avoid this by first copying the file into a buffer, - // and using the size of the buffer to populate the header. - // - // For larger files, we don't want to copy the whole thing into a buffer, - // because that would blow up heap size. There is some danger that this - // will lead to a spurious error when the tar writer validates the sizes. - // That error will be disruptive but will be handled as best as we - // can downstream. - useBuf := header.Size < 5000000 - if useBuf { - a.copyBuf.Reset() - _, err = io.Copy(a.copyBuf, file) - if err != nil && err != io.EOF { - return fmt.Errorf("copying %q: %w", pathInTar, err) - } - header.Size = int64(len(a.copyBuf.Bytes())) - } - - // wait to write the header until _after_ the file is successfully opened - // to avoid generating an invalid tar entry that has a header but no contents - // in the case the file has been deleted - err = a.tw.WriteHeader(header) - if err != nil { - return fmt.Errorf("writing %q header: %w", pathInTar, err) - } - - if useBuf { - _, err = io.Copy(a.tw, a.copyBuf) - } else { - _, err = io.Copy(a.tw, file) - } - - if err != nil && err != io.EOF { - return fmt.Errorf("copying %q: %w", pathInTar, err) - } - - // explicitly flush so that if the entry is invalid we will detect it now and - // provide a more meaningful error - if err := a.tw.Flush(); err != nil { - return fmt.Errorf("finalizing %q: %w", pathInTar, err) - } - return nil -} - -// tarPath writes the given source path into tarWriter at the given dest (recursively for directories). -// e.g. tarring my_dir --> dest d: d/file_a, d/file_b -// If source path does not exist, quietly skips it and returns no err -func (a *ArchiveBuilder) entriesForPath(localPath, containerPath string) ([]archiveEntry, error) { - localInfo, err := os.Stat(localPath) - if err != nil { - if os.IsNotExist(err) { - return nil, nil - } - return nil, err - } - - localPathIsDir := localInfo.IsDir() - if localPathIsDir { - // Make sure we can trim this off filenames to get valid relative filepaths - if !strings.HasSuffix(localPath, string(filepath.Separator)) { - localPath += string(filepath.Separator) - } - } - - containerPath = strings.TrimPrefix(containerPath, "/") - - result := make([]archiveEntry, 0) - err = filepath.Walk(localPath, func(curLocalPath string, info os.FileInfo, err error) error { - if err != nil { - return fmt.Errorf("walking %q: %w", curLocalPath, err) - } - - linkname := "" - if info.Mode()&os.ModeSymlink != 0 { - var err error - linkname, err = os.Readlink(curLocalPath) - if err != nil { - return err - } - } - - var name string - //nolint:gocritic - if localPathIsDir { - // Name of file in tar should be relative to source directory... - tmp, err := filepath.Rel(localPath, curLocalPath) - if err != nil { - return fmt.Errorf("making %q relative to %q: %w", curLocalPath, localPath, err) - } - // ...and live inside `dest` - name = path.Join(containerPath, filepath.ToSlash(tmp)) - } else if strings.HasSuffix(containerPath, "/") { - name = containerPath + filepath.Base(curLocalPath) - } else { - name = containerPath - } - - header, err := archive.FileInfoHeader(name, info, linkname) - if err != nil { - // Not all types of files are allowed in a tarball. That's OK. - // Mimic the Docker behavior and just skip the file. - return nil - } - - result = append(result, archiveEntry{ - path: curLocalPath, - info: info, - header: header, - }) - - return nil - }) - if err != nil { - return nil, err - } - return result, nil -} - -func tarArchive(ops []PathMapping) io.ReadCloser { - pr, pw := io.Pipe() - go func() { - ab := NewArchiveBuilder(pw) - err := ab.ArchivePathsIfExist(ops) - if err != nil { - _ = pw.CloseWithError(fmt.Errorf("adding files to tar: %w", err)) - } else { - // propagate errors from the TarWriter::Close() because it performs a final - // Flush() and any errors mean the tar is invalid - if err := ab.Close(); err != nil { - _ = pw.CloseWithError(fmt.Errorf("closing tar: %w", err)) - } else { - _ = pw.Close() - } - } - }() - return pr -} - -// Dedupe the entries with last-entry-wins semantics. -func dedupeEntries(entries []archiveEntry) []archiveEntry { - seenIndex := make(map[string]int, len(entries)) - result := make([]archiveEntry, 0, len(entries)) - for i, entry := range entries { - seenIndex[entry.header.Name] = i - } - for i, entry := range entries { - if seenIndex[entry.header.Name] == i { - result = append(result, entry) - } - } - return result -} diff --git a/vendor/github.com/docker/compose/v2/internal/sync/writer.go b/vendor/github.com/docker/compose/v2/internal/sync/writer.go deleted file mode 100644 index f5c182d1b..000000000 --- a/vendor/github.com/docker/compose/v2/internal/sync/writer.go +++ /dev/null @@ -1,91 +0,0 @@ -/* - Copyright 2023 Docker Compose CLI 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 sync - -import ( - "errors" - "io" -) - -// lossyMultiWriter attempts to tee all writes to the provided io.PipeWriter -// instances. -// -// If a writer fails during a Write call, the write-side of the pipe is then -// closed with the error and no subsequent attempts are made to write to the -// pipe. -// -// If all writers fail during a write, an error is returned. -// -// On Close, any remaining writers are closed. -type lossyMultiWriter struct { - writers []*io.PipeWriter -} - -// newLossyMultiWriter creates a new writer that *attempts* to tee all data written to it to the provided io.PipeWriter -// instances. Rather than failing a write operation if any writer fails, writes only fail if there are no more valid -// writers. Otherwise, errors for specific writers are propagated via CloseWithError. -func newLossyMultiWriter(writers ...*io.PipeWriter) *lossyMultiWriter { - // reverse the writers because during the write we iterate - // backwards, so this way we'll end up writing in the same - // order as the writers were passed to us - writers = append([]*io.PipeWriter(nil), writers...) - for i, j := 0, len(writers)-1; i < j; i, j = i+1, j-1 { - writers[i], writers[j] = writers[j], writers[i] - } - - return &lossyMultiWriter{ - writers: writers, - } -} - -// Write writes to each writer that is still active (i.e. has not failed/encountered an error on write). -// -// If a writer encounters an error during the write, the write side of the pipe is closed with the error -// and no subsequent attempts will be made to write to that writer. -// -// An error is only returned from this function if ALL writers have failed. -func (l *lossyMultiWriter) Write(p []byte) (int, error) { - // NOTE: this function iterates backwards so that it can - // safely remove elements during the loop - for i := len(l.writers) - 1; i >= 0; i-- { - written, err := l.writers[i].Write(p) - if err == nil && written != len(p) { - err = io.ErrShortWrite - } - if err != nil { - // pipe writer close cannot fail - _ = l.writers[i].CloseWithError(err) - l.writers = append(l.writers[:i], l.writers[i+1:]...) - } - } - - if len(l.writers) == 0 { - return 0, errors.New("no writers remaining") - } - - return len(p), nil -} - -// Close closes any still open (non-failed) writers. -// -// Failed writers have already been closed with an error. -func (l *lossyMultiWriter) Close() { - for i := range l.writers { - // pipe writer close cannot fail - _ = l.writers[i].Close() - } -} diff --git a/vendor/github.com/docker/compose/v2/internal/tracing/attributes.go b/vendor/github.com/docker/compose/v2/internal/tracing/attributes.go deleted file mode 100644 index 76327fe40..000000000 --- a/vendor/github.com/docker/compose/v2/internal/tracing/attributes.go +++ /dev/null @@ -1,152 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 tracing - -import ( - "strings" - "time" - - "github.com/compose-spec/compose-go/types" - moby "github.com/docker/docker/api/types" - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/trace" -) - -// SpanOptions is a small helper type to make it easy to share the options helpers between -// downstream functions that accept slices of trace.SpanStartOption and trace.EventOption. -type SpanOptions []trace.SpanStartEventOption - -func (s SpanOptions) SpanStartOptions() []trace.SpanStartOption { - out := make([]trace.SpanStartOption, len(s)) - for i := range s { - out[i] = s[i] - } - return out -} - -func (s SpanOptions) EventOptions() []trace.EventOption { - out := make([]trace.EventOption, len(s)) - for i := range s { - out[i] = s[i] - } - return out -} - -// ProjectOptions returns common attributes from a Compose project. -// -// For convenience, it's returned as a SpanOptions object to allow it to be -// passed directly to the wrapping helper methods in this package such as -// SpanWrapFunc. -func ProjectOptions(proj *types.Project) SpanOptions { - if proj == nil { - return nil - } - - disabledServiceNames := make([]string, len(proj.DisabledServices)) - for i := range proj.DisabledServices { - disabledServiceNames[i] = proj.DisabledServices[i].Name - } - - attrs := []attribute.KeyValue{ - attribute.String("project.name", proj.Name), - attribute.String("project.dir", proj.WorkingDir), - attribute.StringSlice("project.compose_files", proj.ComposeFiles), - attribute.StringSlice("project.services.active", proj.ServiceNames()), - attribute.StringSlice("project.services.disabled", disabledServiceNames), - attribute.StringSlice("project.profiles", proj.Profiles), - attribute.StringSlice("project.volumes", proj.VolumeNames()), - attribute.StringSlice("project.networks", proj.NetworkNames()), - attribute.StringSlice("project.secrets", proj.SecretNames()), - attribute.StringSlice("project.configs", proj.ConfigNames()), - attribute.StringSlice("project.extensions", keys(proj.Extensions)), - } - return []trace.SpanStartEventOption{ - trace.WithAttributes(attrs...), - } -} - -// ServiceOptions returns common attributes from a Compose service. -// -// For convenience, it's returned as a SpanOptions object to allow it to be -// passed directly to the wrapping helper methods in this package such as -// SpanWrapFunc. -func ServiceOptions(service types.ServiceConfig) SpanOptions { - attrs := []attribute.KeyValue{ - attribute.String("service.name", service.Name), - attribute.String("service.image", service.Image), - attribute.StringSlice("service.networks", keys(service.Networks)), - } - - configNames := make([]string, len(service.Configs)) - for i := range service.Configs { - configNames[i] = service.Configs[i].Source - } - attrs = append(attrs, attribute.StringSlice("service.configs", configNames)) - - secretNames := make([]string, len(service.Secrets)) - for i := range service.Secrets { - secretNames[i] = service.Secrets[i].Source - } - attrs = append(attrs, attribute.StringSlice("service.secrets", secretNames)) - - volNames := make([]string, len(service.Volumes)) - for i := range service.Volumes { - volNames[i] = service.Volumes[i].Source - } - attrs = append(attrs, attribute.StringSlice("service.volumes", volNames)) - - return []trace.SpanStartEventOption{ - trace.WithAttributes(attrs...), - } -} - -// ContainerOptions returns common attributes from a Moby container. -// -// For convenience, it's returned as a SpanOptions object to allow it to be -// passed directly to the wrapping helper methods in this package such as -// SpanWrapFunc. -func ContainerOptions(container moby.Container) SpanOptions { - attrs := []attribute.KeyValue{ - attribute.String("container.id", container.ID), - attribute.String("container.image", container.Image), - unixTimeAttr("container.created_at", container.Created), - } - - if len(container.Names) != 0 { - attrs = append(attrs, attribute.String("container.name", strings.TrimPrefix(container.Names[0], "/"))) - } - - return []trace.SpanStartEventOption{ - trace.WithAttributes(attrs...), - } -} - -func keys[T any](m map[string]T) []string { - out := make([]string, 0, len(m)) - for k := range m { - out = append(out, k) - } - return out -} - -func timeAttr(key string, value time.Time) attribute.KeyValue { - return attribute.String(key, value.Format(time.RFC3339)) -} - -func unixTimeAttr(key string, value int64) attribute.KeyValue { - return timeAttr(key, time.Unix(value, 0).UTC()) -} diff --git a/vendor/github.com/docker/compose/v2/internal/tracing/conn_unix.go b/vendor/github.com/docker/compose/v2/internal/tracing/conn_unix.go deleted file mode 100644 index 78294f4be..000000000 --- a/vendor/github.com/docker/compose/v2/internal/tracing/conn_unix.go +++ /dev/null @@ -1,44 +0,0 @@ -//go:build !windows - -/* - Copyright 2023 Docker Compose CLI 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 tracing - -import ( - "context" - "fmt" - "net" - "strings" - "syscall" -) - -const maxUnixSocketPathSize = len(syscall.RawSockaddrUnix{}.Path) - -func DialInMemory(ctx context.Context, addr string) (net.Conn, error) { - if !strings.HasPrefix(addr, "unix://") { - return nil, fmt.Errorf("not a Unix socket address: %s", addr) - } - addr = strings.TrimPrefix(addr, "unix://") - - if len(addr) > maxUnixSocketPathSize { - //goland:noinspection GoErrorStringFormat - return nil, fmt.Errorf("Unix socket address is too long: %s", addr) - } - - var d net.Dialer - return d.DialContext(ctx, "unix", addr) -} diff --git a/vendor/github.com/docker/compose/v2/internal/tracing/conn_windows.go b/vendor/github.com/docker/compose/v2/internal/tracing/conn_windows.go deleted file mode 100644 index 30deaa464..000000000 --- a/vendor/github.com/docker/compose/v2/internal/tracing/conn_windows.go +++ /dev/null @@ -1,35 +0,0 @@ -/* - Copyright 2023 Docker Compose CLI 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 tracing - -import ( - "context" - "fmt" - "net" - "strings" - - "github.com/Microsoft/go-winio" -) - -func DialInMemory(ctx context.Context, addr string) (net.Conn, error) { - if !strings.HasPrefix(addr, "npipe://") { - return nil, fmt.Errorf("not a named pipe address: %s", addr) - } - addr = strings.TrimPrefix(addr, "npipe://") - - return winio.DialPipeContext(ctx, addr) -} diff --git a/vendor/github.com/docker/compose/v2/internal/tracing/docker_context.go b/vendor/github.com/docker/compose/v2/internal/tracing/docker_context.go deleted file mode 100644 index 092a299b5..000000000 --- a/vendor/github.com/docker/compose/v2/internal/tracing/docker_context.go +++ /dev/null @@ -1,125 +0,0 @@ -/* - Copyright 2023 Docker Compose CLI 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 tracing - -import ( - "context" - "fmt" - "os" - "time" - - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/context/store" - "go.opentelemetry.io/otel/exporters/otlp/otlptrace" - "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" -) - -const otelConfigFieldName = "otel" - -// traceClientFromDockerContext creates a gRPC OTLP client based on metadata -// from the active Docker CLI context. -func traceClientFromDockerContext(dockerCli command.Cli, otelEnv envMap) (otlptrace.Client, error) { - // attempt to extract an OTEL config from the Docker context to enable - // automatic integration with Docker Desktop; - cfg, err := ConfigFromDockerContext(dockerCli.ContextStore(), dockerCli.CurrentContext()) - if err != nil { - return nil, fmt.Errorf("loading otel config from docker context metadata: %v", err) - } - - if cfg.Endpoint == "" { - return nil, nil - } - - // HACK: unfortunately _all_ public OTEL initialization functions - // implicitly read from the OS env, so temporarily unset them all and - // restore afterwards - defer func() { - for k, v := range otelEnv { - if err := os.Setenv(k, v); err != nil { - panic(fmt.Errorf("restoring env for %q: %v", k, err)) - } - } - }() - for k := range otelEnv { - if err := os.Unsetenv(k); err != nil { - return nil, fmt.Errorf("stashing env for %q: %v", k, err) - } - } - - dialCtx, cancel := context.WithTimeout(context.Background(), 1*time.Second) - defer cancel() - conn, err := grpc.DialContext( - dialCtx, - cfg.Endpoint, - grpc.WithContextDialer(DialInMemory), - grpc.WithTransportCredentials(insecure.NewCredentials()), - ) - if err != nil { - return nil, fmt.Errorf("initializing otel connection from docker context metadata: %v", err) - } - - client := otlptracegrpc.NewClient(otlptracegrpc.WithGRPCConn(conn)) - return client, nil -} - -// ConfigFromDockerContext inspects extra metadata included as part of the -// specified Docker context to try and extract a valid OTLP client configuration. -func ConfigFromDockerContext(st store.Store, name string) (OTLPConfig, error) { - meta, err := st.GetMetadata(name) - if err != nil { - return OTLPConfig{}, err - } - - var otelCfg interface{} - switch m := meta.Metadata.(type) { - case command.DockerContext: - otelCfg = m.AdditionalFields[otelConfigFieldName] - case map[string]interface{}: - otelCfg = m[otelConfigFieldName] - } - if otelCfg == nil { - return OTLPConfig{}, nil - } - - otelMap, ok := otelCfg.(map[string]interface{}) - if !ok { - return OTLPConfig{}, fmt.Errorf( - "unexpected type for field %q: %T (expected: %T)", - otelConfigFieldName, - otelCfg, - otelMap, - ) - } - - // keys from https://opentelemetry.io/docs/concepts/sdk-configuration/otlp-exporter-configuration/ - cfg := OTLPConfig{ - Endpoint: valueOrDefault[string](otelMap, "OTEL_EXPORTER_OTLP_ENDPOINT"), - } - return cfg, nil -} - -// valueOrDefault returns the type-cast value at the specified key in the map -// if present and the correct type; otherwise, it returns the default value for -// T. -func valueOrDefault[T any](m map[string]interface{}, key string) T { - if v, ok := m[key].(T); ok { - return v - } - return *new(T) -} diff --git a/vendor/github.com/docker/compose/v2/internal/tracing/errors.go b/vendor/github.com/docker/compose/v2/internal/tracing/errors.go deleted file mode 100644 index 9fa615054..000000000 --- a/vendor/github.com/docker/compose/v2/internal/tracing/errors.go +++ /dev/null @@ -1,29 +0,0 @@ -/* - Copyright 2023 Docker Compose CLI 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 tracing - -import ( - "go.opentelemetry.io/otel" -) - -// skipErrors is a no-op otel.ErrorHandler. -type skipErrors struct{} - -// Handle does nothing, ignoring any errors passed to it. -func (skipErrors) Handle(_ error) {} - -var _ otel.ErrorHandler = skipErrors{} diff --git a/vendor/github.com/docker/compose/v2/internal/tracing/mux.go b/vendor/github.com/docker/compose/v2/internal/tracing/mux.go deleted file mode 100644 index ad5cd1b2e..000000000 --- a/vendor/github.com/docker/compose/v2/internal/tracing/mux.go +++ /dev/null @@ -1,50 +0,0 @@ -/* - Copyright 2023 Docker Compose CLI 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 tracing - -import ( - "context" - - "github.com/hashicorp/go-multierror" - sdktrace "go.opentelemetry.io/otel/sdk/trace" -) - -type MuxExporter struct { - exporters []sdktrace.SpanExporter -} - -func (m MuxExporter) ExportSpans(ctx context.Context, spans []sdktrace.ReadOnlySpan) error { - var eg multierror.Group - for i := range m.exporters { - exporter := m.exporters[i] - eg.Go(func() error { - return exporter.ExportSpans(ctx, spans) - }) - } - return eg.Wait() -} - -func (m MuxExporter) Shutdown(ctx context.Context) error { - var eg multierror.Group - for i := range m.exporters { - exporter := m.exporters[i] - eg.Go(func() error { - return exporter.Shutdown(ctx) - }) - } - return eg.Wait() -} diff --git a/vendor/github.com/docker/compose/v2/internal/tracing/tracing.go b/vendor/github.com/docker/compose/v2/internal/tracing/tracing.go deleted file mode 100644 index afa534d57..000000000 --- a/vendor/github.com/docker/compose/v2/internal/tracing/tracing.go +++ /dev/null @@ -1,156 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 tracing - -import ( - "context" - "errors" - "fmt" - "os" - "strconv" - "strings" - - "github.com/docker/compose/v2/internal" - "go.opentelemetry.io/otel/attribute" - - "github.com/docker/cli/cli/command" - "github.com/moby/buildkit/util/tracing/detect" - _ "github.com/moby/buildkit/util/tracing/detect/delegated" //nolint:blank-imports - _ "github.com/moby/buildkit/util/tracing/env" //nolint:blank-imports - "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/exporters/otlp/otlptrace" - "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc" - "go.opentelemetry.io/otel/propagation" - "go.opentelemetry.io/otel/sdk/resource" - sdktrace "go.opentelemetry.io/otel/sdk/trace" - semconv "go.opentelemetry.io/otel/semconv/v1.18.0" -) - -func init() { - detect.ServiceName = "compose" - // do not log tracing errors to stdio - otel.SetErrorHandler(skipErrors{}) -} - -var Tracer = otel.Tracer("compose") - -// OTLPConfig contains the necessary values to initialize an OTLP client -// manually. -// -// This supports a minimal set of options based on what is necessary for -// automatic OTEL configuration from Docker context metadata. -type OTLPConfig struct { - Endpoint string -} - -// ShutdownFunc flushes and stops an OTEL exporter. -type ShutdownFunc func(ctx context.Context) error - -// envMap is a convenience type for OS environment variables. -type envMap map[string]string - -func InitTracing(dockerCli command.Cli) (ShutdownFunc, error) { - // set global propagator to tracecontext (the default is no-op). - otel.SetTextMapPropagator(propagation.TraceContext{}) - - if v, _ := strconv.ParseBool(os.Getenv("COMPOSE_EXPERIMENTAL_OTEL")); !v { - return nil, nil - } - - return InitProvider(dockerCli) -} - -func InitProvider(dockerCli command.Cli) (ShutdownFunc, error) { - ctx := context.Background() - - var errs []error - var exporters []sdktrace.SpanExporter - - envClient, otelEnv := traceClientFromEnv() - if envClient != nil { - if envExporter, err := otlptrace.New(ctx, envClient); err != nil { - errs = append(errs, err) - } else if envExporter != nil { - exporters = append(exporters, envExporter) - } - } - - if dcClient, err := traceClientFromDockerContext(dockerCli, otelEnv); err != nil { - errs = append(errs, err) - } else if dcClient != nil { - if dcExporter, err := otlptrace.New(ctx, dcClient); err != nil { - errs = append(errs, err) - } else if dcExporter != nil { - exporters = append(exporters, dcExporter) - } - } - if len(errs) != 0 { - return nil, errors.Join(errs...) - } - - res, err := resource.New( - ctx, - resource.WithAttributes( - semconv.ServiceName("compose"), - semconv.ServiceVersion(internal.Version), - attribute.String("docker.context", dockerCli.CurrentContext()), - ), - ) - if err != nil { - return nil, fmt.Errorf("failed to create resource: %v", err) - } - - muxExporter := MuxExporter{exporters: exporters} - sp := sdktrace.NewSimpleSpanProcessor(muxExporter) - tracerProvider := sdktrace.NewTracerProvider( - sdktrace.WithSampler(sdktrace.AlwaysSample()), - sdktrace.WithResource(res), - sdktrace.WithSpanProcessor(sp), - ) - otel.SetTracerProvider(tracerProvider) - - // Shutdown will flush any remaining spans and shut down the exporter. - return tracerProvider.Shutdown, nil -} - -// traceClientFromEnv creates a GRPC OTLP client based on OS environment -// variables. -// -// https://opentelemetry.io/docs/concepts/sdk-configuration/otlp-exporter-configuration/ -func traceClientFromEnv() (otlptrace.Client, envMap) { - hasOtelEndpointInEnv := false - otelEnv := make(map[string]string) - for _, kv := range os.Environ() { - k, v, ok := strings.Cut(kv, "=") - if !ok { - continue - } - if strings.HasPrefix(k, "OTEL_") { - otelEnv[k] = v - if strings.HasSuffix(k, "ENDPOINT") { - hasOtelEndpointInEnv = true - } - } - } - - if !hasOtelEndpointInEnv { - return nil, nil - } - - client := otlptracegrpc.NewClient() - return client, otelEnv -} diff --git a/vendor/github.com/docker/compose/v2/internal/tracing/wrap.go b/vendor/github.com/docker/compose/v2/internal/tracing/wrap.go deleted file mode 100644 index 8de84036f..000000000 --- a/vendor/github.com/docker/compose/v2/internal/tracing/wrap.go +++ /dev/null @@ -1,91 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 tracing - -import ( - "context" - - "go.opentelemetry.io/otel/codes" - semconv "go.opentelemetry.io/otel/semconv/v1.18.0" - "go.opentelemetry.io/otel/trace" -) - -// SpanWrapFunc wraps a function that takes a context with a trace.Span, marking the status as codes.Error if the -// wrapped function returns an error. -// -// The context passed to the function is created from the span to ensure correct propagation. -// -// NOTE: This function is nearly identical to SpanWrapFuncForErrGroup, except the latter is designed specially for -// convenience with errgroup.Group due to its prevalence throughout the codebase. The code is duplicated to avoid -// adding even more levels of function wrapping/indirection. -func SpanWrapFunc(spanName string, opts SpanOptions, fn func(ctx context.Context) error) func(context.Context) error { - return func(ctx context.Context) error { - ctx, span := Tracer.Start(ctx, spanName, opts.SpanStartOptions()...) - defer span.End() - - if err := fn(ctx); err != nil { - span.SetStatus(codes.Error, err.Error()) - return err - } - - span.SetStatus(codes.Ok, "") - return nil - } -} - -// SpanWrapFuncForErrGroup wraps a function that takes a context with a trace.Span, marking the status as codes.Error -// if the wrapped function returns an error. -// -// The context passed to the function is created from the span to ensure correct propagation. -// -// NOTE: This function is nearly identical to SpanWrapFunc, except this function is designed specially for -// convenience with errgroup.Group due to its prevalence throughout the codebase. The code is duplicated to avoid -// adding even more levels of function wrapping/indirection. -func SpanWrapFuncForErrGroup(ctx context.Context, spanName string, opts SpanOptions, fn func(ctx context.Context) error) func() error { - return func() error { - ctx, span := Tracer.Start(ctx, spanName, opts.SpanStartOptions()...) - defer span.End() - - if err := fn(ctx); err != nil { - span.SetStatus(codes.Error, err.Error()) - return err - } - - span.SetStatus(codes.Ok, "") - return nil - } -} - -// EventWrapFuncForErrGroup invokes a function and records an event, optionally including the returned -// error as the "exception message" on the event. -// -// This is intended for lightweight usage to wrap errgroup.Group calls where a full span is not desired. -func EventWrapFuncForErrGroup(ctx context.Context, eventName string, opts SpanOptions, fn func(ctx context.Context) error) func() error { - return func() error { - span := trace.SpanFromContext(ctx) - eventOpts := opts.EventOptions() - - err := fn(ctx) - - if err != nil { - eventOpts = append(eventOpts, trace.WithAttributes(semconv.ExceptionMessage(err.Error()))) - } - span.AddEvent(eventName, eventOpts...) - - return err - } -} diff --git a/vendor/github.com/docker/compose/v2/internal/variables.go b/vendor/github.com/docker/compose/v2/internal/variables.go deleted file mode 100644 index 876b3d3ca..000000000 --- a/vendor/github.com/docker/compose/v2/internal/variables.go +++ /dev/null @@ -1,22 +0,0 @@ -/* - Copyright 2023 Docker Compose CLI 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 internal - -var ( - // Version is the version of the CLI injected in compilation time - Version = "dev" -) diff --git a/vendor/github.com/docker/compose/v2/pkg/api/api.go b/vendor/github.com/docker/compose/v2/pkg/api/api.go deleted file mode 100644 index 41dda691a..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/api/api.go +++ /dev/null @@ -1,569 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 api - -import ( - "context" - "fmt" - "strings" - "time" - - "github.com/compose-spec/compose-go/types" - "github.com/docker/compose/v2/pkg/utils" -) - -// Service manages a compose project -type Service interface { - // Build executes the equivalent to a `compose build` - Build(ctx context.Context, project *types.Project, options BuildOptions) error - // Push executes the equivalent to a `compose push` - Push(ctx context.Context, project *types.Project, options PushOptions) error - // Pull executes the equivalent of a `compose pull` - Pull(ctx context.Context, project *types.Project, options PullOptions) error - // Create executes the equivalent to a `compose create` - Create(ctx context.Context, project *types.Project, options CreateOptions) error - // Start executes the equivalent to a `compose start` - Start(ctx context.Context, projectName string, options StartOptions) error - // Restart restarts containers - Restart(ctx context.Context, projectName string, options RestartOptions) error - // Stop executes the equivalent to a `compose stop` - Stop(ctx context.Context, projectName string, options StopOptions) error - // Up executes the equivalent to a `compose up` - Up(ctx context.Context, project *types.Project, options UpOptions) error - // Down executes the equivalent to a `compose down` - Down(ctx context.Context, projectName string, options DownOptions) error - // Logs executes the equivalent to a `compose logs` - Logs(ctx context.Context, projectName string, consumer LogConsumer, options LogOptions) error - // Ps executes the equivalent to a `compose ps` - Ps(ctx context.Context, projectName string, options PsOptions) ([]ContainerSummary, error) - // List executes the equivalent to a `docker stack ls` - List(ctx context.Context, options ListOptions) ([]Stack, error) - // Config executes the equivalent to a `compose config` - Config(ctx context.Context, project *types.Project, options ConfigOptions) ([]byte, error) - // Kill executes the equivalent to a `compose kill` - Kill(ctx context.Context, projectName string, options KillOptions) error - // RunOneOffContainer creates a service oneoff container and starts its dependencies - RunOneOffContainer(ctx context.Context, project *types.Project, opts RunOptions) (int, error) - // Remove executes the equivalent to a `compose rm` - Remove(ctx context.Context, projectName string, options RemoveOptions) error - // Exec executes a command in a running service container - Exec(ctx context.Context, projectName string, options RunOptions) (int, error) - // Copy copies a file/folder between a service container and the local filesystem - Copy(ctx context.Context, projectName string, options CopyOptions) error - // Pause executes the equivalent to a `compose pause` - Pause(ctx context.Context, projectName string, options PauseOptions) error - // UnPause executes the equivalent to a `compose unpause` - UnPause(ctx context.Context, projectName string, options PauseOptions) error - // Top executes the equivalent to a `compose top` - Top(ctx context.Context, projectName string, services []string) ([]ContainerProcSummary, error) - // Events executes the equivalent to a `compose events` - Events(ctx context.Context, projectName string, options EventsOptions) error - // Port executes the equivalent to a `compose port` - Port(ctx context.Context, projectName string, service string, port uint16, options PortOptions) (string, int, error) - // Images executes the equivalent of a `compose images` - Images(ctx context.Context, projectName string, options ImagesOptions) ([]ImageSummary, error) - // MaxConcurrency defines upper limit for concurrent operations against engine API - MaxConcurrency(parallel int) - // DryRunMode defines if dry run applies to the command - DryRunMode(ctx context.Context, dryRun bool) (context.Context, error) - // Watch services' development context and sync/notify/rebuild/restart on changes - Watch(ctx context.Context, project *types.Project, services []string, options WatchOptions) error - // Viz generates a graphviz graph of the project services - Viz(ctx context.Context, project *types.Project, options VizOptions) (string, error) - // Wait blocks until at least one of the services' container exits - Wait(ctx context.Context, projectName string, options WaitOptions) (int64, error) -} - -type WaitOptions struct { - // Services passed in the command line to be waited - Services []string - // Executes a down when a container exits - DownProjectOnContainerExit bool -} - -type VizOptions struct { - // IncludeNetworks if true, network names a container is attached to should appear in the graph node - IncludeNetworks bool - // IncludePorts if true, ports a container exposes should appear in the graph node - IncludePorts bool - // IncludeImageName if true, name of the image used to create a container should appear in the graph node - IncludeImageName bool - // Indentation string to be used to indent graphviz code, e.g. "\t", " " - Indentation string -} - -// WatchOptions group options of the Watch API -type WatchOptions struct { -} - -// BuildOptions group options of the Build API -type BuildOptions struct { - // Pull always attempt to pull a newer version of the image - Pull bool - // Push pushes service images - Push bool - // Progress set type of progress output ("auto", "plain", "tty") - Progress string - // Args set build-time args - Args types.MappingWithEquals - // NoCache disables cache use - NoCache bool - // Quiet make the build process not output to the console - Quiet bool - // Services passed in the command line to be built - Services []string - // Ssh authentications passed in the command line - SSHs []types.SSHKey - // Memory limit for the build container - Memory int64 - // Builder name passed in the command line - Builder string -} - -// Apply mutates project according to build options -func (o BuildOptions) Apply(project *types.Project) error { - platform := project.Environment["DOCKER_DEFAULT_PLATFORM"] - for i, service := range project.Services { - if service.Image == "" && service.Build == nil { - return fmt.Errorf("invalid service %q. Must specify either image or build", service.Name) - } - - if service.Build == nil { - continue - } - if platform != "" { - if len(service.Build.Platforms) > 0 && !utils.StringContains(service.Build.Platforms, platform) { - return fmt.Errorf("service %q build.platforms does not support value set by DOCKER_DEFAULT_PLATFORM: %s", service.Name, platform) - } - service.Platform = platform - } - if service.Platform != "" { - if len(service.Build.Platforms) > 0 && !utils.StringContains(service.Build.Platforms, service.Platform) { - return fmt.Errorf("service %q build configuration does not support platform: %s", service.Name, service.Platform) - } - } - - service.Build.Pull = service.Build.Pull || o.Pull - service.Build.NoCache = service.Build.NoCache || o.NoCache - - project.Services[i] = service - } - return nil -} - -// CreateOptions group options of the Create API -type CreateOptions struct { - // Services defines the services user interacts with - Services []string - // Remove legacy containers for services that are not defined in the project - RemoveOrphans bool - // Ignore legacy containers for services that are not defined in the project - IgnoreOrphans bool - // Recreate define the strategy to apply on existing containers - Recreate string - // RecreateDependencies define the strategy to apply on dependencies services - RecreateDependencies string - // Inherit reuse anonymous volumes from previous container - Inherit bool - // Timeout set delay to wait for container to gracelfuly stop before sending SIGKILL - Timeout *time.Duration - // QuietPull makes the pulling process quiet - QuietPull bool -} - -// StartOptions group options of the Start API -type StartOptions struct { - // Project is the compose project used to define this app. Might be nil if user ran command just with project name - Project *types.Project - // Attach to container and forward logs if not nil - Attach LogConsumer - // AttachTo set the services to attach to - AttachTo []string - // CascadeStop stops the application when a container stops - CascadeStop bool - // ExitCodeFrom return exit code from specified service - ExitCodeFrom string - // Wait won't return until containers reached the running|healthy state - Wait bool - WaitTimeout time.Duration - // Services passed in the command line to be started - Services []string -} - -// RestartOptions group options of the Restart API -type RestartOptions struct { - // Project is the compose project used to define this app. Might be nil if user ran command just with project name - Project *types.Project - // Timeout override container restart timeout - Timeout *time.Duration - // Services passed in the command line to be restarted - Services []string -} - -// StopOptions group options of the Stop API -type StopOptions struct { - // Project is the compose project used to define this app. Might be nil if user ran command just with project name - Project *types.Project - // Timeout override container stop timeout - Timeout *time.Duration - // Services passed in the command line to be stopped - Services []string -} - -// UpOptions group options of the Up API -type UpOptions struct { - Create CreateOptions - Start StartOptions -} - -// DownOptions group options of the Down API -type DownOptions struct { - // RemoveOrphans will cleanup containers that are not declared on the compose model but own the same labels - RemoveOrphans bool - // Project is the compose project used to define this app. Might be nil if user ran `down` just with project name - Project *types.Project - // Timeout override container stop timeout - Timeout *time.Duration - // Images remove image used by services. 'all': Remove all images. 'local': Remove only images that don't have a tag - Images string - // Volumes remove volumes, both declared in the `volumes` section and anonymous ones - Volumes bool - // Services passed in the command line to be stopped - Services []string -} - -// ConfigOptions group options of the Config API -type ConfigOptions struct { - // Format define the output format used to dump converted application model (json|yaml) - Format string - // Output defines the path to save the application model - Output string - // Resolve image reference to digests - ResolveImageDigests bool -} - -// PushOptions group options of the Push API -type PushOptions struct { - Quiet bool - IgnoreFailures bool -} - -// PullOptions group options of the Pull API -type PullOptions struct { - Quiet bool - IgnoreFailures bool - IgnoreBuildable bool -} - -// ImagesOptions group options of the Images API -type ImagesOptions struct { - Services []string -} - -// KillOptions group options of the Kill API -type KillOptions struct { - // RemoveOrphans will cleanup containers that are not declared on the compose model but own the same labels - RemoveOrphans bool - // Project is the compose project used to define this app. Might be nil if user ran command just with project name - Project *types.Project - // Services passed in the command line to be killed - Services []string - // Signal to send to containers - Signal string -} - -// RemoveOptions group options of the Remove API -type RemoveOptions struct { - // Project is the compose project used to define this app. Might be nil if user ran command just with project name - Project *types.Project - // Stop option passed in the command line - Stop bool - // Volumes remove anonymous volumes - Volumes bool - // Force don't ask to confirm removal - Force bool - // Services passed in the command line to be removed - Services []string -} - -// RunOptions group options of the Run API -type RunOptions struct { - // Project is the compose project used to define this app. Might be nil if user ran command just with project name - Project *types.Project - Name string - Service string - Command []string - Entrypoint []string - Detach bool - AutoRemove bool - Tty bool - Interactive bool - WorkingDir string - User string - Environment []string - CapAdd []string - CapDrop []string - Labels types.Labels - Privileged bool - UseNetworkAliases bool - NoDeps bool - // QuietPull makes the pulling process quiet - QuietPull bool - // used by exec - Index int -} - -// EventsOptions group options of the Events API -type EventsOptions struct { - Services []string - Consumer func(event Event) error -} - -// Event is a container runtime event served by Events API -type Event struct { - Timestamp time.Time - Service string - Container string - Status string - Attributes map[string]string -} - -// PortOptions group options of the Port API -type PortOptions struct { - Protocol string - Index int -} - -func (e Event) String() string { - t := e.Timestamp.Format("2006-01-02 15:04:05.000000") - var attr []string - for k, v := range e.Attributes { - attr = append(attr, fmt.Sprintf("%s=%s", k, v)) - } - return fmt.Sprintf("%s container %s %s (%s)\n", t, e.Status, e.Container, strings.Join(attr, ", ")) - -} - -// ListOptions group options of the ls API -type ListOptions struct { - All bool -} - -// PsOptions group options of the Ps API -type PsOptions struct { - Project *types.Project - All bool - Services []string -} - -// CopyOptions group options of the cp API -type CopyOptions struct { - Source string - Destination string - All bool - Index int - FollowLink bool - CopyUIDGID bool -} - -// PortPublisher hold status about published port -type PortPublisher struct { - URL string - TargetPort int - PublishedPort int - Protocol string -} - -// ContainerSummary hold high-level description of a container -type ContainerSummary struct { - ID string - Name string - Image any - Command string - Project string - Service string - Created int64 - State string - Status string - Health string - ExitCode int - Publishers PortPublishers -} - -// PortPublishers is a slice of PortPublisher -type PortPublishers []PortPublisher - -// Len implements sort.Interface -func (p PortPublishers) Len() int { - return len(p) -} - -// Less implements sort.Interface -func (p PortPublishers) Less(i, j int) bool { - left := p[i] - right := p[j] - if left.URL != right.URL { - return left.URL < right.URL - } - if left.TargetPort != right.TargetPort { - return left.TargetPort < right.TargetPort - } - if left.PublishedPort != right.PublishedPort { - return left.PublishedPort < right.PublishedPort - } - return left.Protocol < right.Protocol -} - -// Swap implements sort.Interface -func (p PortPublishers) Swap(i, j int) { - p[i], p[j] = p[j], p[i] -} - -// ContainerProcSummary holds container processes top data -type ContainerProcSummary struct { - ID string - Name string - Processes [][]string - Titles []string -} - -// ImageSummary holds container image description -type ImageSummary struct { - ID string - ContainerName string - Repository string - Tag string - Size int64 -} - -// ServiceStatus hold status about a service -type ServiceStatus struct { - ID string - Name string - Replicas int - Desired int - Ports []string - Publishers []PortPublisher -} - -// LogOptions defines optional parameters for the `Log` API -type LogOptions struct { - Project *types.Project - Services []string - Tail string - Since string - Until string - Follow bool - Timestamps bool -} - -// PauseOptions group options of the Pause API -type PauseOptions struct { - // Services passed in the command line to be started - Services []string - // Project is the compose project used to define this app. Might be nil if user ran command just with project name - Project *types.Project -} - -const ( - // STARTING indicates that stack is being deployed - STARTING string = "Starting" - // RUNNING indicates that stack is deployed and services are running - RUNNING string = "Running" - // UPDATING indicates that some stack resources are being recreated - UPDATING string = "Updating" - // REMOVING indicates that stack is being deleted - REMOVING string = "Removing" - // UNKNOWN indicates unknown stack state - UNKNOWN string = "Unknown" - // FAILED indicates that stack deployment failed - FAILED string = "Failed" -) - -const ( - // RecreateDiverged to recreate services which configuration diverges from compose model - RecreateDiverged = "diverged" - // RecreateForce to force service container being recreated - RecreateForce = "force" - // RecreateNever to never recreate existing service containers - RecreateNever = "never" -) - -// Stack holds the name and state of a compose application/stack -type Stack struct { - ID string - Name string - Status string - ConfigFiles string - Reason string -} - -// LogConsumer is a callback to process log messages from services -type LogConsumer interface { - Log(containerName, message string) - Err(containerName, message string) - Status(container, msg string) - Register(container string) -} - -// ContainerEventListener is a callback to process ContainerEvent from services -type ContainerEventListener func(event ContainerEvent) - -// ContainerEvent notify an event has been collected on source container implementing Service -type ContainerEvent struct { - Type int - // Container is the name of the container _without the project prefix_. - // - // This is only suitable for display purposes within Compose, as it's - // not guaranteed to be unique across services. - Container string - ID string - Service string - Line string - // ContainerEventExit only - ExitCode int - Restarting bool -} - -const ( - // ContainerEventLog is a ContainerEvent of type log on stdout. Line is set - ContainerEventLog = iota - // ContainerEventErr is a ContainerEvent of type log on stderr. Line is set - ContainerEventErr - // ContainerEventAttach is a ContainerEvent of type attach. First event sent about a container - ContainerEventAttach - // ContainerEventStopped is a ContainerEvent of type stopped. - ContainerEventStopped - // ContainerEventRecreated let consumer know container stopped but his being replaced - ContainerEventRecreated - // ContainerEventExit is a ContainerEvent of type exit. ExitCode is set - ContainerEventExit - // UserCancel user cancelled compose up, we are stopping containers - UserCancel -) - -// Separator is used for naming components -var Separator = "-" - -// GetImageNameOrDefault computes the default image name for a service, used to tag built images -func GetImageNameOrDefault(service types.ServiceConfig, projectName string) string { - imageName := service.Image - if imageName == "" { - imageName = projectName + Separator + service.Name - } - return imageName -} diff --git a/vendor/github.com/docker/compose/v2/pkg/api/dryrunclient.go b/vendor/github.com/docker/compose/v2/pkg/api/dryrunclient.go deleted file mode 100644 index c5926be83..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/api/dryrunclient.go +++ /dev/null @@ -1,697 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 api - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "net" - "net/http" - "runtime" - "strings" - "sync" - - "github.com/docker/buildx/builder" - "github.com/docker/buildx/util/imagetools" - "github.com/docker/cli/cli/command" - - "github.com/distribution/distribution/v3/uuid" - moby "github.com/docker/docker/api/types" - containerType "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/events" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/image" - "github.com/docker/docker/api/types/network" - "github.com/docker/docker/api/types/registry" - "github.com/docker/docker/api/types/swarm" - "github.com/docker/docker/api/types/volume" - "github.com/docker/docker/client" - "github.com/docker/docker/pkg/jsonmessage" - specs "github.com/opencontainers/image-spec/specs-go/v1" - "github.com/pkg/errors" -) - -const ( - DRYRUN_PREFIX = " DRY-RUN MODE - " -) - -var _ client.APIClient = &DryRunClient{} - -type DryRunKey struct{} - -// DryRunClient implements APIClient by delegating to implementation functions. This allows lazy init and per-method overrides -type DryRunClient struct { - apiClient client.APIClient - containers []moby.Container - execs sync.Map - resolver *imagetools.Resolver -} - -type execDetails struct { - container string - command []string -} - -// NewDryRunClient produces a DryRunClient -func NewDryRunClient(apiClient client.APIClient, cli command.Cli) (*DryRunClient, error) { - b, err := builder.New(cli, builder.WithSkippedValidation()) - if err != nil { - return nil, err - } - configFile, err := b.ImageOpt() - if err != nil { - return nil, err - } - return &DryRunClient{ - apiClient: apiClient, - containers: []moby.Container{}, - execs: sync.Map{}, - resolver: imagetools.New(configFile), - }, nil -} - -func getCallingFunction() string { - pc, _, _, _ := runtime.Caller(2) - fullName := runtime.FuncForPC(pc).Name() - return fullName[strings.LastIndex(fullName, ".")+1:] -} - -// All methods and functions which need to be overridden for dry run. - -func (d *DryRunClient) ContainerAttach(ctx context.Context, container string, options moby.ContainerAttachOptions) (moby.HijackedResponse, error) { - return moby.HijackedResponse{}, errors.New("interactive run is not supported in dry-run mode") -} - -func (d *DryRunClient) ContainerCreate(ctx context.Context, config *containerType.Config, hostConfig *containerType.HostConfig, - networkingConfig *network.NetworkingConfig, platform *specs.Platform, containerName string) (containerType.CreateResponse, error) { - d.containers = append(d.containers, moby.Container{ - ID: containerName, - Names: []string{containerName}, - Labels: config.Labels, - HostConfig: struct { - NetworkMode string `json:",omitempty"` - }{}, - }) - return containerType.CreateResponse{ID: containerName}, nil -} - -func (d *DryRunClient) ContainerInspect(ctx context.Context, container string) (moby.ContainerJSON, error) { - containerJSON, err := d.apiClient.ContainerInspect(ctx, container) - if err != nil { - id := "dryRunId" - for _, c := range d.containers { - if c.ID == container { - id = container - } - } - return moby.ContainerJSON{ - ContainerJSONBase: &moby.ContainerJSONBase{ - ID: id, - Name: container, - State: &moby.ContainerState{ - Status: "running", // needed for --wait option - Health: &moby.Health{ - Status: moby.Healthy, // needed for healthcheck control - }, - }, - }, - Mounts: nil, - Config: &containerType.Config{}, - NetworkSettings: &moby.NetworkSettings{}, - }, nil - } - return containerJSON, err -} - -func (d *DryRunClient) ContainerKill(ctx context.Context, container, signal string) error { - return nil -} - -func (d *DryRunClient) ContainerList(ctx context.Context, options moby.ContainerListOptions) ([]moby.Container, error) { - caller := getCallingFunction() - switch caller { - case "start": - return d.containers, nil - case "getContainers": - if len(d.containers) == 0 { - var err error - d.containers, err = d.apiClient.ContainerList(ctx, options) - return d.containers, err - } - } - return d.apiClient.ContainerList(ctx, options) -} - -func (d *DryRunClient) ContainerPause(ctx context.Context, container string) error { - return nil -} - -func (d *DryRunClient) ContainerRemove(ctx context.Context, container string, options moby.ContainerRemoveOptions) error { - return nil -} - -func (d *DryRunClient) ContainerRename(ctx context.Context, container, newContainerName string) error { - return nil -} - -func (d *DryRunClient) ContainerRestart(ctx context.Context, container string, options containerType.StopOptions) error { - return nil -} - -func (d *DryRunClient) ContainerStart(ctx context.Context, container string, options moby.ContainerStartOptions) error { - return nil -} - -func (d *DryRunClient) ContainerStop(ctx context.Context, container string, options containerType.StopOptions) error { - return nil -} - -func (d *DryRunClient) ContainerUnpause(ctx context.Context, container string) error { - return nil -} - -func (d *DryRunClient) CopyFromContainer(ctx context.Context, container, srcPath string) (io.ReadCloser, moby.ContainerPathStat, error) { - rc := io.NopCloser(strings.NewReader("")) - if _, err := d.ContainerStatPath(ctx, container, srcPath); err != nil { - return rc, moby.ContainerPathStat{}, fmt.Errorf(" %s Could not find the file %s in container %s", DRYRUN_PREFIX, srcPath, container) - } - return rc, moby.ContainerPathStat{}, nil -} - -func (d *DryRunClient) CopyToContainer(ctx context.Context, container, path string, content io.Reader, options moby.CopyToContainerOptions) error { - if _, err := d.ContainerStatPath(ctx, container, path); err != nil { - return fmt.Errorf(" %s Could not find the file %s in container %s", DRYRUN_PREFIX, path, container) - } - return nil -} - -func (d *DryRunClient) ImageBuild(ctx context.Context, reader io.Reader, options moby.ImageBuildOptions) (moby.ImageBuildResponse, error) { - jsonMessage, err := json.Marshal(&jsonmessage.JSONMessage{ - Status: fmt.Sprintf("%[1]sSuccessfully built: dryRunID\n%[1]sSuccessfully tagged: %[2]s\n", DRYRUN_PREFIX, options.Tags[0]), - Progress: &jsonmessage.JSONProgress{}, - ID: "", - }) - if err != nil { - return moby.ImageBuildResponse{}, err - } - rc := io.NopCloser(bytes.NewReader(jsonMessage)) - - return moby.ImageBuildResponse{ - Body: rc, - OSType: "", - }, nil -} - -func (d *DryRunClient) ImageInspectWithRaw(ctx context.Context, imageName string) (moby.ImageInspect, []byte, error) { - caller := getCallingFunction() - switch caller { - case "pullServiceImage", "buildContainerVolumes": - return moby.ImageInspect{ID: "dryRunId"}, nil, nil - default: - return d.apiClient.ImageInspectWithRaw(ctx, imageName) - } - -} - -func (d *DryRunClient) ImagePull(ctx context.Context, ref string, options moby.ImagePullOptions) (io.ReadCloser, error) { - if _, _, err := d.resolver.Resolve(ctx, ref); err != nil { - return nil, err - } - rc := io.NopCloser(strings.NewReader("")) - return rc, nil -} - -func (d *DryRunClient) ImagePush(ctx context.Context, ref string, options moby.ImagePushOptions) (io.ReadCloser, error) { - if _, _, err := d.resolver.Resolve(ctx, ref); err != nil { - return nil, err - } - jsonMessage, err := json.Marshal(&jsonmessage.JSONMessage{ - Status: "Pushed", - Progress: &jsonmessage.JSONProgress{ - Current: 100, - Total: 100, - Start: 0, - HideCounts: false, - Units: "Mb", - }, - ID: ref, - }) - if err != nil { - return nil, err - } - rc := io.NopCloser(bytes.NewReader(jsonMessage)) - return rc, nil -} - -func (d *DryRunClient) ImageRemove(ctx context.Context, imageName string, options moby.ImageRemoveOptions) ([]moby.ImageDeleteResponseItem, error) { - return nil, nil -} - -func (d *DryRunClient) NetworkConnect(ctx context.Context, networkName, container string, config *network.EndpointSettings) error { - return nil -} - -func (d *DryRunClient) NetworkCreate(ctx context.Context, name string, options moby.NetworkCreate) (moby.NetworkCreateResponse, error) { - return moby.NetworkCreateResponse{ - ID: name, - Warning: "", - }, nil -} - -func (d *DryRunClient) NetworkDisconnect(ctx context.Context, networkName, container string, force bool) error { - return nil -} - -func (d *DryRunClient) NetworkRemove(ctx context.Context, networkName string) error { - return nil -} - -func (d *DryRunClient) VolumeCreate(ctx context.Context, options volume.CreateOptions) (volume.Volume, error) { - return volume.Volume{ - ClusterVolume: nil, - Driver: options.Driver, - Labels: options.Labels, - Name: options.Name, - Options: options.DriverOpts, - }, nil -} - -func (d *DryRunClient) VolumeRemove(ctx context.Context, volumeID string, force bool) error { - return nil -} - -func (d *DryRunClient) ContainerExecCreate(ctx context.Context, container string, config moby.ExecConfig) (moby.IDResponse, error) { - id := uuid.Generate().String() - d.execs.Store(id, execDetails{ - container: container, - command: config.Cmd, - }) - return moby.IDResponse{ - ID: id, - }, nil -} - -func (d *DryRunClient) ContainerExecStart(ctx context.Context, execID string, config moby.ExecStartCheck) error { - v, ok := d.execs.LoadAndDelete(execID) - if !ok { - return fmt.Errorf("invalid exec ID %q", execID) - } - details := v.(execDetails) - fmt.Printf("%sExecuting command %q in %s (detached mode)\n", DRYRUN_PREFIX, details.command, details.container) - return nil -} - -// Functions delegated to original APIClient (not used by Compose or not modifying the Compose stack - -func (d *DryRunClient) ConfigList(ctx context.Context, options moby.ConfigListOptions) ([]swarm.Config, error) { - return d.apiClient.ConfigList(ctx, options) -} - -func (d *DryRunClient) ConfigCreate(ctx context.Context, config swarm.ConfigSpec) (moby.ConfigCreateResponse, error) { - return d.apiClient.ConfigCreate(ctx, config) -} - -func (d *DryRunClient) ConfigRemove(ctx context.Context, id string) error { - return d.apiClient.ConfigRemove(ctx, id) -} - -func (d *DryRunClient) ConfigInspectWithRaw(ctx context.Context, name string) (swarm.Config, []byte, error) { - return d.apiClient.ConfigInspectWithRaw(ctx, name) -} - -func (d *DryRunClient) ConfigUpdate(ctx context.Context, id string, version swarm.Version, config swarm.ConfigSpec) error { - return d.apiClient.ConfigUpdate(ctx, id, version, config) -} - -func (d *DryRunClient) ContainerCommit(ctx context.Context, container string, options moby.ContainerCommitOptions) (moby.IDResponse, error) { - return d.apiClient.ContainerCommit(ctx, container, options) -} - -func (d *DryRunClient) ContainerDiff(ctx context.Context, container string) ([]containerType.FilesystemChange, error) { - return d.apiClient.ContainerDiff(ctx, container) -} - -func (d *DryRunClient) ContainerExecAttach(ctx context.Context, execID string, config moby.ExecStartCheck) (moby.HijackedResponse, error) { - return moby.HijackedResponse{}, errors.New("interactive exec is not supported in dry-run mode") -} - -func (d *DryRunClient) ContainerExecInspect(ctx context.Context, execID string) (moby.ContainerExecInspect, error) { - return d.apiClient.ContainerExecInspect(ctx, execID) -} - -func (d *DryRunClient) ContainerExecResize(ctx context.Context, execID string, options moby.ResizeOptions) error { - return d.apiClient.ContainerExecResize(ctx, execID, options) -} - -func (d *DryRunClient) ContainerExport(ctx context.Context, container string) (io.ReadCloser, error) { - return d.apiClient.ContainerExport(ctx, container) -} - -func (d *DryRunClient) ContainerInspectWithRaw(ctx context.Context, container string, getSize bool) (moby.ContainerJSON, []byte, error) { - return d.apiClient.ContainerInspectWithRaw(ctx, container, getSize) -} - -func (d *DryRunClient) ContainerLogs(ctx context.Context, container string, options moby.ContainerLogsOptions) (io.ReadCloser, error) { - return d.apiClient.ContainerLogs(ctx, container, options) -} - -func (d *DryRunClient) ContainerResize(ctx context.Context, container string, options moby.ResizeOptions) error { - return d.apiClient.ContainerResize(ctx, container, options) -} - -func (d *DryRunClient) ContainerStatPath(ctx context.Context, container, path string) (moby.ContainerPathStat, error) { - return d.apiClient.ContainerStatPath(ctx, container, path) -} - -func (d *DryRunClient) ContainerStats(ctx context.Context, container string, stream bool) (moby.ContainerStats, error) { - return d.apiClient.ContainerStats(ctx, container, stream) -} - -func (d *DryRunClient) ContainerStatsOneShot(ctx context.Context, container string) (moby.ContainerStats, error) { - return d.apiClient.ContainerStatsOneShot(ctx, container) -} - -func (d *DryRunClient) ContainerTop(ctx context.Context, container string, arguments []string) (containerType.ContainerTopOKBody, error) { - return d.apiClient.ContainerTop(ctx, container, arguments) -} - -func (d *DryRunClient) ContainerUpdate(ctx context.Context, container string, updateConfig containerType.UpdateConfig) (containerType.ContainerUpdateOKBody, error) { - return d.apiClient.ContainerUpdate(ctx, container, updateConfig) -} - -func (d *DryRunClient) ContainerWait(ctx context.Context, container string, condition containerType.WaitCondition) (<-chan containerType.WaitResponse, <-chan error) { - return d.apiClient.ContainerWait(ctx, container, condition) -} - -func (d *DryRunClient) ContainersPrune(ctx context.Context, pruneFilters filters.Args) (moby.ContainersPruneReport, error) { - return d.apiClient.ContainersPrune(ctx, pruneFilters) -} - -func (d *DryRunClient) DistributionInspect(ctx context.Context, imageName, encodedRegistryAuth string) (registry.DistributionInspect, error) { - return d.apiClient.DistributionInspect(ctx, imageName, encodedRegistryAuth) -} - -func (d *DryRunClient) BuildCachePrune(ctx context.Context, opts moby.BuildCachePruneOptions) (*moby.BuildCachePruneReport, error) { - return d.apiClient.BuildCachePrune(ctx, opts) -} - -func (d *DryRunClient) BuildCancel(ctx context.Context, id string) error { - return d.apiClient.BuildCancel(ctx, id) -} - -func (d *DryRunClient) ImageCreate(ctx context.Context, parentReference string, options moby.ImageCreateOptions) (io.ReadCloser, error) { - return d.apiClient.ImageCreate(ctx, parentReference, options) -} - -func (d *DryRunClient) ImageHistory(ctx context.Context, imageName string) ([]image.HistoryResponseItem, error) { - return d.apiClient.ImageHistory(ctx, imageName) -} - -func (d *DryRunClient) ImageImport(ctx context.Context, source moby.ImageImportSource, ref string, options moby.ImageImportOptions) (io.ReadCloser, error) { - return d.apiClient.ImageImport(ctx, source, ref, options) -} - -func (d *DryRunClient) ImageList(ctx context.Context, options moby.ImageListOptions) ([]moby.ImageSummary, error) { - return d.apiClient.ImageList(ctx, options) -} - -func (d *DryRunClient) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (moby.ImageLoadResponse, error) { - return d.apiClient.ImageLoad(ctx, input, quiet) -} - -func (d *DryRunClient) ImageSearch(ctx context.Context, term string, options moby.ImageSearchOptions) ([]registry.SearchResult, error) { - return d.apiClient.ImageSearch(ctx, term, options) -} - -func (d *DryRunClient) ImageSave(ctx context.Context, images []string) (io.ReadCloser, error) { - return d.apiClient.ImageSave(ctx, images) -} - -func (d *DryRunClient) ImageTag(ctx context.Context, imageName, ref string) error { - return d.apiClient.ImageTag(ctx, imageName, ref) -} - -func (d *DryRunClient) ImagesPrune(ctx context.Context, pruneFilter filters.Args) (moby.ImagesPruneReport, error) { - return d.apiClient.ImagesPrune(ctx, pruneFilter) -} - -func (d *DryRunClient) NodeInspectWithRaw(ctx context.Context, nodeID string) (swarm.Node, []byte, error) { - return d.apiClient.NodeInspectWithRaw(ctx, nodeID) -} - -func (d *DryRunClient) NodeList(ctx context.Context, options moby.NodeListOptions) ([]swarm.Node, error) { - return d.apiClient.NodeList(ctx, options) -} - -func (d *DryRunClient) NodeRemove(ctx context.Context, nodeID string, options moby.NodeRemoveOptions) error { - return d.apiClient.NodeRemove(ctx, nodeID, options) -} - -func (d *DryRunClient) NodeUpdate(ctx context.Context, nodeID string, version swarm.Version, node swarm.NodeSpec) error { - return d.apiClient.NodeUpdate(ctx, nodeID, version, node) -} - -func (d *DryRunClient) NetworkInspect(ctx context.Context, networkName string, options moby.NetworkInspectOptions) (moby.NetworkResource, error) { - return d.apiClient.NetworkInspect(ctx, networkName, options) -} - -func (d *DryRunClient) NetworkInspectWithRaw(ctx context.Context, networkName string, options moby.NetworkInspectOptions) (moby.NetworkResource, []byte, error) { - return d.apiClient.NetworkInspectWithRaw(ctx, networkName, options) -} - -func (d *DryRunClient) NetworkList(ctx context.Context, options moby.NetworkListOptions) ([]moby.NetworkResource, error) { - return d.apiClient.NetworkList(ctx, options) -} - -func (d *DryRunClient) NetworksPrune(ctx context.Context, pruneFilter filters.Args) (moby.NetworksPruneReport, error) { - return d.apiClient.NetworksPrune(ctx, pruneFilter) -} - -func (d *DryRunClient) PluginList(ctx context.Context, filter filters.Args) (moby.PluginsListResponse, error) { - return d.apiClient.PluginList(ctx, filter) -} - -func (d *DryRunClient) PluginRemove(ctx context.Context, name string, options moby.PluginRemoveOptions) error { - return d.apiClient.PluginRemove(ctx, name, options) -} - -func (d *DryRunClient) PluginEnable(ctx context.Context, name string, options moby.PluginEnableOptions) error { - return d.apiClient.PluginEnable(ctx, name, options) -} - -func (d *DryRunClient) PluginDisable(ctx context.Context, name string, options moby.PluginDisableOptions) error { - return d.apiClient.PluginDisable(ctx, name, options) -} - -func (d *DryRunClient) PluginInstall(ctx context.Context, name string, options moby.PluginInstallOptions) (io.ReadCloser, error) { - return d.apiClient.PluginInstall(ctx, name, options) -} - -func (d *DryRunClient) PluginUpgrade(ctx context.Context, name string, options moby.PluginInstallOptions) (io.ReadCloser, error) { - return d.apiClient.PluginUpgrade(ctx, name, options) -} - -func (d *DryRunClient) PluginPush(ctx context.Context, name string, registryAuth string) (io.ReadCloser, error) { - return d.apiClient.PluginPush(ctx, name, registryAuth) -} - -func (d *DryRunClient) PluginSet(ctx context.Context, name string, args []string) error { - return d.apiClient.PluginSet(ctx, name, args) -} - -func (d *DryRunClient) PluginInspectWithRaw(ctx context.Context, name string) (*moby.Plugin, []byte, error) { - return d.apiClient.PluginInspectWithRaw(ctx, name) -} - -func (d *DryRunClient) PluginCreate(ctx context.Context, createContext io.Reader, options moby.PluginCreateOptions) error { - return d.apiClient.PluginCreate(ctx, createContext, options) -} - -func (d *DryRunClient) ServiceCreate(ctx context.Context, service swarm.ServiceSpec, options moby.ServiceCreateOptions) (moby.ServiceCreateResponse, error) { - return d.apiClient.ServiceCreate(ctx, service, options) -} - -func (d *DryRunClient) ServiceInspectWithRaw(ctx context.Context, serviceID string, options moby.ServiceInspectOptions) (swarm.Service, []byte, error) { - return d.apiClient.ServiceInspectWithRaw(ctx, serviceID, options) -} - -func (d *DryRunClient) ServiceList(ctx context.Context, options moby.ServiceListOptions) ([]swarm.Service, error) { - return d.apiClient.ServiceList(ctx, options) -} - -func (d *DryRunClient) ServiceRemove(ctx context.Context, serviceID string) error { - return d.apiClient.ServiceRemove(ctx, serviceID) -} - -func (d *DryRunClient) ServiceUpdate(ctx context.Context, serviceID string, version swarm.Version, service swarm.ServiceSpec, options moby.ServiceUpdateOptions) (moby.ServiceUpdateResponse, error) { - return d.apiClient.ServiceUpdate(ctx, serviceID, version, service, options) -} - -func (d *DryRunClient) ServiceLogs(ctx context.Context, serviceID string, options moby.ContainerLogsOptions) (io.ReadCloser, error) { - return d.apiClient.ServiceLogs(ctx, serviceID, options) -} - -func (d *DryRunClient) TaskLogs(ctx context.Context, taskID string, options moby.ContainerLogsOptions) (io.ReadCloser, error) { - return d.apiClient.TaskLogs(ctx, taskID, options) -} - -func (d *DryRunClient) TaskInspectWithRaw(ctx context.Context, taskID string) (swarm.Task, []byte, error) { - return d.apiClient.TaskInspectWithRaw(ctx, taskID) -} - -func (d *DryRunClient) TaskList(ctx context.Context, options moby.TaskListOptions) ([]swarm.Task, error) { - return d.apiClient.TaskList(ctx, options) -} - -func (d *DryRunClient) SwarmInit(ctx context.Context, req swarm.InitRequest) (string, error) { - return d.apiClient.SwarmInit(ctx, req) -} - -func (d *DryRunClient) SwarmJoin(ctx context.Context, req swarm.JoinRequest) error { - return d.apiClient.SwarmJoin(ctx, req) -} - -func (d *DryRunClient) SwarmGetUnlockKey(ctx context.Context) (moby.SwarmUnlockKeyResponse, error) { - return d.apiClient.SwarmGetUnlockKey(ctx) -} - -func (d *DryRunClient) SwarmUnlock(ctx context.Context, req swarm.UnlockRequest) error { - return d.apiClient.SwarmUnlock(ctx, req) -} - -func (d *DryRunClient) SwarmLeave(ctx context.Context, force bool) error { - return d.apiClient.SwarmLeave(ctx, force) -} - -func (d *DryRunClient) SwarmInspect(ctx context.Context) (swarm.Swarm, error) { - return d.apiClient.SwarmInspect(ctx) -} - -func (d *DryRunClient) SwarmUpdate(ctx context.Context, version swarm.Version, swarmSpec swarm.Spec, flags swarm.UpdateFlags) error { - return d.apiClient.SwarmUpdate(ctx, version, swarmSpec, flags) -} - -func (d *DryRunClient) SecretList(ctx context.Context, options moby.SecretListOptions) ([]swarm.Secret, error) { - return d.apiClient.SecretList(ctx, options) -} - -func (d *DryRunClient) SecretCreate(ctx context.Context, secret swarm.SecretSpec) (moby.SecretCreateResponse, error) { - return d.apiClient.SecretCreate(ctx, secret) -} - -func (d *DryRunClient) SecretRemove(ctx context.Context, id string) error { - return d.apiClient.SecretRemove(ctx, id) -} - -func (d *DryRunClient) SecretInspectWithRaw(ctx context.Context, name string) (swarm.Secret, []byte, error) { - return d.apiClient.SecretInspectWithRaw(ctx, name) -} - -func (d *DryRunClient) SecretUpdate(ctx context.Context, id string, version swarm.Version, secret swarm.SecretSpec) error { - return d.apiClient.SecretUpdate(ctx, id, version, secret) -} - -func (d *DryRunClient) Events(ctx context.Context, options moby.EventsOptions) (<-chan events.Message, <-chan error) { - return d.apiClient.Events(ctx, options) -} - -func (d *DryRunClient) Info(ctx context.Context) (moby.Info, error) { - return d.apiClient.Info(ctx) -} - -func (d *DryRunClient) RegistryLogin(ctx context.Context, auth registry.AuthConfig) (registry.AuthenticateOKBody, error) { - return d.apiClient.RegistryLogin(ctx, auth) -} - -func (d *DryRunClient) DiskUsage(ctx context.Context, options moby.DiskUsageOptions) (moby.DiskUsage, error) { - return d.apiClient.DiskUsage(ctx, options) -} - -func (d *DryRunClient) Ping(ctx context.Context) (moby.Ping, error) { - return d.apiClient.Ping(ctx) -} - -func (d *DryRunClient) VolumeInspect(ctx context.Context, volumeID string) (volume.Volume, error) { - return d.apiClient.VolumeInspect(ctx, volumeID) -} - -func (d *DryRunClient) VolumeInspectWithRaw(ctx context.Context, volumeID string) (volume.Volume, []byte, error) { - return d.apiClient.VolumeInspectWithRaw(ctx, volumeID) -} - -func (d *DryRunClient) VolumeList(ctx context.Context, opts volume.ListOptions) (volume.ListResponse, error) { - return d.apiClient.VolumeList(ctx, opts) -} - -func (d *DryRunClient) VolumesPrune(ctx context.Context, pruneFilter filters.Args) (moby.VolumesPruneReport, error) { - return d.apiClient.VolumesPrune(ctx, pruneFilter) -} - -func (d *DryRunClient) VolumeUpdate(ctx context.Context, volumeID string, version swarm.Version, options volume.UpdateOptions) error { - return d.apiClient.VolumeUpdate(ctx, volumeID, version, options) -} - -func (d *DryRunClient) ClientVersion() string { - return d.apiClient.ClientVersion() -} - -func (d *DryRunClient) DaemonHost() string { - return d.apiClient.DaemonHost() -} - -func (d *DryRunClient) HTTPClient() *http.Client { - return d.apiClient.HTTPClient() -} - -func (d *DryRunClient) ServerVersion(ctx context.Context) (moby.Version, error) { - return d.apiClient.ServerVersion(ctx) -} - -func (d *DryRunClient) NegotiateAPIVersion(ctx context.Context) { - d.apiClient.NegotiateAPIVersion(ctx) -} - -func (d *DryRunClient) NegotiateAPIVersionPing(ping moby.Ping) { - d.apiClient.NegotiateAPIVersionPing(ping) -} - -func (d *DryRunClient) DialHijack(ctx context.Context, url, proto string, meta map[string][]string) (net.Conn, error) { - return d.apiClient.DialHijack(ctx, url, proto, meta) -} - -func (d *DryRunClient) Dialer() func(context.Context) (net.Conn, error) { - return d.apiClient.Dialer() -} - -func (d *DryRunClient) Close() error { - return d.apiClient.Close() -} - -func (d *DryRunClient) CheckpointCreate(ctx context.Context, container string, options moby.CheckpointCreateOptions) error { - return d.apiClient.CheckpointCreate(ctx, container, options) -} - -func (d *DryRunClient) CheckpointDelete(ctx context.Context, container string, options moby.CheckpointDeleteOptions) error { - return d.apiClient.CheckpointDelete(ctx, container, options) -} - -func (d *DryRunClient) CheckpointList(ctx context.Context, container string, options moby.CheckpointListOptions) ([]moby.Checkpoint, error) { - return d.apiClient.CheckpointList(ctx, container, options) -} diff --git a/vendor/github.com/docker/compose/v2/pkg/api/errors.go b/vendor/github.com/docker/compose/v2/pkg/api/errors.go deleted file mode 100644 index e7820168e..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/api/errors.go +++ /dev/null @@ -1,94 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 api - -import ( - "github.com/pkg/errors" -) - -const ( - // ExitCodeLoginRequired exit code when command cannot execute because it requires cloud login - // This will be used by VSCode to detect when creating context if the user needs to login first - ExitCodeLoginRequired = 5 -) - -var ( - // ErrNotFound is returned when an object is not found - ErrNotFound = errors.New("not found") - // ErrAlreadyExists is returned when an object already exists - ErrAlreadyExists = errors.New("already exists") - // ErrForbidden is returned when an operation is not permitted - ErrForbidden = errors.New("forbidden") - // ErrUnknown is returned when the error type is unmapped - ErrUnknown = errors.New("unknown") - // ErrLoginFailed is returned when login failed - ErrLoginFailed = errors.New("login failed") - // ErrLoginRequired is returned when login is required for a specific action - ErrLoginRequired = errors.New("login required") - // ErrNotImplemented is returned when a backend doesn't implement - // an action - ErrNotImplemented = errors.New("not implemented") - // ErrUnsupportedFlag is returned when a backend doesn't support a flag - ErrUnsupportedFlag = errors.New("unsupported flag") - // ErrCanceled is returned when the command was canceled by user - ErrCanceled = errors.New("canceled") - // ErrParsingFailed is returned when a string cannot be parsed - ErrParsingFailed = errors.New("parsing failed") - // ErrWrongContextType is returned when the caller tries to get a context - // with the wrong type - ErrWrongContextType = errors.New("wrong context type") -) - -// IsNotFoundError returns true if the unwrapped error is ErrNotFound -func IsNotFoundError(err error) bool { - return errors.Is(err, ErrNotFound) -} - -// IsAlreadyExistsError returns true if the unwrapped error is ErrAlreadyExists -func IsAlreadyExistsError(err error) bool { - return errors.Is(err, ErrAlreadyExists) -} - -// IsForbiddenError returns true if the unwrapped error is ErrForbidden -func IsForbiddenError(err error) bool { - return errors.Is(err, ErrForbidden) -} - -// IsUnknownError returns true if the unwrapped error is ErrUnknown -func IsUnknownError(err error) bool { - return errors.Is(err, ErrUnknown) -} - -// IsErrUnsupportedFlag returns true if the unwrapped error is ErrUnsupportedFlag -func IsErrUnsupportedFlag(err error) bool { - return errors.Is(err, ErrUnsupportedFlag) -} - -// IsErrNotImplemented returns true if the unwrapped error is ErrNotImplemented -func IsErrNotImplemented(err error) bool { - return errors.Is(err, ErrNotImplemented) -} - -// IsErrParsingFailed returns true if the unwrapped error is ErrParsingFailed -func IsErrParsingFailed(err error) bool { - return errors.Is(err, ErrParsingFailed) -} - -// IsErrCanceled returns true if the unwrapped error is ErrCanceled -func IsErrCanceled(err error) bool { - return errors.Is(err, ErrCanceled) -} diff --git a/vendor/github.com/docker/compose/v2/pkg/api/io.go b/vendor/github.com/docker/compose/v2/pkg/api/io.go deleted file mode 100644 index 3bb73e0cc..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/api/io.go +++ /dev/null @@ -1,29 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 api - -import ( - "io" - - "github.com/docker/cli/cli/streams" -) - -type Streams interface { - Out() *streams.Out - Err() io.Writer - In() *streams.In -} diff --git a/vendor/github.com/docker/compose/v2/pkg/api/labels.go b/vendor/github.com/docker/compose/v2/pkg/api/labels.go deleted file mode 100644 index ba110c831..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/api/labels.go +++ /dev/null @@ -1,73 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 api - -import ( - "fmt" - - "github.com/hashicorp/go-version" - - "github.com/docker/compose/v2/internal" -) - -const ( - // ProjectLabel allow to track resource related to a compose project - ProjectLabel = "com.docker.compose.project" - // ServiceLabel allow to track resource related to a compose service - ServiceLabel = "com.docker.compose.service" - // ConfigHashLabel stores configuration hash for a compose service - ConfigHashLabel = "com.docker.compose.config-hash" - // ContainerNumberLabel stores the container index of a replicated service - ContainerNumberLabel = "com.docker.compose.container-number" - // VolumeLabel allow to track resource related to a compose volume - VolumeLabel = "com.docker.compose.volume" - // NetworkLabel allow to track resource related to a compose network - NetworkLabel = "com.docker.compose.network" - // WorkingDirLabel stores absolute path to compose project working directory - WorkingDirLabel = "com.docker.compose.project.working_dir" - // ConfigFilesLabel stores absolute path to compose project configuration files - ConfigFilesLabel = "com.docker.compose.project.config_files" - // EnvironmentFileLabel stores absolute path to compose project env file set by `--env-file` - EnvironmentFileLabel = "com.docker.compose.project.environment_file" - // OneoffLabel stores value 'True' for one-off containers created by `compose run` - OneoffLabel = "com.docker.compose.oneoff" - // SlugLabel stores unique slug used for one-off container identity - SlugLabel = "com.docker.compose.slug" - // ImageDigestLabel stores digest of the container image used to run service - ImageDigestLabel = "com.docker.compose.image" - // DependenciesLabel stores service dependencies - DependenciesLabel = "com.docker.compose.depends_on" - // VersionLabel stores the compose tool version used to build/run application - VersionLabel = "com.docker.compose.version" - // ImageBuilderLabel stores the builder (classic or BuildKit) used to produce the image. - ImageBuilderLabel = "com.docker.compose.image.builder" - // ContainerReplaceLabel is set when container is created to replace another container (recreated) - ContainerReplaceLabel = "com.docker.compose.replace" -) - -// ComposeVersion is the compose tool version as declared by label VersionLabel -var ComposeVersion string - -func init() { - v, err := version.NewVersion(internal.Version) - if err == nil { - segments := v.Segments() - if len(segments) > 2 { - ComposeVersion = fmt.Sprintf("%d.%d.%d", segments[0], segments[1], segments[2]) - } - } -} diff --git a/vendor/github.com/docker/compose/v2/pkg/api/proxy.go b/vendor/github.com/docker/compose/v2/pkg/api/proxy.go deleted file mode 100644 index 4547cb266..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/api/proxy.go +++ /dev/null @@ -1,352 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 api - -import ( - "context" - - "github.com/compose-spec/compose-go/types" -) - -var _ Service = &ServiceProxy{} - -// ServiceProxy implements Service by delegating to implementation functions. This allows lazy init and per-method overrides -type ServiceProxy struct { - BuildFn func(ctx context.Context, project *types.Project, options BuildOptions) error - PushFn func(ctx context.Context, project *types.Project, options PushOptions) error - PullFn func(ctx context.Context, project *types.Project, opts PullOptions) error - CreateFn func(ctx context.Context, project *types.Project, opts CreateOptions) error - StartFn func(ctx context.Context, projectName string, options StartOptions) error - RestartFn func(ctx context.Context, projectName string, options RestartOptions) error - StopFn func(ctx context.Context, projectName string, options StopOptions) error - UpFn func(ctx context.Context, project *types.Project, options UpOptions) error - DownFn func(ctx context.Context, projectName string, options DownOptions) error - LogsFn func(ctx context.Context, projectName string, consumer LogConsumer, options LogOptions) error - PsFn func(ctx context.Context, projectName string, options PsOptions) ([]ContainerSummary, error) - ListFn func(ctx context.Context, options ListOptions) ([]Stack, error) - ConfigFn func(ctx context.Context, project *types.Project, options ConfigOptions) ([]byte, error) - KillFn func(ctx context.Context, project string, options KillOptions) error - RunOneOffContainerFn func(ctx context.Context, project *types.Project, opts RunOptions) (int, error) - RemoveFn func(ctx context.Context, project string, options RemoveOptions) error - ExecFn func(ctx context.Context, project string, opts RunOptions) (int, error) - CopyFn func(ctx context.Context, project string, options CopyOptions) error - PauseFn func(ctx context.Context, project string, options PauseOptions) error - UnPauseFn func(ctx context.Context, project string, options PauseOptions) error - TopFn func(ctx context.Context, projectName string, services []string) ([]ContainerProcSummary, error) - EventsFn func(ctx context.Context, project string, options EventsOptions) error - PortFn func(ctx context.Context, project string, service string, port uint16, options PortOptions) (string, int, error) - ImagesFn func(ctx context.Context, projectName string, options ImagesOptions) ([]ImageSummary, error) - WatchFn func(ctx context.Context, project *types.Project, services []string, options WatchOptions) error - MaxConcurrencyFn func(parallel int) - DryRunModeFn func(ctx context.Context, dryRun bool) (context.Context, error) - VizFn func(ctx context.Context, project *types.Project, options VizOptions) (string, error) - WaitFn func(ctx context.Context, projectName string, options WaitOptions) (int64, error) - interceptors []Interceptor -} - -// NewServiceProxy produces a ServiceProxy -func NewServiceProxy() *ServiceProxy { - return &ServiceProxy{} -} - -// Interceptor allow to customize the compose types.Project before the actual Service method is executed -type Interceptor func(ctx context.Context, project *types.Project) - -// WithService configure proxy to use specified Service as delegate -func (s *ServiceProxy) WithService(service Service) *ServiceProxy { - s.BuildFn = service.Build - s.PushFn = service.Push - s.PullFn = service.Pull - s.CreateFn = service.Create - s.StartFn = service.Start - s.RestartFn = service.Restart - s.StopFn = service.Stop - s.UpFn = service.Up - s.DownFn = service.Down - s.LogsFn = service.Logs - s.PsFn = service.Ps - s.ListFn = service.List - s.ConfigFn = service.Config - s.KillFn = service.Kill - s.RunOneOffContainerFn = service.RunOneOffContainer - s.RemoveFn = service.Remove - s.ExecFn = service.Exec - s.CopyFn = service.Copy - s.PauseFn = service.Pause - s.UnPauseFn = service.UnPause - s.TopFn = service.Top - s.EventsFn = service.Events - s.PortFn = service.Port - s.ImagesFn = service.Images - s.WatchFn = service.Watch - s.MaxConcurrencyFn = service.MaxConcurrency - s.DryRunModeFn = service.DryRunMode - s.VizFn = service.Viz - s.WaitFn = service.Wait - return s -} - -// WithInterceptor configures Interceptor to be applied to Service method execution -func (s *ServiceProxy) WithInterceptor(interceptors ...Interceptor) *ServiceProxy { - s.interceptors = append(s.interceptors, interceptors...) - return s -} - -// Build implements Service interface -func (s *ServiceProxy) Build(ctx context.Context, project *types.Project, options BuildOptions) error { - if s.BuildFn == nil { - return ErrNotImplemented - } - for _, i := range s.interceptors { - i(ctx, project) - } - return s.BuildFn(ctx, project, options) -} - -// Push implements Service interface -func (s *ServiceProxy) Push(ctx context.Context, project *types.Project, options PushOptions) error { - if s.PushFn == nil { - return ErrNotImplemented - } - for _, i := range s.interceptors { - i(ctx, project) - } - return s.PushFn(ctx, project, options) -} - -// Pull implements Service interface -func (s *ServiceProxy) Pull(ctx context.Context, project *types.Project, options PullOptions) error { - if s.PullFn == nil { - return ErrNotImplemented - } - for _, i := range s.interceptors { - i(ctx, project) - } - return s.PullFn(ctx, project, options) -} - -// Create implements Service interface -func (s *ServiceProxy) Create(ctx context.Context, project *types.Project, options CreateOptions) error { - if s.CreateFn == nil { - return ErrNotImplemented - } - for _, i := range s.interceptors { - i(ctx, project) - } - return s.CreateFn(ctx, project, options) -} - -// Start implements Service interface -func (s *ServiceProxy) Start(ctx context.Context, projectName string, options StartOptions) error { - if s.StartFn == nil { - return ErrNotImplemented - } - return s.StartFn(ctx, projectName, options) -} - -// Restart implements Service interface -func (s *ServiceProxy) Restart(ctx context.Context, projectName string, options RestartOptions) error { - if s.RestartFn == nil { - return ErrNotImplemented - } - return s.RestartFn(ctx, projectName, options) -} - -// Stop implements Service interface -func (s *ServiceProxy) Stop(ctx context.Context, projectName string, options StopOptions) error { - if s.StopFn == nil { - return ErrNotImplemented - } - return s.StopFn(ctx, projectName, options) -} - -// Up implements Service interface -func (s *ServiceProxy) Up(ctx context.Context, project *types.Project, options UpOptions) error { - if s.UpFn == nil { - return ErrNotImplemented - } - for _, i := range s.interceptors { - i(ctx, project) - } - return s.UpFn(ctx, project, options) -} - -// Down implements Service interface -func (s *ServiceProxy) Down(ctx context.Context, project string, options DownOptions) error { - if s.DownFn == nil { - return ErrNotImplemented - } - return s.DownFn(ctx, project, options) -} - -// Logs implements Service interface -func (s *ServiceProxy) Logs(ctx context.Context, projectName string, consumer LogConsumer, options LogOptions) error { - if s.LogsFn == nil { - return ErrNotImplemented - } - return s.LogsFn(ctx, projectName, consumer, options) -} - -// Ps implements Service interface -func (s *ServiceProxy) Ps(ctx context.Context, project string, options PsOptions) ([]ContainerSummary, error) { - if s.PsFn == nil { - return nil, ErrNotImplemented - } - return s.PsFn(ctx, project, options) -} - -// List implements Service interface -func (s *ServiceProxy) List(ctx context.Context, options ListOptions) ([]Stack, error) { - if s.ListFn == nil { - return nil, ErrNotImplemented - } - return s.ListFn(ctx, options) -} - -// Config implements Service interface -func (s *ServiceProxy) Config(ctx context.Context, project *types.Project, options ConfigOptions) ([]byte, error) { - if s.ConfigFn == nil { - return nil, ErrNotImplemented - } - for _, i := range s.interceptors { - i(ctx, project) - } - return s.ConfigFn(ctx, project, options) -} - -// Kill implements Service interface -func (s *ServiceProxy) Kill(ctx context.Context, projectName string, options KillOptions) error { - if s.KillFn == nil { - return ErrNotImplemented - } - return s.KillFn(ctx, projectName, options) -} - -// RunOneOffContainer implements Service interface -func (s *ServiceProxy) RunOneOffContainer(ctx context.Context, project *types.Project, options RunOptions) (int, error) { - if s.RunOneOffContainerFn == nil { - return 0, ErrNotImplemented - } - for _, i := range s.interceptors { - i(ctx, project) - } - return s.RunOneOffContainerFn(ctx, project, options) -} - -// Remove implements Service interface -func (s *ServiceProxy) Remove(ctx context.Context, projectName string, options RemoveOptions) error { - if s.RemoveFn == nil { - return ErrNotImplemented - } - return s.RemoveFn(ctx, projectName, options) -} - -// Exec implements Service interface -func (s *ServiceProxy) Exec(ctx context.Context, projectName string, options RunOptions) (int, error) { - if s.ExecFn == nil { - return 0, ErrNotImplemented - } - return s.ExecFn(ctx, projectName, options) -} - -// Copy implements Service interface -func (s *ServiceProxy) Copy(ctx context.Context, projectName string, options CopyOptions) error { - if s.CopyFn == nil { - return ErrNotImplemented - } - return s.CopyFn(ctx, projectName, options) -} - -// Pause implements Service interface -func (s *ServiceProxy) Pause(ctx context.Context, projectName string, options PauseOptions) error { - if s.PauseFn == nil { - return ErrNotImplemented - } - return s.PauseFn(ctx, projectName, options) -} - -// UnPause implements Service interface -func (s *ServiceProxy) UnPause(ctx context.Context, projectName string, options PauseOptions) error { - if s.UnPauseFn == nil { - return ErrNotImplemented - } - return s.UnPauseFn(ctx, projectName, options) -} - -// Top implements Service interface -func (s *ServiceProxy) Top(ctx context.Context, project string, services []string) ([]ContainerProcSummary, error) { - if s.TopFn == nil { - return nil, ErrNotImplemented - } - return s.TopFn(ctx, project, services) -} - -// Events implements Service interface -func (s *ServiceProxy) Events(ctx context.Context, projectName string, options EventsOptions) error { - if s.EventsFn == nil { - return ErrNotImplemented - } - return s.EventsFn(ctx, projectName, options) -} - -// Port implements Service interface -func (s *ServiceProxy) Port(ctx context.Context, projectName string, service string, port uint16, options PortOptions) (string, int, error) { - if s.PortFn == nil { - return "", 0, ErrNotImplemented - } - return s.PortFn(ctx, projectName, service, port, options) -} - -// Images implements Service interface -func (s *ServiceProxy) Images(ctx context.Context, project string, options ImagesOptions) ([]ImageSummary, error) { - if s.ImagesFn == nil { - return nil, ErrNotImplemented - } - return s.ImagesFn(ctx, project, options) -} - -// Watch implements Service interface -func (s *ServiceProxy) Watch(ctx context.Context, project *types.Project, services []string, options WatchOptions) error { - if s.WatchFn == nil { - return ErrNotImplemented - } - return s.WatchFn(ctx, project, services, options) -} - -// Viz implements Service interface -func (s *ServiceProxy) Viz(ctx context.Context, project *types.Project, options VizOptions) (string, error) { - if s.VizFn == nil { - return "", ErrNotImplemented - } - return s.VizFn(ctx, project, options) -} - -// Wait implements Service interface -func (s *ServiceProxy) Wait(ctx context.Context, projectName string, options WaitOptions) (int64, error) { - if s.WaitFn == nil { - return 0, ErrNotImplemented - } - return s.WaitFn(ctx, projectName, options) -} - -func (s *ServiceProxy) MaxConcurrency(i int) { - s.MaxConcurrencyFn(i) -} - -func (s *ServiceProxy) DryRunMode(ctx context.Context, dryRun bool) (context.Context, error) { - return s.DryRunModeFn(ctx, dryRun) -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/attach.go b/vendor/github.com/docker/compose/v2/pkg/compose/attach.go deleted file mode 100644 index d019068dc..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/attach.go +++ /dev/null @@ -1,179 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "fmt" - "io" - "strings" - - "github.com/compose-spec/compose-go/types" - "github.com/docker/cli/cli/streams" - moby "github.com/docker/docker/api/types" - "github.com/docker/docker/pkg/stdcopy" - "github.com/moby/term" - - "github.com/docker/compose/v2/pkg/api" - "github.com/docker/compose/v2/pkg/utils" -) - -func (s *composeService) attach(ctx context.Context, project *types.Project, listener api.ContainerEventListener, selectedServices []string) (Containers, error) { - containers, err := s.getContainers(ctx, project.Name, oneOffExclude, true, selectedServices...) - if err != nil { - return nil, err - } - if len(containers) == 0 { - return containers, nil - } - - containers.sorted() // This enforce predictable colors assignment - - var names []string - for _, c := range containers { - names = append(names, getContainerNameWithoutProject(c)) - } - - fmt.Fprintf(s.stdout(), "Attaching to %s\n", strings.Join(names, ", ")) - - for _, container := range containers { - err := s.attachContainer(ctx, container, listener) - if err != nil { - return nil, err - } - } - return containers, err -} - -func (s *composeService) attachContainer(ctx context.Context, container moby.Container, listener api.ContainerEventListener) error { - serviceName := container.Labels[api.ServiceLabel] - containerName := getContainerNameWithoutProject(container) - - listener(api.ContainerEvent{ - Type: api.ContainerEventAttach, - Container: containerName, - ID: container.ID, - Service: serviceName, - }) - - wOut := utils.GetWriter(func(line string) { - listener(api.ContainerEvent{ - Type: api.ContainerEventLog, - Container: containerName, - ID: container.ID, - Service: serviceName, - Line: line, - }) - }) - wErr := utils.GetWriter(func(line string) { - listener(api.ContainerEvent{ - Type: api.ContainerEventErr, - Container: containerName, - ID: container.ID, - Service: serviceName, - Line: line, - }) - }) - - inspect, err := s.apiClient().ContainerInspect(ctx, container.ID) - if err != nil { - return err - } - - _, _, err = s.attachContainerStreams(ctx, container.ID, inspect.Config.Tty, nil, wOut, wErr) - return err -} - -func (s *composeService) attachContainerStreams(ctx context.Context, container string, tty bool, stdin io.ReadCloser, stdout, stderr io.Writer) (func(), chan bool, error) { - detached := make(chan bool) - var ( - restore = func() { /* noop */ } - ) - if stdin != nil { - in := streams.NewIn(stdin) - if in.IsTerminal() { - state, err := term.SetRawTerminal(in.FD()) - if err != nil { - return restore, detached, err - } - restore = func() { - term.RestoreTerminal(in.FD(), state) //nolint:errcheck - } - } - } - - streamIn, streamOut, err := s.getContainerStreams(ctx, container) - if err != nil { - return restore, detached, err - } - - go func() { - <-ctx.Done() - if stdin != nil { - stdin.Close() //nolint:errcheck - } - streamOut.Close() //nolint:errcheck - }() - - if streamIn != nil && stdin != nil { - go func() { - _, err := io.Copy(streamIn, stdin) - if _, ok := err.(term.EscapeError); ok { - close(detached) - } - }() - } - - if stdout != nil { - go func() { - if tty { - io.Copy(stdout, streamOut) //nolint:errcheck - } else { - stdcopy.StdCopy(stdout, stderr, streamOut) //nolint:errcheck - } - }() - } - return restore, detached, nil -} - -func (s *composeService) getContainerStreams(ctx context.Context, container string) (io.WriteCloser, io.ReadCloser, error) { - var stdout io.ReadCloser - var stdin io.WriteCloser - cnx, err := s.apiClient().ContainerAttach(ctx, container, moby.ContainerAttachOptions{ - Stream: true, - Stdin: true, - Stdout: true, - Stderr: true, - Logs: false, - }) - if err == nil { - stdout = ContainerStdout{HijackedResponse: cnx} - stdin = ContainerStdin{HijackedResponse: cnx} - return stdin, stdout, nil - } - - // Fallback to logs API - logs, err := s.apiClient().ContainerLogs(ctx, container, moby.ContainerLogsOptions{ - ShowStdout: true, - ShowStderr: true, - Follow: true, - }) - if err != nil { - return nil, nil, err - } - return stdin, logs, nil -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/build.go b/vendor/github.com/docker/compose/v2/pkg/compose/build.go deleted file mode 100644 index cf2f8a363..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/build.go +++ /dev/null @@ -1,590 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "fmt" - "os" - "path/filepath" - - "github.com/compose-spec/compose-go/types" - "github.com/containerd/containerd/platforms" - "github.com/docker/buildx/build" - "github.com/docker/buildx/builder" - "github.com/docker/buildx/controller/pb" - "github.com/docker/buildx/store/storeutil" - "github.com/docker/buildx/util/buildflags" - xprogress "github.com/docker/buildx/util/progress" - "github.com/docker/cli/cli/command" - "github.com/docker/compose/v2/internal/tracing" - "github.com/docker/compose/v2/pkg/api" - "github.com/docker/compose/v2/pkg/progress" - "github.com/docker/compose/v2/pkg/utils" - "github.com/docker/docker/builder/remotecontext/urlutil" - bclient "github.com/moby/buildkit/client" - "github.com/moby/buildkit/session" - "github.com/moby/buildkit/session/auth/authprovider" - "github.com/moby/buildkit/session/secrets/secretsprovider" - "github.com/moby/buildkit/session/sshforward/sshprovider" - "github.com/moby/buildkit/util/entitlements" - specs "github.com/opencontainers/image-spec/specs-go/v1" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" - - // required to get default driver registered - _ "github.com/docker/buildx/driver/docker" -) - -func (s *composeService) Build(ctx context.Context, project *types.Project, options api.BuildOptions) error { - err := options.Apply(project) - if err != nil { - return err - } - return progress.RunWithTitle(ctx, func(ctx context.Context) error { - _, err := s.build(ctx, project, options) - return err - }, s.stdinfo(), "Building") -} - -//nolint:gocyclo -func (s *composeService) build(ctx context.Context, project *types.Project, options api.BuildOptions) (map[string]string, error) { - buildkitEnabled, err := s.dockerCli.BuildKitEnabled() - if err != nil { - return nil, err - } - - // Initialize buildkit nodes - var ( - b *builder.Builder - nodes []builder.Node - w *xprogress.Printer - ) - if buildkitEnabled { - builderName := options.Builder - if builderName == "" { - builderName = os.Getenv("BUILDX_BUILDER") - } - b, err = builder.New(s.dockerCli, builder.WithName(builderName)) - if err != nil { - return nil, err - } - - nodes, err = b.LoadNodes(ctx, false) - if err != nil { - return nil, err - } - - // Progress needs its own context that lives longer than the - // build one otherwise it won't read all the messages from - // build and will lock - progressCtx, cancel := context.WithCancel(context.Background()) - defer cancel() - - w, err = xprogress.NewPrinter(progressCtx, s.stdout(), os.Stdout, options.Progress, - xprogress.WithDesc( - fmt.Sprintf("building with %q instance using %s driver", b.Name, b.Driver), - fmt.Sprintf("%s:%s", b.Driver, b.Name), - )) - - if err != nil { - return nil, err - } - } - - builtDigests := make([]string, len(project.Services)) - err = InDependencyOrder(ctx, project, func(ctx context.Context, name string) error { - if len(options.Services) > 0 && !utils.Contains(options.Services, name) { - return nil - } - service, idx := getServiceIndex(project, name) - - if service.Build == nil { - return nil - } - - if !buildkitEnabled { - id, err := s.doBuildClassic(ctx, project, service, options) - if err != nil { - return err - } - builtDigests[idx] = id - - if options.Push { - return s.push(ctx, project, api.PushOptions{}) - } - return nil - } - - if options.Memory != 0 { - fmt.Fprintln(s.stderr(), "WARNING: --memory is not supported by BuildKit and will be ignored.") - } - - buildOptions, err := s.toBuildOptions(project, service, options) - if err != nil { - return err - } - - digest, err := s.doBuildBuildkit(ctx, service.Name, buildOptions, w, nodes) - if err != nil { - return err - } - builtDigests[idx] = digest - - return nil - }, func(traversal *graphTraversal) { - traversal.maxConcurrency = s.maxConcurrency - }) - - // enforce all build event get consumed - if buildkitEnabled { - if errw := w.Wait(); errw != nil { - return nil, errw - } - } - - if err != nil { - return nil, err - } - - imageIDs := map[string]string{} - for i, imageDigest := range builtDigests { - if imageDigest != "" { - imageRef := api.GetImageNameOrDefault(project.Services[i], project.Name) - imageIDs[imageRef] = imageDigest - } - } - return imageIDs, err -} - -func getServiceIndex(project *types.Project, name string) (types.ServiceConfig, int) { - var service types.ServiceConfig - var idx int - for i, s := range project.Services { - if s.Name == name { - idx, service = i, s - break - } - } - return service, idx -} - -func (s *composeService) ensureImagesExists(ctx context.Context, project *types.Project, quietPull bool) error { - for _, service := range project.Services { - if service.Image == "" && service.Build == nil { - return fmt.Errorf("invalid service %q. Must specify either image or build", service.Name) - } - } - - images, err := s.getLocalImagesDigests(ctx, project) - if err != nil { - return err - } - - err = tracing.SpanWrapFunc("project/pull", tracing.ProjectOptions(project), - func(ctx context.Context) error { - return s.pullRequiredImages(ctx, project, images, quietPull) - }, - )(ctx) - if err != nil { - return err - } - - mode := xprogress.PrinterModeAuto - if quietPull { - mode = xprogress.PrinterModeQuiet - } - - buildRequired, err := s.prepareProjectForBuild(project, images) - if err != nil { - return err - } - - if buildRequired { - err = tracing.SpanWrapFunc("project/build", tracing.ProjectOptions(project), - func(ctx context.Context) error { - builtImages, err := s.build(ctx, project, api.BuildOptions{ - Progress: mode, - }) - if err != nil { - return err - } - - for name, digest := range builtImages { - images[name] = digest - } - return nil - }, - )(ctx) - if err != nil { - return err - } - } - - // set digest as com.docker.compose.image label so we can detect outdated containers - for i, service := range project.Services { - image := api.GetImageNameOrDefault(service, project.Name) - digest, ok := images[image] - if ok { - if project.Services[i].Labels == nil { - project.Services[i].Labels = types.Labels{} - } - project.Services[i].CustomLabels.Add(api.ImageDigestLabel, digest) - } - } - return nil -} - -func (s *composeService) prepareProjectForBuild(project *types.Project, images map[string]string) (bool, error) { - buildRequired := false - err := api.BuildOptions{}.Apply(project) - if err != nil { - return false, err - } - for i, service := range project.Services { - if service.Build == nil { - continue - } - - image := api.GetImageNameOrDefault(service, project.Name) - _, localImagePresent := images[image] - if localImagePresent && service.PullPolicy != types.PullPolicyBuild { - service.Build = nil - project.Services[i] = service - continue - } - - if service.Platform == "" { - // let builder to build for default platform - service.Build.Platforms = nil - } else { - service.Build.Platforms = []string{service.Platform} - } - project.Services[i] = service - buildRequired = true - } - return buildRequired, nil -} - -func (s *composeService) getLocalImagesDigests(ctx context.Context, project *types.Project) (map[string]string, error) { - var imageNames []string - for _, s := range project.Services { - imgName := api.GetImageNameOrDefault(s, project.Name) - if !utils.StringContains(imageNames, imgName) { - imageNames = append(imageNames, imgName) - } - } - imgs, err := s.getImages(ctx, imageNames) - if err != nil { - return nil, err - } - images := map[string]string{} - for name, info := range imgs { - images[name] = info.ID - } - - for i, service := range project.Services { - imgName := api.GetImageNameOrDefault(service, project.Name) - digest, ok := images[imgName] - if !ok { - continue - } - if service.Platform != "" { - platform, err := platforms.Parse(service.Platform) - if err != nil { - return nil, err - } - inspect, _, err := s.apiClient().ImageInspectWithRaw(ctx, digest) - if err != nil { - return nil, err - } - actual := specs.Platform{ - Architecture: inspect.Architecture, - OS: inspect.Os, - Variant: inspect.Variant, - } - if !platforms.NewMatcher(platform).Match(actual) { - return nil, errors.Errorf("image with reference %s was found but does not match the specified platform: wanted %s, actual: %s", - imgName, platforms.Format(platform), platforms.Format(actual)) - } - } - - project.Services[i].CustomLabels.Add(api.ImageDigestLabel, digest) - - } - - return images, nil -} - -// resolveAndMergeBuildArgs returns the final set of build arguments to use for the service image build. -// -// First, args directly defined via `build.args` in YAML are considered. -// Then, any explicitly passed args in opts (e.g. via `--build-arg` on the CLI) are merged, overwriting any -// keys that already exist. -// Next, any keys without a value are resolved using the project environment. -// -// Finally, standard proxy variables based on the Docker client configuration are added, but will not overwrite -// any values if already present. -func resolveAndMergeBuildArgs( - dockerCli command.Cli, - project *types.Project, - service types.ServiceConfig, - opts api.BuildOptions, -) types.MappingWithEquals { - result := make(types.MappingWithEquals). - OverrideBy(service.Build.Args). - OverrideBy(opts.Args). - Resolve(envResolver(project.Environment)) - - // proxy arguments do NOT override and should NOT have env resolution applied, - // so they're handled last - for k, v := range storeutil.GetProxyConfig(dockerCli) { - if _, ok := result[k]; !ok { - result[k] = &v - } - } - return result -} - -func (s *composeService) toBuildOptions(project *types.Project, service types.ServiceConfig, options api.BuildOptions) (build.Options, error) { - plats, err := addPlatforms(project, service) - if err != nil { - return build.Options{}, err - } - - cacheFrom, err := buildflags.ParseCacheEntry(service.Build.CacheFrom) - if err != nil { - return build.Options{}, err - } - cacheTo, err := buildflags.ParseCacheEntry(service.Build.CacheTo) - if err != nil { - return build.Options{}, err - } - - sessionConfig := []session.Attachable{ - authprovider.NewDockerAuthProvider(s.configFile()), - } - if len(options.SSHs) > 0 || len(service.Build.SSH) > 0 { - sshAgentProvider, err := sshAgentProvider(append(service.Build.SSH, options.SSHs...)) - if err != nil { - return build.Options{}, err - } - sessionConfig = append(sessionConfig, sshAgentProvider) - } - - if len(service.Build.Secrets) > 0 { - secretsProvider, err := addSecretsConfig(project, service) - if err != nil { - return build.Options{}, err - } - sessionConfig = append(sessionConfig, secretsProvider) - } - - tags := []string{api.GetImageNameOrDefault(service, project.Name)} - if len(service.Build.Tags) > 0 { - tags = append(tags, service.Build.Tags...) - } - var allow []entitlements.Entitlement - if service.Build.Privileged { - allow = append(allow, entitlements.EntitlementSecurityInsecure) - } - - imageLabels := getImageBuildLabels(project, service) - - push := options.Push && service.Image != "" - exports := []bclient.ExportEntry{{ - Type: "docker", - Attrs: map[string]string{ - "load": "true", - "push": fmt.Sprint(push), - }, - }} - if len(service.Build.Platforms) > 1 { - exports = []bclient.ExportEntry{{ - Type: "image", - Attrs: map[string]string{ - "push": fmt.Sprint(push), - }, - }} - } - - return build.Options{ - Inputs: build.Inputs{ - ContextPath: service.Build.Context, - DockerfileInline: service.Build.DockerfileInline, - DockerfilePath: dockerFilePath(service.Build.Context, service.Build.Dockerfile), - NamedContexts: toBuildContexts(service.Build.AdditionalContexts), - }, - CacheFrom: pb.CreateCaches(cacheFrom), - CacheTo: pb.CreateCaches(cacheTo), - NoCache: service.Build.NoCache, - Pull: service.Build.Pull, - BuildArgs: flatten(resolveAndMergeBuildArgs(s.dockerCli, project, service, options)), - Tags: tags, - Target: service.Build.Target, - Exports: exports, - Platforms: plats, - Labels: imageLabels, - NetworkMode: service.Build.Network, - ExtraHosts: service.Build.ExtraHosts.AsList(), - Session: sessionConfig, - Allow: allow, - }, nil -} - -func flatten(in types.MappingWithEquals) types.Mapping { - out := types.Mapping{} - if len(in) == 0 { - return out - } - for k, v := range in { - if v == nil { - continue - } - out[k] = *v - } - return out -} - -func dockerFilePath(ctxName string, dockerfile string) string { - if dockerfile == "" { - return "" - } - if urlutil.IsGitURL(ctxName) || filepath.IsAbs(dockerfile) { - return dockerfile - } - return filepath.Join(ctxName, dockerfile) -} - -func sshAgentProvider(sshKeys types.SSHConfig) (session.Attachable, error) { - sshConfig := make([]sshprovider.AgentConfig, 0, len(sshKeys)) - for _, sshKey := range sshKeys { - sshConfig = append(sshConfig, sshprovider.AgentConfig{ - ID: sshKey.ID, - Paths: []string{sshKey.Path}, - }) - } - return sshprovider.NewSSHAgentProvider(sshConfig) -} - -func addSecretsConfig(project *types.Project, service types.ServiceConfig) (session.Attachable, error) { - var sources []secretsprovider.Source - for _, secret := range service.Build.Secrets { - config := project.Secrets[secret.Source] - id := secret.Source - if secret.Target != "" { - id = secret.Target - } - switch { - case config.File != "": - sources = append(sources, secretsprovider.Source{ - ID: id, - FilePath: config.File, - }) - case config.Environment != "": - sources = append(sources, secretsprovider.Source{ - ID: id, - Env: config.Environment, - }) - default: - return nil, fmt.Errorf("build.secrets only supports environment or file-based secrets: %q", secret.Source) - } - if secret.UID != "" || secret.GID != "" || secret.Mode != nil { - logrus.Warn("secrets `uid`, `gid` and `mode` are not supported by BuildKit, they will be ignored") - } - } - store, err := secretsprovider.NewStore(sources) - if err != nil { - return nil, err - } - return secretsprovider.NewSecretProvider(store), nil -} - -func addPlatforms(project *types.Project, service types.ServiceConfig) ([]specs.Platform, error) { - plats, err := useDockerDefaultOrServicePlatform(project, service, false) - if err != nil { - return nil, err - } - - for _, buildPlatform := range service.Build.Platforms { - p, err := platforms.Parse(buildPlatform) - if err != nil { - return nil, err - } - if !utils.Contains(plats, p) { - plats = append(plats, p) - } - } - return plats, nil -} - -func getImageBuildLabels(project *types.Project, service types.ServiceConfig) types.Labels { - ret := make(types.Labels) - if service.Build != nil { - for k, v := range service.Build.Labels { - ret.Add(k, v) - } - } - - ret.Add(api.VersionLabel, api.ComposeVersion) - ret.Add(api.ProjectLabel, project.Name) - ret.Add(api.ServiceLabel, service.Name) - return ret -} - -func toBuildContexts(additionalContexts types.Mapping) map[string]build.NamedContext { - namedContexts := map[string]build.NamedContext{} - for name, context := range additionalContexts { - namedContexts[name] = build.NamedContext{Path: context} - } - return namedContexts -} - -func useDockerDefaultPlatform(project *types.Project, platformList types.StringList) ([]specs.Platform, error) { - var plats []specs.Platform - if platform, ok := project.Environment["DOCKER_DEFAULT_PLATFORM"]; ok { - if len(platformList) > 0 && !utils.StringContains(platformList, platform) { - return nil, fmt.Errorf("the DOCKER_DEFAULT_PLATFORM %q value should be part of the service.build.platforms: %q", platform, platformList) - } - p, err := platforms.Parse(platform) - if err != nil { - return nil, err - } - plats = append(plats, p) - } - return plats, nil -} - -func useDockerDefaultOrServicePlatform(project *types.Project, service types.ServiceConfig, useOnePlatform bool) ([]specs.Platform, error) { - plats, err := useDockerDefaultPlatform(project, service.Build.Platforms) - if (len(plats) > 0 && useOnePlatform) || err != nil { - return plats, err - } - - if service.Platform != "" { - if len(service.Build.Platforms) > 0 && !utils.StringContains(service.Build.Platforms, service.Platform) { - return nil, fmt.Errorf("service.platform %q should be part of the service.build.platforms: %q", service.Platform, service.Build.Platforms) - } - // User defined a service platform and no build platforms, so we should keep the one define on the service level - p, err := platforms.Parse(service.Platform) - if !utils.Contains(plats, p) { - plats = append(plats, p) - } - return plats, err - } - return plats, nil -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/build_buildkit.go b/vendor/github.com/docker/compose/v2/pkg/compose/build_buildkit.go deleted file mode 100644 index b530d463c..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/build_buildkit.go +++ /dev/null @@ -1,92 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "crypto/sha1" - "fmt" - - "github.com/docker/buildx/build" - "github.com/docker/buildx/builder" - _ "github.com/docker/buildx/driver/docker" //nolint:blank-imports - _ "github.com/docker/buildx/driver/docker-container" //nolint:blank-imports - _ "github.com/docker/buildx/driver/kubernetes" //nolint:blank-imports - _ "github.com/docker/buildx/driver/remote" //nolint:blank-imports - "github.com/docker/buildx/util/confutil" - "github.com/docker/buildx/util/dockerutil" - buildx "github.com/docker/buildx/util/progress" - "github.com/docker/compose/v2/pkg/progress" - "github.com/moby/buildkit/client" -) - -func (s *composeService) doBuildBuildkit(ctx context.Context, service string, opts build.Options, p *buildx.Printer, nodes []builder.Node) (string, error) { - var ( - response map[string]*client.SolveResponse - err error - ) - if s.dryRun { - response = s.dryRunBuildResponse(ctx, service, opts) - } else { - response, err = build.Build(ctx, nodes, - map[string]build.Options{service: opts}, - dockerutil.NewClient(s.dockerCli), - confutil.ConfigDir(s.dockerCli), - buildx.WithPrefix(p, service, true)) - if err != nil { - return "", WrapCategorisedComposeError(err, BuildFailure) - } - } - - for _, img := range response { - if img == nil || len(img.ExporterResponse) == 0 { - continue - } - digest, ok := img.ExporterResponse["containerimage.digest"] - if !ok { - continue - } - return digest, nil - } - - return "", fmt.Errorf("buildkit response is missing expected result for %s", service) -} - -func (s composeService) dryRunBuildResponse(ctx context.Context, name string, options build.Options) map[string]*client.SolveResponse { - w := progress.ContextWriter(ctx) - buildResponse := map[string]*client.SolveResponse{} - dryRunUUID := fmt.Sprintf("dryRun-%x", sha1.Sum([]byte(name))) - w.Event(progress.Event{ - ID: " ", - Status: progress.Done, - Text: fmt.Sprintf("build service %s", name), - }) - w.Event(progress.Event{ - ID: "==>", - Status: progress.Done, - Text: fmt.Sprintf("==> writing image %s", dryRunUUID), - }) - w.Event(progress.Event{ - ID: "==> ==>", - Status: progress.Done, - Text: fmt.Sprintf(`naming to %s`, options.Tags[0]), - }) - buildResponse[name] = &client.SolveResponse{ExporterResponse: map[string]string{ - "containerimage.digest": dryRunUUID, - }} - return buildResponse -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/build_classic.go b/vendor/github.com/docker/compose/v2/pkg/compose/build_classic.go deleted file mode 100644 index 243ffb17e..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/build_classic.go +++ /dev/null @@ -1,235 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "encoding/json" - "fmt" - "io" - "os" - "path/filepath" - "runtime" - "strings" - - "github.com/docker/cli/cli/command" - - "github.com/docker/docker/api/types/registry" - - "github.com/compose-spec/compose-go/types" - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command/image/build" - dockertypes "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/builder/remotecontext/urlutil" - "github.com/docker/docker/pkg/archive" - "github.com/docker/docker/pkg/idtools" - "github.com/docker/docker/pkg/jsonmessage" - "github.com/docker/docker/pkg/progress" - "github.com/docker/docker/pkg/streamformatter" - "github.com/pkg/errors" - - "github.com/docker/compose/v2/pkg/api" -) - -//nolint:gocyclo -func (s *composeService) doBuildClassic(ctx context.Context, project *types.Project, service types.ServiceConfig, options api.BuildOptions) (string, error) { - var ( - buildCtx io.ReadCloser - dockerfileCtx io.ReadCloser - contextDir string - tempDir string - relDockerfile string - - err error - ) - - dockerfileName := dockerFilePath(service.Build.Context, service.Build.Dockerfile) - specifiedContext := service.Build.Context - progBuff := s.stdout() - buildBuff := s.stdout() - - if len(service.Build.Platforms) > 1 { - return "", errors.Errorf("the classic builder doesn't support multi-arch build, set DOCKER_BUILDKIT=1 to use BuildKit") - } - if service.Build.Privileged { - return "", errors.Errorf("the classic builder doesn't support privileged mode, set DOCKER_BUILDKIT=1 to use BuildKit") - } - if len(service.Build.AdditionalContexts) > 0 { - return "", errors.Errorf("the classic builder doesn't support additional contexts, set DOCKER_BUILDKIT=1 to use BuildKit") - } - if len(service.Build.SSH) > 0 { - return "", errors.Errorf("the classic builder doesn't support SSH keys, set DOCKER_BUILDKIT=1 to use BuildKit") - } - if len(service.Build.Secrets) > 0 { - return "", errors.Errorf("the classic builder doesn't support secrets, set DOCKER_BUILDKIT=1 to use BuildKit") - } - - if service.Build.Labels == nil { - service.Build.Labels = make(map[string]string) - } - service.Build.Labels[api.ImageBuilderLabel] = "classic" - - switch { - case isLocalDir(specifiedContext): - contextDir, relDockerfile, err = build.GetContextFromLocalDir(specifiedContext, dockerfileName) - if err == nil && strings.HasPrefix(relDockerfile, ".."+string(filepath.Separator)) { - // Dockerfile is outside of build-context; read the Dockerfile and pass it as dockerfileCtx - dockerfileCtx, err = os.Open(dockerfileName) - if err != nil { - return "", errors.Errorf("unable to open Dockerfile: %v", err) - } - defer dockerfileCtx.Close() //nolint:errcheck - } - case urlutil.IsGitURL(specifiedContext): - tempDir, relDockerfile, err = build.GetContextFromGitURL(specifiedContext, dockerfileName) - case urlutil.IsURL(specifiedContext): - buildCtx, relDockerfile, err = build.GetContextFromURL(progBuff, specifiedContext, dockerfileName) - default: - return "", errors.Errorf("unable to prepare context: path %q not found", specifiedContext) - } - - if err != nil { - return "", errors.Errorf("unable to prepare context: %s", err) - } - - if tempDir != "" { - defer os.RemoveAll(tempDir) //nolint:errcheck - contextDir = tempDir - } - - // read from a directory into tar archive - if buildCtx == nil { - excludes, err := build.ReadDockerignore(contextDir) - if err != nil { - return "", err - } - - if err := build.ValidateContextDirectory(contextDir, excludes); err != nil { - return "", errors.Wrap(err, "checking context") - } - - // And canonicalize dockerfile name to a platform-independent one - relDockerfile = archive.CanonicalTarNameForPath(relDockerfile) - - excludes = build.TrimBuildFilesFromExcludes(excludes, relDockerfile, false) - buildCtx, err = archive.TarWithOptions(contextDir, &archive.TarOptions{ - ExcludePatterns: excludes, - ChownOpts: &idtools.Identity{}, - }) - if err != nil { - return "", err - } - } - - // replace Dockerfile if it was added from stdin or a file outside the build-context, and there is archive context - if dockerfileCtx != nil && buildCtx != nil { - buildCtx, relDockerfile, err = build.AddDockerfileToBuildContext(dockerfileCtx, buildCtx) - if err != nil { - return "", err - } - } - - buildCtx, err = build.Compress(buildCtx) - if err != nil { - return "", err - } - - progressOutput := streamformatter.NewProgressOutput(progBuff) - body := progress.NewProgressReader(buildCtx, progressOutput, 0, "", "Sending build context to Docker daemon") - - configFile := s.configFile() - creds, err := configFile.GetAllCredentials() - if err != nil { - return "", err - } - authConfigs := make(map[string]registry.AuthConfig, len(creds)) - for k, auth := range creds { - authConfigs[k] = registry.AuthConfig(auth) - } - buildOptions := imageBuildOptions(s.dockerCli, project, service, options) - imageName := api.GetImageNameOrDefault(service, project.Name) - buildOptions.Tags = append(buildOptions.Tags, imageName) - buildOptions.Dockerfile = relDockerfile - buildOptions.AuthConfigs = authConfigs - buildOptions.Memory = options.Memory - - ctx, cancel := context.WithCancel(ctx) - defer cancel() - response, err := s.apiClient().ImageBuild(ctx, body, buildOptions) - if err != nil { - return "", err - } - defer response.Body.Close() //nolint:errcheck - - imageID := "" - aux := func(msg jsonmessage.JSONMessage) { - var result dockertypes.BuildResult - if err := json.Unmarshal(*msg.Aux, &result); err != nil { - fmt.Fprintf(s.stderr(), "Failed to parse aux message: %s", err) - } else { - imageID = result.ID - } - } - - err = jsonmessage.DisplayJSONMessagesStream(response.Body, buildBuff, progBuff.FD(), true, aux) - if err != nil { - if jerr, ok := err.(*jsonmessage.JSONError); ok { - // If no error code is set, default to 1 - if jerr.Code == 0 { - jerr.Code = 1 - } - return "", cli.StatusError{Status: jerr.Message, StatusCode: jerr.Code} - } - return "", err - } - - // Windows: show error message about modified file permissions if the - // daemon isn't running Windows. - if response.OSType != "windows" && runtime.GOOS == "windows" { - // if response.OSType != "windows" && runtime.GOOS == "windows" && !options.quiet { - fmt.Fprintln(s.stdout(), "SECURITY WARNING: You are building a Docker "+ - "image from Windows against a non-Windows Docker host. All files and "+ - "directories added to build context will have '-rwxr-xr-x' permissions. "+ - "It is recommended to double check and reset permissions for sensitive "+ - "files and directories.") - } - - return imageID, nil -} - -func isLocalDir(c string) bool { - _, err := os.Stat(c) - return err == nil -} - -func imageBuildOptions(dockerCli command.Cli, project *types.Project, service types.ServiceConfig, options api.BuildOptions) dockertypes.ImageBuildOptions { - config := service.Build - return dockertypes.ImageBuildOptions{ - Version: dockertypes.BuilderV1, - Tags: config.Tags, - NoCache: config.NoCache, - Remove: true, - PullParent: config.Pull, - BuildArgs: resolveAndMergeBuildArgs(dockerCli, project, service, options), - Labels: config.Labels, - NetworkMode: config.Network, - ExtraHosts: config.ExtraHosts.AsList(), - Target: config.Target, - Isolation: container.Isolation(config.Isolation), - } -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/compose.go b/vendor/github.com/docker/compose/v2/pkg/compose/compose.go deleted file mode 100644 index 33f93397a..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/compose.go +++ /dev/null @@ -1,302 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "encoding/json" - "fmt" - "io" - "os" - "strconv" - "strings" - "sync" - - "github.com/jonboulle/clockwork" - - "github.com/docker/docker/api/types/volume" - - "github.com/compose-spec/compose-go/types" - "github.com/distribution/distribution/v3/reference" - "github.com/docker/cli/cli/command" - "github.com/docker/cli/cli/config/configfile" - "github.com/docker/cli/cli/flags" - "github.com/docker/cli/cli/streams" - moby "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/swarm" - "github.com/docker/docker/client" - "github.com/opencontainers/go-digest" - "github.com/pkg/errors" - "gopkg.in/yaml.v2" - - "github.com/docker/compose/v2/pkg/api" -) - -var stdioToStdout bool - -func init() { - out, ok := os.LookupEnv("COMPOSE_STATUS_STDOUT") - if ok { - stdioToStdout, _ = strconv.ParseBool(out) - } -} - -// NewComposeService create a local implementation of the compose.Service API -func NewComposeService(dockerCli command.Cli) api.Service { - return &composeService{ - dockerCli: dockerCli, - clock: clockwork.NewRealClock(), - maxConcurrency: -1, - dryRun: false, - } -} - -type composeService struct { - dockerCli command.Cli - clock clockwork.Clock - maxConcurrency int - dryRun bool -} - -func (s *composeService) apiClient() client.APIClient { - return s.dockerCli.Client() -} - -func (s *composeService) configFile() *configfile.ConfigFile { - return s.dockerCli.ConfigFile() -} - -func (s *composeService) MaxConcurrency(i int) { - s.maxConcurrency = i -} - -func (s *composeService) DryRunMode(ctx context.Context, dryRun bool) (context.Context, error) { - s.dryRun = dryRun - if dryRun { - cli, err := command.NewDockerCli() - if err != nil { - return ctx, err - } - - options := flags.NewClientOptions() - options.Context = s.dockerCli.CurrentContext() - err = cli.Initialize(options, command.WithInitializeClient(func(cli *command.DockerCli) (client.APIClient, error) { - return api.NewDryRunClient(s.apiClient(), s.dockerCli) - })) - if err != nil { - return ctx, err - } - s.dockerCli = cli - } - return context.WithValue(ctx, api.DryRunKey{}, dryRun), nil -} - -func (s *composeService) stdout() *streams.Out { - return s.dockerCli.Out() -} - -func (s *composeService) stdin() *streams.In { - return s.dockerCli.In() -} - -func (s *composeService) stderr() io.Writer { - return s.dockerCli.Err() -} - -func (s *composeService) stdinfo() io.Writer { - if stdioToStdout { - return s.dockerCli.Out() - } - return s.dockerCli.Err() -} - -func getCanonicalContainerName(c moby.Container) string { - if len(c.Names) == 0 { - // corner case, sometime happens on removal. return short ID as a safeguard value - return c.ID[:12] - } - // Names return container canonical name /foo + link aliases /linked_by/foo - for _, name := range c.Names { - if strings.LastIndex(name, "/") == 0 { - return name[1:] - } - } - return c.Names[0][1:] -} - -func getContainerNameWithoutProject(c moby.Container) string { - name := getCanonicalContainerName(c) - project := c.Labels[api.ProjectLabel] - prefix := fmt.Sprintf("%s_%s_", project, c.Labels[api.ServiceLabel]) - if strings.HasPrefix(name, prefix) { - return name[len(project)+1:] - } - return name -} - -func (s *composeService) Config(ctx context.Context, project *types.Project, options api.ConfigOptions) ([]byte, error) { - if options.ResolveImageDigests { - err := project.ResolveImages(func(named reference.Named) (digest.Digest, error) { - auth, err := encodedAuth(named, s.configFile()) - if err != nil { - return "", err - } - inspect, err := s.apiClient().DistributionInspect(ctx, named.String(), auth) - if err != nil { - return "", err - } - return inspect.Descriptor.Digest, nil - }) - if err != nil { - return nil, err - } - } - - switch options.Format { - case "json": - return json.MarshalIndent(project, "", " ") - case "yaml": - return yaml.Marshal(project) - default: - return nil, fmt.Errorf("unsupported format %q", options.Format) - } -} - -// projectFromName builds a types.Project based on actual resources with compose labels set -func (s *composeService) projectFromName(containers Containers, projectName string, services ...string) (*types.Project, error) { - project := &types.Project{ - Name: projectName, - } - if len(containers) == 0 { - return project, errors.Wrap(api.ErrNotFound, fmt.Sprintf("no container found for project %q", projectName)) - } - set := map[string]*types.ServiceConfig{} - for _, c := range containers { - serviceLabel := c.Labels[api.ServiceLabel] - _, ok := set[serviceLabel] - if !ok { - set[serviceLabel] = &types.ServiceConfig{ - Name: serviceLabel, - Image: c.Image, - Labels: c.Labels, - } - } - set[serviceLabel].Scale++ - } - for _, service := range set { - dependencies := service.Labels[api.DependenciesLabel] - if len(dependencies) > 0 { - service.DependsOn = types.DependsOnConfig{} - for _, dc := range strings.Split(dependencies, ",") { - dcArr := strings.Split(dc, ":") - condition := ServiceConditionRunningOrHealthy - // Let's restart the dependency by default if we don't have the info stored in the label - restart := true - required := true - dependency := dcArr[0] - - // backward compatibility - if len(dcArr) > 1 { - condition = dcArr[1] - if len(dcArr) > 2 { - restart, _ = strconv.ParseBool(dcArr[2]) - } - } - service.DependsOn[dependency] = types.ServiceDependency{Condition: condition, Restart: restart, Required: required} - } - } - project.Services = append(project.Services, *service) - } -SERVICES: - for _, qs := range services { - for _, es := range project.Services { - if es.Name == qs { - continue SERVICES - } - } - return project, errors.Wrapf(api.ErrNotFound, "no such service: %q", qs) - } - err := project.ForServices(services) - if err != nil { - return project, err - } - - return project, nil -} - -func (s *composeService) actualVolumes(ctx context.Context, projectName string) (types.Volumes, error) { - opts := volume.ListOptions{ - Filters: filters.NewArgs(projectFilter(projectName)), - } - volumes, err := s.apiClient().VolumeList(ctx, opts) - if err != nil { - return nil, err - } - - actual := types.Volumes{} - for _, vol := range volumes.Volumes { - actual[vol.Labels[api.VolumeLabel]] = types.VolumeConfig{ - Name: vol.Name, - Driver: vol.Driver, - Labels: vol.Labels, - } - } - return actual, nil -} - -func (s *composeService) actualNetworks(ctx context.Context, projectName string) (types.Networks, error) { - networks, err := s.apiClient().NetworkList(ctx, moby.NetworkListOptions{ - Filters: filters.NewArgs(projectFilter(projectName)), - }) - if err != nil { - return nil, err - } - - actual := types.Networks{} - for _, net := range networks { - actual[net.Labels[api.NetworkLabel]] = types.NetworkConfig{ - Name: net.Name, - Driver: net.Driver, - Labels: net.Labels, - } - } - return actual, nil -} - -var swarmEnabled = struct { - once sync.Once - val bool - err error -}{} - -func (s *composeService) isSWarmEnabled(ctx context.Context) (bool, error) { - swarmEnabled.once.Do(func() { - info, err := s.apiClient().Info(ctx) - if err != nil { - swarmEnabled.err = err - } - switch info.Swarm.LocalNodeState { - case swarm.LocalNodeStateInactive, swarm.LocalNodeStateLocked: - swarmEnabled.val = false - default: - swarmEnabled.val = true - } - }) - return swarmEnabled.val, swarmEnabled.err - -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/container.go b/vendor/github.com/docker/compose/v2/pkg/compose/container.go deleted file mode 100644 index 004ac4167..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/container.go +++ /dev/null @@ -1,75 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "io" - - moby "github.com/docker/docker/api/types" -) - -const ( - // ContainerCreated created status - ContainerCreated = "created" - // ContainerRestarting restarting status - ContainerRestarting = "restarting" - // ContainerRunning running status - ContainerRunning = "running" - // ContainerRemoving removing status - ContainerRemoving = "removing" - // ContainerPaused paused status - ContainerPaused = "paused" - // ContainerExited exited status - ContainerExited = "exited" - // ContainerDead dead status - ContainerDead = "dead" -) - -var _ io.ReadCloser = ContainerStdout{} - -// ContainerStdout implement ReadCloser for moby.HijackedResponse -type ContainerStdout struct { - moby.HijackedResponse -} - -// Read implement io.ReadCloser -func (l ContainerStdout) Read(p []byte) (n int, err error) { - return l.Reader.Read(p) -} - -// Close implement io.ReadCloser -func (l ContainerStdout) Close() error { - l.HijackedResponse.Close() - return nil -} - -var _ io.WriteCloser = ContainerStdin{} - -// ContainerStdin implement WriteCloser for moby.HijackedResponse -type ContainerStdin struct { - moby.HijackedResponse -} - -// Write implement io.WriteCloser -func (c ContainerStdin) Write(p []byte) (n int, err error) { - return c.Conn.Write(p) -} - -// Close implement io.WriteCloser -func (c ContainerStdin) Close() error { - return c.CloseWrite() -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/containers.go b/vendor/github.com/docker/compose/v2/pkg/compose/containers.go deleted file mode 100644 index 47df374d5..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/containers.go +++ /dev/null @@ -1,161 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "fmt" - "sort" - "strconv" - - "github.com/docker/compose/v2/pkg/api" - "github.com/docker/compose/v2/pkg/utils" - moby "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" -) - -// Containers is a set of moby Container -type Containers []moby.Container - -type oneOff int - -const ( - oneOffInclude = oneOff(iota) - oneOffExclude - oneOffOnly -) - -func (s *composeService) getContainers(ctx context.Context, project string, oneOff oneOff, stopped bool, selectedServices ...string) (Containers, error) { - var containers Containers - f := getDefaultFilters(project, oneOff, selectedServices...) - containers, err := s.apiClient().ContainerList(ctx, moby.ContainerListOptions{ - Filters: filters.NewArgs(f...), - All: stopped, - }) - if err != nil { - return nil, err - } - if len(selectedServices) > 1 { - containers = containers.filter(isService(selectedServices...)) - } - return containers, nil -} - -func getDefaultFilters(projectName string, oneOff oneOff, selectedServices ...string) []filters.KeyValuePair { - f := []filters.KeyValuePair{projectFilter(projectName)} - if len(selectedServices) == 1 { - f = append(f, serviceFilter(selectedServices[0])) - } - f = append(f, hasConfigHashLabel()) - switch oneOff { - case oneOffOnly: - f = append(f, oneOffFilter(true)) - case oneOffExclude: - f = append(f, oneOffFilter(false)) - case oneOffInclude: - } - return f -} - -func (s *composeService) getSpecifiedContainer(ctx context.Context, projectName string, oneOff oneOff, stopped bool, serviceName string, containerIndex int) (moby.Container, error) { - defaultFilters := getDefaultFilters(projectName, oneOff, serviceName) - if containerIndex > 0 { - defaultFilters = append(defaultFilters, containerNumberFilter(containerIndex)) - } - containers, err := s.apiClient().ContainerList(ctx, moby.ContainerListOptions{ - Filters: filters.NewArgs( - defaultFilters..., - ), - All: stopped, - }) - if err != nil { - return moby.Container{}, err - } - if len(containers) < 1 { - if containerIndex > 0 { - return moby.Container{}, fmt.Errorf("service %q is not running container #%d", serviceName, containerIndex) - } - return moby.Container{}, fmt.Errorf("service %q is not running", serviceName) - } - sort.Slice(containers, func(i, j int) bool { - x, _ := strconv.Atoi(containers[i].Labels[api.ContainerNumberLabel]) - y, _ := strconv.Atoi(containers[j].Labels[api.ContainerNumberLabel]) - return x < y - }) - container := containers[0] - return container, nil -} - -// containerPredicate define a predicate we want container to satisfy for filtering operations -type containerPredicate func(c moby.Container) bool - -func isService(services ...string) containerPredicate { - return func(c moby.Container) bool { - service := c.Labels[api.ServiceLabel] - return utils.StringContains(services, service) - } -} - -func isRunning() containerPredicate { - return func(c moby.Container) bool { - return c.State == "running" - } -} - -func isNotService(services ...string) containerPredicate { - return func(c moby.Container) bool { - service := c.Labels[api.ServiceLabel] - return !utils.StringContains(services, service) - } -} - -func isNotOneOff(c moby.Container) bool { - v, ok := c.Labels[api.OneoffLabel] - return !ok || v == "False" -} - -// filter return Containers with elements to match predicate -func (containers Containers) filter(predicate containerPredicate) Containers { - var filtered Containers - for _, c := range containers { - if predicate(c) { - filtered = append(filtered, c) - } - } - return filtered -} - -func (containers Containers) names() []string { - var names []string - for _, c := range containers { - names = append(names, getCanonicalContainerName(c)) - } - return names -} - -func (containers Containers) forEach(fn func(moby.Container)) { - for _, c := range containers { - fn(c) - } -} - -func (containers Containers) sorted() Containers { - sort.Slice(containers, func(i, j int) bool { - return getCanonicalContainerName(containers[i]) < getCanonicalContainerName(containers[j]) - }) - return containers -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/convergence.go b/vendor/github.com/docker/compose/v2/pkg/compose/convergence.go deleted file mode 100644 index 33b97344b..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/convergence.go +++ /dev/null @@ -1,756 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "fmt" - "sort" - "strconv" - "strings" - "sync" - "time" - - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/trace" - - "github.com/compose-spec/compose-go/types" - "github.com/containerd/containerd/platforms" - "github.com/docker/compose/v2/internal/tracing" - moby "github.com/docker/docker/api/types" - containerType "github.com/docker/docker/api/types/container" - specs "github.com/opencontainers/image-spec/specs-go/v1" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" - "golang.org/x/sync/errgroup" - - "github.com/docker/compose/v2/pkg/api" - "github.com/docker/compose/v2/pkg/progress" - "github.com/docker/compose/v2/pkg/utils" -) - -const ( - extLifecycle = "x-lifecycle" - forceRecreate = "force_recreate" - - doubledContainerNameWarning = "WARNING: The %q service is using the custom container name %q. " + - "Docker requires each container to have a unique name. " + - "Remove the custom name to scale the service.\n" -) - -// convergence manages service's container lifecycle. -// Based on initially observed state, it reconciles the existing container with desired state, which might include -// re-creating container, adding or removing replicas, or starting stopped containers. -// Cross services dependencies are managed by creating services in expected order and updating `service:xx` reference -// when a service has converged, so dependent ones can be managed with resolved containers references. -type convergence struct { - service *composeService - observedState map[string]Containers - stateMutex sync.Mutex -} - -func (c *convergence) getObservedState(serviceName string) Containers { - c.stateMutex.Lock() - defer c.stateMutex.Unlock() - return c.observedState[serviceName] -} - -func (c *convergence) setObservedState(serviceName string, containers Containers) { - c.stateMutex.Lock() - defer c.stateMutex.Unlock() - c.observedState[serviceName] = containers -} - -func newConvergence(services []string, state Containers, s *composeService) *convergence { - observedState := map[string]Containers{} - for _, s := range services { - observedState[s] = Containers{} - } - for _, c := range state.filter(isNotOneOff) { - service := c.Labels[api.ServiceLabel] - observedState[service] = append(observedState[service], c) - } - return &convergence{ - service: s, - observedState: observedState, - } -} - -func (c *convergence) apply(ctx context.Context, project *types.Project, options api.CreateOptions) error { - return InDependencyOrder(ctx, project, func(ctx context.Context, name string) error { - service, err := project.GetService(name) - if err != nil { - return err - } - - return tracing.SpanWrapFunc("service/apply", tracing.ServiceOptions(service), func(ctx context.Context) error { - strategy := options.RecreateDependencies - if utils.StringContains(options.Services, name) { - strategy = options.Recreate - } - err = c.ensureService(ctx, project, service, strategy, options.Inherit, options.Timeout) - if err != nil { - return err - } - - c.updateProject(project, name) - return nil - })(ctx) - }) -} - -var mu sync.Mutex - -// updateProject updates project after service converged, so dependent services relying on `service:xx` can refer to actual containers. -func (c *convergence) updateProject(project *types.Project, serviceName string) { - // operation is protected by a Mutex so that we can safely update project.Services while running concurrent convergence on services - mu.Lock() - defer mu.Unlock() - - cnts := c.getObservedState(serviceName) - for i, s := range project.Services { - updateServices(&s, cnts) - project.Services[i] = s - } -} - -func updateServices(service *types.ServiceConfig, cnts Containers) { - if len(cnts) == 0 { - return - } - - for _, str := range []*string{&service.NetworkMode, &service.Ipc, &service.Pid} { - if d := getDependentServiceFromMode(*str); d != "" { - if serviceContainers := cnts.filter(isService(d)); len(serviceContainers) > 0 { - *str = types.NetworkModeContainerPrefix + serviceContainers[0].ID - } - } - } - var links []string - for _, serviceLink := range service.Links { - parts := strings.Split(serviceLink, ":") - serviceName := serviceLink - serviceAlias := "" - if len(parts) == 2 { - serviceName = parts[0] - serviceAlias = parts[1] - } - if serviceName != service.Name { - links = append(links, serviceLink) - continue - } - for _, container := range cnts { - name := getCanonicalContainerName(container) - if serviceAlias != "" { - links = append(links, - fmt.Sprintf("%s:%s", name, serviceAlias)) - } - links = append(links, - fmt.Sprintf("%s:%s", name, name), - fmt.Sprintf("%s:%s", name, getContainerNameWithoutProject(container))) - } - service.Links = links - } -} - -func (c *convergence) ensureService(ctx context.Context, project *types.Project, service types.ServiceConfig, recreate string, inherit bool, timeout *time.Duration) error { - expected, err := getScale(service) - if err != nil { - return err - } - containers := c.getObservedState(service.Name) - actual := len(containers) - updated := make(Containers, expected) - - eg, _ := errgroup.WithContext(ctx) - - sort.Slice(containers, func(i, j int) bool { - return containers[i].Created < containers[j].Created - }) - for i, container := range containers { - if i >= expected { - // Scale Down - container := container - traceOpts := append(tracing.ServiceOptions(service), tracing.ContainerOptions(container)...) - eg.Go(tracing.SpanWrapFuncForErrGroup(ctx, "service/scale/down", traceOpts, func(ctx context.Context) error { - timeoutInSecond := utils.DurationSecondToInt(timeout) - err := c.service.apiClient().ContainerStop(ctx, container.ID, containerType.StopOptions{ - Timeout: timeoutInSecond, - }) - if err != nil { - return err - } - return c.service.apiClient().ContainerRemove(ctx, container.ID, moby.ContainerRemoveOptions{}) - })) - continue - } - - mustRecreate, err := mustRecreate(service, container, recreate) - if err != nil { - return err - } - if mustRecreate { - i, container := i, container - eg.Go(tracing.SpanWrapFuncForErrGroup(ctx, "container/recreate", tracing.ContainerOptions(container), func(ctx context.Context) error { - recreated, err := c.service.recreateContainer(ctx, project, service, container, inherit, timeout) - updated[i] = recreated - return err - })) - continue - } - - // Enforce non-diverged containers are running - w := progress.ContextWriter(ctx) - name := getContainerProgressName(container) - switch container.State { - case ContainerRunning: - w.Event(progress.RunningEvent(name)) - case ContainerCreated: - case ContainerRestarting: - case ContainerExited: - w.Event(progress.CreatedEvent(name)) - default: - container := container - eg.Go(tracing.EventWrapFuncForErrGroup(ctx, "service/start", tracing.ContainerOptions(container), func(ctx context.Context) error { - return c.service.startContainer(ctx, container) - })) - } - updated[i] = container - } - - next := nextContainerNumber(containers) - for i := 0; i < expected-actual; i++ { - // Scale UP - number := next + i - name := getContainerName(project.Name, service, number) - i := i - eventOpts := tracing.SpanOptions{trace.WithAttributes(attribute.String("container.name", name))} - eg.Go(tracing.EventWrapFuncForErrGroup(ctx, "service/scale/up", eventOpts, func(ctx context.Context) error { - opts := createOptions{ - AutoRemove: false, - AttachStdin: false, - UseNetworkAliases: true, - Labels: mergeLabels(service.Labels, service.CustomLabels), - } - container, err := c.service.createContainer(ctx, project, service, name, number, opts) - updated[actual+i] = container - return err - })) - continue - } - - err = eg.Wait() - c.setObservedState(service.Name, updated) - return err -} - -func mustRecreate(expected types.ServiceConfig, actual moby.Container, policy string) (bool, error) { - if policy == api.RecreateNever { - return false, nil - } - if policy == api.RecreateForce || expected.Extensions[extLifecycle] == forceRecreate { - return true, nil - } - configHash, err := ServiceHash(expected) - if err != nil { - return false, err - } - configChanged := actual.Labels[api.ConfigHashLabel] != configHash - imageUpdated := actual.Labels[api.ImageDigestLabel] != expected.CustomLabels[api.ImageDigestLabel] - return configChanged || imageUpdated, nil -} - -func getContainerName(projectName string, service types.ServiceConfig, number int) string { - name := strings.Join([]string{projectName, service.Name, strconv.Itoa(number)}, api.Separator) - if service.ContainerName != "" { - name = service.ContainerName - } - return name -} - -func getContainerProgressName(container moby.Container) string { - return "Container " + getCanonicalContainerName(container) -} - -func containerEvents(containers Containers, eventFunc func(string) progress.Event) []progress.Event { - events := []progress.Event{} - for _, container := range containers { - events = append(events, eventFunc(getContainerProgressName(container))) - } - return events -} - -func containerReasonEvents(containers Containers, eventFunc func(string, string) progress.Event, reason string) []progress.Event { - events := []progress.Event{} - for _, container := range containers { - events = append(events, eventFunc(getContainerProgressName(container), reason)) - } - return events -} - -// ServiceConditionRunningOrHealthy is a service condition on status running or healthy -const ServiceConditionRunningOrHealthy = "running_or_healthy" - -//nolint:gocyclo -func (s *composeService) waitDependencies(ctx context.Context, project *types.Project, dependencies types.DependsOnConfig, containers Containers) error { - eg, _ := errgroup.WithContext(ctx) - w := progress.ContextWriter(ctx) - for dep, config := range dependencies { - if shouldWait, err := shouldWaitForDependency(dep, config, project); err != nil { - return err - } else if !shouldWait { - continue - } - - waitingFor := containers.filter(isService(dep)) - w.Events(containerEvents(waitingFor, progress.Waiting)) - - dep, config := dep, config - eg.Go(func() error { - ticker := time.NewTicker(500 * time.Millisecond) - defer ticker.Stop() - for { - select { - case <-ticker.C: - case <-ctx.Done(): - return nil - } - switch config.Condition { - case ServiceConditionRunningOrHealthy: - healthy, err := s.isServiceHealthy(ctx, waitingFor, true) - if err != nil { - if !config.Required { - w.Events(containerReasonEvents(waitingFor, progress.SkippedEvent, fmt.Sprintf("optional dependency %q is not running or is unhealthy", dep))) - logrus.Warnf("optional dependency %q is not running or is unhealthy: %s", dep, err.Error()) - return nil - } - return err - } - if healthy { - w.Events(containerEvents(waitingFor, progress.Healthy)) - return nil - } - case types.ServiceConditionHealthy: - healthy, err := s.isServiceHealthy(ctx, waitingFor, false) - if err != nil { - if !config.Required { - w.Events(containerReasonEvents(waitingFor, progress.SkippedEvent, fmt.Sprintf("optional dependency %q failed to start", dep))) - logrus.Warnf("optional dependency %q failed to start: %s", dep, err.Error()) - return nil - } - w.Events(containerEvents(waitingFor, progress.ErrorEvent)) - return errors.Wrap(err, "dependency failed to start") - } - if healthy { - w.Events(containerEvents(waitingFor, progress.Healthy)) - return nil - } - case types.ServiceConditionCompletedSuccessfully: - exited, code, err := s.isServiceCompleted(ctx, waitingFor) - if err != nil { - return err - } - if exited { - if code == 0 { - w.Events(containerEvents(waitingFor, progress.Exited)) - return nil - } - - messageSuffix := fmt.Sprintf("%q didn't complete successfully: exit %d", dep, code) - if !config.Required { - // optional -> mark as skipped & don't propagate error - w.Events(containerReasonEvents(waitingFor, progress.SkippedEvent, fmt.Sprintf("optional dependency %s", messageSuffix))) - logrus.Warnf("optional dependency %s", messageSuffix) - return nil - } - - msg := fmt.Sprintf("service %s", messageSuffix) - w.Events(containerReasonEvents(waitingFor, progress.ErrorMessageEvent, msg)) - return errors.New(msg) - } - default: - logrus.Warnf("unsupported depends_on condition: %s", config.Condition) - return nil - } - } - }) - } - return eg.Wait() -} - -func shouldWaitForDependency(serviceName string, dependencyConfig types.ServiceDependency, project *types.Project) (bool, error) { - if dependencyConfig.Condition == types.ServiceConditionStarted { - // already managed by InDependencyOrder - return false, nil - } - if service, err := project.GetService(serviceName); err != nil { - for _, ds := range project.DisabledServices { - if ds.Name == serviceName { - // don't wait for disabled service (--no-deps) - return false, nil - } - } - return false, err - } else if service.Scale == 0 { - // don't wait for the dependency which configured to have 0 containers running - return false, nil - } - return true, nil -} - -func nextContainerNumber(containers []moby.Container) int { - max := 0 - for _, c := range containers { - s, ok := c.Labels[api.ContainerNumberLabel] - if !ok { - logrus.Warnf("container %s is missing %s label", c.ID, api.ContainerNumberLabel) - } - n, err := strconv.Atoi(s) - if err != nil { - logrus.Warnf("container %s has invalid %s label: %s", c.ID, api.ContainerNumberLabel, s) - continue - } - if n > max { - max = n - } - } - return max + 1 - -} - -func getScale(config types.ServiceConfig) (int, error) { - scale := 1 - if config.Deploy != nil && config.Deploy.Replicas != nil { - scale = int(*config.Deploy.Replicas) - } - if scale > 1 && config.ContainerName != "" { - return 0, fmt.Errorf(doubledContainerNameWarning, - config.Name, - config.ContainerName) - } - return scale, nil -} - -func (s *composeService) createContainer(ctx context.Context, project *types.Project, service types.ServiceConfig, - name string, number int, opts createOptions) (container moby.Container, err error) { - w := progress.ContextWriter(ctx) - eventName := "Container " + name - w.Event(progress.CreatingEvent(eventName)) - container, err = s.createMobyContainer(ctx, project, service, name, number, nil, opts, w) - if err != nil { - return - } - w.Event(progress.CreatedEvent(eventName)) - return -} - -func (s *composeService) recreateContainer(ctx context.Context, project *types.Project, service types.ServiceConfig, - replaced moby.Container, inherit bool, timeout *time.Duration) (moby.Container, error) { - var created moby.Container - w := progress.ContextWriter(ctx) - w.Event(progress.NewEvent(getContainerProgressName(replaced), progress.Working, "Recreate")) - - number, err := strconv.Atoi(replaced.Labels[api.ContainerNumberLabel]) - if err != nil { - return created, err - } - - var inherited *moby.Container - if inherit { - inherited = &replaced - } - name := getContainerName(project.Name, service, number) - tmpName := fmt.Sprintf("%s_%s", replaced.ID[:12], name) - opts := createOptions{ - AutoRemove: false, - AttachStdin: false, - UseNetworkAliases: true, - Labels: mergeLabels(service.Labels, service.CustomLabels).Add(api.ContainerReplaceLabel, replaced.ID), - } - created, err = s.createMobyContainer(ctx, project, service, tmpName, number, inherited, opts, w) - if err != nil { - return created, err - } - - timeoutInSecond := utils.DurationSecondToInt(timeout) - err = s.apiClient().ContainerStop(ctx, replaced.ID, containerType.StopOptions{Timeout: timeoutInSecond}) - if err != nil { - return created, err - } - - err = s.apiClient().ContainerRemove(ctx, replaced.ID, moby.ContainerRemoveOptions{}) - if err != nil { - return created, err - } - - err = s.apiClient().ContainerRename(ctx, created.ID, name) - if err != nil { - return created, err - } - - w.Event(progress.NewEvent(getContainerProgressName(replaced), progress.Done, "Recreated")) - setDependentLifecycle(project, service.Name, forceRecreate) - return created, err -} - -// setDependentLifecycle define the Lifecycle strategy for all services to depend on specified service -func setDependentLifecycle(project *types.Project, service string, strategy string) { - mu.Lock() - defer mu.Unlock() - - for i, s := range project.Services { - if utils.StringContains(s.GetDependencies(), service) { - if s.Extensions == nil { - s.Extensions = map[string]interface{}{} - } - s.Extensions[extLifecycle] = strategy - project.Services[i] = s - } - } -} - -func (s *composeService) startContainer(ctx context.Context, container moby.Container) error { - w := progress.ContextWriter(ctx) - w.Event(progress.NewEvent(getContainerProgressName(container), progress.Working, "Restart")) - err := s.apiClient().ContainerStart(ctx, container.ID, moby.ContainerStartOptions{}) - if err != nil { - return err - } - w.Event(progress.NewEvent(getContainerProgressName(container), progress.Done, "Restarted")) - return nil -} - -func (s *composeService) createMobyContainer(ctx context.Context, - project *types.Project, - service types.ServiceConfig, - name string, - number int, - inherit *moby.Container, - opts createOptions, - w progress.Writer, -) (moby.Container, error) { - var created moby.Container - cfgs, err := s.getCreateConfigs(ctx, project, service, number, inherit, opts) - - if err != nil { - return created, err - } - platform := service.Platform - if platform == "" { - platform = project.Environment["DOCKER_DEFAULT_PLATFORM"] - } - var plat *specs.Platform - if platform != "" { - var p specs.Platform - p, err = platforms.Parse(platform) - if err != nil { - return created, err - } - plat = &p - } - - response, err := s.apiClient().ContainerCreate(ctx, cfgs.Container, cfgs.Host, cfgs.Network, plat, name) - if err != nil { - return created, err - } - for _, warning := range response.Warnings { - w.Event(progress.Event{ - ID: service.Name, - Status: progress.Warning, - Text: warning, - }) - } - inspectedContainer, err := s.apiClient().ContainerInspect(ctx, response.ID) - if err != nil { - return created, err - } - created = moby.Container{ - ID: inspectedContainer.ID, - Labels: inspectedContainer.Config.Labels, - Names: []string{inspectedContainer.Name}, - NetworkSettings: &moby.SummaryNetworkSettings{ - Networks: inspectedContainer.NetworkSettings.Networks, - }, - } - - // the highest-priority network is the primary and is included in the ContainerCreate API - // call via container.NetworkMode & network.NetworkingConfig - // any remaining networks are connected one-by-one here after creation (but before start) - serviceNetworks := service.NetworksByPriority() - for _, networkKey := range serviceNetworks { - mobyNetworkName := project.Networks[networkKey].Name - if string(cfgs.Host.NetworkMode) == mobyNetworkName { - // primary network already configured as part of ContainerCreate - continue - } - epSettings := createEndpointSettings(project, service, number, networkKey, cfgs.Links, opts.UseNetworkAliases) - if err := s.apiClient().NetworkConnect(ctx, mobyNetworkName, created.ID, epSettings); err != nil { - return created, err - } - } - - err = s.injectSecrets(ctx, project, service, created.ID) - return created, err -} - -// getLinks mimics V1 compose/service.py::Service::_get_links() -func (s *composeService) getLinks(ctx context.Context, projectName string, service types.ServiceConfig, number int) ([]string, error) { - var links []string - format := func(k, v string) string { - return fmt.Sprintf("%s:%s", k, v) - } - getServiceContainers := func(serviceName string) (Containers, error) { - return s.getContainers(ctx, projectName, oneOffExclude, true, serviceName) - } - - for _, rawLink := range service.Links { - linkSplit := strings.Split(rawLink, ":") - linkServiceName := linkSplit[0] - linkName := linkServiceName - if len(linkSplit) == 2 { - linkName = linkSplit[1] // linkName if informed like in: "serviceName:linkName" - } - cnts, err := getServiceContainers(linkServiceName) - if err != nil { - return nil, err - } - for _, c := range cnts { - containerName := getCanonicalContainerName(c) - links = append(links, - format(containerName, linkName), - format(containerName, linkServiceName+api.Separator+strconv.Itoa(number)), - format(containerName, strings.Join([]string{projectName, linkServiceName, strconv.Itoa(number)}, api.Separator)), - ) - } - } - - if service.Labels[api.OneoffLabel] == "True" { - cnts, err := getServiceContainers(service.Name) - if err != nil { - return nil, err - } - for _, c := range cnts { - containerName := getCanonicalContainerName(c) - links = append(links, - format(containerName, service.Name), - format(containerName, strings.TrimPrefix(containerName, projectName+api.Separator)), - format(containerName, containerName), - ) - } - } - - for _, rawExtLink := range service.ExternalLinks { - extLinkSplit := strings.Split(rawExtLink, ":") - externalLink := extLinkSplit[0] - linkName := externalLink - if len(extLinkSplit) == 2 { - linkName = extLinkSplit[1] - } - links = append(links, format(externalLink, linkName)) - } - return links, nil -} - -func (s *composeService) isServiceHealthy(ctx context.Context, containers Containers, fallbackRunning bool) (bool, error) { - for _, c := range containers { - container, err := s.apiClient().ContainerInspect(ctx, c.ID) - if err != nil { - return false, err - } - name := container.Name[1:] - - if container.State.Status == "exited" { - return false, fmt.Errorf("container %s exited (%d)", name, container.State.ExitCode) - } - - if container.Config.Healthcheck == nil && fallbackRunning { - // Container does not define a health check, but we can fall back to "running" state - return container.State != nil && container.State.Status == "running", nil - } - - if container.State == nil || container.State.Health == nil { - return false, fmt.Errorf("container %s has no healthcheck configured", name) - } - switch container.State.Health.Status { - case moby.Healthy: - // Continue by checking the next container. - case moby.Unhealthy: - return false, fmt.Errorf("container %s is unhealthy", name) - case moby.Starting: - return false, nil - default: - return false, fmt.Errorf("container %s had unexpected health status %q", name, container.State.Health.Status) - } - } - return true, nil -} - -func (s *composeService) isServiceCompleted(ctx context.Context, containers Containers) (bool, int, error) { - for _, c := range containers { - container, err := s.apiClient().ContainerInspect(ctx, c.ID) - if err != nil { - return false, 0, err - } - if container.State != nil && container.State.Status == "exited" { - return true, container.State.ExitCode, nil - } - } - return false, 0, nil -} - -func (s *composeService) startService(ctx context.Context, project *types.Project, service types.ServiceConfig, containers Containers) error { - if service.Deploy != nil && service.Deploy.Replicas != nil && *service.Deploy.Replicas == 0 { - return nil - } - - err := s.waitDependencies(ctx, project, service.DependsOn, containers) - if err != nil { - return err - } - - if len(containers) == 0 { - if scale, err := getScale(service); err != nil && scale == 0 { - return nil - } - return fmt.Errorf("service %q has no container to start", service.Name) - } - - w := progress.ContextWriter(ctx) - for _, container := range containers.filter(isService(service.Name)) { - if container.State == ContainerRunning { - continue - } - eventName := getContainerProgressName(container) - w.Event(progress.StartingEvent(eventName)) - err := s.apiClient().ContainerStart(ctx, container.ID, moby.ContainerStartOptions{}) - if err != nil { - return err - } - w.Event(progress.StartedEvent(eventName)) - } - return nil -} - -func mergeLabels(ls ...types.Labels) types.Labels { - merged := types.Labels{} - for _, l := range ls { - for k, v := range l { - merged[k] = v - } - } - return merged -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/convert.go b/vendor/github.com/docker/compose/v2/pkg/compose/convert.go deleted file mode 100644 index 6f092ee2d..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/convert.go +++ /dev/null @@ -1,83 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "fmt" - "time" - - compose "github.com/compose-spec/compose-go/types" - "github.com/docker/docker/api/types/container" -) - -// ToMobyEnv convert into []string -func ToMobyEnv(environment compose.MappingWithEquals) []string { - var env []string - for k, v := range environment { - if v == nil { - env = append(env, k) - } else { - env = append(env, fmt.Sprintf("%s=%s", k, *v)) - } - } - return env -} - -// ToMobyHealthCheck convert into container.HealthConfig -func ToMobyHealthCheck(check *compose.HealthCheckConfig) *container.HealthConfig { - if check == nil { - return nil - } - var ( - interval time.Duration - timeout time.Duration - period time.Duration - retries int - ) - if check.Interval != nil { - interval = time.Duration(*check.Interval) - } - if check.Timeout != nil { - timeout = time.Duration(*check.Timeout) - } - if check.StartPeriod != nil { - period = time.Duration(*check.StartPeriod) - } - if check.Retries != nil { - retries = int(*check.Retries) - } - test := check.Test - if check.Disable { - test = []string{"NONE"} - } - return &container.HealthConfig{ - Test: test, - Interval: interval, - Timeout: timeout, - StartPeriod: period, - Retries: retries, - } -} - -// ToSeconds convert into seconds -func ToSeconds(d *compose.Duration) *int { - if d == nil { - return nil - } - s := int(time.Duration(*d).Seconds()) - return &s -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/cp.go b/vendor/github.com/docker/compose/v2/pkg/compose/cp.go deleted file mode 100644 index fdba0a8d0..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/cp.go +++ /dev/null @@ -1,329 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "fmt" - "io" - "os" - "path/filepath" - "strings" - - "github.com/docker/compose/v2/pkg/progress" - "golang.org/x/sync/errgroup" - - "github.com/docker/cli/cli/command" - "github.com/docker/compose/v2/pkg/api" - moby "github.com/docker/docker/api/types" - "github.com/docker/docker/pkg/archive" - "github.com/docker/docker/pkg/system" - "github.com/pkg/errors" -) - -type copyDirection int - -const ( - fromService copyDirection = 1 << iota - toService - acrossServices = fromService | toService -) - -func (s *composeService) Copy(ctx context.Context, projectName string, options api.CopyOptions) error { - return progress.RunWithTitle(ctx, func(ctx context.Context) error { - return s.copy(ctx, projectName, options) - }, s.stdinfo(), "Copying") -} - -func (s *composeService) copy(ctx context.Context, projectName string, options api.CopyOptions) error { - projectName = strings.ToLower(projectName) - srcService, srcPath := splitCpArg(options.Source) - destService, dstPath := splitCpArg(options.Destination) - - var direction copyDirection - var serviceName string - var copyFunc func(ctx context.Context, containerID string, srcPath string, dstPath string, opts api.CopyOptions) error - if srcService != "" { - direction |= fromService - serviceName = srcService - copyFunc = s.copyFromContainer - - // copying from multiple containers of a services doesn't make sense. - if options.All { - return errors.New("cannot use the --all flag when copying from a service") - } - } - if destService != "" { - direction |= toService - serviceName = destService - copyFunc = s.copyToContainer - } - if direction == acrossServices { - return errors.New("copying between services is not supported") - } - - if direction == 0 { - return errors.New("unknown copy direction") - } - - containers, err := s.listContainersTargetedForCopy(ctx, projectName, options.Index, direction, serviceName) - if err != nil { - return err - } - - w := progress.ContextWriter(ctx) - g := errgroup.Group{} - for _, cont := range containers { - container := cont - g.Go(func() error { - name := getCanonicalContainerName(container) - var msg string - if direction == fromService { - msg = fmt.Sprintf("copy %s:%s to %s", name, srcPath, dstPath) - } else { - msg = fmt.Sprintf("copy %s to %s:%s", srcPath, name, dstPath) - } - w.Event(progress.Event{ - ID: name, - Text: msg, - Status: progress.Working, - StatusText: "Copying", - }) - if err := copyFunc(ctx, container.ID, srcPath, dstPath, options); err != nil { - return err - } - w.Event(progress.Event{ - ID: name, - Text: msg, - Status: progress.Done, - StatusText: "Copied", - }) - return nil - }) - } - - return g.Wait() -} - -func (s *composeService) listContainersTargetedForCopy(ctx context.Context, projectName string, index int, direction copyDirection, serviceName string) (Containers, error) { - var containers Containers - var err error - switch { - case index > 0: - container, err := s.getSpecifiedContainer(ctx, projectName, oneOffExclude, true, serviceName, index) - if err != nil { - return nil, err - } - return append(containers, container), nil - default: - containers, err = s.getContainers(ctx, projectName, oneOffExclude, true, serviceName) - if err != nil { - return nil, err - } - - if len(containers) < 1 { - return nil, fmt.Errorf("no container found for service %q", serviceName) - } - if direction == fromService { - return containers[:1], err - - } - return containers, err - } -} - -func (s *composeService) copyToContainer(ctx context.Context, containerID string, srcPath string, dstPath string, opts api.CopyOptions) error { - var err error - if srcPath != "-" { - // Get an absolute source path. - srcPath, err = resolveLocalPath(srcPath) - if err != nil { - return err - } - } - - // Prepare destination copy info by stat-ing the container path. - dstInfo := archive.CopyInfo{Path: dstPath} - dstStat, err := s.apiClient().ContainerStatPath(ctx, containerID, dstPath) - - // If the destination is a symbolic link, we should evaluate it. - if err == nil && dstStat.Mode&os.ModeSymlink != 0 { - linkTarget := dstStat.LinkTarget - if !system.IsAbs(linkTarget) { - // Join with the parent directory. - dstParent, _ := archive.SplitPathDirEntry(dstPath) - linkTarget = filepath.Join(dstParent, linkTarget) - } - - dstInfo.Path = linkTarget - dstStat, err = s.apiClient().ContainerStatPath(ctx, containerID, linkTarget) - } - - // Validate the destination path - if err := command.ValidateOutputPathFileMode(dstStat.Mode); err != nil { - return errors.Wrapf(err, `destination "%s:%s" must be a directory or a regular file`, containerID, dstPath) - } - - // Ignore any error and assume that the parent directory of the destination - // path exists, in which case the copy may still succeed. If there is any - // type of conflict (e.g., non-directory overwriting an existing directory - // or vice versa) the extraction will fail. If the destination simply did - // not exist, but the parent directory does, the extraction will still - // succeed. - if err == nil { - dstInfo.Exists, dstInfo.IsDir = true, dstStat.Mode.IsDir() - } - - var ( - content io.Reader - resolvedDstPath string - ) - - if srcPath == "-" { - content = s.stdin() - resolvedDstPath = dstInfo.Path - if !dstInfo.IsDir { - return errors.Errorf("destination \"%s:%s\" must be a directory", containerID, dstPath) - } - } else { - // Prepare source copy info. - srcInfo, err := archive.CopyInfoSourcePath(srcPath, opts.FollowLink) - if err != nil { - return err - } - - srcArchive, err := archive.TarResource(srcInfo) - if err != nil { - return err - } - defer srcArchive.Close() //nolint:errcheck - - // With the stat info about the local source as well as the - // destination, we have enough information to know whether we need to - // alter the archive that we upload so that when the server extracts - // it to the specified directory in the container we get the desired - // copy behavior. - - // See comments in the implementation of `archive.PrepareArchiveCopy` - // for exactly what goes into deciding how and whether the source - // archive needs to be altered for the correct copy behavior when it is - // extracted. This function also infers from the source and destination - // info which directory to extract to, which may be the parent of the - // destination that the user specified. - // Don't create the archive if running in Dry Run mode - if !s.dryRun { - dstDir, preparedArchive, err := archive.PrepareArchiveCopy(srcArchive, srcInfo, dstInfo) - if err != nil { - return err - } - defer preparedArchive.Close() //nolint:errcheck - - resolvedDstPath = dstDir - content = preparedArchive - } - } - - options := moby.CopyToContainerOptions{ - AllowOverwriteDirWithFile: false, - CopyUIDGID: opts.CopyUIDGID, - } - return s.apiClient().CopyToContainer(ctx, containerID, resolvedDstPath, content, options) -} - -func (s *composeService) copyFromContainer(ctx context.Context, containerID, srcPath, dstPath string, opts api.CopyOptions) error { - var err error - if dstPath != "-" { - // Get an absolute destination path. - dstPath, err = resolveLocalPath(dstPath) - if err != nil { - return err - } - } - - if err := command.ValidateOutputPath(dstPath); err != nil { - return err - } - - // if client requests to follow symbol link, then must decide target file to be copied - var rebaseName string - if opts.FollowLink { - srcStat, err := s.apiClient().ContainerStatPath(ctx, containerID, srcPath) - - // If the destination is a symbolic link, we should follow it. - if err == nil && srcStat.Mode&os.ModeSymlink != 0 { - linkTarget := srcStat.LinkTarget - if !system.IsAbs(linkTarget) { - // Join with the parent directory. - srcParent, _ := archive.SplitPathDirEntry(srcPath) - linkTarget = filepath.Join(srcParent, linkTarget) - } - - linkTarget, rebaseName = archive.GetRebaseName(srcPath, linkTarget) - srcPath = linkTarget - } - } - - content, stat, err := s.apiClient().CopyFromContainer(ctx, containerID, srcPath) - if err != nil { - return err - } - defer content.Close() //nolint:errcheck - - if dstPath == "-" { - _, err = io.Copy(s.stdout(), content) - return err - } - - srcInfo := archive.CopyInfo{ - Path: srcPath, - Exists: true, - IsDir: stat.Mode.IsDir(), - RebaseName: rebaseName, - } - - preArchive := content - if srcInfo.RebaseName != "" { - _, srcBase := archive.SplitPathDirEntry(srcInfo.Path) - preArchive = archive.RebaseArchiveEntries(content, srcBase, srcInfo.RebaseName) - } - - return archive.CopyTo(preArchive, srcInfo, dstPath) -} - -func splitCpArg(arg string) (container, path string) { - if system.IsAbs(arg) { - // Explicit local absolute path, e.g., `C:\foo` or `/foo`. - return "", arg - } - - parts := strings.SplitN(arg, ":", 2) - - if len(parts) == 1 || strings.HasPrefix(parts[0], ".") { - // Either there's no `:` in the arg - // OR it's an explicit local relative path like `./file:name.txt`. - return "", arg - } - - return parts[0], parts[1] -} - -func resolveLocalPath(localPath string) (absPath string, err error) { - if absPath, err = filepath.Abs(localPath); err != nil { - return - } - return archive.PreserveTrailingDotOrSeparator(absPath, localPath), nil -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/create.go b/vendor/github.com/docker/compose/v2/pkg/compose/create.go deleted file mode 100644 index f82f8f23f..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/create.go +++ /dev/null @@ -1,1269 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "os" - "path" - "path/filepath" - "strconv" - "strings" - - moby "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/blkiodev" - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/mount" - "github.com/docker/docker/api/types/network" - "github.com/docker/docker/api/types/strslice" - volume_api "github.com/docker/docker/api/types/volume" - "github.com/docker/docker/errdefs" - "github.com/docker/go-connections/nat" - "github.com/docker/go-units" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" - - "github.com/compose-spec/compose-go/types" - - "github.com/docker/compose/v2/pkg/api" - "github.com/docker/compose/v2/pkg/progress" - "github.com/docker/compose/v2/pkg/utils" -) - -type createOptions struct { - AutoRemove bool - AttachStdin bool - UseNetworkAliases bool - Labels types.Labels -} - -type createConfigs struct { - Container *container.Config - Host *container.HostConfig - Network *network.NetworkingConfig - Links []string -} - -func (s *composeService) Create(ctx context.Context, project *types.Project, options api.CreateOptions) error { - return progress.RunWithTitle(ctx, func(ctx context.Context) error { - return s.create(ctx, project, options) - }, s.stdinfo(), "Creating") -} - -func (s *composeService) create(ctx context.Context, project *types.Project, options api.CreateOptions) error { - if len(options.Services) == 0 { - options.Services = project.ServiceNames() - } - - var observedState Containers - observedState, err := s.getContainers(ctx, project.Name, oneOffInclude, true) - if err != nil { - return err - } - - err = s.ensureImagesExists(ctx, project, options.QuietPull) - if err != nil { - return err - } - - prepareNetworks(project) - - err = prepareVolumes(project) - if err != nil { - return err - } - - if err := s.ensureNetworks(ctx, project.Networks); err != nil { - return err - } - - if err := s.ensureProjectVolumes(ctx, project); err != nil { - return err - } - - allServices := project.AllServices() - allServiceNames := []string{} - for _, service := range allServices { - allServiceNames = append(allServiceNames, service.Name) - } - orphans := observedState.filter(isNotService(allServiceNames...)) - if len(orphans) > 0 && !options.IgnoreOrphans { - if options.RemoveOrphans { - w := progress.ContextWriter(ctx) - err := s.removeContainers(ctx, w, orphans, nil, false) - if err != nil { - return err - } - } else { - logrus.Warnf("Found orphan containers (%s) for this project. If "+ - "you removed or renamed this service in your compose "+ - "file, you can run this command with the "+ - "--remove-orphans flag to clean it up.", orphans.names()) - } - } - - return newConvergence(options.Services, observedState, s).apply(ctx, project, options) -} - -func prepareVolumes(p *types.Project) error { - for i := range p.Services { - volumesFrom, dependServices, err := getVolumesFrom(p, p.Services[i].VolumesFrom) - if err != nil { - return err - } - p.Services[i].VolumesFrom = volumesFrom - if len(dependServices) > 0 { - if p.Services[i].DependsOn == nil { - p.Services[i].DependsOn = make(types.DependsOnConfig, len(dependServices)) - } - for _, service := range p.Services { - if utils.StringContains(dependServices, service.Name) && - p.Services[i].DependsOn[service.Name].Condition == "" { - p.Services[i].DependsOn[service.Name] = types.ServiceDependency{ - Condition: types.ServiceConditionStarted, - Required: true, - } - } - } - } - } - return nil -} - -func prepareNetworks(project *types.Project) { - for k, network := range project.Networks { - network.Labels = network.Labels.Add(api.NetworkLabel, k) - network.Labels = network.Labels.Add(api.ProjectLabel, project.Name) - network.Labels = network.Labels.Add(api.VersionLabel, api.ComposeVersion) - project.Networks[k] = network - } -} - -func (s *composeService) ensureNetworks(ctx context.Context, networks types.Networks) error { - for i, network := range networks { - err := s.ensureNetwork(ctx, &network) - if err != nil { - return err - } - networks[i] = network - } - return nil -} - -func (s *composeService) ensureProjectVolumes(ctx context.Context, project *types.Project) error { - for k, volume := range project.Volumes { - volume.Labels = volume.Labels.Add(api.VolumeLabel, k) - volume.Labels = volume.Labels.Add(api.ProjectLabel, project.Name) - volume.Labels = volume.Labels.Add(api.VersionLabel, api.ComposeVersion) - err := s.ensureVolume(ctx, volume, project.Name) - if err != nil { - return err - } - } - return nil -} - -func (s *composeService) getCreateConfigs(ctx context.Context, - p *types.Project, - service types.ServiceConfig, - number int, - inherit *moby.Container, - opts createOptions, -) (createConfigs, error) { - labels, err := s.prepareLabels(opts.Labels, service, number) - if err != nil { - return createConfigs{}, err - } - - var ( - runCmd strslice.StrSlice - entrypoint strslice.StrSlice - ) - if service.Command != nil { - runCmd = strslice.StrSlice(service.Command) - } - if service.Entrypoint != nil { - entrypoint = strslice.StrSlice(service.Entrypoint) - } - - var ( - tty = service.Tty - stdinOpen = service.StdinOpen - ) - - proxyConfig := types.MappingWithEquals(s.configFile().ParseProxyConfig(s.apiClient().DaemonHost(), nil)) - env := proxyConfig.OverrideBy(service.Environment) - - containerConfig := container.Config{ - Hostname: service.Hostname, - Domainname: service.DomainName, - User: service.User, - ExposedPorts: buildContainerPorts(service), - Tty: tty, - OpenStdin: stdinOpen, - StdinOnce: opts.AttachStdin && stdinOpen, - AttachStdin: opts.AttachStdin, - AttachStderr: true, - AttachStdout: true, - Cmd: runCmd, - Image: api.GetImageNameOrDefault(service, p.Name), - WorkingDir: service.WorkingDir, - Entrypoint: entrypoint, - NetworkDisabled: service.NetworkMode == "disabled", - MacAddress: service.MacAddress, - Labels: labels, - StopSignal: service.StopSignal, - Env: ToMobyEnv(env), - Healthcheck: ToMobyHealthCheck(service.HealthCheck), - StopTimeout: ToSeconds(service.StopGracePeriod), - } - - // VOLUMES/MOUNTS/FILESYSTEMS - tmpfs := map[string]string{} - for _, t := range service.Tmpfs { - if arr := strings.SplitN(t, ":", 2); len(arr) > 1 { - tmpfs[arr[0]] = arr[1] - } else { - tmpfs[arr[0]] = "" - } - } - binds, mounts, err := s.buildContainerVolumes(ctx, *p, service, inherit) - if err != nil { - return createConfigs{}, err - } - var volumesFrom []string - for _, v := range service.VolumesFrom { - if !strings.HasPrefix(v, "container:") { - return createConfigs{}, fmt.Errorf("invalid volume_from: %s", v) - } - volumesFrom = append(volumesFrom, v[len("container:"):]) - } - - // NETWORKING - links, err := s.getLinks(ctx, p.Name, service, number) - if err != nil { - return createConfigs{}, err - } - networkMode, networkingConfig := defaultNetworkSettings(p, service, number, links, opts.UseNetworkAliases) - portBindings := buildContainerPortBindingOptions(service) - - // MISC - resources := getDeployResources(service) - var logConfig container.LogConfig - if service.Logging != nil { - logConfig = container.LogConfig{ - Type: service.Logging.Driver, - Config: service.Logging.Options, - } - } - securityOpts, unconfined, err := parseSecurityOpts(p, service.SecurityOpt) - if err != nil { - return createConfigs{}, err - } - - hostConfig := container.HostConfig{ - AutoRemove: opts.AutoRemove, - Binds: binds, - Mounts: mounts, - CapAdd: strslice.StrSlice(service.CapAdd), - CapDrop: strslice.StrSlice(service.CapDrop), - NetworkMode: networkMode, - Init: service.Init, - IpcMode: container.IpcMode(service.Ipc), - CgroupnsMode: container.CgroupnsMode(service.Cgroup), - ReadonlyRootfs: service.ReadOnly, - RestartPolicy: getRestartPolicy(service), - ShmSize: int64(service.ShmSize), - Sysctls: service.Sysctls, - PortBindings: portBindings, - Resources: resources, - VolumeDriver: service.VolumeDriver, - VolumesFrom: volumesFrom, - DNS: service.DNS, - DNSSearch: service.DNSSearch, - DNSOptions: service.DNSOpts, - ExtraHosts: service.ExtraHosts.AsList(), - SecurityOpt: securityOpts, - UsernsMode: container.UsernsMode(service.UserNSMode), - UTSMode: container.UTSMode(service.Uts), - Privileged: service.Privileged, - PidMode: container.PidMode(service.Pid), - Tmpfs: tmpfs, - Isolation: container.Isolation(service.Isolation), - Runtime: service.Runtime, - LogConfig: logConfig, - GroupAdd: service.GroupAdd, - Links: links, - OomScoreAdj: int(service.OomScoreAdj), - } - - if unconfined { - hostConfig.MaskedPaths = []string{} - hostConfig.ReadonlyPaths = []string{} - } - - cfgs := createConfigs{ - Container: &containerConfig, - Host: &hostConfig, - Network: networkingConfig, - Links: links, - } - return cfgs, nil -} - -func getAliases(project *types.Project, service types.ServiceConfig, serviceIndex int, networkKey string, useNetworkAliases bool) []string { - aliases := []string{getContainerName(project.Name, service, serviceIndex)} - if useNetworkAliases { - aliases = append(aliases, service.Name) - if cfg := service.Networks[networkKey]; cfg != nil { - aliases = append(aliases, cfg.Aliases...) - } - } - return aliases -} - -func createEndpointSettings(p *types.Project, service types.ServiceConfig, serviceIndex int, networkKey string, links []string, useNetworkAliases bool) *network.EndpointSettings { - config := service.Networks[networkKey] - var ipam *network.EndpointIPAMConfig - var ( - ipv4Address string - ipv6Address string - ) - if config != nil { - ipv4Address = config.Ipv4Address - ipv6Address = config.Ipv6Address - ipam = &network.EndpointIPAMConfig{ - IPv4Address: ipv4Address, - IPv6Address: ipv6Address, - LinkLocalIPs: config.LinkLocalIPs, - } - } - return &network.EndpointSettings{ - Aliases: getAliases(p, service, serviceIndex, networkKey, useNetworkAliases), - Links: links, - IPAddress: ipv4Address, - IPv6Gateway: ipv6Address, - IPAMConfig: ipam, - } -} - -// copy/pasted from https://github.com/docker/cli/blob/9de1b162f/cli/command/container/opts.go#L673-L697 + RelativePath -// TODO find so way to share this code with docker/cli -func parseSecurityOpts(p *types.Project, securityOpts []string) ([]string, bool, error) { - var ( - unconfined bool - parsed []string - ) - for _, opt := range securityOpts { - if opt == "systempaths=unconfined" { - unconfined = true - continue - } - con := strings.SplitN(opt, "=", 2) - if len(con) == 1 && con[0] != "no-new-privileges" { - if strings.Contains(opt, ":") { - con = strings.SplitN(opt, ":", 2) - } else { - return securityOpts, false, errors.Errorf("Invalid security-opt: %q", opt) - } - } - if con[0] == "seccomp" && con[1] != "unconfined" { - f, err := os.ReadFile(p.RelativePath(con[1])) - if err != nil { - return securityOpts, false, errors.Errorf("opening seccomp profile (%s) failed: %v", con[1], err) - } - b := bytes.NewBuffer(nil) - if err := json.Compact(b, f); err != nil { - return securityOpts, false, errors.Errorf("compacting json for seccomp profile (%s) failed: %v", con[1], err) - } - parsed = append(parsed, fmt.Sprintf("seccomp=%s", b.Bytes())) - } else { - parsed = append(parsed, opt) - } - } - - return parsed, unconfined, nil -} - -func (s *composeService) prepareLabels(labels types.Labels, service types.ServiceConfig, number int) (map[string]string, error) { - hash, err := ServiceHash(service) - if err != nil { - return nil, err - } - labels[api.ConfigHashLabel] = hash - - labels[api.ContainerNumberLabel] = strconv.Itoa(number) - - var dependencies []string - for s, d := range service.DependsOn { - dependencies = append(dependencies, fmt.Sprintf("%s:%s:%t", s, d.Condition, d.Restart)) - } - labels[api.DependenciesLabel] = strings.Join(dependencies, ",") - return labels, nil -} - -// defaultNetworkSettings determines the container.NetworkMode and corresponding network.NetworkingConfig (nil if not applicable). -func defaultNetworkSettings( - project *types.Project, - service types.ServiceConfig, - serviceIndex int, - links []string, - useNetworkAliases bool, -) (container.NetworkMode, *network.NetworkingConfig) { - if service.NetworkMode != "" { - return container.NetworkMode(service.NetworkMode), nil - } - - if len(project.Networks) == 0 { - return "none", nil - } - - var networkKey string - if len(service.Networks) > 0 { - networkKey = service.NetworksByPriority()[0] - } else { - networkKey = "default" - } - mobyNetworkName := project.Networks[networkKey].Name - epSettings := createEndpointSettings(project, service, serviceIndex, networkKey, links, useNetworkAliases) - networkConfig := &network.NetworkingConfig{ - EndpointsConfig: map[string]*network.EndpointSettings{ - mobyNetworkName: epSettings, - }, - } - // From the Engine API docs: - // > Supported standard values are: bridge, host, none, and container:. - // > Any other value is taken as a custom network's name to which this container should connect to. - return container.NetworkMode(mobyNetworkName), networkConfig -} - -func getRestartPolicy(service types.ServiceConfig) container.RestartPolicy { - var restart container.RestartPolicy - if service.Restart != "" { - split := strings.Split(service.Restart, ":") - var attempts int - if len(split) > 1 { - attempts, _ = strconv.Atoi(split[1]) - } - restart = container.RestartPolicy{ - Name: split[0], - MaximumRetryCount: attempts, - } - } - if service.Deploy != nil && service.Deploy.RestartPolicy != nil { - policy := *service.Deploy.RestartPolicy - var attempts int - if policy.MaxAttempts != nil { - attempts = int(*policy.MaxAttempts) - } - restart = container.RestartPolicy{ - Name: mapRestartPolicyCondition(policy.Condition), - MaximumRetryCount: attempts, - } - } - return restart -} - -func mapRestartPolicyCondition(condition string) string { - // map definitions of deploy.restart_policy to engine definitions - switch condition { - case "none", "no": - return "no" - case "on-failure", "unless-stopped": - return condition - case "any", "always": - return "always" - default: - return condition - } -} - -func getDeployResources(s types.ServiceConfig) container.Resources { - var swappiness *int64 - if s.MemSwappiness != 0 { - val := int64(s.MemSwappiness) - swappiness = &val - } - resources := container.Resources{ - CgroupParent: s.CgroupParent, - Memory: int64(s.MemLimit), - MemorySwap: int64(s.MemSwapLimit), - MemorySwappiness: swappiness, - MemoryReservation: int64(s.MemReservation), - OomKillDisable: &s.OomKillDisable, - CPUCount: s.CPUCount, - CPUPeriod: s.CPUPeriod, - CPUQuota: s.CPUQuota, - CPURealtimePeriod: s.CPURTPeriod, - CPURealtimeRuntime: s.CPURTRuntime, - CPUShares: s.CPUShares, - NanoCPUs: int64(s.CPUS * 1e9), - CPUPercent: int64(s.CPUPercent * 100), - CpusetCpus: s.CPUSet, - DeviceCgroupRules: s.DeviceCgroupRules, - } - - if s.PidsLimit != 0 { - resources.PidsLimit = &s.PidsLimit - } - - setBlkio(s.BlkioConfig, &resources) - - if s.Deploy != nil { - setLimits(s.Deploy.Resources.Limits, &resources) - setReservations(s.Deploy.Resources.Reservations, &resources) - } - - for _, device := range s.Devices { - // FIXME should use docker/cli parseDevice, unfortunately private - src := "" - dst := "" - permissions := "rwm" - arr := strings.Split(device, ":") - switch len(arr) { - case 3: - permissions = arr[2] - fallthrough - case 2: - dst = arr[1] - fallthrough - case 1: - src = arr[0] - } - if dst == "" { - dst = src - } - resources.Devices = append(resources.Devices, container.DeviceMapping{ - PathOnHost: src, - PathInContainer: dst, - CgroupPermissions: permissions, - }) - } - - for name, u := range s.Ulimits { - soft := u.Single - if u.Soft != 0 { - soft = u.Soft - } - hard := u.Single - if u.Hard != 0 { - hard = u.Hard - } - resources.Ulimits = append(resources.Ulimits, &units.Ulimit{ - Name: name, - Hard: int64(hard), - Soft: int64(soft), - }) - } - return resources -} - -func setReservations(reservations *types.Resource, resources *container.Resources) { - if reservations == nil { - return - } - // Cpu reservation is a swarm option and PIDs is only a limit - // So we only need to map memory reservation and devices - if reservations.MemoryBytes != 0 { - resources.MemoryReservation = int64(reservations.MemoryBytes) - } - - for _, device := range reservations.Devices { - resources.DeviceRequests = append(resources.DeviceRequests, container.DeviceRequest{ - Capabilities: [][]string{device.Capabilities}, - Count: int(device.Count), - DeviceIDs: device.IDs, - Driver: device.Driver, - }) - } -} - -func setLimits(limits *types.Resource, resources *container.Resources) { - if limits == nil { - return - } - if limits.MemoryBytes != 0 { - resources.Memory = int64(limits.MemoryBytes) - } - if limits.NanoCPUs != "" { - if f, err := strconv.ParseFloat(limits.NanoCPUs, 64); err == nil { - resources.NanoCPUs = int64(f * 1e9) - } - } - if limits.Pids > 0 { - resources.PidsLimit = &limits.Pids - } -} - -func setBlkio(blkio *types.BlkioConfig, resources *container.Resources) { - if blkio == nil { - return - } - resources.BlkioWeight = blkio.Weight - for _, b := range blkio.WeightDevice { - resources.BlkioWeightDevice = append(resources.BlkioWeightDevice, &blkiodev.WeightDevice{ - Path: b.Path, - Weight: b.Weight, - }) - } - for _, b := range blkio.DeviceReadBps { - resources.BlkioDeviceReadBps = append(resources.BlkioDeviceReadBps, &blkiodev.ThrottleDevice{ - Path: b.Path, - Rate: uint64(b.Rate), - }) - } - for _, b := range blkio.DeviceReadIOps { - resources.BlkioDeviceReadIOps = append(resources.BlkioDeviceReadIOps, &blkiodev.ThrottleDevice{ - Path: b.Path, - Rate: uint64(b.Rate), - }) - } - for _, b := range blkio.DeviceWriteBps { - resources.BlkioDeviceWriteBps = append(resources.BlkioDeviceWriteBps, &blkiodev.ThrottleDevice{ - Path: b.Path, - Rate: uint64(b.Rate), - }) - } - for _, b := range blkio.DeviceWriteIOps { - resources.BlkioDeviceWriteIOps = append(resources.BlkioDeviceWriteIOps, &blkiodev.ThrottleDevice{ - Path: b.Path, - Rate: uint64(b.Rate), - }) - } -} - -func buildContainerPorts(s types.ServiceConfig) nat.PortSet { - ports := nat.PortSet{} - for _, s := range s.Expose { - p := nat.Port(s) - ports[p] = struct{}{} - } - for _, p := range s.Ports { - p := nat.Port(fmt.Sprintf("%d/%s", p.Target, p.Protocol)) - ports[p] = struct{}{} - } - return ports -} - -func buildContainerPortBindingOptions(s types.ServiceConfig) nat.PortMap { - bindings := nat.PortMap{} - for _, port := range s.Ports { - p := nat.Port(fmt.Sprintf("%d/%s", port.Target, port.Protocol)) - binding := nat.PortBinding{ - HostIP: port.HostIP, - HostPort: port.Published, - } - bindings[p] = append(bindings[p], binding) - } - return bindings -} - -func getVolumesFrom(project *types.Project, volumesFrom []string) ([]string, []string, error) { - var volumes = []string{} - var services = []string{} - // parse volumes_from - if len(volumesFrom) == 0 { - return volumes, services, nil - } - for _, vol := range volumesFrom { - spec := strings.Split(vol, ":") - if len(spec) == 0 { - continue - } - if spec[0] == "container" { - volumes = append(volumes, vol) - continue - } - serviceName := spec[0] - services = append(services, serviceName) - service, err := project.GetService(serviceName) - if err != nil { - return nil, nil, err - } - - firstContainer := getContainerName(project.Name, service, 1) - v := fmt.Sprintf("container:%s", firstContainer) - if len(spec) > 2 { - v = fmt.Sprintf("container:%s:%s", firstContainer, strings.Join(spec[1:], ":")) - } - volumes = append(volumes, v) - } - return volumes, services, nil - -} - -func getDependentServiceFromMode(mode string) string { - if strings.HasPrefix( - mode, - types.NetworkModeServicePrefix, - ) { - return mode[len(types.NetworkModeServicePrefix):] - } - return "" -} - -func (s *composeService) buildContainerVolumes( - ctx context.Context, - p types.Project, - service types.ServiceConfig, - inherit *moby.Container, -) ([]string, []mount.Mount, error) { - var mounts []mount.Mount - var binds []string - - image := api.GetImageNameOrDefault(service, p.Name) - imgInspect, _, err := s.apiClient().ImageInspectWithRaw(ctx, image) - if err != nil { - return nil, nil, err - } - - mountOptions, err := buildContainerMountOptions(p, service, imgInspect, inherit) - if err != nil { - return nil, nil, err - } - -MOUNTS: - for _, m := range mountOptions { - if m.Type == mount.TypeNamedPipe { - mounts = append(mounts, m) - continue - } - if m.Type == mount.TypeBind { - // `Mount` is preferred but does not offer option to created host path if missing - // so `Bind` API is used here with raw volume string - // see https://github.com/moby/moby/issues/43483 - for _, v := range service.Volumes { - if v.Target == m.Target { - switch { - case string(m.Type) != v.Type: - v.Source = m.Source - fallthrough - case v.Bind != nil && v.Bind.CreateHostPath: - binds = append(binds, v.String()) - continue MOUNTS - } - } - } - } - mounts = append(mounts, m) - } - return binds, mounts, nil -} - -func buildContainerMountOptions(p types.Project, s types.ServiceConfig, img moby.ImageInspect, inherit *moby.Container) ([]mount.Mount, error) { - var mounts = map[string]mount.Mount{} - if inherit != nil { - for _, m := range inherit.Mounts { - if m.Type == "tmpfs" { - continue - } - src := m.Source - if m.Type == "volume" { - src = m.Name - } - m.Destination = path.Clean(m.Destination) - - if img.Config != nil { - if _, ok := img.Config.Volumes[m.Destination]; ok { - // inherit previous container's anonymous volume - mounts[m.Destination] = mount.Mount{ - Type: m.Type, - Source: src, - Target: m.Destination, - ReadOnly: !m.RW, - } - } - } - volumes := []types.ServiceVolumeConfig{} - for _, v := range s.Volumes { - if v.Target != m.Destination || v.Source != "" { - volumes = append(volumes, v) - continue - } - // inherit previous container's anonymous volume - mounts[m.Destination] = mount.Mount{ - Type: m.Type, - Source: src, - Target: m.Destination, - ReadOnly: !m.RW, - } - } - s.Volumes = volumes - } - } - - mounts, err := fillBindMounts(p, s, mounts) - if err != nil { - return nil, err - } - - values := make([]mount.Mount, 0, len(mounts)) - for _, v := range mounts { - values = append(values, v) - } - return values, nil -} - -func fillBindMounts(p types.Project, s types.ServiceConfig, m map[string]mount.Mount) (map[string]mount.Mount, error) { - for _, v := range s.Volumes { - bindMount, err := buildMount(p, v) - if err != nil { - return nil, err - } - m[bindMount.Target] = bindMount - } - - secrets, err := buildContainerSecretMounts(p, s) - if err != nil { - return nil, err - } - for _, s := range secrets { - if _, found := m[s.Target]; found { - continue - } - m[s.Target] = s - } - - configs, err := buildContainerConfigMounts(p, s) - if err != nil { - return nil, err - } - for _, c := range configs { - if _, found := m[c.Target]; found { - continue - } - m[c.Target] = c - } - return m, nil -} - -func buildContainerConfigMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) { - var mounts = map[string]mount.Mount{} - - configsBaseDir := "/" - for _, config := range s.Configs { - target := config.Target - if config.Target == "" { - target = configsBaseDir + config.Source - } else if !isAbsTarget(config.Target) { - target = configsBaseDir + config.Target - } - - definedConfig := p.Configs[config.Source] - if definedConfig.External.External { - return nil, fmt.Errorf("unsupported external config %s", definedConfig.Name) - } - - bindMount, err := buildMount(p, types.ServiceVolumeConfig{ - Type: types.VolumeTypeBind, - Source: definedConfig.File, - Target: target, - ReadOnly: true, - }) - if err != nil { - return nil, err - } - mounts[target] = bindMount - } - values := make([]mount.Mount, 0, len(mounts)) - for _, v := range mounts { - values = append(values, v) - } - return values, nil -} - -func buildContainerSecretMounts(p types.Project, s types.ServiceConfig) ([]mount.Mount, error) { - var mounts = map[string]mount.Mount{} - - secretsDir := "/run/secrets/" - for _, secret := range s.Secrets { - target := secret.Target - if secret.Target == "" { - target = secretsDir + secret.Source - } else if !isAbsTarget(secret.Target) { - target = secretsDir + secret.Target - } - - definedSecret := p.Secrets[secret.Source] - if definedSecret.External.External { - return nil, fmt.Errorf("unsupported external secret %s", definedSecret.Name) - } - - if definedSecret.Environment != "" { - continue - } - - mnt, err := buildMount(p, types.ServiceVolumeConfig{ - Type: types.VolumeTypeBind, - Source: definedSecret.File, - Target: target, - ReadOnly: true, - }) - if err != nil { - return nil, err - } - mounts[target] = mnt - } - values := make([]mount.Mount, 0, len(mounts)) - for _, v := range mounts { - values = append(values, v) - } - return values, nil -} - -func isAbsTarget(p string) bool { - return isUnixAbs(p) || isWindowsAbs(p) -} - -func isUnixAbs(p string) bool { - return strings.HasPrefix(p, "/") -} - -func isWindowsAbs(p string) bool { - if strings.HasPrefix(p, "\\\\") { - return true - } - if len(p) > 2 && p[1] == ':' { - return p[2] == '\\' - } - return false -} - -func buildMount(project types.Project, volume types.ServiceVolumeConfig) (mount.Mount, error) { - source := volume.Source - // on windows, filepath.IsAbs(source) is false for unix style abs path like /var/run/docker.sock. - // do not replace these with filepath.Abs(source) that will include a default drive. - if volume.Type == types.VolumeTypeBind && !filepath.IsAbs(source) && !strings.HasPrefix(source, "/") { - // volume source has already been prefixed with workdir if required, by compose-go project loader - var err error - source, err = filepath.Abs(source) - if err != nil { - return mount.Mount{}, err - } - } - if volume.Type == types.VolumeTypeVolume { - if volume.Source != "" { - pVolume, ok := project.Volumes[volume.Source] - if ok { - source = pVolume.Name - } - } - } - - bind, vol, tmpfs := buildMountOptions(project, volume) - - volume.Target = path.Clean(volume.Target) - - if bind != nil { - volume.Type = types.VolumeTypeBind - } - - return mount.Mount{ - Type: mount.Type(volume.Type), - Source: source, - Target: volume.Target, - ReadOnly: volume.ReadOnly, - Consistency: mount.Consistency(volume.Consistency), - BindOptions: bind, - VolumeOptions: vol, - TmpfsOptions: tmpfs, - }, nil -} - -func buildMountOptions(project types.Project, volume types.ServiceVolumeConfig) (*mount.BindOptions, *mount.VolumeOptions, *mount.TmpfsOptions) { - switch volume.Type { - case "bind": - if volume.Volume != nil { - logrus.Warnf("mount of type `bind` should not define `volume` option") - } - if volume.Tmpfs != nil { - logrus.Warnf("mount of type `bind` should not define `tmpfs` option") - } - return buildBindOption(volume.Bind), nil, nil - case "volume": - if volume.Bind != nil { - logrus.Warnf("mount of type `volume` should not define `bind` option") - } - if volume.Tmpfs != nil { - logrus.Warnf("mount of type `volume` should not define `tmpfs` option") - } - if v, ok := project.Volumes[volume.Source]; ok && v.DriverOpts["o"] == types.VolumeTypeBind { - return buildBindOption(&types.ServiceVolumeBind{ - CreateHostPath: true, - }), nil, nil - } - return nil, buildVolumeOptions(volume.Volume), nil - case "tmpfs": - if volume.Bind != nil { - logrus.Warnf("mount of type `tmpfs` should not define `bind` option") - } - if volume.Volume != nil { - logrus.Warnf("mount of type `tmpfs` should not define `volume` option") - } - return nil, nil, buildTmpfsOptions(volume.Tmpfs) - } - return nil, nil, nil -} - -func buildBindOption(bind *types.ServiceVolumeBind) *mount.BindOptions { - if bind == nil { - return nil - } - return &mount.BindOptions{ - Propagation: mount.Propagation(bind.Propagation), - // NonRecursive: false, FIXME missing from model ? - } -} - -func buildVolumeOptions(vol *types.ServiceVolumeVolume) *mount.VolumeOptions { - if vol == nil { - return nil - } - return &mount.VolumeOptions{ - NoCopy: vol.NoCopy, - // Labels: , // FIXME missing from model ? - // DriverConfig: , // FIXME missing from model ? - } -} - -func buildTmpfsOptions(tmpfs *types.ServiceVolumeTmpfs) *mount.TmpfsOptions { - if tmpfs == nil { - return nil - } - return &mount.TmpfsOptions{ - SizeBytes: int64(tmpfs.Size), - Mode: os.FileMode(tmpfs.Mode), - } -} - -func (s *composeService) ensureNetwork(ctx context.Context, n *types.NetworkConfig) error { - if n.External.External { - return s.resolveExternalNetwork(ctx, n) - } - - err := s.resolveOrCreateNetwork(ctx, n) - if errdefs.IsConflict(err) { - // Maybe another execution of `docker compose up|run` created same network - // let's retry once - return s.resolveOrCreateNetwork(ctx, n) - } - return err -} - -func (s *composeService) resolveOrCreateNetwork(ctx context.Context, n *types.NetworkConfig) error { //nolint:gocyclo - expectedNetworkLabel := n.Labels[api.NetworkLabel] - expectedProjectLabel := n.Labels[api.ProjectLabel] - - // First, try to find a unique network matching by name or ID - inspect, err := s.apiClient().NetworkInspect(ctx, n.Name, moby.NetworkInspectOptions{}) - if err == nil { - // NetworkInspect will match on ID prefix, so double check we get the expected one - // as looking for network named `db` we could erroneously matched network ID `db9086999caf` - if inspect.Name == n.Name || inspect.ID == n.Name { - p, ok := inspect.Labels[api.ProjectLabel] - if !ok { - logrus.Warnf("a network with name %s exists but was not created by compose.\n"+ - "Set `external: true` to use an existing network", n.Name) - } else if p != expectedProjectLabel { - logrus.Warnf("a network with name %s exists but was not created for project %q.\n"+ - "Set `external: true` to use an existing network", n.Name, expectedProjectLabel) - } - if inspect.Labels[api.NetworkLabel] != expectedNetworkLabel { - return fmt.Errorf("network %s was found but has incorrect label %s set to %q", n.Name, api.NetworkLabel, inspect.Labels[api.NetworkLabel]) - } - return nil - } - } - // ignore other errors. Typically, an ambiguous request by name results in some generic `invalidParameter` error - - // Either not found, or name is ambiguous - use NetworkList to list by name - networks, err := s.apiClient().NetworkList(ctx, moby.NetworkListOptions{ - Filters: filters.NewArgs(filters.Arg("name", n.Name)), - }) - if err != nil { - return err - } - - // NetworkList Matches all or part of a network name, so we have to filter for a strict match - networks = utils.Filter(networks, func(net moby.NetworkResource) bool { - return net.Name == n.Name - }) - - for _, net := range networks { - if net.Labels[api.ProjectLabel] == expectedProjectLabel && - net.Labels[api.NetworkLabel] == expectedNetworkLabel { - return nil - } - } - - // we could have set NetworkList with a projectFilter and networkFilter but not doing so allows to catch this - // scenario were a network with same name exists but doesn't have label, and use of `CheckDuplicate: true` - // prevents to create another one. - if len(networks) > 0 { - logrus.Warnf("a network with name %s exists but was not created by compose.\n"+ - "Set `external: true` to use an existing network", n.Name) - return nil - } - - var ipam *network.IPAM - if n.Ipam.Config != nil { - var config []network.IPAMConfig - for _, pool := range n.Ipam.Config { - config = append(config, network.IPAMConfig{ - Subnet: pool.Subnet, - IPRange: pool.IPRange, - Gateway: pool.Gateway, - AuxAddress: pool.AuxiliaryAddresses, - }) - } - ipam = &network.IPAM{ - Driver: n.Ipam.Driver, - Config: config, - } - } - createOpts := moby.NetworkCreate{ - CheckDuplicate: true, - Labels: n.Labels, - Driver: n.Driver, - Options: n.DriverOpts, - Internal: n.Internal, - Attachable: n.Attachable, - IPAM: ipam, - EnableIPv6: n.EnableIPv6, - } - - if n.Ipam.Driver != "" || len(n.Ipam.Config) > 0 { - createOpts.IPAM = &network.IPAM{} - } - - if n.Ipam.Driver != "" { - createOpts.IPAM.Driver = n.Ipam.Driver - } - - for _, ipamConfig := range n.Ipam.Config { - config := network.IPAMConfig{ - Subnet: ipamConfig.Subnet, - IPRange: ipamConfig.IPRange, - Gateway: ipamConfig.Gateway, - AuxAddress: ipamConfig.AuxiliaryAddresses, - } - createOpts.IPAM.Config = append(createOpts.IPAM.Config, config) - } - networkEventName := fmt.Sprintf("Network %s", n.Name) - w := progress.ContextWriter(ctx) - w.Event(progress.CreatingEvent(networkEventName)) - - _, err = s.apiClient().NetworkCreate(ctx, n.Name, createOpts) - if err != nil { - w.Event(progress.ErrorEvent(networkEventName)) - return errors.Wrapf(err, "failed to create network %s", n.Name) - } - w.Event(progress.CreatedEvent(networkEventName)) - return nil -} - -func (s *composeService) resolveExternalNetwork(ctx context.Context, n *types.NetworkConfig) error { - // NetworkInspect will match on ID prefix, so NetworkList with a name - // filter is used to look for an exact match to prevent e.g. a network - // named `db` from getting erroneously matched to a network with an ID - // like `db9086999caf` - networks, err := s.apiClient().NetworkList(ctx, moby.NetworkListOptions{ - Filters: filters.NewArgs(filters.Arg("name", n.Name)), - }) - if err != nil { - return err - } - - // NetworkList API doesn't return the exact name match, so we can retrieve more than one network with a request - networks = utils.Filter(networks, func(net moby.NetworkResource) bool { - return net.Name == n.Name - }) - - switch len(networks) { - case 1: - n.Name = networks[0].ID - return nil - case 0: - if n.Driver == "overlay" { - // Swarm nodes do not register overlay networks that were - // created on a different node unless they're in use. - // Here we assume `driver` is relevant for a network we don't manage - // which is a non-sense, but this is our legacy ¯\(ツ)/¯ - // networkAttach will later fail anyway if network actually doesn't exists - enabled, err := s.isSWarmEnabled(ctx) - if err != nil { - return err - } - if enabled { - return nil - } - } - return fmt.Errorf("network %s declared as external, but could not be found", n.Name) - default: - return fmt.Errorf("multiple networks with name %q were found. Use network ID as `name` to avoid ambiguity", n.Name) - } -} - -func (s *composeService) ensureVolume(ctx context.Context, volume types.VolumeConfig, project string) error { - inspected, err := s.apiClient().VolumeInspect(ctx, volume.Name) - if err != nil { - if !errdefs.IsNotFound(err) { - return err - } - if volume.External.External { - return fmt.Errorf("external volume %q not found", volume.Name) - } - err := s.createVolume(ctx, volume) - return err - } - - if volume.External.External { - return nil - } - - // Volume exists with name, but let's double-check this is the expected one - p, ok := inspected.Labels[api.ProjectLabel] - if !ok { - logrus.Warnf("volume %q already exists but was not created by Docker Compose. Use `external: true` to use an existing volume", volume.Name) - } - if ok && p != project { - logrus.Warnf("volume %q already exists but was created for project %q (expected %q). Use `external: true` to use an existing volume", volume.Name, p, project) - } - return nil -} - -func (s *composeService) createVolume(ctx context.Context, volume types.VolumeConfig) error { - eventName := fmt.Sprintf("Volume %q", volume.Name) - w := progress.ContextWriter(ctx) - w.Event(progress.CreatingEvent(eventName)) - _, err := s.apiClient().VolumeCreate(ctx, volume_api.CreateOptions{ - Labels: volume.Labels, - Name: volume.Name, - Driver: volume.Driver, - DriverOpts: volume.DriverOpts, - }) - if err != nil { - w.Event(progress.ErrorEvent(eventName)) - return err - } - w.Event(progress.CreatedEvent(eventName)) - return nil -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/dependencies.go b/vendor/github.com/docker/compose/v2/pkg/compose/dependencies.go deleted file mode 100644 index 5205b30e0..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/dependencies.go +++ /dev/null @@ -1,481 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "fmt" - "strings" - "sync" - - "github.com/compose-spec/compose-go/types" - "github.com/docker/compose/v2/pkg/api" - "github.com/pkg/errors" - "golang.org/x/sync/errgroup" - - "github.com/docker/compose/v2/pkg/utils" -) - -// ServiceStatus indicates the status of a service -type ServiceStatus int - -// Services status flags -const ( - ServiceStopped ServiceStatus = iota - ServiceStarted -) - -type graphTraversal struct { - mu sync.Mutex - seen map[string]struct{} - ignored map[string]struct{} - - extremityNodesFn func(*Graph) []*Vertex // leaves or roots - adjacentNodesFn func(*Vertex) []*Vertex // getParents or getChildren - filterAdjacentByStatusFn func(*Graph, string, ServiceStatus) []*Vertex // filterChildren or filterParents - targetServiceStatus ServiceStatus - adjacentServiceStatusToSkip ServiceStatus - - visitorFn func(context.Context, string) error - maxConcurrency int -} - -func upDirectionTraversal(visitorFn func(context.Context, string) error) *graphTraversal { - return &graphTraversal{ - extremityNodesFn: leaves, - adjacentNodesFn: getParents, - filterAdjacentByStatusFn: filterChildren, - adjacentServiceStatusToSkip: ServiceStopped, - targetServiceStatus: ServiceStarted, - visitorFn: visitorFn, - } -} - -func downDirectionTraversal(visitorFn func(context.Context, string) error) *graphTraversal { - return &graphTraversal{ - extremityNodesFn: roots, - adjacentNodesFn: getChildren, - filterAdjacentByStatusFn: filterParents, - adjacentServiceStatusToSkip: ServiceStarted, - targetServiceStatus: ServiceStopped, - visitorFn: visitorFn, - } -} - -// InDependencyOrder applies the function to the services of the project taking in account the dependency order -func InDependencyOrder(ctx context.Context, project *types.Project, fn func(context.Context, string) error, options ...func(*graphTraversal)) error { - graph, err := NewGraph(project, ServiceStopped) - if err != nil { - return err - } - t := upDirectionTraversal(fn) - for _, option := range options { - option(t) - } - return t.visit(ctx, graph) -} - -// InReverseDependencyOrder applies the function to the services of the project in reverse order of dependencies -func InReverseDependencyOrder(ctx context.Context, project *types.Project, fn func(context.Context, string) error, options ...func(*graphTraversal)) error { - graph, err := NewGraph(project, ServiceStarted) - if err != nil { - return err - } - t := downDirectionTraversal(fn) - for _, option := range options { - option(t) - } - return t.visit(ctx, graph) -} - -func WithRootNodesAndDown(nodes []string) func(*graphTraversal) { - return func(t *graphTraversal) { - if len(nodes) == 0 { - return - } - originalFn := t.extremityNodesFn - t.extremityNodesFn = func(graph *Graph) []*Vertex { - var want []string - for _, node := range nodes { - vertex := graph.Vertices[node] - want = append(want, vertex.Service) - for _, v := range getAncestors(vertex) { - want = append(want, v.Service) - } - } - - t.ignored = map[string]struct{}{} - for k := range graph.Vertices { - if !utils.Contains(want, k) { - t.ignored[k] = struct{}{} - } - } - - return originalFn(graph) - } - } -} - -func (t *graphTraversal) visit(ctx context.Context, g *Graph) error { - expect := len(g.Vertices) - if expect == 0 { - return nil - } - - eg, ctx := errgroup.WithContext(ctx) - if t.maxConcurrency > 0 { - eg.SetLimit(t.maxConcurrency + 1) - } - nodeCh := make(chan *Vertex, expect) - defer close(nodeCh) - // nodeCh need to allow n=expect writers while reader goroutine could have returner after ctx.Done - eg.Go(func() error { - for { - select { - case <-ctx.Done(): - return nil - case node := <-nodeCh: - expect-- - if expect == 0 { - return nil - } - t.run(ctx, g, eg, t.adjacentNodesFn(node), nodeCh) - } - } - }) - - nodes := t.extremityNodesFn(g) - t.run(ctx, g, eg, nodes, nodeCh) - - return eg.Wait() -} - -// Note: this could be `graph.walk` or whatever -func (t *graphTraversal) run(ctx context.Context, graph *Graph, eg *errgroup.Group, nodes []*Vertex, nodeCh chan *Vertex) { - for _, node := range nodes { - // Don't start this service yet if all of its children have - // not been started yet. - if len(t.filterAdjacentByStatusFn(graph, node.Key, t.adjacentServiceStatusToSkip)) != 0 { - continue - } - - node := node - if !t.consume(node.Key) { - // another worker already visited this node - continue - } - - eg.Go(func() error { - var err error - if _, ignore := t.ignored[node.Service]; !ignore { - err = t.visitorFn(ctx, node.Service) - } - if err == nil { - graph.UpdateStatus(node.Key, t.targetServiceStatus) - } - nodeCh <- node - return err - }) - } -} - -func (t *graphTraversal) consume(nodeKey string) bool { - t.mu.Lock() - defer t.mu.Unlock() - if t.seen == nil { - t.seen = make(map[string]struct{}) - } - if _, ok := t.seen[nodeKey]; ok { - return false - } - t.seen[nodeKey] = struct{}{} - return true -} - -// Graph represents project as service dependencies -type Graph struct { - Vertices map[string]*Vertex - lock sync.RWMutex -} - -// Vertex represents a service in the dependencies structure -type Vertex struct { - Key string - Service string - Status ServiceStatus - Children map[string]*Vertex - Parents map[string]*Vertex -} - -func getParents(v *Vertex) []*Vertex { - return v.GetParents() -} - -// GetParents returns a slice with the parent vertices of the a Vertex -func (v *Vertex) GetParents() []*Vertex { - var res []*Vertex - for _, p := range v.Parents { - res = append(res, p) - } - return res -} - -func getChildren(v *Vertex) []*Vertex { - return v.GetChildren() -} - -// getAncestors return all descendents for a vertex, might contain duplicates -func getAncestors(v *Vertex) []*Vertex { - var descendents []*Vertex - for _, parent := range v.GetParents() { - descendents = append(descendents, parent) - descendents = append(descendents, getAncestors(parent)...) - } - return descendents -} - -// GetChildren returns a slice with the child vertices of the a Vertex -func (v *Vertex) GetChildren() []*Vertex { - var res []*Vertex - for _, p := range v.Children { - res = append(res, p) - } - return res -} - -// NewGraph returns the dependency graph of the services -func NewGraph(project *types.Project, initialStatus ServiceStatus) (*Graph, error) { - graph := &Graph{ - lock: sync.RWMutex{}, - Vertices: map[string]*Vertex{}, - } - - for _, s := range project.Services { - graph.AddVertex(s.Name, s.Name, initialStatus) - } - - for index, s := range project.Services { - for _, name := range s.GetDependencies() { - err := graph.AddEdge(s.Name, name) - if err != nil { - if !s.DependsOn[name].Required { - delete(s.DependsOn, name) - project.Services[index] = s - continue - } - if api.IsNotFoundError(err) { - ds, err := project.GetDisabledService(name) - if err == nil { - return nil, fmt.Errorf("service %s is required by %s but is disabled. Can be enabled by profiles %s", name, s.Name, ds.Profiles) - } - } - return nil, err - } - } - } - - if b, err := graph.HasCycles(); b { - return nil, err - } - - return graph, nil -} - -// NewVertex is the constructor function for the Vertex -func NewVertex(key string, service string, initialStatus ServiceStatus) *Vertex { - return &Vertex{ - Key: key, - Service: service, - Status: initialStatus, - Parents: map[string]*Vertex{}, - Children: map[string]*Vertex{}, - } -} - -// AddVertex adds a vertex to the Graph -func (g *Graph) AddVertex(key string, service string, initialStatus ServiceStatus) { - g.lock.Lock() - defer g.lock.Unlock() - - v := NewVertex(key, service, initialStatus) - g.Vertices[key] = v -} - -// AddEdge adds a relationship of dependency between vertices `source` and `destination` -func (g *Graph) AddEdge(source string, destination string) error { - g.lock.Lock() - defer g.lock.Unlock() - - sourceVertex := g.Vertices[source] - destinationVertex := g.Vertices[destination] - - if sourceVertex == nil { - return errors.Wrapf(api.ErrNotFound, "could not find %s", source) - } - if destinationVertex == nil { - return errors.Wrapf(api.ErrNotFound, "could not find %s", destination) - } - - // If they are already connected - if _, ok := sourceVertex.Children[destination]; ok { - return nil - } - - sourceVertex.Children[destination] = destinationVertex - destinationVertex.Parents[source] = sourceVertex - - return nil -} - -func leaves(g *Graph) []*Vertex { - return g.Leaves() -} - -// Leaves returns the slice of leaves of the graph -func (g *Graph) Leaves() []*Vertex { - g.lock.Lock() - defer g.lock.Unlock() - - var res []*Vertex - for _, v := range g.Vertices { - if len(v.Children) == 0 { - res = append(res, v) - } - } - - return res -} - -func roots(g *Graph) []*Vertex { - return g.Roots() -} - -// Roots returns the slice of "Roots" of the graph -func (g *Graph) Roots() []*Vertex { - g.lock.Lock() - defer g.lock.Unlock() - - var res []*Vertex - for _, v := range g.Vertices { - if len(v.Parents) == 0 { - res = append(res, v) - } - } - return res -} - -// UpdateStatus updates the status of a certain vertex -func (g *Graph) UpdateStatus(key string, status ServiceStatus) { - g.lock.Lock() - defer g.lock.Unlock() - g.Vertices[key].Status = status -} - -func filterChildren(g *Graph, k string, s ServiceStatus) []*Vertex { - return g.FilterChildren(k, s) -} - -// FilterChildren returns children of a certain vertex that are in a certain status -func (g *Graph) FilterChildren(key string, status ServiceStatus) []*Vertex { - g.lock.Lock() - defer g.lock.Unlock() - - var res []*Vertex - vertex := g.Vertices[key] - - for _, child := range vertex.Children { - if child.Status == status { - res = append(res, child) - } - } - - return res -} - -func filterParents(g *Graph, k string, s ServiceStatus) []*Vertex { - return g.FilterParents(k, s) -} - -// FilterParents returns the parents of a certain vertex that are in a certain status -func (g *Graph) FilterParents(key string, status ServiceStatus) []*Vertex { - g.lock.Lock() - defer g.lock.Unlock() - - var res []*Vertex - vertex := g.Vertices[key] - - for _, parent := range vertex.Parents { - if parent.Status == status { - res = append(res, parent) - } - } - - return res -} - -// HasCycles detects cycles in the graph -func (g *Graph) HasCycles() (bool, error) { - discovered := []string{} - finished := []string{} - - for _, vertex := range g.Vertices { - path := []string{ - vertex.Key, - } - if !utils.StringContains(discovered, vertex.Key) && !utils.StringContains(finished, vertex.Key) { - var err error - discovered, finished, err = g.visit(vertex.Key, path, discovered, finished) - - if err != nil { - return true, err - } - } - } - - return false, nil -} - -func (g *Graph) visit(key string, path []string, discovered []string, finished []string) ([]string, []string, error) { - discovered = append(discovered, key) - - for _, v := range g.Vertices[key].Children { - path := append(path, v.Key) - if utils.StringContains(discovered, v.Key) { - return nil, nil, fmt.Errorf("cycle found: %s", strings.Join(path, " -> ")) - } - - if !utils.StringContains(finished, v.Key) { - if _, _, err := g.visit(v.Key, path, discovered, finished); err != nil { - return nil, nil, err - } - } - } - - discovered = remove(discovered, key) - finished = append(finished, key) - return discovered, finished, nil -} - -func remove(slice []string, item string) []string { - var s []string - for _, i := range slice { - if i != item { - s = append(s, i) - } - } - return s -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/down.go b/vendor/github.com/docker/compose/v2/pkg/compose/down.go deleted file mode 100644 index 3f5910c6e..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/down.go +++ /dev/null @@ -1,352 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "fmt" - "strings" - "time" - - "github.com/docker/compose/v2/pkg/utils" - - "github.com/compose-spec/compose-go/types" - moby "github.com/docker/docker/api/types" - containerType "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/errdefs" - "github.com/pkg/errors" - "golang.org/x/sync/errgroup" - - "github.com/docker/compose/v2/pkg/api" - "github.com/docker/compose/v2/pkg/progress" -) - -type downOp func() error - -func (s *composeService) Down(ctx context.Context, projectName string, options api.DownOptions) error { - return progress.Run(ctx, func(ctx context.Context) error { - return s.down(ctx, strings.ToLower(projectName), options) - }, s.stdinfo()) -} - -func (s *composeService) down(ctx context.Context, projectName string, options api.DownOptions) error { //nolint:gocyclo - w := progress.ContextWriter(ctx) - resourceToRemove := false - - include := oneOffExclude - if options.RemoveOrphans { - include = oneOffInclude - } - containers, err := s.getContainers(ctx, projectName, include, true) - if err != nil { - return err - } - - project := options.Project - if project == nil { - project, err = s.getProjectWithResources(ctx, containers, projectName) - if err != nil { - return err - } - } - - // Check requested services exists in model - options.Services, err = checkSelectedServices(options, project) - if err != nil { - return err - } - - if len(containers) > 0 { - resourceToRemove = true - } - - err = InReverseDependencyOrder(ctx, project, func(c context.Context, service string) error { - serviceContainers := containers.filter(isService(service)) - err := s.removeContainers(ctx, w, serviceContainers, options.Timeout, options.Volumes) - return err - }, WithRootNodesAndDown(options.Services)) - if err != nil { - return err - } - - orphans := containers.filter(isNotService(project.ServiceNames()...)) - if options.RemoveOrphans && len(orphans) > 0 { - err := s.removeContainers(ctx, w, orphans, options.Timeout, false) - if err != nil { - return err - } - } - - ops := s.ensureNetworksDown(ctx, project, w) - - if options.Images != "" { - imgOps, err := s.ensureImagesDown(ctx, project, options, w) - if err != nil { - return err - } - ops = append(ops, imgOps...) - } - - if options.Volumes { - ops = append(ops, s.ensureVolumesDown(ctx, project, w)...) - } - - if !resourceToRemove && len(ops) == 0 { - fmt.Fprintf(s.stderr(), "Warning: No resource found to remove for project %q.\n", projectName) - } - - eg, _ := errgroup.WithContext(ctx) - for _, op := range ops { - eg.Go(op) - } - return eg.Wait() -} - -func checkSelectedServices(options api.DownOptions, project *types.Project) ([]string, error) { - var services []string - for _, service := range options.Services { - _, err := project.GetService(service) - if err != nil { - if options.Project != nil { - // ran with an explicit compose.yaml file, so we should not ignore - return nil, err - } - // ran without an explicit compose.yaml file, so can't distinguish typo vs container already removed - } else { - services = append(services, service) - } - } - return services, nil -} - -func (s *composeService) ensureVolumesDown(ctx context.Context, project *types.Project, w progress.Writer) []downOp { - var ops []downOp - for _, vol := range project.Volumes { - if vol.External.External { - continue - } - volumeName := vol.Name - ops = append(ops, func() error { - return s.removeVolume(ctx, volumeName, w) - }) - } - return ops -} - -func (s *composeService) ensureImagesDown(ctx context.Context, project *types.Project, options api.DownOptions, w progress.Writer) ([]downOp, error) { - imagePruner := NewImagePruner(s.apiClient(), project) - pruneOpts := ImagePruneOptions{ - Mode: ImagePruneMode(options.Images), - RemoveOrphans: options.RemoveOrphans, - } - images, err := imagePruner.ImagesToPrune(ctx, pruneOpts) - if err != nil { - return nil, err - } - - var ops []downOp - for i := range images { - img := images[i] - ops = append(ops, func() error { - return s.removeImage(ctx, img, w) - }) - } - return ops, nil -} - -func (s *composeService) ensureNetworksDown(ctx context.Context, project *types.Project, w progress.Writer) []downOp { - var ops []downOp - for key, n := range project.Networks { - if n.External.External { - continue - } - // loop capture variable for op closure - networkKey := key - idOrName := n.Name - ops = append(ops, func() error { - return s.removeNetwork(ctx, networkKey, project.Name, idOrName, w) - }) - } - return ops -} - -func (s *composeService) removeNetwork(ctx context.Context, composeNetworkName string, projectName string, name string, w progress.Writer) error { - networks, err := s.apiClient().NetworkList(ctx, moby.NetworkListOptions{ - Filters: filters.NewArgs( - projectFilter(projectName), - networkFilter(composeNetworkName)), - }) - if err != nil { - return errors.Wrapf(err, "failed to list networks") - } - - if len(networks) == 0 { - return nil - } - - eventName := fmt.Sprintf("Network %s", name) - w.Event(progress.RemovingEvent(eventName)) - - var found int - for _, net := range networks { - if net.Name != name { - continue - } - network, err := s.apiClient().NetworkInspect(ctx, net.ID, moby.NetworkInspectOptions{}) - if errdefs.IsNotFound(err) { - w.Event(progress.NewEvent(eventName, progress.Warning, "No resource found to remove")) - return nil - } - if err != nil { - return err - } - if len(network.Containers) > 0 { - w.Event(progress.NewEvent(eventName, progress.Warning, "Resource is still in use")) - found++ - continue - } - - if err := s.apiClient().NetworkRemove(ctx, net.ID); err != nil { - if errdefs.IsNotFound(err) { - continue - } - w.Event(progress.ErrorEvent(eventName)) - return errors.Wrapf(err, fmt.Sprintf("failed to remove network %s", name)) - } - w.Event(progress.RemovedEvent(eventName)) - found++ - } - - if found == 0 { - // in practice, it's extremely unlikely for this to ever occur, as it'd - // mean the network was present when we queried at the start of this - // method but was then deleted by something else in the interim - w.Event(progress.NewEvent(eventName, progress.Warning, "No resource found to remove")) - return nil - } - return nil -} - -func (s *composeService) removeImage(ctx context.Context, image string, w progress.Writer) error { - id := fmt.Sprintf("Image %s", image) - w.Event(progress.NewEvent(id, progress.Working, "Removing")) - _, err := s.apiClient().ImageRemove(ctx, image, moby.ImageRemoveOptions{}) - if err == nil { - w.Event(progress.NewEvent(id, progress.Done, "Removed")) - return nil - } - if errdefs.IsConflict(err) { - w.Event(progress.NewEvent(id, progress.Warning, "Resource is still in use")) - return nil - } - if errdefs.IsNotFound(err) { - w.Event(progress.NewEvent(id, progress.Done, "Warning: No resource found to remove")) - return nil - } - return err -} - -func (s *composeService) removeVolume(ctx context.Context, id string, w progress.Writer) error { - resource := fmt.Sprintf("Volume %s", id) - w.Event(progress.NewEvent(resource, progress.Working, "Removing")) - err := s.apiClient().VolumeRemove(ctx, id, true) - if err == nil { - w.Event(progress.NewEvent(resource, progress.Done, "Removed")) - return nil - } - if errdefs.IsConflict(err) { - w.Event(progress.NewEvent(resource, progress.Warning, "Resource is still in use")) - return nil - } - if errdefs.IsNotFound(err) { - w.Event(progress.NewEvent(resource, progress.Done, "Warning: No resource found to remove")) - return nil - } - return err -} - -func (s *composeService) stopContainer(ctx context.Context, w progress.Writer, container moby.Container, timeout *time.Duration) error { - eventName := getContainerProgressName(container) - w.Event(progress.StoppingEvent(eventName)) - timeoutInSecond := utils.DurationSecondToInt(timeout) - err := s.apiClient().ContainerStop(ctx, container.ID, containerType.StopOptions{Timeout: timeoutInSecond}) - if err != nil { - w.Event(progress.ErrorMessageEvent(eventName, "Error while Stopping")) - return err - } - w.Event(progress.StoppedEvent(eventName)) - return nil -} - -func (s *composeService) stopContainers(ctx context.Context, w progress.Writer, containers []moby.Container, timeout *time.Duration) error { - eg, ctx := errgroup.WithContext(ctx) - for _, container := range containers { - container := container - eg.Go(func() error { - return s.stopContainer(ctx, w, container, timeout) - }) - } - return eg.Wait() -} - -func (s *composeService) removeContainers(ctx context.Context, w progress.Writer, containers []moby.Container, timeout *time.Duration, volumes bool) error { - eg, _ := errgroup.WithContext(ctx) - for _, container := range containers { - container := container - eg.Go(func() error { - eventName := getContainerProgressName(container) - err := s.stopContainer(ctx, w, container, timeout) - if err != nil { - return err - } - w.Event(progress.RemovingEvent(eventName)) - err = s.apiClient().ContainerRemove(ctx, container.ID, moby.ContainerRemoveOptions{ - Force: true, - RemoveVolumes: volumes, - }) - if err != nil && !errdefs.IsNotFound(err) && !errdefs.IsConflict(err) { - w.Event(progress.ErrorMessageEvent(eventName, "Error while Removing")) - return err - } - w.Event(progress.RemovedEvent(eventName)) - return nil - }) - } - return eg.Wait() -} - -func (s *composeService) getProjectWithResources(ctx context.Context, containers Containers, projectName string) (*types.Project, error) { - containers = containers.filter(isNotOneOff) - project, err := s.projectFromName(containers, projectName) - if err != nil && !api.IsNotFoundError(err) { - return nil, err - } - - volumes, err := s.actualVolumes(ctx, projectName) - if err != nil { - return nil, err - } - project.Volumes = volumes - - networks, err := s.actualNetworks(ctx, projectName) - if err != nil { - return nil, err - } - project.Networks = networks - return project, nil -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/envresolver.go b/vendor/github.com/docker/compose/v2/pkg/compose/envresolver.go deleted file mode 100644 index 0d12c3dc5..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/envresolver.go +++ /dev/null @@ -1,68 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "runtime" - "strings" -) - -var ( - // isCaseInsensitiveEnvVars is true on platforms where environment variable names are treated case-insensitively. - isCaseInsensitiveEnvVars = (runtime.GOOS == "windows") -) - -// envResolver returns resolver for environment variables suitable for the current platform. -// Expected to be used with `MappingWithEquals.Resolve`. -// Updates in `environment` may not be reflected. -func envResolver(environment map[string]string) func(string) (string, bool) { - return envResolverWithCase(environment, isCaseInsensitiveEnvVars) -} - -// envResolverWithCase returns resolver for environment variables with the specified case-sensitive condition. -// Expected to be used with `MappingWithEquals.Resolve`. -// Updates in `environment` may not be reflected. -func envResolverWithCase(environment map[string]string, caseInsensitive bool) func(string) (string, bool) { - if environment == nil { - return func(s string) (string, bool) { - return "", false - } - } - if !caseInsensitive { - return func(s string) (string, bool) { - v, ok := environment[s] - return v, ok - } - } - // variable names must be treated case-insensitively. - // Resolves in this way: - // * Return the value if its name matches with the passed name case-sensitively. - // * Otherwise, return the value if its lower-cased name matches lower-cased passed name. - // * The value is indefinite if multiple variable matches. - loweredEnvironment := make(map[string]string, len(environment)) - for k, v := range environment { - loweredEnvironment[strings.ToLower(k)] = v - } - return func(s string) (string, bool) { - v, ok := environment[s] - if ok { - return v, ok - } - v, ok = loweredEnvironment[strings.ToLower(s)] - return v, ok - } -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/errors.go b/vendor/github.com/docker/compose/v2/pkg/compose/errors.go deleted file mode 100644 index d97fe713d..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/errors.go +++ /dev/null @@ -1,72 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "io/fs" - - "github.com/pkg/errors" - - "github.com/compose-spec/compose-go/errdefs" -) - -// Error error to categorize failures and extract metrics info -type Error struct { - Err error - Category *FailureCategory -} - -// WrapComposeError wraps the error if not nil, otherwise returns nil -func WrapComposeError(err error) error { - if err == nil { - return nil - } - return Error{ - Err: err, - } -} - -// WrapCategorisedComposeError wraps the error if not nil, otherwise returns nil -func WrapCategorisedComposeError(err error, failure FailureCategory) error { - if err == nil { - return nil - } - return Error{ - Err: err, - Category: &failure, - } -} - -// Unwrap get underlying error -func (e Error) Unwrap() error { return e.Err } - -func (e Error) Error() string { return e.Err.Error() } - -// GetMetricsFailureCategory get metrics status and error code corresponding to this error -func (e Error) GetMetricsFailureCategory() FailureCategory { - if e.Category != nil { - return *e.Category - } - var pathError *fs.PathError - if errors.As(e.Err, &pathError) { - return FileNotFoundFailure - } - if errdefs.IsNotFoundError(e.Err) { - return FileNotFoundFailure - } - return ComposeParseFailure -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/events.go b/vendor/github.com/docker/compose/v2/pkg/compose/events.go deleted file mode 100644 index e664133be..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/events.go +++ /dev/null @@ -1,81 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "strings" - "time" - - moby "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - - "github.com/docker/compose/v2/pkg/api" - "github.com/docker/compose/v2/pkg/utils" -) - -func (s *composeService) Events(ctx context.Context, projectName string, options api.EventsOptions) error { - projectName = strings.ToLower(projectName) - events, errors := s.apiClient().Events(ctx, moby.EventsOptions{ - Filters: filters.NewArgs(projectFilter(projectName)), - }) - for { - select { - case event := <-events: - // TODO: support other event types - if event.Type != "container" { - continue - } - - oneOff := event.Actor.Attributes[api.OneoffLabel] - if oneOff == "True" { - // ignore - continue - } - service := event.Actor.Attributes[api.ServiceLabel] - if len(options.Services) > 0 && !utils.StringContains(options.Services, service) { - continue - } - - attributes := map[string]string{} - for k, v := range event.Actor.Attributes { - if strings.HasPrefix(k, "com.docker.compose.") { - continue - } - attributes[k] = v - } - - timestamp := time.Unix(event.Time, 0) - if event.TimeNano != 0 { - timestamp = time.Unix(0, event.TimeNano) - } - err := options.Consumer(api.Event{ - Timestamp: timestamp, - Service: service, - Container: event.Actor.ID, - Status: event.Action, - Attributes: attributes, - }) - if err != nil { - return err - } - - case err := <-errors: - return err - } - } -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/exec.go b/vendor/github.com/docker/compose/v2/pkg/compose/exec.go deleted file mode 100644 index 6477ca06a..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/exec.go +++ /dev/null @@ -1,61 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "strings" - - "github.com/docker/cli/cli" - "github.com/docker/cli/cli/command/container" - "github.com/docker/compose/v2/pkg/api" - moby "github.com/docker/docker/api/types" -) - -func (s *composeService) Exec(ctx context.Context, projectName string, options api.RunOptions) (int, error) { - projectName = strings.ToLower(projectName) - target, err := s.getExecTarget(ctx, projectName, options) - if err != nil { - return 0, err - } - - exec := container.NewExecOptions() - exec.Interactive = options.Interactive - exec.TTY = options.Tty - exec.Detach = options.Detach - exec.User = options.User - exec.Privileged = options.Privileged - exec.Workdir = options.WorkingDir - exec.Container = target.ID - exec.Command = options.Command - for _, v := range options.Environment { - err := exec.Env.Set(v) - if err != nil { - return 0, err - } - } - - err = container.RunExec(s.dockerCli, exec) - if sterr, ok := err.(cli.StatusError); ok { - return sterr.StatusCode, nil - } - return 0, err -} - -func (s *composeService) getExecTarget(ctx context.Context, projectName string, opts api.RunOptions) (moby.Container, error) { - return s.getSpecifiedContainer(ctx, projectName, oneOffInclude, false, opts.Service, opts.Index) -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/filters.go b/vendor/github.com/docker/compose/v2/pkg/compose/filters.go deleted file mode 100644 index d6c814977..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/filters.go +++ /dev/null @@ -1,56 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "fmt" - - "github.com/docker/compose/v2/pkg/api" - "github.com/docker/docker/api/types/filters" -) - -func projectFilter(projectName string) filters.KeyValuePair { - return filters.Arg("label", fmt.Sprintf("%s=%s", api.ProjectLabel, projectName)) -} - -func serviceFilter(serviceName string) filters.KeyValuePair { - return filters.Arg("label", fmt.Sprintf("%s=%s", api.ServiceLabel, serviceName)) -} - -func networkFilter(name string) filters.KeyValuePair { - return filters.Arg("label", fmt.Sprintf("%s=%s", api.NetworkLabel, name)) -} - -func oneOffFilter(b bool) filters.KeyValuePair { - v := "False" - if b { - v = "True" - } - return filters.Arg("label", fmt.Sprintf("%s=%s", api.OneoffLabel, v)) -} - -func containerNumberFilter(index int) filters.KeyValuePair { - return filters.Arg("label", fmt.Sprintf("%s=%d", api.ContainerNumberLabel, index)) -} - -func hasProjectLabelFilter() filters.KeyValuePair { - return filters.Arg("label", api.ProjectLabel) -} - -func hasConfigHashLabel() filters.KeyValuePair { - return filters.Arg("label", api.ConfigHashLabel) -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/hash.go b/vendor/github.com/docker/compose/v2/pkg/compose/hash.go deleted file mode 100644 index c4a4c91a4..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/hash.go +++ /dev/null @@ -1,42 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "encoding/json" - - "github.com/compose-spec/compose-go/types" - "github.com/opencontainers/go-digest" -) - -// ServiceHash computes the configuration hash for a service. -func ServiceHash(o types.ServiceConfig) (string, error) { - // remove the Build config when generating the service hash - o.Build = nil - o.PullPolicy = "" - if o.Deploy == nil { - o.Deploy = &types.DeployConfig{} - } - o.Scale = 1 - var one uint64 = 1 - o.Deploy.Replicas = &one - bytes, err := json.Marshal(o) - if err != nil { - return "", err - } - return digest.SHA256.FromBytes(bytes).Encoded(), nil -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/image_pruner.go b/vendor/github.com/docker/compose/v2/pkg/compose/image_pruner.go deleted file mode 100644 index 5fce5f0e9..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/image_pruner.go +++ /dev/null @@ -1,248 +0,0 @@ -/* - Copyright 2022 Docker Compose CLI 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 compose - -import ( - "context" - "fmt" - "sort" - "sync" - - "github.com/compose-spec/compose-go/types" - "github.com/distribution/distribution/v3/reference" - moby "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/client" - "github.com/docker/docker/errdefs" - "golang.org/x/sync/errgroup" - - "github.com/docker/compose/v2/pkg/api" -) - -// ImagePruneMode controls how aggressively images associated with the project -// are removed from the engine. -type ImagePruneMode string - -const ( - // ImagePruneNone indicates that no project images should be removed. - ImagePruneNone ImagePruneMode = "" - // ImagePruneLocal indicates that only images built locally by Compose - // should be removed. - ImagePruneLocal ImagePruneMode = "local" - // ImagePruneAll indicates that all project-associated images, including - // remote images should be removed. - ImagePruneAll ImagePruneMode = "all" -) - -// ImagePruneOptions controls the behavior of image pruning. -type ImagePruneOptions struct { - Mode ImagePruneMode - - // RemoveOrphans will result in the removal of images that were built for - // the project regardless of whether they are for a known service if true. - RemoveOrphans bool -} - -// ImagePruner handles image removal during Compose `down` operations. -type ImagePruner struct { - client client.ImageAPIClient - project *types.Project -} - -// NewImagePruner creates an ImagePruner object for a project. -func NewImagePruner(imageClient client.ImageAPIClient, project *types.Project) *ImagePruner { - return &ImagePruner{ - client: imageClient, - project: project, - } -} - -// ImagesToPrune returns the set of images that should be removed. -func (p *ImagePruner) ImagesToPrune(ctx context.Context, opts ImagePruneOptions) ([]string, error) { - if opts.Mode == ImagePruneNone { - return nil, nil - } else if opts.Mode != ImagePruneLocal && opts.Mode != ImagePruneAll { - return nil, fmt.Errorf("unsupported image prune mode: %s", opts.Mode) - } - var images []string - - if opts.Mode == ImagePruneAll { - namedImages, err := p.namedImages(ctx) - if err != nil { - return nil, err - } - images = append(images, namedImages...) - } - - projectImages, err := p.labeledLocalImages(ctx) - if err != nil { - return nil, err - } - for _, img := range projectImages { - if len(img.RepoTags) == 0 { - // currently, we're only pruning the tagged references, but - // if we start removing the dangling images and grouping by - // service, we can remove this (and should rely on `Image::ID`) - continue - } - - var shouldPrune bool - if opts.RemoveOrphans { - // indiscriminately prune all project images even if they're not - // referenced by the current Compose state (e.g. the service was - // removed from YAML) - shouldPrune = true - } else { - // only prune the image if it belongs to a known service for the project. - if _, err := p.project.GetService(img.Labels[api.ServiceLabel]); err == nil { - shouldPrune = true - } - } - - if shouldPrune { - images = append(images, img.RepoTags[0]) - } - } - - fallbackImages, err := p.unlabeledLocalImages(ctx) - if err != nil { - return nil, err - } - images = append(images, fallbackImages...) - - images = normalizeAndDedupeImages(images) - return images, nil -} - -// namedImages are those that are explicitly named in the service config. -// -// These could be registry-only images (no local build), hybrid (support build -// as a fallback if cannot pull), or local-only (image does not exist in a -// registry). -func (p *ImagePruner) namedImages(ctx context.Context) ([]string, error) { - var images []string - for _, service := range p.project.Services { - if service.Image == "" { - continue - } - images = append(images, service.Image) - } - return p.filterImagesByExistence(ctx, images) -} - -// labeledLocalImages are images that were locally-built by a current version of -// Compose (it did not always label built images). -// -// The image name could either have been defined by the user or implicitly -// created from the project + service name. -func (p *ImagePruner) labeledLocalImages(ctx context.Context) ([]moby.ImageSummary, error) { - imageListOpts := moby.ImageListOptions{ - Filters: filters.NewArgs( - projectFilter(p.project.Name), - // TODO(milas): we should really clean up the dangling images as - // well (historically we have NOT); need to refactor this to handle - // it gracefully without producing confusing CLI output, i.e. we - // do not want to print out a bunch of untagged/dangling image IDs, - // they should be grouped into a logical operation for the relevant - // service - filters.Arg("dangling", "false"), - ), - } - projectImages, err := p.client.ImageList(ctx, imageListOpts) - if err != nil { - return nil, err - } - return projectImages, nil -} - -// unlabeledLocalImages are images that match the implicit naming convention -// for locally-built images but did not get labeled, presumably because they -// were produced by an older version of Compose. -// -// This is transitional to ensure `down` continues to work as expected on -// projects built/launched by previous versions of Compose. It can safely -// be removed after some time. -func (p *ImagePruner) unlabeledLocalImages(ctx context.Context) ([]string, error) { - var images []string - for _, service := range p.project.Services { - if service.Image != "" { - continue - } - img := api.GetImageNameOrDefault(service, p.project.Name) - images = append(images, img) - } - return p.filterImagesByExistence(ctx, images) -} - -// filterImagesByExistence returns the subset of images that exist in the -// engine store. -// -// NOTE: Any transient errors communicating with the API will result in an -// image being returned as "existing", as this method is exclusively used to -// find images to remove, so the worst case of being conservative here is an -// attempt to remove an image that doesn't exist, which will cause a warning -// but is otherwise harmless. -func (p *ImagePruner) filterImagesByExistence(ctx context.Context, imageNames []string) ([]string, error) { - var mu sync.Mutex - var ret []string - - eg, ctx := errgroup.WithContext(ctx) - for _, img := range imageNames { - img := img - eg.Go(func() error { - _, _, err := p.client.ImageInspectWithRaw(ctx, img) - if errdefs.IsNotFound(err) { - // err on the side of caution: only skip if we successfully - // queried the API and got back a definitive "not exists" - return nil - } - mu.Lock() - defer mu.Unlock() - ret = append(ret, img) - return nil - }) - } - - if err := eg.Wait(); err != nil { - return nil, err - } - - return ret, nil -} - -// normalizeAndDedupeImages returns the unique set of images after normalization. -func normalizeAndDedupeImages(images []string) []string { - seen := make(map[string]struct{}, len(images)) - for _, img := range images { - // since some references come from user input (service.image) and some - // come from the engine API, we standardize them, opting for the - // familiar name format since they'll also be displayed in the CLI - ref, err := reference.ParseNormalizedNamed(img) - if err == nil { - ref = reference.TagNameOnly(ref) - img = reference.FamiliarString(ref) - } - seen[img] = struct{}{} - } - ret := make([]string, 0, len(seen)) - for v := range seen { - ret = append(ret, v) - } - // ensure a deterministic return result - the actual ordering is not useful - sort.Strings(ret) - return ret -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/images.go b/vendor/github.com/docker/compose/v2/pkg/compose/images.go deleted file mode 100644 index cef8b4fa1..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/images.go +++ /dev/null @@ -1,119 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "fmt" - "strings" - "sync" - - "github.com/distribution/distribution/v3/reference" - moby "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/errdefs" - "golang.org/x/sync/errgroup" - - "github.com/docker/compose/v2/pkg/api" - "github.com/docker/compose/v2/pkg/utils" -) - -func (s *composeService) Images(ctx context.Context, projectName string, options api.ImagesOptions) ([]api.ImageSummary, error) { - projectName = strings.ToLower(projectName) - allContainers, err := s.apiClient().ContainerList(ctx, moby.ContainerListOptions{ - All: true, - Filters: filters.NewArgs(projectFilter(projectName)), - }) - if err != nil { - return nil, err - } - containers := []moby.Container{} - if len(options.Services) > 0 { - // filter service containers - for _, c := range allContainers { - if utils.StringContains(options.Services, c.Labels[api.ServiceLabel]) { - containers = append(containers, c) - - } - } - } else { - containers = allContainers - } - - imageIDs := []string{} - // aggregate image IDs - for _, c := range containers { - if !utils.StringContains(imageIDs, c.ImageID) { - imageIDs = append(imageIDs, c.ImageID) - } - } - images, err := s.getImages(ctx, imageIDs) - if err != nil { - return nil, err - } - summary := make([]api.ImageSummary, len(containers)) - for i, container := range containers { - img, ok := images[container.ImageID] - if !ok { - return nil, fmt.Errorf("failed to retrieve image for container %s", getCanonicalContainerName(container)) - } - - summary[i] = img - summary[i].ContainerName = getCanonicalContainerName(container) - } - return summary, nil -} - -func (s *composeService) getImages(ctx context.Context, images []string) (map[string]api.ImageSummary, error) { - summary := map[string]api.ImageSummary{} - l := sync.Mutex{} - eg, ctx := errgroup.WithContext(ctx) - for _, img := range images { - img := img - eg.Go(func() error { - inspect, _, err := s.apiClient().ImageInspectWithRaw(ctx, img) - if err != nil { - if errdefs.IsNotFound(err) { - return nil - } - return err - } - tag := "" - repository := "" - if len(inspect.RepoTags) > 0 { - ref, err := reference.ParseDockerRef(inspect.RepoTags[0]) - if err != nil { - return err - } - repository = reference.FamiliarName(ref) - if tagged, ok := ref.(reference.Tagged); ok { - tag = tagged.Tag() - } - } - l.Lock() - summary[img] = api.ImageSummary{ - ID: inspect.ID, - Repository: repository, - Tag: tag, - Size: inspect.Size, - } - l.Unlock() - return nil - }) - } - return summary, eg.Wait() -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/kill.go b/vendor/github.com/docker/compose/v2/pkg/compose/kill.go deleted file mode 100644 index ca7039cee..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/kill.go +++ /dev/null @@ -1,80 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "fmt" - "strings" - - moby "github.com/docker/docker/api/types" - "golang.org/x/sync/errgroup" - - "github.com/docker/compose/v2/pkg/api" - "github.com/docker/compose/v2/pkg/progress" -) - -func (s *composeService) Kill(ctx context.Context, projectName string, options api.KillOptions) error { - return progress.RunWithTitle(ctx, func(ctx context.Context) error { - return s.kill(ctx, strings.ToLower(projectName), options) - }, s.stdinfo(), "Killing") -} - -func (s *composeService) kill(ctx context.Context, projectName string, options api.KillOptions) error { - w := progress.ContextWriter(ctx) - - services := options.Services - - var containers Containers - containers, err := s.getContainers(ctx, projectName, oneOffInclude, false, services...) - if err != nil { - return err - } - - project := options.Project - if project == nil { - project, err = s.getProjectWithResources(ctx, containers, projectName) - if err != nil { - return err - } - } - - if !options.RemoveOrphans { - containers = containers.filter(isService(project.ServiceNames()...)) - } - if len(containers) == 0 { - fmt.Fprintf(s.stdinfo(), "no container to kill") - return nil - } - - eg, ctx := errgroup.WithContext(ctx) - containers. - forEach(func(container moby.Container) { - eg.Go(func() error { - eventName := getContainerProgressName(container) - w.Event(progress.KillingEvent(eventName)) - err := s.apiClient().ContainerKill(ctx, container.ID, options.Signal) - if err != nil { - w.Event(progress.ErrorMessageEvent(eventName, "Error while Killing")) - return err - } - w.Event(progress.KilledEvent(eventName)) - return nil - }) - }) - return eg.Wait() -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/logs.go b/vendor/github.com/docker/compose/v2/pkg/compose/logs.go deleted file mode 100644 index f5a20b16a..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/logs.go +++ /dev/null @@ -1,154 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "io" - "strings" - "time" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/errdefs" - "github.com/docker/docker/pkg/stdcopy" - "github.com/sirupsen/logrus" - "golang.org/x/sync/errgroup" - - "github.com/docker/compose/v2/pkg/api" - "github.com/docker/compose/v2/pkg/utils" -) - -func (s *composeService) Logs( - ctx context.Context, - projectName string, - consumer api.LogConsumer, - options api.LogOptions, -) error { - projectName = strings.ToLower(projectName) - - containers, err := s.getContainers(ctx, projectName, oneOffExclude, true, options.Services...) - if err != nil { - return err - } - - if options.Project != nil && len(options.Services) == 0 { - // we run with an explicit compose.yaml, so only consider services defined in this file - options.Services = options.Project.ServiceNames() - containers = containers.filter(isService(options.Services...)) - } - - eg, ctx := errgroup.WithContext(ctx) - for _, c := range containers { - c := c - eg.Go(func() error { - err := s.logContainers(ctx, consumer, c, options) - if _, ok := err.(errdefs.ErrNotImplemented); ok { - logrus.Warnf("Can't retrieve logs for %q: %s", getCanonicalContainerName(c), err.Error()) - return nil - } - return err - }) - } - - if options.Follow { - containers = containers.filter(isRunning()) - printer := newLogPrinter(consumer) - eg.Go(func() error { - _, err := printer.Run(false, "", nil) - return err - }) - - for _, c := range containers { - printer.HandleEvent(api.ContainerEvent{ - Type: api.ContainerEventAttach, - Container: getContainerNameWithoutProject(c), - ID: c.ID, - Service: c.Labels[api.ServiceLabel], - }) - } - - eg.Go(func() error { - err := s.watchContainers(ctx, projectName, options.Services, nil, printer.HandleEvent, containers, func(c types.Container, t time.Time) error { - printer.HandleEvent(api.ContainerEvent{ - Type: api.ContainerEventAttach, - Container: getContainerNameWithoutProject(c), - ID: c.ID, - Service: c.Labels[api.ServiceLabel], - }) - eg.Go(func() error { - err := s.logContainers(ctx, consumer, c, api.LogOptions{ - Follow: options.Follow, - Since: t.Format(time.RFC3339Nano), - Until: options.Until, - Tail: options.Tail, - Timestamps: options.Timestamps, - }) - if _, ok := err.(errdefs.ErrNotImplemented); ok { - // ignore - return nil - } - return err - }) - return nil - }, func(c types.Container, t time.Time) error { - printer.HandleEvent(api.ContainerEvent{ - Type: api.ContainerEventAttach, - Container: "", // actual name will be set by start event - ID: c.ID, - Service: c.Labels[api.ServiceLabel], - }) - return nil - }) - printer.Stop() - return err - }) - } - - return eg.Wait() -} - -func (s *composeService) logContainers(ctx context.Context, consumer api.LogConsumer, c types.Container, options api.LogOptions) error { - cnt, err := s.apiClient().ContainerInspect(ctx, c.ID) - if err != nil { - return err - } - - r, err := s.apiClient().ContainerLogs(ctx, cnt.ID, types.ContainerLogsOptions{ - ShowStdout: true, - ShowStderr: true, - Follow: options.Follow, - Since: options.Since, - Until: options.Until, - Tail: options.Tail, - Timestamps: options.Timestamps, - }) - if err != nil { - return err - } - defer r.Close() //nolint:errcheck - - name := getContainerNameWithoutProject(c) - w := utils.GetWriter(func(line string) { - consumer.Log(name, line) - }) - if cnt.Config.Tty { - _, err = io.Copy(w, r) - } else { - _, err = stdcopy.StdCopy(w, w, r) - } - return err -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/ls.go b/vendor/github.com/docker/compose/v2/pkg/compose/ls.go deleted file mode 100644 index 25588f8d3..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/ls.go +++ /dev/null @@ -1,135 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "fmt" - "sort" - "strings" - - "github.com/docker/compose/v2/pkg/api" - "github.com/docker/compose/v2/pkg/utils" - moby "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/sirupsen/logrus" -) - -func (s *composeService) List(ctx context.Context, opts api.ListOptions) ([]api.Stack, error) { - list, err := s.apiClient().ContainerList(ctx, moby.ContainerListOptions{ - Filters: filters.NewArgs(hasProjectLabelFilter(), hasConfigHashLabel()), - All: opts.All, - }) - if err != nil { - return nil, err - } - - return containersToStacks(list) -} - -func containersToStacks(containers []moby.Container) ([]api.Stack, error) { - containersByLabel, keys, err := groupContainerByLabel(containers, api.ProjectLabel) - if err != nil { - return nil, err - } - var projects []api.Stack - for _, project := range keys { - configFiles, err := combinedConfigFiles(containersByLabel[project]) - if err != nil { - logrus.Warn(err.Error()) - configFiles = "N/A" - } - - projects = append(projects, api.Stack{ - ID: project, - Name: project, - Status: combinedStatus(containerToState(containersByLabel[project])), - ConfigFiles: configFiles, - }) - } - return projects, nil -} - -func combinedConfigFiles(containers []moby.Container) (string, error) { - configFiles := []string{} - - for _, c := range containers { - files, ok := c.Labels[api.ConfigFilesLabel] - if !ok { - return "", fmt.Errorf("No label %q set on container %q of compose project", api.ConfigFilesLabel, c.ID) - } - - for _, f := range strings.Split(files, ",") { - if !utils.StringContains(configFiles, f) { - configFiles = append(configFiles, f) - } - } - } - - return strings.Join(configFiles, ","), nil -} - -func containerToState(containers []moby.Container) []string { - statuses := []string{} - for _, c := range containers { - statuses = append(statuses, c.State) - } - return statuses -} - -func combinedStatus(statuses []string) string { - nbByStatus := map[string]int{} - keys := []string{} - for _, status := range statuses { - nb, ok := nbByStatus[status] - if !ok { - nb = 0 - keys = append(keys, status) - } - nbByStatus[status] = nb + 1 - } - sort.Strings(keys) - result := "" - for _, status := range keys { - nb := nbByStatus[status] - if result != "" { - result += ", " - } - result += fmt.Sprintf("%s(%d)", status, nb) - } - return result -} - -func groupContainerByLabel(containers []moby.Container, labelName string) (map[string][]moby.Container, []string, error) { - containersByLabel := map[string][]moby.Container{} - keys := []string{} - for _, c := range containers { - label, ok := c.Labels[labelName] - if !ok { - return nil, nil, fmt.Errorf("No label %q set on container %q of compose project", labelName, c.ID) - } - labelContainers, ok := containersByLabel[label] - if !ok { - labelContainers = []moby.Container{} - keys = append(keys, label) - } - labelContainers = append(labelContainers, c) - containersByLabel[label] = labelContainers - } - sort.Strings(keys) - return containersByLabel, keys, nil -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/metrics.go b/vendor/github.com/docker/compose/v2/pkg/compose/metrics.go deleted file mode 100644 index 7bd9ad698..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/metrics.go +++ /dev/null @@ -1,79 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -// FailureCategory sruct regrouping metrics failure status and specific exit code -type FailureCategory struct { - MetricsStatus string - ExitCode int -} - -const ( - // APISource is sent for API metrics - APISource = "api" - // SuccessStatus command success - SuccessStatus = "success" - // FailureStatus command failure - FailureStatus = "failure" - // ComposeParseFailureStatus failure while parsing compose file - ComposeParseFailureStatus = "failure-compose-parse" - // FileNotFoundFailureStatus failure getting compose file - FileNotFoundFailureStatus = "failure-file-not-found" - // CommandSyntaxFailureStatus failure reading command - CommandSyntaxFailureStatus = "failure-cmd-syntax" - // BuildFailureStatus failure building imge - BuildFailureStatus = "failure-build" - // PullFailureStatus failure pulling imge - PullFailureStatus = "failure-pull" - // CanceledStatus command canceled - CanceledStatus = "canceled" -) - -var ( - // FileNotFoundFailure failure for compose file not found - FileNotFoundFailure = FailureCategory{MetricsStatus: FileNotFoundFailureStatus, ExitCode: 14} - // ComposeParseFailure failure for composefile parse error - ComposeParseFailure = FailureCategory{MetricsStatus: ComposeParseFailureStatus, ExitCode: 15} - // CommandSyntaxFailure failure for command line syntax - CommandSyntaxFailure = FailureCategory{MetricsStatus: CommandSyntaxFailureStatus, ExitCode: 16} - // BuildFailure failure while building images. - BuildFailure = FailureCategory{MetricsStatus: BuildFailureStatus, ExitCode: 17} - // PullFailure failure while pulling image - PullFailure = FailureCategory{MetricsStatus: PullFailureStatus, ExitCode: 18} -) - -// ByExitCode retrieve FailureCategory based on command exit code -func ByExitCode(exitCode int) FailureCategory { - switch exitCode { - case 0: - return FailureCategory{MetricsStatus: SuccessStatus, ExitCode: 0} - case 14: - return FileNotFoundFailure - case 15: - return ComposeParseFailure - case 16: - return CommandSyntaxFailure - case 17: - return BuildFailure - case 18: - return PullFailure - case 130: - return FailureCategory{MetricsStatus: CanceledStatus, ExitCode: exitCode} - default: - return FailureCategory{MetricsStatus: FailureStatus, ExitCode: exitCode} - } -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/pause.go b/vendor/github.com/docker/compose/v2/pkg/compose/pause.go deleted file mode 100644 index 575222846..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/pause.go +++ /dev/null @@ -1,92 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "strings" - - moby "github.com/docker/docker/api/types" - "golang.org/x/sync/errgroup" - - "github.com/docker/compose/v2/pkg/api" - "github.com/docker/compose/v2/pkg/progress" -) - -func (s *composeService) Pause(ctx context.Context, projectName string, options api.PauseOptions) error { - return progress.RunWithTitle(ctx, func(ctx context.Context) error { - return s.pause(ctx, strings.ToLower(projectName), options) - }, s.stdinfo(), "Pausing") -} - -func (s *composeService) pause(ctx context.Context, projectName string, options api.PauseOptions) error { - containers, err := s.getContainers(ctx, projectName, oneOffExclude, false, options.Services...) - if err != nil { - return err - } - - if options.Project != nil { - containers = containers.filter(isService(options.Project.ServiceNames()...)) - } - - w := progress.ContextWriter(ctx) - eg, ctx := errgroup.WithContext(ctx) - containers.forEach(func(container moby.Container) { - eg.Go(func() error { - err := s.apiClient().ContainerPause(ctx, container.ID) - if err == nil { - eventName := getContainerProgressName(container) - w.Event(progress.NewEvent(eventName, progress.Done, "Paused")) - } - return err - }) - - }) - return eg.Wait() -} - -func (s *composeService) UnPause(ctx context.Context, projectName string, options api.PauseOptions) error { - return progress.Run(ctx, func(ctx context.Context) error { - return s.unPause(ctx, strings.ToLower(projectName), options) - }, s.stdinfo()) -} - -func (s *composeService) unPause(ctx context.Context, projectName string, options api.PauseOptions) error { - containers, err := s.getContainers(ctx, projectName, oneOffExclude, false, options.Services...) - if err != nil { - return err - } - - if options.Project != nil { - containers = containers.filter(isService(options.Project.ServiceNames()...)) - } - - w := progress.ContextWriter(ctx) - eg, ctx := errgroup.WithContext(ctx) - containers.forEach(func(container moby.Container) { - eg.Go(func() error { - err = s.apiClient().ContainerUnpause(ctx, container.ID) - if err == nil { - eventName := getContainerProgressName(container) - w.Event(progress.NewEvent(eventName, progress.Done, "Unpaused")) - } - return err - }) - - }) - return eg.Wait() -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/port.go b/vendor/github.com/docker/compose/v2/pkg/compose/port.go deleted file mode 100644 index 570c6202f..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/port.go +++ /dev/null @@ -1,55 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "fmt" - "strings" - - "github.com/docker/compose/v2/pkg/api" - - moby "github.com/docker/docker/api/types" -) - -func (s *composeService) Port(ctx context.Context, projectName string, service string, port uint16, options api.PortOptions) (string, int, error) { - projectName = strings.ToLower(projectName) - container, err := s.getSpecifiedContainer(ctx, projectName, oneOffInclude, false, service, options.Index) - if err != nil { - return "", 0, err - } - for _, p := range container.Ports { - if p.PrivatePort == port && p.Type == options.Protocol { - return p.IP, int(p.PublicPort), nil - } - } - return "", 0, portNotFoundError(options.Protocol, port, container) -} - -func portNotFoundError(protocol string, port uint16, ctr moby.Container) error { - formatPort := func(protocol string, port uint16) string { - return fmt.Sprintf("%d/%s", port, protocol) - } - - var containerPorts []string - for _, p := range ctr.Ports { - containerPorts = append(containerPorts, formatPort(p.Type, p.PublicPort)) - } - - name := strings.TrimPrefix(ctr.Names[0], "/") - return fmt.Errorf("no port %s for container %s: %s", formatPort(protocol, port), name, strings.Join(containerPorts, ", ")) -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/printer.go b/vendor/github.com/docker/compose/v2/pkg/compose/printer.go deleted file mode 100644 index 5c8db7e80..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/printer.go +++ /dev/null @@ -1,129 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "fmt" - - "github.com/docker/compose/v2/pkg/api" -) - -// logPrinter watch application containers an collect their logs -type logPrinter interface { - HandleEvent(event api.ContainerEvent) - Run(cascadeStop bool, exitCodeFrom string, stopFn func() error) (int, error) - Cancel() - Stop() -} - -type printer struct { - queue chan api.ContainerEvent - consumer api.LogConsumer - stopCh chan struct{} -} - -// newLogPrinter builds a LogPrinter passing containers logs to LogConsumer -func newLogPrinter(consumer api.LogConsumer) logPrinter { - queue := make(chan api.ContainerEvent) - stopCh := make(chan struct{}, 1) // printer MAY stop on his own, so Stop MUST not be blocking - printer := printer{ - consumer: consumer, - queue: queue, - stopCh: stopCh, - } - return &printer -} - -func (p *printer) Cancel() { - p.queue <- api.ContainerEvent{ - Type: api.UserCancel, - } -} - -func (p *printer) Stop() { - p.stopCh <- struct{}{} -} - -func (p *printer) HandleEvent(event api.ContainerEvent) { - p.queue <- event -} - -//nolint:gocyclo -func (p *printer) Run(cascadeStop bool, exitCodeFrom string, stopFn func() error) (int, error) { - var ( - aborting bool - exitCode int - ) - containers := map[string]struct{}{} - for { - select { - case <-p.stopCh: - return exitCode, nil - case event := <-p.queue: - container, id := event.Container, event.ID - switch event.Type { - case api.UserCancel: - aborting = true - case api.ContainerEventAttach: - if _, ok := containers[id]; ok { - continue - } - containers[id] = struct{}{} - p.consumer.Register(container) - case api.ContainerEventExit, api.ContainerEventStopped, api.ContainerEventRecreated: - if !event.Restarting { - delete(containers, id) - } - if !aborting { - p.consumer.Status(container, fmt.Sprintf("exited with code %d", event.ExitCode)) - if event.Type == api.ContainerEventRecreated { - p.consumer.Status(container, "has been recreated") - } - } - if cascadeStop { - if !aborting { - aborting = true - err := stopFn() - if err != nil { - return 0, err - } - } - if event.Type == api.ContainerEventExit { - if exitCodeFrom == "" { - exitCodeFrom = event.Service - } - if exitCodeFrom == event.Service { - exitCode = event.ExitCode - } - } - } - if len(containers) == 0 { - // Last container terminated, done - return exitCode, nil - } - case api.ContainerEventLog: - if !aborting { - p.consumer.Log(container, event.Line) - } - case api.ContainerEventErr: - if !aborting { - p.consumer.Err(container, event.Line) - } - } - } - } -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/ps.go b/vendor/github.com/docker/compose/v2/pkg/compose/ps.go deleted file mode 100644 index 2b2a0b950..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/ps.go +++ /dev/null @@ -1,99 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "sort" - "strings" - - "golang.org/x/sync/errgroup" - - "github.com/docker/compose/v2/pkg/api" -) - -func (s *composeService) Ps(ctx context.Context, projectName string, options api.PsOptions) ([]api.ContainerSummary, error) { - projectName = strings.ToLower(projectName) - oneOff := oneOffExclude - if options.All { - oneOff = oneOffInclude - } - containers, err := s.getContainers(ctx, projectName, oneOff, options.All, options.Services...) - if err != nil { - return nil, err - } - - if len(options.Services) != 0 { - containers = containers.filter(isService(options.Services...)) - } - summary := make([]api.ContainerSummary, len(containers)) - eg, ctx := errgroup.WithContext(ctx) - for i, container := range containers { - i, container := i, container - eg.Go(func() error { - var publishers []api.PortPublisher - sort.Slice(container.Ports, func(i, j int) bool { - return container.Ports[i].PrivatePort < container.Ports[j].PrivatePort - }) - for _, p := range container.Ports { - publishers = append(publishers, api.PortPublisher{ - URL: p.IP, - TargetPort: int(p.PrivatePort), - PublishedPort: int(p.PublicPort), - Protocol: p.Type, - }) - } - - inspect, err := s.apiClient().ContainerInspect(ctx, container.ID) - if err != nil { - return err - } - - var ( - health string - exitCode int - ) - if inspect.State != nil { - switch inspect.State.Status { - case "running": - if inspect.State.Health != nil { - health = inspect.State.Health.Status - } - case "exited", "dead": - exitCode = inspect.State.ExitCode - } - } - - summary[i] = api.ContainerSummary{ - ID: container.ID, - Name: getCanonicalContainerName(container), - Image: container.Image, - Project: container.Labels[api.ProjectLabel], - Service: container.Labels[api.ServiceLabel], - Command: container.Command, - State: container.State, - Status: container.Status, - Created: container.Created, - Health: health, - ExitCode: exitCode, - Publishers: publishers, - } - return nil - }) - } - return summary, eg.Wait() -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/pull.go b/vendor/github.com/docker/compose/v2/pkg/compose/pull.go deleted file mode 100644 index 41fd6d768..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/pull.go +++ /dev/null @@ -1,395 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "io" - "strings" - - "github.com/compose-spec/compose-go/types" - "github.com/distribution/distribution/v3/reference" - "github.com/docker/buildx/driver" - moby "github.com/docker/docker/api/types" - "github.com/docker/docker/pkg/jsonmessage" - "github.com/docker/docker/registry" - "github.com/hashicorp/go-multierror" - "golang.org/x/sync/errgroup" - - "github.com/docker/compose/v2/pkg/api" - "github.com/docker/compose/v2/pkg/progress" -) - -func (s *composeService) Pull(ctx context.Context, project *types.Project, options api.PullOptions) error { - if options.Quiet { - return s.pull(ctx, project, options) - } - return progress.RunWithTitle(ctx, func(ctx context.Context) error { - return s.pull(ctx, project, options) - }, s.stdinfo(), "Pulling") -} - -func (s *composeService) pull(ctx context.Context, project *types.Project, opts api.PullOptions) error { //nolint:gocyclo - images, err := s.getLocalImagesDigests(ctx, project) - if err != nil { - return err - } - - w := progress.ContextWriter(ctx) - eg, ctx := errgroup.WithContext(ctx) - eg.SetLimit(s.maxConcurrency) - - var ( - mustBuild []string - pullErrors = make([]error, len(project.Services)) - imagesBeingPulled = map[string]string{} - ) - - for i, service := range project.Services { - i, service := i, service - if service.Image == "" { - w.Event(progress.Event{ - ID: service.Name, - Status: progress.Done, - Text: "Skipped - No image to be pulled", - }) - continue - } - - switch service.PullPolicy { - case types.PullPolicyNever, types.PullPolicyBuild: - w.Event(progress.Event{ - ID: service.Name, - Status: progress.Done, - Text: "Skipped", - }) - continue - case types.PullPolicyMissing, types.PullPolicyIfNotPresent: - if imageAlreadyPresent(service.Image, images) { - w.Event(progress.Event{ - ID: service.Name, - Status: progress.Done, - Text: "Skipped - Image is already present locally", - }) - continue - } - } - - if service.Build != nil && opts.IgnoreBuildable { - w.Event(progress.Event{ - ID: service.Name, - Status: progress.Done, - Text: "Skipped - Image can be built", - }) - continue - } - - if s, ok := imagesBeingPulled[service.Image]; ok { - w.Event(progress.Event{ - ID: service.Name, - Status: progress.Done, - Text: fmt.Sprintf("Skipped - Image is already being pulled by %v", s), - }) - continue - } - - imagesBeingPulled[service.Image] = service.Name - - eg.Go(func() error { - _, err := s.pullServiceImage(ctx, service, s.configFile(), w, false, project.Environment["DOCKER_DEFAULT_PLATFORM"]) - if err != nil { - pullErrors[i] = err - if service.Build != nil { - mustBuild = append(mustBuild, service.Name) - } - if !opts.IgnoreFailures && service.Build == nil { - if s.dryRun { - w.Event(progress.Event{ - ID: service.Name, - Status: progress.Error, - Text: fmt.Sprintf(" - Pull error for image: %s", service.Image), - }) - } - // fail fast if image can't be pulled nor built - return err - } - } - return nil - }) - } - - err = eg.Wait() - - if len(mustBuild) > 0 { - w.TailMsgf("WARNING: Some service image(s) must be built from source by running:\n docker compose build %s", strings.Join(mustBuild, " ")) - } - - if err != nil { - return err - } - if opts.IgnoreFailures { - return nil - } - return multierror.Append(nil, pullErrors...).ErrorOrNil() -} - -func imageAlreadyPresent(serviceImage string, localImages map[string]string) bool { - normalizedImage, err := reference.ParseDockerRef(serviceImage) - if err != nil { - return false - } - tagged, ok := normalizedImage.(reference.NamedTagged) - if !ok { - return false - } - _, ok = localImages[serviceImage] - return ok && tagged.Tag() != "latest" -} - -func (s *composeService) pullServiceImage(ctx context.Context, service types.ServiceConfig, - configFile driver.Auth, w progress.Writer, quietPull bool, defaultPlatform string) (string, error) { - w.Event(progress.Event{ - ID: service.Name, - Status: progress.Working, - Text: "Pulling", - }) - ref, err := reference.ParseNormalizedNamed(service.Image) - if err != nil { - return "", err - } - - encodedAuth, err := encodedAuth(ref, configFile) - if err != nil { - return "", err - } - - platform := service.Platform - if platform == "" { - platform = defaultPlatform - } - - stream, err := s.apiClient().ImagePull(ctx, service.Image, moby.ImagePullOptions{ - RegistryAuth: encodedAuth, - Platform: platform, - }) - - // check if has error and the service has a build section - // then the status should be warning instead of error - if err != nil && service.Build != nil { - w.Event(progress.Event{ - ID: service.Name, - Status: progress.Warning, - Text: "Warning", - }) - return "", WrapCategorisedComposeError(err, PullFailure) - } - - if err != nil { - w.Event(progress.Event{ - ID: service.Name, - Status: progress.Error, - Text: "Error", - }) - return "", WrapCategorisedComposeError(err, PullFailure) - } - - dec := json.NewDecoder(stream) - for { - var jm jsonmessage.JSONMessage - if err := dec.Decode(&jm); err != nil { - if err == io.EOF { - break - } - return "", WrapCategorisedComposeError(err, PullFailure) - } - if jm.Error != nil { - return "", WrapCategorisedComposeError(errors.New(jm.Error.Message), PullFailure) - } - if !quietPull { - toPullProgressEvent(service.Name, jm, w) - } - } - w.Event(progress.Event{ - ID: service.Name, - Status: progress.Done, - Text: "Pulled", - }) - - inspected, _, err := s.apiClient().ImageInspectWithRaw(ctx, service.Image) - if err != nil { - return "", err - } - return inspected.ID, nil -} - -func encodedAuth(ref reference.Named, configFile driver.Auth) (string, error) { - repoInfo, err := registry.ParseRepositoryInfo(ref) - if err != nil { - return "", err - } - - key := registry.GetAuthConfigKey(repoInfo.Index) - authConfig, err := configFile.GetAuthConfig(key) - if err != nil { - return "", err - } - - buf, err := json.Marshal(authConfig) - if err != nil { - return "", err - } - return base64.URLEncoding.EncodeToString(buf), nil -} - -func (s *composeService) pullRequiredImages(ctx context.Context, project *types.Project, images map[string]string, quietPull bool) error { - var needPull []types.ServiceConfig - for _, service := range project.Services { - if service.Image == "" { - continue - } - switch service.PullPolicy { - case "", types.PullPolicyMissing, types.PullPolicyIfNotPresent: - if _, ok := images[service.Image]; ok { - continue - } - case types.PullPolicyNever, types.PullPolicyBuild: - continue - case types.PullPolicyAlways: - // force pull - } - needPull = append(needPull, service) - } - if len(needPull) == 0 { - return nil - } - - return progress.Run(ctx, func(ctx context.Context) error { - w := progress.ContextWriter(ctx) - eg, ctx := errgroup.WithContext(ctx) - eg.SetLimit(s.maxConcurrency) - pulledImages := make([]string, len(needPull)) - for i, service := range needPull { - i, service := i, service - eg.Go(func() error { - id, err := s.pullServiceImage(ctx, service, s.configFile(), w, quietPull, project.Environment["DOCKER_DEFAULT_PLATFORM"]) - pulledImages[i] = id - if err != nil && isServiceImageToBuild(service, project.Services) { - // image can be built, so we can ignore pull failure - return nil - } - return err - }) - } - err := eg.Wait() - for i, service := range needPull { - if pulledImages[i] != "" { - images[service.Image] = pulledImages[i] - } - } - return err - }, s.stdinfo()) -} - -func isServiceImageToBuild(service types.ServiceConfig, services []types.ServiceConfig) bool { - if service.Build != nil { - return true - } - - if service.Image == "" { - // N.B. this should be impossible as service must have either `build` or `image` (or both) - return false - } - - // look through the other services to see if another has a build definition for the same - // image name - for _, svc := range services { - if svc.Image == service.Image && svc.Build != nil { - return true - } - } - return false -} - -const ( - PreparingPhase = "Preparing" - WaitingPhase = "Waiting" - PullingFsPhase = "Pulling fs layer" - DownloadingPhase = "Downloading" - DownloadCompletePhase = "Download complete" - ExtractingPhase = "Extracting" - VerifyingChecksumPhase = "Verifying Checksum" - AlreadyExistsPhase = "Already exists" - PullCompletePhase = "Pull complete" -) - -func toPullProgressEvent(parent string, jm jsonmessage.JSONMessage, w progress.Writer) { - if jm.ID == "" || jm.Progress == nil { - return - } - - var ( - text string - total int64 - percent int - current int64 - status = progress.Working - ) - - text = jm.Progress.String() - - switch jm.Status { - case PreparingPhase, WaitingPhase, PullingFsPhase: - percent = 0 - case DownloadingPhase, ExtractingPhase, VerifyingChecksumPhase: - if jm.Progress != nil { - current = jm.Progress.Current - total = jm.Progress.Total - if jm.Progress.Total > 0 { - percent = int(jm.Progress.Current * 100 / jm.Progress.Total) - } - } - case DownloadCompletePhase, AlreadyExistsPhase, PullCompletePhase: - status = progress.Done - percent = 100 - } - - if strings.Contains(jm.Status, "Image is up to date") || - strings.Contains(jm.Status, "Downloaded newer image") { - status = progress.Done - percent = 100 - } - - if jm.Error != nil { - status = progress.Error - text = jm.Error.Message - } - - w.Event(progress.Event{ - ID: jm.ID, - ParentID: parent, - Current: current, - Total: total, - Percent: percent, - Text: jm.Status, - Status: status, - StatusText: text, - }) -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/push.go b/vendor/github.com/docker/compose/v2/pkg/compose/push.go deleted file mode 100644 index c60262b6f..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/push.go +++ /dev/null @@ -1,176 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "encoding/base64" - "encoding/json" - "fmt" - "io" - - "github.com/compose-spec/compose-go/types" - "github.com/distribution/distribution/v3/reference" - "github.com/docker/buildx/driver" - moby "github.com/docker/docker/api/types" - "github.com/docker/docker/pkg/jsonmessage" - "github.com/docker/docker/registry" - "github.com/pkg/errors" - "golang.org/x/sync/errgroup" - - "github.com/docker/compose/v2/pkg/api" - "github.com/docker/compose/v2/pkg/progress" -) - -func (s *composeService) Push(ctx context.Context, project *types.Project, options api.PushOptions) error { - if options.Quiet { - return s.push(ctx, project, options) - } - return progress.RunWithTitle(ctx, func(ctx context.Context) error { - return s.push(ctx, project, options) - }, s.stdinfo(), "Pushing") -} - -func (s *composeService) push(ctx context.Context, project *types.Project, options api.PushOptions) error { - eg, ctx := errgroup.WithContext(ctx) - eg.SetLimit(s.maxConcurrency) - - info, err := s.apiClient().Info(ctx) - if err != nil { - return err - } - if info.IndexServerAddress == "" { - info.IndexServerAddress = registry.IndexServer - } - - w := progress.ContextWriter(ctx) - for _, service := range project.Services { - if service.Build == nil || service.Image == "" { - w.Event(progress.Event{ - ID: service.Name, - Status: progress.Done, - Text: "Skipped", - }) - continue - } - service := service - eg.Go(func() error { - err := s.pushServiceImage(ctx, service, info, s.configFile(), w, options.Quiet) - if err != nil { - if !options.IgnoreFailures { - return err - } - w.TailMsgf("Pushing %s: %s", service.Name, err.Error()) - } - return nil - }) - } - return eg.Wait() -} - -func (s *composeService) pushServiceImage(ctx context.Context, service types.ServiceConfig, info moby.Info, configFile driver.Auth, w progress.Writer, quietPush bool) error { - ref, err := reference.ParseNormalizedNamed(service.Image) - if err != nil { - return err - } - - repoInfo, err := registry.ParseRepositoryInfo(ref) - if err != nil { - return err - } - - key := repoInfo.Index.Name - if repoInfo.Index.Official { - key = info.IndexServerAddress - } - authConfig, err := configFile.GetAuthConfig(key) - if err != nil { - return err - } - - buf, err := json.Marshal(authConfig) - if err != nil { - return err - } - - stream, err := s.apiClient().ImagePush(ctx, service.Image, moby.ImagePushOptions{ - RegistryAuth: base64.URLEncoding.EncodeToString(buf), - }) - if err != nil { - return err - } - dec := json.NewDecoder(stream) - for { - var jm jsonmessage.JSONMessage - if err := dec.Decode(&jm); err != nil { - if err == io.EOF { - break - } - return err - } - if jm.Error != nil { - return errors.New(jm.Error.Message) - } - - if !quietPush { - toPushProgressEvent(service.Name, jm, w) - } - } - return nil -} - -func toPushProgressEvent(prefix string, jm jsonmessage.JSONMessage, w progress.Writer) { - if jm.ID == "" { - // skipped - return - } - var ( - text string - status = progress.Working - total int64 - current int64 - percent int - ) - if jm.Status == "Pushed" || jm.Status == "Already exists" { - status = progress.Done - percent = 100 - } - if jm.Error != nil { - status = progress.Error - text = jm.Error.Message - } - if jm.Progress != nil { - text = jm.Progress.String() - if jm.Progress.Total != 0 { - current = jm.Progress.Current - total = jm.Progress.Total - if jm.Progress.Total > 0 { - percent = int(jm.Progress.Current * 100 / jm.Progress.Total) - } - } - } - - w.Event(progress.Event{ - ID: fmt.Sprintf("Pushing %s: %s", prefix, jm.ID), - Text: jm.Status, - Status: status, - Current: current, - Total: total, - Percent: percent, - StatusText: text, - }) -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/remove.go b/vendor/github.com/docker/compose/v2/pkg/compose/remove.go deleted file mode 100644 index 79511be3f..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/remove.go +++ /dev/null @@ -1,119 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "fmt" - "strings" - - "github.com/docker/compose/v2/pkg/api" - moby "github.com/docker/docker/api/types" - "golang.org/x/sync/errgroup" - - "github.com/docker/compose/v2/pkg/progress" - "github.com/docker/compose/v2/pkg/prompt" -) - -func (s *composeService) Remove(ctx context.Context, projectName string, options api.RemoveOptions) error { - projectName = strings.ToLower(projectName) - - if options.Stop { - err := s.Stop(ctx, projectName, api.StopOptions{ - Services: options.Services, - Project: options.Project, - }) - if err != nil { - return err - } - } - - containers, err := s.getContainers(ctx, projectName, oneOffExclude, true, options.Services...) - if err != nil { - if api.IsNotFoundError(err) { - fmt.Fprintln(s.stderr(), "No stopped containers") - return nil - } - return err - } - - if options.Project != nil { - containers = containers.filter(isService(options.Project.ServiceNames()...)) - } - - var stoppedContainers Containers - for _, container := range containers { - // We have to inspect containers, as State reported by getContainers suffers a race condition - inspected, err := s.apiClient().ContainerInspect(ctx, container.ID) - if api.IsNotFoundError(err) { - // Already removed. Maybe configured with auto-remove - continue - } - if err != nil { - return err - } - if !inspected.State.Running || (options.Stop && s.dryRun) { - stoppedContainers = append(stoppedContainers, container) - } - } - - var names []string - stoppedContainers.forEach(func(c moby.Container) { - names = append(names, getCanonicalContainerName(c)) - }) - - if len(names) == 0 { - fmt.Fprintln(s.stdinfo(), "No stopped containers") - return nil - } - msg := fmt.Sprintf("Going to remove %s", strings.Join(names, ", ")) - if options.Force { - fmt.Fprintln(s.stdout(), msg) - } else { - confirm, err := prompt.NewPrompt(s.stdin(), s.stdout()).Confirm(msg, false) - if err != nil { - return err - } - if !confirm { - return nil - } - } - return progress.RunWithTitle(ctx, func(ctx context.Context) error { - return s.remove(ctx, stoppedContainers, options) - }, s.stdinfo(), "Removing") -} - -func (s *composeService) remove(ctx context.Context, containers Containers, options api.RemoveOptions) error { - w := progress.ContextWriter(ctx) - eg, ctx := errgroup.WithContext(ctx) - for _, container := range containers { - container := container - eg.Go(func() error { - eventName := getContainerProgressName(container) - w.Event(progress.RemovingEvent(eventName)) - err := s.apiClient().ContainerRemove(ctx, container.ID, moby.ContainerRemoveOptions{ - RemoveVolumes: options.Volumes, - Force: options.Force, - }) - if err == nil { - w.Event(progress.RemovedEvent(eventName)) - } - return err - }) - } - return eg.Wait() -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/restart.go b/vendor/github.com/docker/compose/v2/pkg/compose/restart.go deleted file mode 100644 index 72cf0a816..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/restart.go +++ /dev/null @@ -1,86 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "strings" - - "github.com/compose-spec/compose-go/types" - "github.com/docker/compose/v2/pkg/api" - "github.com/docker/compose/v2/pkg/progress" - "github.com/docker/compose/v2/pkg/utils" - containerType "github.com/docker/docker/api/types/container" - "golang.org/x/sync/errgroup" -) - -func (s *composeService) Restart(ctx context.Context, projectName string, options api.RestartOptions) error { - return progress.RunWithTitle(ctx, func(ctx context.Context) error { - return s.restart(ctx, strings.ToLower(projectName), options) - }, s.stdinfo(), "Restarting") -} - -func (s *composeService) restart(ctx context.Context, projectName string, options api.RestartOptions) error { - containers, err := s.getContainers(ctx, projectName, oneOffExclude, true) - if err != nil { - return err - } - - project := options.Project - if project == nil { - project, err = s.getProjectWithResources(ctx, containers, projectName) - if err != nil { - return err - } - } - - // ignore depends_on relations which are not impacted by restarting service or not required - for i, service := range project.Services { - for name, r := range service.DependsOn { - if !r.Restart { - delete(service.DependsOn, name) - } - } - project.Services[i] = service - } - - if len(options.Services) != 0 { - err = project.ForServices(options.Services, types.IncludeDependents) - if err != nil { - return err - } - } - - w := progress.ContextWriter(ctx) - return InDependencyOrder(ctx, project, func(c context.Context, service string) error { - eg, ctx := errgroup.WithContext(ctx) - for _, container := range containers.filter(isService(service)) { - container := container - eg.Go(func() error { - eventName := getContainerProgressName(container) - w.Event(progress.RestartingEvent(eventName)) - timeout := utils.DurationSecondToInt(options.Timeout) - err := s.apiClient().ContainerRestart(ctx, container.ID, containerType.StopOptions{Timeout: timeout}) - if err == nil { - w.Event(progress.StartedEvent(eventName)) - } - return err - }) - } - return eg.Wait() - }) -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/run.go b/vendor/github.com/docker/compose/v2/pkg/compose/run.go deleted file mode 100644 index 6924c2061..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/run.go +++ /dev/null @@ -1,157 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "errors" - "fmt" - "os" - "os/signal" - - "github.com/compose-spec/compose-go/types" - "github.com/docker/cli/cli" - cmd "github.com/docker/cli/cli/command/container" - "github.com/docker/compose/v2/pkg/api" - "github.com/docker/compose/v2/pkg/utils" - "github.com/docker/docker/pkg/stringid" -) - -func (s *composeService) RunOneOffContainer(ctx context.Context, project *types.Project, opts api.RunOptions) (int, error) { - containerID, err := s.prepareRun(ctx, project, opts) - if err != nil { - return 0, err - } - - // remove cancellable context signal handler so we can forward signals to container without compose to exit - signal.Reset() - - sigc := make(chan os.Signal, 128) - signal.Notify(sigc) - go cmd.ForwardAllSignals(ctx, s.dockerCli, containerID, sigc) - defer signal.Stop(sigc) - - err = cmd.RunStart(s.dockerCli, &cmd.StartOptions{ - OpenStdin: !opts.Detach && opts.Interactive, - Attach: !opts.Detach, - Containers: []string{containerID}, - }) - var stErr cli.StatusError - if errors.As(err, &stErr) { - return stErr.StatusCode, nil - } - return 0, err -} - -func (s *composeService) prepareRun(ctx context.Context, project *types.Project, opts api.RunOptions) (string, error) { - if err := prepareVolumes(project); err != nil { // all dependencies already checked, but might miss service img - return "", err - } - service, err := project.GetService(opts.Service) - if err != nil { - return "", err - } - - applyRunOptions(project, &service, opts) - - if err := s.stdin().CheckTty(opts.Interactive, service.Tty); err != nil { - return "", err - } - - slug := stringid.GenerateRandomID() - if service.ContainerName == "" { - service.ContainerName = fmt.Sprintf("%[1]s%[4]s%[2]s%[4]srun%[4]s%[3]s", project.Name, service.Name, stringid.TruncateID(slug), api.Separator) - } - service.Scale = 1 - service.Restart = "" - if service.Deploy != nil { - service.Deploy.RestartPolicy = nil - } - service.CustomLabels = service.CustomLabels. - Add(api.SlugLabel, slug). - Add(api.OneoffLabel, "True") - - if err := s.ensureImagesExists(ctx, project, opts.QuietPull); err != nil { // all dependencies already checked, but might miss service img - return "", err - } - - observedState, err := s.getContainers(ctx, project.Name, oneOffInclude, true) - if err != nil { - return "", err - } - updateServices(&service, observedState) - - if !opts.NoDeps { - if err := s.waitDependencies(ctx, project, service.DependsOn, observedState); err != nil { - return "", err - } - } - createOpts := createOptions{ - AutoRemove: opts.AutoRemove, - AttachStdin: opts.Interactive, - UseNetworkAliases: opts.UseNetworkAliases, - Labels: mergeLabels(service.Labels, service.CustomLabels), - } - - created, err := s.createContainer(ctx, project, service, service.ContainerName, 1, createOpts) - if err != nil { - return "", err - } - return created.ID, nil -} - -func applyRunOptions(project *types.Project, service *types.ServiceConfig, opts api.RunOptions) { - service.Tty = opts.Tty - service.StdinOpen = opts.Interactive - service.ContainerName = opts.Name - - if len(opts.Command) > 0 { - service.Command = opts.Command - } - if len(opts.User) > 0 { - service.User = opts.User - } - - if len(opts.CapAdd) > 0 { - service.CapAdd = append(service.CapAdd, opts.CapAdd...) - service.CapDrop = utils.Remove(service.CapDrop, opts.CapAdd...) - } - if len(opts.CapDrop) > 0 { - service.CapDrop = append(service.CapDrop, opts.CapDrop...) - service.CapAdd = utils.Remove(service.CapAdd, opts.CapDrop...) - } - if len(opts.WorkingDir) > 0 { - service.WorkingDir = opts.WorkingDir - } - if opts.Entrypoint != nil { - service.Entrypoint = opts.Entrypoint - if len(opts.Command) == 0 { - service.Command = []string{} - } - } - if len(opts.Environment) > 0 { - cmdEnv := types.NewMappingWithEquals(opts.Environment) - serviceOverrideEnv := cmdEnv.Resolve(func(s string) (string, bool) { - v, ok := envResolver(project.Environment)(s) - return v, ok - }).RemoveEmpty() - service.Environment.OverrideBy(serviceOverrideEnv) - } - for k, v := range opts.Labels { - service.Labels = service.Labels.Add(k, v) - } -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/secrets.go b/vendor/github.com/docker/compose/v2/pkg/compose/secrets.go deleted file mode 100644 index 26573fbd0..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/secrets.go +++ /dev/null @@ -1,107 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "archive/tar" - "bytes" - "context" - "fmt" - "strconv" - "time" - - "github.com/compose-spec/compose-go/types" - moby "github.com/docker/docker/api/types" -) - -func (s *composeService) injectSecrets(ctx context.Context, project *types.Project, service types.ServiceConfig, id string) error { - for _, config := range service.Secrets { - secret := project.Secrets[config.Source] - if secret.Environment == "" { - continue - } - - env, ok := project.Environment[secret.Environment] - if !ok { - return fmt.Errorf("environment variable %q required by secret %q is not set", secret.Environment, secret.Name) - } - b, err := createTar(env, config) - if err != nil { - return err - } - - err = s.apiClient().CopyToContainer(ctx, id, "/", &b, moby.CopyToContainerOptions{ - CopyUIDGID: config.UID != "" || config.GID != "", - }) - if err != nil { - return err - } - } - return nil -} - -func createTar(env string, config types.ServiceSecretConfig) (bytes.Buffer, error) { - value := []byte(env) - b := bytes.Buffer{} - tarWriter := tar.NewWriter(&b) - mode := uint32(0o444) - if config.Mode != nil { - mode = *config.Mode - } - - target := config.Target - if config.Target == "" { - target = "/run/secrets/" + config.Source - } else if !isAbsTarget(config.Target) { - target = "/run/secrets/" + config.Target - } - - var uid, gid int - if config.UID != "" { - v, err := strconv.Atoi(config.UID) - if err != nil { - return b, err - } - uid = v - } - if config.GID != "" { - v, err := strconv.Atoi(config.GID) - if err != nil { - return b, err - } - gid = v - } - - header := &tar.Header{ - Name: target, - Size: int64(len(value)), - Mode: int64(mode), - ModTime: time.Now(), - Uid: uid, - Gid: gid, - } - err := tarWriter.WriteHeader(header) - if err != nil { - return bytes.Buffer{}, err - } - _, err = tarWriter.Write(value) - if err != nil { - return bytes.Buffer{}, err - } - err = tarWriter.Close() - return b, err -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/start.go b/vendor/github.com/docker/compose/v2/pkg/compose/start.go deleted file mode 100644 index 9dacb7a80..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/start.go +++ /dev/null @@ -1,304 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "fmt" - "strings" - "time" - - "github.com/docker/docker/errdefs" - - "github.com/docker/compose/v2/pkg/api" - "github.com/docker/compose/v2/pkg/progress" - "github.com/docker/compose/v2/pkg/utils" - - "github.com/compose-spec/compose-go/types" - moby "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/pkg/errors" - "golang.org/x/sync/errgroup" -) - -func (s *composeService) Start(ctx context.Context, projectName string, options api.StartOptions) error { - return progress.Run(ctx, func(ctx context.Context) error { - return s.start(ctx, strings.ToLower(projectName), options, nil) - }, s.stdinfo()) -} - -func (s *composeService) start(ctx context.Context, projectName string, options api.StartOptions, listener api.ContainerEventListener) error { - project := options.Project - if project == nil { - var containers Containers - containers, err := s.getContainers(ctx, projectName, oneOffExclude, true) - if err != nil { - return err - } - - project, err = s.projectFromName(containers, projectName, options.AttachTo...) - if err != nil { - return err - } - } - - eg, ctx := errgroup.WithContext(ctx) - if listener != nil { - attached, err := s.attach(ctx, project, listener, options.AttachTo) - if err != nil { - return err - } - - eg.Go(func() error { - return s.watchContainers(context.Background(), project.Name, options.AttachTo, options.Services, listener, attached, - func(container moby.Container, _ time.Time) error { - return s.attachContainer(ctx, container, listener) - }, func(container moby.Container, _ time.Time) error { - listener(api.ContainerEvent{ - Type: api.ContainerEventAttach, - Container: "", // actual name will be set by start event - ID: container.ID, - Service: container.Labels[api.ServiceLabel], - }) - return nil - }) - }) - } - - var containers Containers - containers, err := s.apiClient().ContainerList(ctx, moby.ContainerListOptions{ - Filters: filters.NewArgs( - projectFilter(project.Name), - oneOffFilter(false), - ), - All: true, - }) - if err != nil { - return err - } - - err = InDependencyOrder(ctx, project, func(c context.Context, name string) error { - service, err := project.GetService(name) - if err != nil { - return err - } - - return s.startService(ctx, project, service, containers) - }) - if err != nil { - return err - } - - if options.Wait { - depends := types.DependsOnConfig{} - for _, s := range project.Services { - depends[s.Name] = types.ServiceDependency{ - Condition: getDependencyCondition(s, project), - Required: true, - } - } - if options.WaitTimeout > 0 { - withTimeout, cancel := context.WithTimeout(ctx, options.WaitTimeout) - ctx = withTimeout - defer cancel() - } - - err = s.waitDependencies(ctx, project, depends, containers) - if err != nil { - if ctx.Err() == context.DeadlineExceeded { - return fmt.Errorf("application not healthy after %s", options.WaitTimeout) - } - return err - } - } - - return eg.Wait() -} - -// getDependencyCondition checks if service is depended on by other services -// with service_completed_successfully condition, and applies that condition -// instead, or --wait will never finish waiting for one-shot containers -func getDependencyCondition(service types.ServiceConfig, project *types.Project) string { - for _, services := range project.Services { - for dependencyService, dependencyConfig := range services.DependsOn { - if dependencyService == service.Name && dependencyConfig.Condition == types.ServiceConditionCompletedSuccessfully { - return types.ServiceConditionCompletedSuccessfully - } - } - } - return ServiceConditionRunningOrHealthy -} - -type containerWatchFn func(container moby.Container, t time.Time) error - -// watchContainers uses engine events to capture container start/die and notify ContainerEventListener -func (s *composeService) watchContainers(ctx context.Context, //nolint:gocyclo - projectName string, services, required []string, - listener api.ContainerEventListener, containers Containers, onStart, onRecreate containerWatchFn) error { - if len(containers) == 0 { - return nil - } - if len(required) == 0 { - required = services - } - - // predicate to tell if a container we receive event for should be considered or ignored - ofInterest := func(c moby.Container) bool { - if len(services) > 0 { - // we only watch some services - return utils.Contains(services, c.Labels[api.ServiceLabel]) - } - return true - } - - // predicate to tell if a container we receive event for should be watched until termination - isRequired := func(c moby.Container) bool { - if len(services) > 0 && len(required) > 0 { - // we only watch some services - return utils.Contains(required, c.Labels[api.ServiceLabel]) - } - return true - } - - var ( - expected []string - watched = map[string]int{} - replaced []string - ) - for _, c := range containers { - if isRequired(c) { - expected = append(expected, c.ID) - } - watched[c.ID] = 0 - } - - ctx, stop := context.WithCancel(ctx) - err := s.Events(ctx, projectName, api.EventsOptions{ - Services: services, - Consumer: func(event api.Event) error { - inspected, err := s.apiClient().ContainerInspect(ctx, event.Container) - if err != nil { - if errdefs.IsNotFound(err) { - // it's possible to get "destroy" or "kill" events but not - // be able to inspect in time before they're gone from the - // API, so just remove the watch without erroring - delete(watched, event.Container) - expected = utils.Remove(expected, event.Container) - return nil - } - return err - } - container := moby.Container{ - ID: inspected.ID, - Names: []string{inspected.Name}, - Labels: inspected.Config.Labels, - } - name := getContainerNameWithoutProject(container) - - service := container.Labels[api.ServiceLabel] - switch event.Status { - case "stop": - if _, ok := watched[container.ID]; ok { - eType := api.ContainerEventStopped - if utils.Contains(replaced, container.ID) { - utils.Remove(replaced, container.ID) - eType = api.ContainerEventRecreated - } - listener(api.ContainerEvent{ - Type: eType, - Container: name, - ID: container.ID, - Service: service, - }) - } - - delete(watched, container.ID) - expected = utils.Remove(expected, container.ID) - case "die": - restarted := watched[container.ID] - watched[container.ID] = restarted + 1 - // Container terminated. - willRestart := inspected.State.Restarting - - eType := api.ContainerEventExit - if utils.Contains(replaced, container.ID) { - utils.Remove(replaced, container.ID) - eType = api.ContainerEventRecreated - } - - listener(api.ContainerEvent{ - Type: eType, - Container: name, - ID: container.ID, - Service: service, - ExitCode: inspected.State.ExitCode, - Restarting: willRestart, - }) - - if !willRestart { - // we're done with this one - delete(watched, container.ID) - expected = utils.Remove(expected, container.ID) - } - case "start": - count, ok := watched[container.ID] - mustAttach := ok && count > 0 // Container restarted, need to re-attach - if !ok { - // A new container has just been added to service by scale - watched[container.ID] = 0 - expected = append(expected, container.ID) - mustAttach = true - } - if mustAttach { - // Container restarted, need to re-attach - err := onStart(container, event.Timestamp) - if err != nil { - return err - } - } - case "create": - if id, ok := container.Labels[api.ContainerReplaceLabel]; ok { - replaced = append(replaced, id) - err = onRecreate(container, event.Timestamp) - if err != nil { - return err - } - if utils.StringContains(expected, id) { - expected = append(expected, inspected.ID) - } - watched[container.ID] = 1 - if utils.Contains(expected, id) { - expected = append(expected, container.ID) - } - } else if ofInterest(container) { - watched[container.ID] = 1 - if isRequired(container) { - expected = append(expected, container.ID) - } - } - } - if len(expected) == 0 { - stop() - } - return nil - }, - }) - if errors.Is(ctx.Err(), context.Canceled) { - return nil - } - return err -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/stop.go b/vendor/github.com/docker/compose/v2/pkg/compose/stop.go deleted file mode 100644 index a7f6d68db..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/stop.go +++ /dev/null @@ -1,59 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "strings" - - "github.com/docker/compose/v2/pkg/api" - "github.com/docker/compose/v2/pkg/progress" - "github.com/docker/compose/v2/pkg/utils" -) - -func (s *composeService) Stop(ctx context.Context, projectName string, options api.StopOptions) error { - return progress.RunWithTitle(ctx, func(ctx context.Context) error { - return s.stop(ctx, strings.ToLower(projectName), options) - }, s.stdinfo(), "Stopping") -} - -func (s *composeService) stop(ctx context.Context, projectName string, options api.StopOptions) error { - containers, err := s.getContainers(ctx, projectName, oneOffExclude, true) - if err != nil { - return err - } - - project := options.Project - if project == nil { - project, err = s.getProjectWithResources(ctx, containers, projectName) - if err != nil { - return err - } - } - - if len(options.Services) == 0 { - options.Services = project.ServiceNames() - } - - w := progress.ContextWriter(ctx) - return InReverseDependencyOrder(ctx, project, func(c context.Context, service string) error { - if !utils.StringContains(options.Services, service) { - return nil - } - return s.stopContainers(ctx, w, containers.filter(isService(service)).filter(isNotOneOff), options.Timeout) - }) -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/top.go b/vendor/github.com/docker/compose/v2/pkg/compose/top.go deleted file mode 100644 index 1ac4cd4c4..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/top.go +++ /dev/null @@ -1,56 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "strings" - - "github.com/docker/compose/v2/pkg/api" - "golang.org/x/sync/errgroup" -) - -func (s *composeService) Top(ctx context.Context, projectName string, services []string) ([]api.ContainerProcSummary, error) { - projectName = strings.ToLower(projectName) - var containers Containers - containers, err := s.getContainers(ctx, projectName, oneOffInclude, false) - if err != nil { - return nil, err - } - if len(services) > 0 { - containers = containers.filter(isService(services...)) - } - summary := make([]api.ContainerProcSummary, len(containers)) - eg, ctx := errgroup.WithContext(ctx) - for i, container := range containers { - i, container := i, container - eg.Go(func() error { - topContent, err := s.apiClient().ContainerTop(ctx, container.ID, []string{}) - if err != nil { - return err - } - summary[i] = api.ContainerProcSummary{ - ID: container.ID, - Name: getCanonicalContainerName(container), - Processes: topContent.Processes, - Titles: topContent.Titles, - } - return nil - }) - } - return summary, eg.Wait() -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/up.go b/vendor/github.com/docker/compose/v2/pkg/compose/up.go deleted file mode 100644 index a0225c45a..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/up.go +++ /dev/null @@ -1,114 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "fmt" - "os" - "os/signal" - "syscall" - - "github.com/docker/compose/v2/internal/tracing" - - "github.com/compose-spec/compose-go/types" - "github.com/docker/cli/cli" - "github.com/docker/compose/v2/pkg/api" - "github.com/docker/compose/v2/pkg/progress" - "golang.org/x/sync/errgroup" -) - -func (s *composeService) Up(ctx context.Context, project *types.Project, options api.UpOptions) error { - err := progress.Run(ctx, tracing.SpanWrapFunc("project/up", tracing.ProjectOptions(project), func(ctx context.Context) error { - err := s.create(ctx, project, options.Create) - if err != nil { - return err - } - if options.Start.Attach == nil { - return s.start(ctx, project.Name, options.Start, nil) - } - return nil - }), s.stdinfo()) - if err != nil { - return err - } - - if options.Start.Attach == nil { - return err - } - if s.dryRun { - fmt.Fprintln(s.stdout(), "end of 'compose up' output, interactive run is not supported in dry-run mode") - return err - } - - printer := newLogPrinter(options.Start.Attach) - - signalChan := make(chan os.Signal, 1) - signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM) - - stopFunc := func() error { - fmt.Fprintln(s.stdinfo(), "Aborting on container exit...") - ctx := context.Background() - return progress.Run(ctx, func(ctx context.Context) error { - go func() { - <-signalChan - s.Kill(ctx, project.Name, api.KillOptions{ //nolint:errcheck - Services: options.Create.Services, - Project: project, - }) - }() - - return s.Stop(ctx, project.Name, api.StopOptions{ - Services: options.Create.Services, - Project: project, - }) - }, s.stdinfo()) - } - - var isTerminated bool - eg, ctx := errgroup.WithContext(ctx) - go func() { - <-signalChan - isTerminated = true - printer.Cancel() - fmt.Fprintln(s.stdinfo(), "Gracefully stopping... (press Ctrl+C again to force)") - eg.Go(stopFunc) - }() - - var exitCode int - eg.Go(func() error { - code, err := printer.Run(options.Start.CascadeStop, options.Start.ExitCodeFrom, stopFunc) - exitCode = code - return err - }) - - err = s.start(ctx, project.Name, options.Start, printer.HandleEvent) - if err != nil && !isTerminated { // Ignore error if the process is terminated - return err - } - - printer.Stop() - err = eg.Wait() - if exitCode != 0 { - errMsg := "" - if err != nil { - errMsg = err.Error() - } - return cli.StatusError{StatusCode: exitCode, Status: errMsg} - } - return err -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/viz.go b/vendor/github.com/docker/compose/v2/pkg/compose/viz.go deleted file mode 100644 index 25ea7a2be..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/viz.go +++ /dev/null @@ -1,141 +0,0 @@ -/* - Copyright 2023 Docker Compose CLI 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 compose - -import ( - "context" - "strconv" - "strings" - - "github.com/compose-spec/compose-go/types" - "github.com/docker/compose/v2/pkg/api" -) - -// maps a service with the services it depends on -type vizGraph map[*types.ServiceConfig][]*types.ServiceConfig - -func (s *composeService) Viz(_ context.Context, project *types.Project, opts api.VizOptions) (string, error) { - graph := make(vizGraph) - for i, serviceConfig := range project.Services { - serviceConfigPtr := &project.Services[i] - graph[serviceConfigPtr] = make([]*types.ServiceConfig, 0, len(serviceConfig.DependsOn)) - for dependencyName := range serviceConfig.DependsOn { - // no error should be returned since dependencyName should exist - dependency, _ := project.GetService(dependencyName) - graph[serviceConfigPtr] = append(graph[serviceConfigPtr], &dependency) - } - } - - // build graphviz graph - var graphBuilder strings.Builder - - // graph name - graphBuilder.WriteString("digraph ") - writeQuoted(&graphBuilder, project.Name) - graphBuilder.WriteString(" {\n") - - // graph layout - // dot is the perfect layout for this use case since graph is directed and hierarchical - graphBuilder.WriteString(opts.Indentation + "layout=dot;\n") - - addNodes(&graphBuilder, graph, project.Name, &opts) - graphBuilder.WriteByte('\n') - - addEdges(&graphBuilder, graph, &opts) - graphBuilder.WriteString("}\n") - - return graphBuilder.String(), nil -} - -// addNodes adds the corresponding graphviz representation of all the nodes in the given graph to the graphBuilder -// returns the same graphBuilder -func addNodes(graphBuilder *strings.Builder, graph vizGraph, projectName string, opts *api.VizOptions) *strings.Builder { - for serviceNode := range graph { - // write: - // "service name" [style="filled" label<service name - graphBuilder.WriteString(opts.Indentation) - writeQuoted(graphBuilder, serviceNode.Name) - graphBuilder.WriteString(" [style=\"filled\" label=<") - graphBuilder.WriteString(serviceNode.Name) - graphBuilder.WriteString("") - - if opts.IncludeNetworks && len(serviceNode.Networks) > 0 { - graphBuilder.WriteString("") - graphBuilder.WriteString("

Networks:") - for _, networkName := range serviceNode.NetworksByPriority() { - graphBuilder.WriteString("
") - graphBuilder.WriteString(networkName) - } - graphBuilder.WriteString("
") - } - - if opts.IncludePorts && len(serviceNode.Ports) > 0 { - graphBuilder.WriteString("") - graphBuilder.WriteString("

Ports:") - for _, portConfig := range serviceNode.Ports { - graphBuilder.WriteString("
") - if len(portConfig.HostIP) > 0 { - graphBuilder.WriteString(portConfig.HostIP) - graphBuilder.WriteByte(':') - } - graphBuilder.WriteString(portConfig.Published) - graphBuilder.WriteByte(':') - graphBuilder.WriteString(strconv.Itoa(int(portConfig.Target))) - graphBuilder.WriteString(" (") - graphBuilder.WriteString(portConfig.Protocol) - graphBuilder.WriteString(", ") - graphBuilder.WriteString(portConfig.Mode) - graphBuilder.WriteString(")") - } - graphBuilder.WriteString("
") - } - - if opts.IncludeImageName { - graphBuilder.WriteString("") - graphBuilder.WriteString("

Image:
") - graphBuilder.WriteString(api.GetImageNameOrDefault(*serviceNode, projectName)) - graphBuilder.WriteString("
") - } - - graphBuilder.WriteString(">];\n") - } - - return graphBuilder -} - -// addEdges adds the corresponding graphviz representation of all edges in the given graph to the graphBuilder -// returns the same graphBuilder -func addEdges(graphBuilder *strings.Builder, graph vizGraph, opts *api.VizOptions) *strings.Builder { - for parent, children := range graph { - for _, child := range children { - graphBuilder.WriteString(opts.Indentation) - writeQuoted(graphBuilder, parent.Name) - graphBuilder.WriteString(" -> ") - writeQuoted(graphBuilder, child.Name) - graphBuilder.WriteString(";\n") - } - } - - return graphBuilder -} - -// writeQuoted writes "str" to builder -func writeQuoted(builder *strings.Builder, str string) { - builder.WriteByte('"') - builder.WriteString(str) - builder.WriteByte('"') -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/wait.go b/vendor/github.com/docker/compose/v2/pkg/compose/wait.go deleted file mode 100644 index 952e65cf8..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/wait.go +++ /dev/null @@ -1,67 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "fmt" - - "github.com/docker/compose/v2/pkg/api" - "golang.org/x/sync/errgroup" -) - -func (s *composeService) Wait(ctx context.Context, projectName string, options api.WaitOptions) (int64, error) { - containers, err := s.getContainers(ctx, projectName, oneOffInclude, false, options.Services...) - if err != nil { - return 0, err - } - if len(containers) == 0 { - return 0, fmt.Errorf("no containers for project %q", projectName) - } - - eg, waitCtx := errgroup.WithContext(ctx) - var statusCode int64 - for _, c := range containers { - c := c - eg.Go(func() error { - var err error - resultC, errC := s.dockerCli.Client().ContainerWait(waitCtx, c.ID, "") - - select { - case result := <-resultC: - fmt.Fprintf(s.dockerCli.Out(), "container %q exited with status code %d\n", c.ID, result.StatusCode) - statusCode = result.StatusCode - case err = <-errC: - } - - return err - }) - } - - err = eg.Wait() - if err != nil { - return 42, err // Ignore abort flag in case of error in wait - } - - if options.DownProjectOnContainerExit { - return statusCode, s.Down(ctx, projectName, api.DownOptions{ - RemoveOrphans: true, - }) - } - - return statusCode, err -} diff --git a/vendor/github.com/docker/compose/v2/pkg/compose/watch.go b/vendor/github.com/docker/compose/v2/pkg/compose/watch.go deleted file mode 100644 index 7d7ba4c58..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/compose/watch.go +++ /dev/null @@ -1,515 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 compose - -import ( - "context" - "fmt" - "io" - "os" - "path" - "path/filepath" - "sort" - "strconv" - "strings" - "time" - - moby "github.com/docker/docker/api/types" - - "github.com/docker/compose/v2/internal/sync" - - "github.com/compose-spec/compose-go/types" - "github.com/jonboulle/clockwork" - "github.com/mitchellh/mapstructure" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" - "golang.org/x/sync/errgroup" - - "github.com/docker/compose/v2/pkg/api" - "github.com/docker/compose/v2/pkg/watch" -) - -type DevelopmentConfig struct { - Watch []Trigger `json:"watch,omitempty"` -} - -type WatchAction string - -const ( - WatchActionSync WatchAction = "sync" - WatchActionRebuild WatchAction = "rebuild" -) - -type Trigger struct { - Path string `json:"path,omitempty"` - Action string `json:"action,omitempty"` - Target string `json:"target,omitempty"` - Ignore []string `json:"ignore,omitempty"` -} - -const quietPeriod = 500 * time.Millisecond - -// fileEvent contains the Compose service and modified host system path. -type fileEvent struct { - sync.PathMapping - Action WatchAction -} - -// getSyncImplementation returns the the tar-based syncer unless it has been explicitly -// disabled with `COMPOSE_EXPERIMENTAL_WATCH_TAR=0`. Note that the absence of the env -// var means enabled. -func (s *composeService) getSyncImplementation(project *types.Project) sync.Syncer { - var useTar bool - if useTarEnv, ok := os.LookupEnv("COMPOSE_EXPERIMENTAL_WATCH_TAR"); ok { - useTar, _ = strconv.ParseBool(useTarEnv) - } else { - useTar = true - } - if useTar { - return sync.NewTar(project.Name, tarDockerClient{s: s}) - } - - return sync.NewDockerCopy(project.Name, s, s.stdinfo()) -} - -func (s *composeService) Watch(ctx context.Context, project *types.Project, services []string, _ api.WatchOptions) error { //nolint: gocyclo - _, err := s.prepareProjectForBuild(project, nil) - if err != nil { - return err - } - if err := project.ForServices(services); err != nil { - return err - } - syncer := s.getSyncImplementation(project) - eg, ctx := errgroup.WithContext(ctx) - watching := false - for i := range project.Services { - service := project.Services[i] - config, err := loadDevelopmentConfig(service, project) - if err != nil { - return err - } - - if config == nil { - continue - } - - if len(config.Watch) > 0 && service.Build == nil { - // service configured with watchers but no build section - return fmt.Errorf("can't watch service %q without a build context", service.Name) - } - - if len(services) > 0 && service.Build == nil { - // service explicitly selected for watch has no build section - return fmt.Errorf("can't watch service %q without a build context", service.Name) - } - - if len(services) == 0 && service.Build == nil { - continue - } - - // set the service to always be built - watch triggers `Up()` when it receives a rebuild event - service.PullPolicy = types.PullPolicyBuild - project.Services[i] = service - - dockerIgnores, err := watch.LoadDockerIgnore(service.Build.Context) - if err != nil { - return err - } - - // add a hardcoded set of ignores on top of what came from .dockerignore - // some of this should likely be configurable (e.g. there could be cases - // where you want `.git` to be synced) but this is suitable for now - dotGitIgnore, err := watch.NewDockerPatternMatcher("/", []string{".git/"}) - if err != nil { - return err - } - ignore := watch.NewCompositeMatcher( - dockerIgnores, - watch.EphemeralPathMatcher(), - dotGitIgnore, - ) - - var paths []string - for _, trigger := range config.Watch { - if checkIfPathAlreadyBindMounted(trigger.Path, service.Volumes) { - logrus.Warnf("path '%s' also declared by a bind mount volume, this path won't be monitored!\n", trigger.Path) - continue - } - paths = append(paths, trigger.Path) - } - - watcher, err := watch.NewWatcher(paths, ignore) - if err != nil { - return err - } - - fmt.Fprintf(s.stdinfo(), "watching %s\n", paths) - err = watcher.Start() - if err != nil { - return err - } - watching = true - - eg.Go(func() error { - defer watcher.Close() //nolint:errcheck - return s.watch(ctx, project, service.Name, watcher, syncer, config.Watch) - }) - } - - if !watching { - return fmt.Errorf("none of the selected services is configured for watch, consider setting an 'x-develop' section") - } - - return eg.Wait() -} - -func (s *composeService) watch( - ctx context.Context, - project *types.Project, - name string, - watcher watch.Notify, - syncer sync.Syncer, - triggers []Trigger, -) error { - ctx, cancel := context.WithCancel(ctx) - defer cancel() - - ignores := make([]watch.PathMatcher, len(triggers)) - for i, trigger := range triggers { - ignore, err := watch.NewDockerPatternMatcher(trigger.Path, trigger.Ignore) - if err != nil { - return err - } - ignores[i] = ignore - } - - events := make(chan fileEvent) - batchEvents := batchDebounceEvents(ctx, s.clock, quietPeriod, events) - go func() { - for { - select { - case <-ctx.Done(): - return - case batch := <-batchEvents: - start := time.Now() - logrus.Debugf("batch start: service[%s] count[%d]", name, len(batch)) - if err := s.handleWatchBatch(ctx, project, name, batch, syncer); err != nil { - logrus.Warnf("Error handling changed files for service %s: %v", name, err) - } - logrus.Debugf("batch complete: service[%s] duration[%s] count[%d]", - name, time.Since(start), len(batch)) - } - } - }() - - for { - select { - case <-ctx.Done(): - return nil - case err := <-watcher.Errors(): - return err - case event := <-watcher.Events(): - hostPath := event.Path() - for i, trigger := range triggers { - logrus.Debugf("change for %s - comparing with %s", hostPath, trigger.Path) - if fileEvent := maybeFileEvent(trigger, hostPath, ignores[i]); fileEvent != nil { - events <- *fileEvent - } - } - } - } -} - -// maybeFileEvent returns a file event object if hostPath is valid for the provided trigger and ignore -// rules. -// -// Any errors are logged as warnings and nil (no file event) is returned. -func maybeFileEvent(trigger Trigger, hostPath string, ignore watch.PathMatcher) *fileEvent { - if !watch.IsChild(trigger.Path, hostPath) { - return nil - } - isIgnored, err := ignore.Matches(hostPath) - if err != nil { - logrus.Warnf("error ignore matching %q: %v", hostPath, err) - return nil - } - - if isIgnored { - logrus.Debugf("%s is matching ignore pattern", hostPath) - return nil - } - - var containerPath string - if trigger.Target != "" { - rel, err := filepath.Rel(trigger.Path, hostPath) - if err != nil { - logrus.Warnf("error making %s relative to %s: %v", hostPath, trigger.Path, err) - return nil - } - // always use Unix-style paths for inside the container - containerPath = path.Join(trigger.Target, rel) - } - - return &fileEvent{ - Action: WatchAction(trigger.Action), - PathMapping: sync.PathMapping{ - HostPath: hostPath, - ContainerPath: containerPath, - }, - } -} - -func loadDevelopmentConfig(service types.ServiceConfig, project *types.Project) (*DevelopmentConfig, error) { - var config DevelopmentConfig - y, ok := service.Extensions["x-develop"] - if !ok { - return nil, nil - } - err := mapstructure.Decode(y, &config) - if err != nil { - return nil, err - } - baseDir, err := filepath.EvalSymlinks(project.WorkingDir) - if err != nil { - return nil, fmt.Errorf("resolving symlink for %q: %w", project.WorkingDir, err) - } - - for i, trigger := range config.Watch { - if !filepath.IsAbs(trigger.Path) { - trigger.Path = filepath.Join(baseDir, trigger.Path) - } - if p, err := filepath.EvalSymlinks(trigger.Path); err == nil { - // this might fail because the path doesn't exist, etc. - trigger.Path = p - } - trigger.Path = filepath.Clean(trigger.Path) - if trigger.Path == "" { - return nil, errors.New("watch rules MUST define a path") - } - - if trigger.Action == string(WatchActionRebuild) && service.Build == nil { - return nil, fmt.Errorf("service %s doesn't have a build section, can't apply 'rebuild' on watch", service.Name) - } - - config.Watch[i] = trigger - } - return &config, nil -} - -// batchDebounceEvents groups identical file events within a sliding time window and writes the results to the returned -// channel. -// -// The returned channel is closed when the debouncer is stopped via context cancellation or by closing the input channel. -func batchDebounceEvents(ctx context.Context, clock clockwork.Clock, delay time.Duration, input <-chan fileEvent) <-chan []fileEvent { - out := make(chan []fileEvent) - go func() { - defer close(out) - seen := make(map[fileEvent]time.Time) - flushEvents := func() { - if len(seen) == 0 { - return - } - events := make([]fileEvent, 0, len(seen)) - for e := range seen { - events = append(events, e) - } - // sort batch by oldest -> newest - // (if an event is seen > 1 per batch, it gets the latest timestamp) - sort.SliceStable(events, func(i, j int) bool { - x := events[i] - y := events[j] - return seen[x].Before(seen[y]) - }) - out <- events - seen = make(map[fileEvent]time.Time) - } - - t := clock.NewTicker(delay) - defer t.Stop() - for { - select { - case <-ctx.Done(): - return - case <-t.Chan(): - flushEvents() - case e, ok := <-input: - if !ok { - // input channel was closed - flushEvents() - return - } - seen[e] = time.Now() - t.Reset(delay) - } - } - }() - return out -} - -func checkIfPathAlreadyBindMounted(watchPath string, volumes []types.ServiceVolumeConfig) bool { - for _, volume := range volumes { - if volume.Bind != nil && strings.HasPrefix(watchPath, volume.Source) { - return true - } - } - return false -} - -type tarDockerClient struct { - s *composeService -} - -func (t tarDockerClient) ContainersForService(ctx context.Context, projectName string, serviceName string) ([]moby.Container, error) { - containers, err := t.s.getContainers(ctx, projectName, oneOffExclude, true, serviceName) - if err != nil { - return nil, err - } - return containers, nil -} - -func (t tarDockerClient) Exec(ctx context.Context, containerID string, cmd []string, in io.Reader) error { - execCfg := moby.ExecConfig{ - Cmd: cmd, - AttachStdout: false, - AttachStderr: true, - AttachStdin: in != nil, - Tty: false, - } - execCreateResp, err := t.s.apiClient().ContainerExecCreate(ctx, containerID, execCfg) - if err != nil { - return err - } - - startCheck := moby.ExecStartCheck{Tty: false, Detach: false} - conn, err := t.s.apiClient().ContainerExecAttach(ctx, execCreateResp.ID, startCheck) - if err != nil { - return err - } - defer conn.Close() - - var eg errgroup.Group - if in != nil { - eg.Go(func() error { - defer func() { - _ = conn.CloseWrite() - }() - _, err := io.Copy(conn.Conn, in) - return err - }) - } - eg.Go(func() error { - _, err := io.Copy(t.s.stdinfo(), conn.Reader) - return err - }) - - err = t.s.apiClient().ContainerExecStart(ctx, execCreateResp.ID, startCheck) - if err != nil { - return err - } - - // although the errgroup is not tied directly to the context, the operations - // in it are reading/writing to the connection, which is tied to the context, - // so they won't block indefinitely - if err := eg.Wait(); err != nil { - return err - } - - execResult, err := t.s.apiClient().ContainerExecInspect(ctx, execCreateResp.ID) - if err != nil { - return err - } - if execResult.Running { - return errors.New("process still running") - } - if execResult.ExitCode != 0 { - return fmt.Errorf("exit code %d", execResult.ExitCode) - } - return nil -} - -func (s *composeService) handleWatchBatch( - ctx context.Context, - project *types.Project, - serviceName string, - batch []fileEvent, - syncer sync.Syncer, -) error { - pathMappings := make([]sync.PathMapping, len(batch)) - for i := range batch { - if batch[i].Action == WatchActionRebuild { - fmt.Fprintf( - s.stdinfo(), - "Rebuilding %s after changes were detected:%s\n", - serviceName, - strings.Join(append([]string{""}, batch[i].HostPath), "\n - "), - ) - err := s.Up(ctx, project, api.UpOptions{ - Create: api.CreateOptions{ - Services: []string{serviceName}, - Inherit: true, - }, - Start: api.StartOptions{ - Services: []string{serviceName}, - Project: project, - }, - }) - if err != nil { - fmt.Fprintf(s.stderr(), "Application failed to start after update\n") - } - return nil - } - pathMappings[i] = batch[i].PathMapping - } - - writeWatchSyncMessage(s.stdinfo(), serviceName, pathMappings) - - service, err := project.GetService(serviceName) - if err != nil { - return err - } - if err := syncer.Sync(ctx, service, pathMappings); err != nil { - return err - } - return nil -} - -// writeWatchSyncMessage prints out a message about the sync for the changed paths. -func writeWatchSyncMessage(w io.Writer, serviceName string, pathMappings []sync.PathMapping) { - const maxPathsToShow = 10 - if len(pathMappings) <= maxPathsToShow || logrus.IsLevelEnabled(logrus.DebugLevel) { - hostPathsToSync := make([]string, len(pathMappings)) - for i := range pathMappings { - hostPathsToSync[i] = pathMappings[i].HostPath - } - fmt.Fprintf( - w, - "Syncing %s after changes were detected:%s\n", - serviceName, - strings.Join(append([]string{""}, hostPathsToSync...), "\n - "), - ) - } else { - hostPathsToSync := make([]string, len(pathMappings)) - for i := range pathMappings { - hostPathsToSync[i] = pathMappings[i].HostPath - } - fmt.Fprintf( - w, - "Syncing %s after %d changes were detected\n", - serviceName, - len(pathMappings), - ) - } -} diff --git a/vendor/github.com/docker/compose/v2/pkg/progress/colors.go b/vendor/github.com/docker/compose/v2/pkg/progress/colors.go deleted file mode 100644 index 716171df8..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/progress/colors.go +++ /dev/null @@ -1,47 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 progress - -import ( - "github.com/morikuni/aec" -) - -type colorFunc func(string) string - -var ( - nocolor colorFunc = func(s string) string { - return s - } - - DoneColor colorFunc = aec.BlueF.Apply - TimerColor colorFunc = aec.BlueF.Apply - CountColor colorFunc = aec.YellowF.Apply - WarningColor colorFunc = aec.YellowF.With(aec.Bold).Apply - SuccessColor colorFunc = aec.GreenF.Apply - ErrorColor colorFunc = aec.RedF.With(aec.Bold).Apply - PrefixColor colorFunc = aec.CyanF.Apply -) - -func NoColor() { - DoneColor = nocolor - TimerColor = nocolor - CountColor = nocolor - WarningColor = nocolor - SuccessColor = nocolor - ErrorColor = nocolor - PrefixColor = nocolor -} diff --git a/vendor/github.com/docker/compose/v2/pkg/progress/event.go b/vendor/github.com/docker/compose/v2/pkg/progress/event.go deleted file mode 100644 index 26aca98d8..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/progress/event.go +++ /dev/null @@ -1,196 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 progress - -import ( - "time" -) - -// EventStatus indicates the status of an action -type EventStatus int - -func (s EventStatus) colorFn() colorFunc { - switch s { - case Done: - return SuccessColor - case Warning: - return WarningColor - case Error: - return ErrorColor - default: - return nocolor - } -} - -const ( - // Working means that the current task is working - Working EventStatus = iota - // Done means that the current task is done - Done - // Warning means that the current task has warning - Warning - // Error means that the current task has errored - Error -) - -// Event represents a progress event. -type Event struct { - ID string - ParentID string - Text string - Status EventStatus - StatusText string - Current int64 - Percent int - - Total int64 - startTime time.Time - endTime time.Time - spinner *spinner -} - -// ErrorMessageEvent creates a new Error Event with message -func ErrorMessageEvent(id string, msg string) Event { - return NewEvent(id, Error, msg) -} - -// ErrorEvent creates a new Error Event -func ErrorEvent(id string) Event { - return NewEvent(id, Error, "Error") -} - -// CreatingEvent creates a new Create in progress Event -func CreatingEvent(id string) Event { - return NewEvent(id, Working, "Creating") -} - -// StartingEvent creates a new Starting in progress Event -func StartingEvent(id string) Event { - return NewEvent(id, Working, "Starting") -} - -// StartedEvent creates a new Started in progress Event -func StartedEvent(id string) Event { - return NewEvent(id, Done, "Started") -} - -// Waiting creates a new waiting event -func Waiting(id string) Event { - return NewEvent(id, Working, "Waiting") -} - -// Healthy creates a new healthy event -func Healthy(id string) Event { - return NewEvent(id, Done, "Healthy") -} - -// Exited creates a new exited event -func Exited(id string) Event { - return NewEvent(id, Done, "Exited") -} - -// RestartingEvent creates a new Restarting in progress Event -func RestartingEvent(id string) Event { - return NewEvent(id, Working, "Restarting") -} - -// RestartedEvent creates a new Restarted in progress Event -func RestartedEvent(id string) Event { - return NewEvent(id, Done, "Restarted") -} - -// RunningEvent creates a new Running in progress Event -func RunningEvent(id string) Event { - return NewEvent(id, Done, "Running") -} - -// CreatedEvent creates a new Created (done) Event -func CreatedEvent(id string) Event { - return NewEvent(id, Done, "Created") -} - -// StoppingEvent creates a new Stopping in progress Event -func StoppingEvent(id string) Event { - return NewEvent(id, Working, "Stopping") -} - -// StoppedEvent creates a new Stopping in progress Event -func StoppedEvent(id string) Event { - return NewEvent(id, Done, "Stopped") -} - -// KillingEvent creates a new Killing in progress Event -func KillingEvent(id string) Event { - return NewEvent(id, Working, "Killing") -} - -// KilledEvent creates a new Killed in progress Event -func KilledEvent(id string) Event { - return NewEvent(id, Done, "Killed") -} - -// RemovingEvent creates a new Removing in progress Event -func RemovingEvent(id string) Event { - return NewEvent(id, Working, "Removing") -} - -// RemovedEvent creates a new removed (done) Event -func RemovedEvent(id string) Event { - return NewEvent(id, Done, "Removed") -} - -// SkippedEvent creates a new Skipped Event -func SkippedEvent(id string, reason string) Event { - return Event{ - ID: id, - Status: Warning, - StatusText: "Skipped: " + reason, - } -} - -// NewEvent new event -func NewEvent(id string, status EventStatus, statusText string) Event { - return Event{ - ID: id, - Status: status, - StatusText: statusText, - } -} - -func (e *Event) stop() { - e.endTime = time.Now() - e.spinner.Stop() -} - -var ( - spinnerDone = "✔" - spinnerWarning = "!" - spinnerError = "✘" -) - -func (e *Event) Spinner() any { - switch e.Status { - case Done: - return SuccessColor(spinnerDone) - case Warning: - return WarningColor(spinnerWarning) - case Error: - return ErrorColor(spinnerError) - default: - return e.spinner.String() - } -} diff --git a/vendor/github.com/docker/compose/v2/pkg/progress/noop.go b/vendor/github.com/docker/compose/v2/pkg/progress/noop.go deleted file mode 100644 index 98852705c..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/progress/noop.go +++ /dev/null @@ -1,40 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 progress - -import ( - "context" -) - -type noopWriter struct { -} - -func (p *noopWriter) Start(ctx context.Context) error { - return nil -} - -func (p *noopWriter) Event(Event) { -} - -func (p *noopWriter) Events([]Event) { -} - -func (p *noopWriter) TailMsgf(_ string, _ ...interface{}) { -} - -func (p *noopWriter) Stop() { -} diff --git a/vendor/github.com/docker/compose/v2/pkg/progress/plain.go b/vendor/github.com/docker/compose/v2/pkg/progress/plain.go deleted file mode 100644 index 4a061e183..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/progress/plain.go +++ /dev/null @@ -1,66 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 progress - -import ( - "context" - "fmt" - "io" - - "github.com/docker/compose/v2/pkg/api" -) - -type plainWriter struct { - out io.Writer - done chan bool - dryRun bool -} - -func (p *plainWriter) Start(ctx context.Context) error { - select { - case <-ctx.Done(): - return ctx.Err() - case <-p.done: - return nil - } -} - -func (p *plainWriter) Event(e Event) { - prefix := "" - if p.dryRun { - prefix = api.DRYRUN_PREFIX - } - fmt.Fprintln(p.out, prefix, e.ID, e.Text, e.StatusText) -} - -func (p *plainWriter) Events(events []Event) { - for _, e := range events { - p.Event(e) - } -} - -func (p *plainWriter) TailMsgf(msg string, args ...interface{}) { - msg = fmt.Sprintf(msg, args...) - if p.dryRun { - msg = api.DRYRUN_PREFIX + msg - } - fmt.Fprintln(p.out, msg) -} - -func (p *plainWriter) Stop() { - p.done <- true -} diff --git a/vendor/github.com/docker/compose/v2/pkg/progress/quiet.go b/vendor/github.com/docker/compose/v2/pkg/progress/quiet.go deleted file mode 100644 index 5c5530d76..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/progress/quiet.go +++ /dev/null @@ -1,37 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 progress - -import "context" - -type quiet struct{} - -func (q quiet) Start(_ context.Context) error { - return nil -} - -func (q quiet) Stop() { -} - -func (q quiet) Event(_ Event) { -} - -func (q quiet) Events(_ []Event) { -} - -func (q quiet) TailMsgf(_ string, _ ...interface{}) { -} diff --git a/vendor/github.com/docker/compose/v2/pkg/progress/spinner.go b/vendor/github.com/docker/compose/v2/pkg/progress/spinner.go deleted file mode 100644 index 3e757acf4..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/progress/spinner.go +++ /dev/null @@ -1,66 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 progress - -import ( - "runtime" - "time" -) - -type spinner struct { - time time.Time - index int - chars []string - stop bool - done string -} - -func newSpinner() *spinner { - chars := []string{ - "⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏", - } - done := "⠿" - - if runtime.GOOS == "windows" { - chars = []string{"-"} - done = "-" - } - - return &spinner{ - index: 0, - time: time.Now(), - chars: chars, - done: done, - } -} - -func (s *spinner) String() string { - if s.stop { - return s.done - } - - d := time.Since(s.time) - if d.Milliseconds() > 100 { - s.index = (s.index + 1) % len(s.chars) - } - - return s.chars[s.index] -} - -func (s *spinner) Stop() { - s.stop = true -} diff --git a/vendor/github.com/docker/compose/v2/pkg/progress/tty.go b/vendor/github.com/docker/compose/v2/pkg/progress/tty.go deleted file mode 100644 index c6b806819..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/progress/tty.go +++ /dev/null @@ -1,326 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 progress - -import ( - "context" - "fmt" - "io" - "strings" - "sync" - "time" - - "github.com/docker/compose/v2/pkg/api" - "github.com/docker/compose/v2/pkg/utils" - - "github.com/buger/goterm" - "github.com/docker/go-units" - "github.com/morikuni/aec" -) - -type ttyWriter struct { - out io.Writer - events map[string]Event - eventIDs []string - repeated bool - numLines int - done chan bool - mtx *sync.Mutex - tailEvents []string - dryRun bool - skipChildEvents bool - progressTitle string -} - -func (w *ttyWriter) Start(ctx context.Context) error { - ticker := time.NewTicker(100 * time.Millisecond) - defer ticker.Stop() - - for { - select { - case <-ctx.Done(): - w.print() - w.printTailEvents() - return ctx.Err() - case <-w.done: - w.print() - w.printTailEvents() - return nil - case <-ticker.C: - w.print() - } - } -} - -func (w *ttyWriter) Stop() { - w.done <- true -} - -func (w *ttyWriter) Event(e Event) { - w.mtx.Lock() - defer w.mtx.Unlock() - w.event(e) -} - -func (w *ttyWriter) event(e Event) { - if !utils.StringContains(w.eventIDs, e.ID) { - w.eventIDs = append(w.eventIDs, e.ID) - } - if _, ok := w.events[e.ID]; ok { - last := w.events[e.ID] - switch e.Status { - case Done, Error, Warning: - if last.endTime.IsZero() { - last.stop() - } - case Working: - if !last.endTime.IsZero() { - // already done, don't overwrite - return - } - } - last.Status = e.Status - last.Text = e.Text - last.StatusText = e.StatusText - last.Total = e.Total - last.Current = e.Current - last.Percent = e.Percent - // allow set/unset of parent, but not swapping otherwise prompt is flickering - if last.ParentID == "" || e.ParentID == "" { - last.ParentID = e.ParentID - } - w.events[e.ID] = last - } else { - e.startTime = time.Now() - e.spinner = newSpinner() - if e.Status == Done || e.Status == Error { - e.stop() - } - w.events[e.ID] = e - } -} - -func (w *ttyWriter) Events(events []Event) { - w.mtx.Lock() - defer w.mtx.Unlock() - for _, e := range events { - w.event(e) - } -} - -func (w *ttyWriter) TailMsgf(msg string, args ...interface{}) { - w.mtx.Lock() - defer w.mtx.Unlock() - msgWithPrefix := msg - if w.dryRun { - msgWithPrefix = strings.TrimSpace(api.DRYRUN_PREFIX + msg) - } - w.tailEvents = append(w.tailEvents, fmt.Sprintf(msgWithPrefix, args...)) -} - -func (w *ttyWriter) printTailEvents() { - w.mtx.Lock() - defer w.mtx.Unlock() - for _, msg := range w.tailEvents { - fmt.Fprintln(w.out, msg) - } -} - -func (w *ttyWriter) print() { //nolint:gocyclo - w.mtx.Lock() - defer w.mtx.Unlock() - if len(w.eventIDs) == 0 { - return - } - terminalWidth := goterm.Width() - b := aec.EmptyBuilder - for i := 0; i <= w.numLines; i++ { - b = b.Up(1) - } - if !w.repeated { - b = b.Down(1) - } - w.repeated = true - fmt.Fprint(w.out, b.Column(0).ANSI) - - // Hide the cursor while we are printing - fmt.Fprint(w.out, aec.Hide) - defer fmt.Fprint(w.out, aec.Show) - - firstLine := fmt.Sprintf("[+] %s %d/%d", w.progressTitle, numDone(w.events), w.numLines) - if w.numLines != 0 && numDone(w.events) == w.numLines { - firstLine = DoneColor(firstLine) - } - fmt.Fprintln(w.out, firstLine) - - var statusPadding int - for _, v := range w.eventIDs { - event := w.events[v] - l := len(fmt.Sprintf("%s %s", event.ID, event.Text)) - if statusPadding < l { - statusPadding = l - } - if event.ParentID != "" { - statusPadding -= 2 - } - } - - if len(w.eventIDs) > goterm.Height()-2 { - w.skipChildEvents = true - } - numLines := 0 - for _, v := range w.eventIDs { - event := w.events[v] - if event.ParentID != "" { - continue - } - line := w.lineText(event, "", terminalWidth, statusPadding, w.dryRun) - fmt.Fprint(w.out, line) - numLines++ - for _, v := range w.eventIDs { - ev := w.events[v] - if ev.ParentID == event.ID { - if w.skipChildEvents { - continue - } - line := w.lineText(ev, " ", terminalWidth, statusPadding, w.dryRun) - fmt.Fprint(w.out, line) - numLines++ - } - } - } - for i := numLines; i < w.numLines; i++ { - if numLines < goterm.Height()-2 { - fmt.Fprintln(w.out, strings.Repeat(" ", terminalWidth)) - numLines++ - } - } - w.numLines = numLines -} - -func (w *ttyWriter) lineText(event Event, pad string, terminalWidth, statusPadding int, dryRun bool) string { - endTime := time.Now() - if event.Status != Working { - endTime = event.startTime - if (event.endTime != time.Time{}) { - endTime = event.endTime - } - } - prefix := "" - if dryRun { - prefix = PrefixColor(api.DRYRUN_PREFIX) - } - - elapsed := endTime.Sub(event.startTime).Seconds() - - var ( - total int64 - current int64 - completion []string - ) - - for _, v := range w.eventIDs { - ev := w.events[v] - if ev.ParentID == event.ID { - total += ev.Total - current += ev.Current - completion = append(completion, percentChars[(len(percentChars)-1)*ev.Percent/100]) - } - } - - var txt string - if len(completion) > 0 { - txt = fmt.Sprintf("%s %s [%s] %7s/%-7s %s", - event.ID, - CountColor(fmt.Sprintf("%d layers", len(completion))), - SuccessColor(strings.Join(completion, "")), - units.HumanSize(float64(current)), units.HumanSize(float64(total)), - event.Text) - } else { - txt = fmt.Sprintf("%s %s", event.ID, event.Text) - } - textLen := len(txt) - padding := statusPadding - textLen - if padding < 0 { - padding = 0 - } - // calculate the max length for the status text, on errors it - // is 2-3 lines long and breaks the line formatting - maxStatusLen := terminalWidth - textLen - statusPadding - 15 - status := event.StatusText - // in some cases (debugging under VS Code), terminalWidth is set to zero by goterm.Width() ; ensuring we don't tweak strings with negative char index - if maxStatusLen > 0 && len(status) > maxStatusLen { - status = status[:maxStatusLen] + "..." - } - text := fmt.Sprintf("%s %s%s %s%s %s", - pad, - event.Spinner(), - prefix, - txt, - strings.Repeat(" ", padding), - event.Status.colorFn()(status), - ) - timer := fmt.Sprintf("%.1fs ", elapsed) - o := align(text, TimerColor(timer), terminalWidth) - - return o -} - -func numDone(events map[string]Event) int { - i := 0 - for _, e := range events { - if e.Status != Working { - i++ - } - } - return i -} - -func align(l, r string, w int) string { - ll := lenAnsi(l) - lr := lenAnsi(r) - pad := "" - count := w - ll - lr - if count > 0 { - pad = strings.Repeat(" ", count) - } - return fmt.Sprintf("%s%s%s\n", l, pad, r) -} - -// lenAnsi count of user-perceived characters in ANSI string. -func lenAnsi(s string) int { - length := 0 - ansiCode := false - for _, r := range s { - if r == '\x1b' { - ansiCode = true - continue - } - if ansiCode && r == 'm' { - ansiCode = false - continue - } - if !ansiCode { - length++ - } - } - return length -} - -var ( - percentChars = strings.Split("⠀⡀⣀⣄⣤⣦⣶⣷⣿", "") -) diff --git a/vendor/github.com/docker/compose/v2/pkg/progress/writer.go b/vendor/github.com/docker/compose/v2/pkg/progress/writer.go deleted file mode 100644 index f1dec3c79..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/progress/writer.go +++ /dev/null @@ -1,161 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 progress - -import ( - "context" - "io" - "sync" - - "github.com/containerd/console" - "github.com/moby/term" - "github.com/sirupsen/logrus" - "golang.org/x/sync/errgroup" - - "github.com/docker/compose/v2/pkg/api" -) - -// Writer can write multiple progress events -type Writer interface { - Start(context.Context) error - Stop() - Event(Event) - Events([]Event) - TailMsgf(string, ...interface{}) -} - -type writerKey struct{} - -// WithContextWriter adds the writer to the context -func WithContextWriter(ctx context.Context, writer Writer) context.Context { - return context.WithValue(ctx, writerKey{}, writer) -} - -// ContextWriter returns the writer from the context -func ContextWriter(ctx context.Context) Writer { - s, ok := ctx.Value(writerKey{}).(Writer) - if !ok { - return &noopWriter{} - } - return s -} - -type progressFunc func(context.Context) error - -type progressFuncWithStatus func(context.Context) (string, error) - -// Run will run a writer and the progress function in parallel -func Run(ctx context.Context, pf progressFunc, out io.Writer) error { - _, err := RunWithStatus(ctx, func(ctx context.Context) (string, error) { - return "", pf(ctx) - }, out, "Running") - return err -} - -func RunWithTitle(ctx context.Context, pf progressFunc, out io.Writer, progressTitle string) error { - _, err := RunWithStatus(ctx, func(ctx context.Context) (string, error) { - return "", pf(ctx) - }, out, progressTitle) - return err -} - -// RunWithStatus will run a writer and the progress function in parallel and return a status -func RunWithStatus(ctx context.Context, pf progressFuncWithStatus, out io.Writer, progressTitle string) (string, error) { - eg, _ := errgroup.WithContext(ctx) - w, err := NewWriter(ctx, out, progressTitle) - var result string - if err != nil { - return "", err - } - eg.Go(func() error { - return w.Start(context.Background()) - }) - - ctx = WithContextWriter(ctx, w) - - eg.Go(func() error { - defer w.Stop() - s, err := pf(ctx) - if err == nil { - result = s - } - return err - }) - - err = eg.Wait() - return result, err -} - -const ( - // ModeAuto detect console capabilities - ModeAuto = "auto" - // ModeTTY use terminal capability for advanced rendering - ModeTTY = "tty" - // ModePlain dump raw events to output - ModePlain = "plain" - // ModeQuiet don't display events - ModeQuiet = "quiet" -) - -// Mode define how progress should be rendered, either as ModePlain or ModeTTY -var Mode = ModeAuto - -// NewWriter returns a new multi-progress writer -func NewWriter(ctx context.Context, out io.Writer, progressTitle string) (Writer, error) { - _, isTerminal := term.GetFdInfo(out) - dryRun, ok := ctx.Value(api.DryRunKey{}).(bool) - if !ok { - dryRun = false - } - if Mode == ModeQuiet { - return quiet{}, nil - } - f, isConsole := out.(console.File) // see https://github.com/docker/compose/issues/10560 - if Mode == ModeAuto && isTerminal && isConsole { - return newTTYWriter(f, dryRun, progressTitle) - } - if Mode == ModeTTY { - if !isConsole { - logrus.Warn("Terminal is not a POSIX console") - } else { - return newTTYWriter(f, dryRun, progressTitle) - } - } - return &plainWriter{ - out: out, - done: make(chan bool), - dryRun: dryRun, - }, nil -} - -func newTTYWriter(out console.File, dryRun bool, progressTitle string) (Writer, error) { - con, err := console.ConsoleFromFile(out) - if err != nil { - return nil, err - } - - return &ttyWriter{ - out: con, - eventIDs: []string{}, - events: map[string]Event{}, - repeated: false, - done: make(chan bool), - mtx: &sync.Mutex{}, - dryRun: dryRun, - progressTitle: progressTitle, - }, nil -} diff --git a/vendor/github.com/docker/compose/v2/pkg/prompt/prompt.go b/vendor/github.com/docker/compose/v2/pkg/prompt/prompt.go deleted file mode 100644 index a6c7fbe49..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/prompt/prompt.go +++ /dev/null @@ -1,101 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 prompt - -import ( - "fmt" - "io" - - "github.com/AlecAivazis/survey/v2" - "github.com/docker/cli/cli/streams" - "github.com/docker/compose/v2/pkg/utils" -) - -//go:generate mockgen -destination=./prompt_mock.go -self_package "github.com/docker/compose/v2/pkg/prompt" -package=prompt . UI - -// UI - prompt user input -type UI interface { - Confirm(message string, defaultValue bool) (bool, error) -} - -func NewPrompt(stdin *streams.In, stdout *streams.Out) UI { - if stdin.IsTerminal() { - return User{stdin: streamsFileReader{stdin}, stdout: streamsFileWriter{stdout}} - } - return Pipe{stdin: stdin, stdout: stdout} -} - -// User - in a terminal -type User struct { - stdout streamsFileWriter - stdin streamsFileReader -} - -// adapt streams.Out to terminal.FileWriter -type streamsFileWriter struct { - stream *streams.Out -} - -func (s streamsFileWriter) Write(p []byte) (n int, err error) { - return s.stream.Write(p) -} - -func (s streamsFileWriter) Fd() uintptr { - return s.stream.FD() -} - -// adapt streams.In to terminal.FileReader -type streamsFileReader struct { - stream *streams.In -} - -func (s streamsFileReader) Read(p []byte) (n int, err error) { - return s.stream.Read(p) -} - -func (s streamsFileReader) Fd() uintptr { - return s.stream.FD() -} - -// Confirm asks for yes or no input -func (u User) Confirm(message string, defaultValue bool) (bool, error) { - qs := &survey.Confirm{ - Message: message, - Default: defaultValue, - } - var b bool - err := survey.AskOne(qs, &b, func(options *survey.AskOptions) error { - options.Stdio.In = u.stdin - options.Stdio.Out = u.stdout - return nil - }) - return b, err -} - -// Pipe - aggregates prompt methods -type Pipe struct { - stdout io.Writer - stdin io.Reader -} - -// Confirm asks for yes or no input -func (u Pipe) Confirm(message string, defaultValue bool) (bool, error) { - fmt.Fprint(u.stdout, message) - var answer string - fmt.Scanln(&answer) - return utils.StringToBool(answer), nil -} diff --git a/vendor/github.com/docker/compose/v2/pkg/prompt/prompt_mock.go b/vendor/github.com/docker/compose/v2/pkg/prompt/prompt_mock.go deleted file mode 100644 index 9acee1ddb..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/prompt/prompt_mock.go +++ /dev/null @@ -1,94 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Container: github.com/docker/compose-cli/pkg/prompt (interfaces: UI) - -// Package prompt is a generated GoMock package. -package prompt - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" -) - -// MockUI is a mock of UI interface -type MockUI struct { - ctrl *gomock.Controller - recorder *MockUIMockRecorder -} - -// MockUIMockRecorder is the mock recorder for MockUI -type MockUIMockRecorder struct { - mock *MockUI -} - -// NewMockUI creates a new mock instance -func NewMockUI(ctrl *gomock.Controller) *MockUI { - mock := &MockUI{ctrl: ctrl} - mock.recorder = &MockUIMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockUI) EXPECT() *MockUIMockRecorder { - return m.recorder -} - -// Confirm mocks base method -func (m *MockUI) Confirm(arg0 string, arg1 bool) (bool, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Confirm", arg0, arg1) - ret0, _ := ret[0].(bool) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Confirm indicates an expected call of Confirm -func (mr *MockUIMockRecorder) Confirm(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Confirm", reflect.TypeOf((*MockUI)(nil).Confirm), arg0, arg1) -} - -// Input mocks base method -func (m *MockUI) Input(arg0, arg1 string) (string, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Input", arg0, arg1) - ret0, _ := ret[0].(string) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Input indicates an expected call of Input -func (mr *MockUIMockRecorder) Input(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Input", reflect.TypeOf((*MockUI)(nil).Input), arg0, arg1) -} - -// Password mocks base method -func (m *MockUI) Password(arg0 string) (string, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Password", arg0) - ret0, _ := ret[0].(string) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Password indicates an expected call of Password -func (mr *MockUIMockRecorder) Password(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Password", reflect.TypeOf((*MockUI)(nil).Password), arg0) -} - -// Select mocks base method -func (m *MockUI) Select(arg0 string, arg1 []string) (int, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Select", arg0, arg1) - ret0, _ := ret[0].(int) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Select indicates an expected call of Select -func (mr *MockUIMockRecorder) Select(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Select", reflect.TypeOf((*MockUI)(nil).Select), arg0, arg1) -} diff --git a/vendor/github.com/docker/compose/v2/pkg/utils/durationutils.go b/vendor/github.com/docker/compose/v2/pkg/utils/durationutils.go deleted file mode 100644 index 98ab3c916..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/utils/durationutils.go +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 utils - -import "time" - -func DurationSecondToInt(d *time.Duration) *int { - if d == nil { - return nil - } - timeout := int(d.Seconds()) - return &timeout -} diff --git a/vendor/github.com/docker/compose/v2/pkg/utils/safebuffer.go b/vendor/github.com/docker/compose/v2/pkg/utils/safebuffer.go deleted file mode 100644 index 0545c463c..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/utils/safebuffer.go +++ /dev/null @@ -1,78 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 utils - -import ( - "bytes" - "strings" - "sync" - "testing" - "time" - - "github.com/stretchr/testify/require" -) - -// SafeBuffer is a thread safe version of bytes.Buffer -type SafeBuffer struct { - m sync.RWMutex - b bytes.Buffer -} - -// Read is a thread safe version of bytes.Buffer::Read -func (b *SafeBuffer) Read(p []byte) (n int, err error) { - b.m.RLock() - defer b.m.RUnlock() - return b.b.Read(p) -} - -// Write is a thread safe version of bytes.Buffer::Write -func (b *SafeBuffer) Write(p []byte) (n int, err error) { - b.m.Lock() - defer b.m.Unlock() - return b.b.Write(p) -} - -// String is a thread safe version of bytes.Buffer::String -func (b *SafeBuffer) String() string { - b.m.RLock() - defer b.m.RUnlock() - return b.b.String() -} - -// Bytes is a thread safe version of bytes.Buffer::Bytes -func (b *SafeBuffer) Bytes() []byte { - b.m.RLock() - defer b.m.RUnlock() - return b.b.Bytes() -} - -// RequireEventuallyContains is a thread safe eventual checker for the buffer content -func (b *SafeBuffer) RequireEventuallyContains(t testing.TB, v string) { - t.Helper() - var bufContents strings.Builder - require.Eventuallyf(t, func() bool { - b.m.Lock() - defer b.m.Unlock() - if _, err := b.b.WriteTo(&bufContents); err != nil { - require.FailNowf(t, "Failed to copy from buffer", - "Error: %v", err) - } - return strings.Contains(bufContents.String(), v) - }, 2*time.Second, 20*time.Millisecond, - "Buffer did not contain %q\n============\n%s\n============", - v, &bufContents) -} diff --git a/vendor/github.com/docker/compose/v2/pkg/utils/set.go b/vendor/github.com/docker/compose/v2/pkg/utils/set.go deleted file mode 100644 index 4688cb9ef..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/utils/set.go +++ /dev/null @@ -1,55 +0,0 @@ -/* - - Copyright 2020 Docker Compose CLI 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 utils - -type Set[T comparable] map[T]struct{} - -func (s Set[T]) Add(v T) { - s[v] = struct{}{} -} - -func (s Set[T]) AddAll(v ...T) { - for _, e := range v { - s[e] = struct{}{} - } -} - -func (s Set[T]) Remove(v T) bool { - _, ok := s[v] - if ok { - delete(s, v) - } - return ok -} - -func (s Set[T]) Clear() { - for v := range s { - delete(s, v) - } -} - -func (s Set[T]) Elements() []T { - elements := make([]T, 0, len(s)) - for v := range s { - elements = append(elements, v) - } - return elements -} - -func (s Set[T]) RemoveAll(elements ...T) { - for _, e := range elements { - s.Remove(e) - } -} diff --git a/vendor/github.com/docker/compose/v2/pkg/utils/slices.go b/vendor/github.com/docker/compose/v2/pkg/utils/slices.go deleted file mode 100644 index 6dbf1c6e7..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/utils/slices.go +++ /dev/null @@ -1,51 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 utils - -import "reflect" - -// Contains helps to detect if a non-comparable struct is part of an array -// only use this method if you can't rely on existing golang Contains function of slices (https://pkg.go.dev/golang.org/x/exp/slices#Contains) -func Contains[T any](origin []T, element T) bool { - for _, v := range origin { - if reflect.DeepEqual(v, element) { - return true - } - } - return false -} - -// Remove removes all elements from origin slice -func Remove[T any](origin []T, elements ...T) []T { - var filtered []T - for _, v := range origin { - if !Contains(elements, v) { - filtered = append(filtered, v) - } - } - return filtered -} - -func Filter[T any](elements []T, predicate func(T) bool) []T { - var filtered []T - for _, v := range elements { - if predicate(v) { - filtered = append(filtered, v) - } - } - return filtered -} diff --git a/vendor/github.com/docker/compose/v2/pkg/utils/stringutils.go b/vendor/github.com/docker/compose/v2/pkg/utils/stringutils.go deleted file mode 100644 index 1004263bb..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/utils/stringutils.go +++ /dev/null @@ -1,42 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 utils - -import ( - "strconv" - "strings" -) - -// StringContains check if an array contains a specific value -func StringContains(array []string, needle string) bool { - for _, val := range array { - if val == needle { - return true - } - } - return false -} - -// StringToBool converts a string to a boolean ignoring errors -func StringToBool(s string) bool { - s = strings.ToLower(strings.TrimSpace(s)) - if s == "y" { - return true - } - b, _ := strconv.ParseBool(s) - return b -} diff --git a/vendor/github.com/docker/compose/v2/pkg/utils/writer.go b/vendor/github.com/docker/compose/v2/pkg/utils/writer.go deleted file mode 100644 index fc9547197..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/utils/writer.go +++ /dev/null @@ -1,68 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 utils - -import ( - "bytes" - "io" -) - -// GetWriter creates a io.Writer that will actually split by line and format by LogConsumer -func GetWriter(consumer func(string)) io.WriteCloser { - return &splitWriter{ - buffer: bytes.Buffer{}, - consumer: consumer, - } -} - -type splitWriter struct { - buffer bytes.Buffer - consumer func(string) -} - -// Write implements io.Writer. joins all input, splits on the separator and yields each chunk -func (s *splitWriter) Write(b []byte) (int, error) { - n, err := s.buffer.Write(b) - if err != nil { - return n, err - } - for { - b = s.buffer.Bytes() - index := bytes.Index(b, []byte{'\n'}) - if index > 0 { - line := s.buffer.Next(index + 1) - s.consumer(string(line[:len(line)-1])) - } else { - line := s.buffer.String() - s.buffer.Reset() - if len(line) > 0 { - s.consumer(line) - } - break - } - } - return n, nil -} - -func (s *splitWriter) Close() error { - b := s.buffer.Bytes() - if len(b) == 0 { - return nil - } - s.consumer(string(b)) - return nil -} diff --git a/vendor/github.com/docker/compose/v2/pkg/watch/dockerignore.go b/vendor/github.com/docker/compose/v2/pkg/watch/dockerignore.go deleted file mode 100644 index e036883ab..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/watch/dockerignore.go +++ /dev/null @@ -1,146 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 watch - -import ( - "fmt" - "os" - "path/filepath" - "strings" - - "github.com/moby/buildkit/frontend/dockerfile/dockerignore" - "github.com/moby/patternmatcher" -) - -type dockerPathMatcher struct { - repoRoot string - matcher *patternmatcher.PatternMatcher -} - -func (i dockerPathMatcher) Matches(f string) (bool, error) { - if !filepath.IsAbs(f) { - f = filepath.Join(i.repoRoot, f) - } - return i.matcher.MatchesOrParentMatches(f) -} - -func (i dockerPathMatcher) MatchesEntireDir(f string) (bool, error) { - matches, err := i.Matches(f) - if !matches || err != nil { - return matches, err - } - - // We match the dir, but we might exclude files underneath it. - if i.matcher.Exclusions() { - for _, pattern := range i.matcher.Patterns() { - if !pattern.Exclusion() { - continue - } - if IsChild(f, pattern.String()) { - // Found an exclusion match -- we don't match this whole dir - return false, nil - } - } - return true, nil - } - return true, nil -} - -func LoadDockerIgnore(repoRoot string) (*dockerPathMatcher, error) { - absRoot, err := filepath.Abs(repoRoot) - if err != nil { - return nil, err - } - - patterns, err := readDockerignorePatterns(absRoot) - if err != nil { - return nil, err - } - - return NewDockerPatternMatcher(absRoot, patterns) -} - -// Make all the patterns use absolute paths. -func absPatterns(absRoot string, patterns []string) []string { - absPatterns := make([]string, 0, len(patterns)) - for _, p := range patterns { - // The pattern parsing here is loosely adapted from fileutils' NewPatternMatcher - p = strings.TrimSpace(p) - if p == "" { - continue - } - p = filepath.Clean(p) - - pPath := p - isExclusion := false - if p[0] == '!' { - pPath = p[1:] - isExclusion = true - } - - if !filepath.IsAbs(pPath) { - pPath = filepath.Join(absRoot, pPath) - } - absPattern := pPath - if isExclusion { - absPattern = fmt.Sprintf("!%s", pPath) - } - absPatterns = append(absPatterns, absPattern) - } - return absPatterns -} - -func NewDockerPatternMatcher(repoRoot string, patterns []string) (*dockerPathMatcher, error) { - absRoot, err := filepath.Abs(repoRoot) - if err != nil { - return nil, err - } - - pm, err := patternmatcher.New(absPatterns(absRoot, patterns)) - if err != nil { - return nil, err - } - - return &dockerPathMatcher{ - repoRoot: absRoot, - matcher: pm, - }, nil -} - -func readDockerignorePatterns(repoRoot string) ([]string, error) { - var excludes []string - - f, err := os.Open(filepath.Join(repoRoot, ".dockerignore")) - switch { - case os.IsNotExist(err): - return excludes, nil - case err != nil: - return nil, err - } - defer func() { _ = f.Close() }() - - return dockerignore.ReadAll(f) -} - -func DockerIgnoreTesterFromContents(repoRoot string, contents string) (*dockerPathMatcher, error) { - patterns, err := dockerignore.ReadAll(strings.NewReader(contents)) - if err != nil { - return nil, err - } - - return NewDockerPatternMatcher(repoRoot, patterns) -} diff --git a/vendor/github.com/docker/compose/v2/pkg/watch/ephemeral.go b/vendor/github.com/docker/compose/v2/pkg/watch/ephemeral.go deleted file mode 100644 index c7a82f5ed..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/watch/ephemeral.go +++ /dev/null @@ -1,59 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 watch - -// EphemeralPathMatcher filters out spurious changes that we don't want to -// rebuild on, like IDE temp/lock files. -// -// This isn't an ideal solution. In an ideal world, the user would put -// everything to ignore in their tiltignore/dockerignore files. This is a -// stop-gap so they don't have a terrible experience if those files aren't -// there or aren't in the right places. -// -// NOTE: The underlying `patternmatcher` is NOT always Goroutine-safe, so -// this is not a singleton; we create an instance for each watcher currently. -func EphemeralPathMatcher() PathMatcher { - golandPatterns := []string{"**/*___jb_old___", "**/*___jb_tmp___", "**/.idea/**"} - emacsPatterns := []string{"**/.#*", "**/#*#"} - // if .swp is taken (presumably because multiple vims are running in that dir), - // vim will go with .swo, .swn, etc, and then even .svz, .svy! - // https://github.com/vim/vim/blob/ea781459b9617aa47335061fcc78403495260315/src/memline.c#L5076 - // ignoring .sw? seems dangerous, since things like .swf or .swi exist, but ignoring the first few - // seems safe and should catch most cases - vimPatterns := []string{"**/4913", "**/*~", "**/.*.swp", "**/.*.swx", "**/.*.swo", "**/.*.swn"} - // kate (the default text editor for KDE) uses a file similar to Vim's .swp - // files, but it doesn't have the "incrememnting" character problem mentioned - // above - katePatterns := []string{"**/.*.kate-swp"} - // go stdlib creates tmpfiles to determine umask for setting permissions - // during file creation; they are then immediately deleted - // https://github.com/golang/go/blob/0b5218cf4e3e5c17344ea113af346e8e0836f6c4/src/cmd/go/internal/work/exec.go#L1764 - goPatterns := []string{"**/*-go-tmp-umask"} - - var allPatterns []string - allPatterns = append(allPatterns, golandPatterns...) - allPatterns = append(allPatterns, emacsPatterns...) - allPatterns = append(allPatterns, vimPatterns...) - allPatterns = append(allPatterns, katePatterns...) - allPatterns = append(allPatterns, goPatterns...) - - matcher, err := NewDockerPatternMatcher("/", allPatterns) - if err != nil { - panic(err) - } - return matcher -} diff --git a/vendor/github.com/docker/compose/v2/pkg/watch/notify.go b/vendor/github.com/docker/compose/v2/pkg/watch/notify.go deleted file mode 100644 index 7f28d84b6..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/watch/notify.go +++ /dev/null @@ -1,144 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 watch - -import ( - "expvar" - "fmt" - "os" - "path/filepath" - "runtime" - "strconv" - - "github.com/pkg/errors" - "github.com/tilt-dev/fsnotify" -) - -var ( - numberOfWatches = expvar.NewInt("watch.naive.numberOfWatches") -) - -type FileEvent struct { - path string -} - -func NewFileEvent(p string) FileEvent { - if !filepath.IsAbs(p) { - panic(fmt.Sprintf("NewFileEvent only accepts absolute paths. Actual: %s", p)) - } - return FileEvent{path: p} -} - -func (e FileEvent) Path() string { - return e.path -} - -type Notify interface { - // Start watching the paths set at init time - Start() error - - // Stop watching and close all channels - Close() error - - // A channel to read off incoming file changes - Events() chan FileEvent - - // A channel to read off show-stopping errors - Errors() chan error -} - -// When we specify directories to watch, we often want to -// ignore some subset of the files under those directories. -// -// For example: -// - Watch /src/repo, but ignore /src/repo/.git -// - Watch /src/repo, but ignore everything in /src/repo/bazel-bin except /src/repo/bazel-bin/app-binary -// -// The PathMatcher interface helps us manage these ignores. -type PathMatcher interface { - Matches(file string) (bool, error) - - // If this matches the entire dir, we can often optimize filetree walks a bit. - MatchesEntireDir(file string) (bool, error) -} - -type EmptyMatcher struct { -} - -func (EmptyMatcher) Matches(f string) (bool, error) { return false, nil } -func (EmptyMatcher) MatchesEntireDir(f string) (bool, error) { return false, nil } - -var _ PathMatcher = EmptyMatcher{} - -func NewWatcher(paths []string, ignore PathMatcher) (Notify, error) { - return newWatcher(paths, ignore) -} - -const WindowsBufferSizeEnvVar = "COMPOSE_WATCH_WINDOWS_BUFFER_SIZE" - -const defaultBufferSize int = 65536 - -func DesiredWindowsBufferSize() int { - envVar := os.Getenv(WindowsBufferSizeEnvVar) - if envVar != "" { - size, err := strconv.Atoi(envVar) - if err == nil { - return size - } - } - return defaultBufferSize -} - -func IsWindowsShortReadError(err error) bool { - return runtime.GOOS == "windows" && !errors.Is(err, fsnotify.ErrEventOverflow) -} - -type CompositePathMatcher struct { - Matchers []PathMatcher -} - -func NewCompositeMatcher(matchers ...PathMatcher) PathMatcher { - if len(matchers) == 0 { - return EmptyMatcher{} - } - return CompositePathMatcher{Matchers: matchers} -} - -func (c CompositePathMatcher) Matches(f string) (bool, error) { - for _, t := range c.Matchers { - ret, err := t.Matches(f) - if err != nil { - return false, err - } - if ret { - return true, nil - } - } - return false, nil -} - -func (c CompositePathMatcher) MatchesEntireDir(f string) (bool, error) { - for _, t := range c.Matchers { - matches, err := t.MatchesEntireDir(f) - if matches || err != nil { - return matches, err - } - } - return false, nil -} - -var _ PathMatcher = CompositePathMatcher{} diff --git a/vendor/github.com/docker/compose/v2/pkg/watch/paths.go b/vendor/github.com/docker/compose/v2/pkg/watch/paths.go deleted file mode 100644 index 4d057c25b..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/watch/paths.go +++ /dev/null @@ -1,139 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 watch - -import ( - "fmt" - "os" - "path/filepath" - "strings" - - "github.com/pkg/errors" -) - -func greatestExistingAncestor(path string) (string, error) { - if path == string(filepath.Separator) || - path == fmt.Sprintf("%s%s", filepath.VolumeName(path), string(filepath.Separator)) { - return "", fmt.Errorf("cannot watch root directory") - } - - _, err := os.Stat(path) - if err != nil && !os.IsNotExist(err) { - return "", errors.Wrapf(err, "os.Stat(%q)", path) - } - - if os.IsNotExist(err) { - return greatestExistingAncestor(filepath.Dir(path)) - } - - return path, nil -} - -// If we're recursively watching a path, it doesn't -// make sense to watch any of its descendants. -func dedupePathsForRecursiveWatcher(paths []string) []string { - result := []string{} - for _, current := range paths { - isCovered := false - hasRemovals := false - - for i, existing := range result { - if IsChild(existing, current) { - // The path is already covered, so there's no need to include it - isCovered = true - break - } - - if IsChild(current, existing) { - // Mark the element empty for removal. - result[i] = "" - hasRemovals = true - } - } - - if !isCovered { - result = append(result, current) - } - - if hasRemovals { - // Remove all the empties - newResult := []string{} - for _, r := range result { - if r != "" { - newResult = append(newResult, r) - } - } - result = newResult - } - } - return result -} - -func IsChild(dir string, file string) bool { - if dir == "" { - return false - } - - dir = filepath.Clean(dir) - current := filepath.Clean(file) - child := "." - for { - if strings.EqualFold(dir, current) { - // If the two paths are exactly equal, then they must be the same. - if dir == current { - return true - } - - // If the two paths are equal under case-folding, but not exactly equal, - // then the only way to check if they're truly "equal" is to check - // to see if we're on a case-insensitive file system. - // - // This is a notoriously tricky problem. See how dep solves it here: - // https://github.com/golang/dep/blob/v0.5.4/internal/fs/fs.go#L33 - // - // because you can mount case-sensitive filesystems onto case-insensitive - // file-systems, and vice versa :scream: - // - // We want to do as much of this check as possible with strings-only - // (to avoid a file system read and error handling), so we only - // do this check if we have no other choice. - dirInfo, err := os.Stat(dir) - if err != nil { - return false - } - - currentInfo, err := os.Stat(current) - if err != nil { - return false - } - - if !os.SameFile(dirInfo, currentInfo) { - return false - } - return true - } - - if len(current) <= len(dir) || current == "." { - return false - } - - cDir := filepath.Dir(current) - cBase := filepath.Base(current) - child = filepath.Join(cBase, child) - current = cDir - } -} diff --git a/vendor/github.com/docker/compose/v2/pkg/watch/temp.go b/vendor/github.com/docker/compose/v2/pkg/watch/temp.go deleted file mode 100644 index 4e5c52535..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/watch/temp.go +++ /dev/null @@ -1,88 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 watch - -import ( - "os" - "path/filepath" -) - -// TempDir holds a temp directory and allows easy access to new temp directories. -type TempDir struct { - dir string -} - -// NewDir creates a new TempDir in the default location (typically $TMPDIR) -func NewDir(prefix string) (*TempDir, error) { - return NewDirAtRoot("", prefix) -} - -// NewDir creates a new TempDir at the given root. -func NewDirAtRoot(root, prefix string) (*TempDir, error) { - tmpDir, err := os.MkdirTemp(root, prefix) - if err != nil { - return nil, err - } - - realTmpDir, err := filepath.EvalSymlinks(tmpDir) - if err != nil { - return nil, err - } - - return &TempDir{dir: realTmpDir}, nil -} - -// NewDirAtSlashTmp creates a new TempDir at /tmp -func NewDirAtSlashTmp(prefix string) (*TempDir, error) { - fullyResolvedPath, err := filepath.EvalSymlinks("/tmp") - if err != nil { - return nil, err - } - return NewDirAtRoot(fullyResolvedPath, prefix) -} - -// d.NewDir creates a new TempDir under d -func (d *TempDir) NewDir(prefix string) (*TempDir, error) { - d2, err := os.MkdirTemp(d.dir, prefix) - if err != nil { - return nil, err - } - return &TempDir{d2}, nil -} - -func (d *TempDir) NewDeterministicDir(name string) (*TempDir, error) { - d2 := filepath.Join(d.dir, name) - err := os.Mkdir(d2, 0o700) - if os.IsExist(err) { - return nil, err - } else if err != nil { - return nil, err - } - return &TempDir{d2}, nil -} - -func (d *TempDir) TearDown() error { - return os.RemoveAll(d.dir) -} - -func (d *TempDir) Path() string { - return d.dir -} - -// Possible extensions: -// temp file -// named directories or files (e.g., we know we want one git repo for our object, but it should be temporary) diff --git a/vendor/github.com/docker/compose/v2/pkg/watch/temp_dir_fixture.go b/vendor/github.com/docker/compose/v2/pkg/watch/temp_dir_fixture.go deleted file mode 100644 index a0855e875..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/watch/temp_dir_fixture.go +++ /dev/null @@ -1,199 +0,0 @@ -/* - Copyright 2020 Docker Compose CLI 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 watch - -import ( - "os" - "path/filepath" - "regexp" - "runtime" - "strings" - "testing" -) - -type TempDirFixture struct { - t testing.TB - dir *TempDir - oldDir string -} - -// everything not listed in this character class will get replaced by _, so that it's a safe filename -var sanitizeForFilenameRe = regexp.MustCompile("[^a-zA-Z0-9.]") - -func SanitizeFileName(name string) string { - return sanitizeForFilenameRe.ReplaceAllString(name, "_") -} - -func NewTempDirFixture(t testing.TB) *TempDirFixture { - dir, err := NewDir(SanitizeFileName(t.Name())) - if err != nil { - t.Fatalf("Error making temp dir: %v", err) - } - - ret := &TempDirFixture{ - t: t, - dir: dir, - } - - t.Cleanup(ret.tearDown) - - return ret -} - -func (f *TempDirFixture) T() testing.TB { - return f.t -} - -func (f *TempDirFixture) Path() string { - return f.dir.Path() -} - -func (f *TempDirFixture) Chdir() { - cwd, err := os.Getwd() - if err != nil { - f.t.Fatal(err) - } - - f.oldDir = cwd - - err = os.Chdir(f.Path()) - if err != nil { - f.t.Fatal(err) - } -} - -func (f *TempDirFixture) JoinPath(path ...string) string { - p := []string{} - isAbs := len(path) > 0 && filepath.IsAbs(path[0]) - if isAbs { - if !strings.HasPrefix(path[0], f.Path()) { - f.t.Fatalf("Path outside fixture tempdir are forbidden: %s", path[0]) - } - } else { - p = append(p, f.Path()) - } - - p = append(p, path...) - return filepath.Join(p...) -} - -func (f *TempDirFixture) JoinPaths(paths []string) []string { - joined := make([]string, len(paths)) - for i, p := range paths { - joined[i] = f.JoinPath(p) - } - return joined -} - -// Returns the full path to the file written. -func (f *TempDirFixture) WriteFile(path string, contents string) string { - fullPath := f.JoinPath(path) - base := filepath.Dir(fullPath) - err := os.MkdirAll(base, os.FileMode(0o777)) - if err != nil { - f.t.Fatal(err) - } - err = os.WriteFile(fullPath, []byte(contents), os.FileMode(0o777)) - if err != nil { - f.t.Fatal(err) - } - return fullPath -} - -// Returns the full path to the file written. -func (f *TempDirFixture) CopyFile(originalPath, newPath string) { - contents, err := os.ReadFile(originalPath) - if err != nil { - f.t.Fatal(err) - } - f.WriteFile(newPath, string(contents)) -} - -// Read the file. -func (f *TempDirFixture) ReadFile(path string) string { - fullPath := f.JoinPath(path) - contents, err := os.ReadFile(fullPath) - if err != nil { - f.t.Fatal(err) - } - return string(contents) -} - -func (f *TempDirFixture) WriteSymlink(linkContents, destPath string) { - fullDestPath := f.JoinPath(destPath) - err := os.MkdirAll(filepath.Dir(fullDestPath), os.FileMode(0o777)) - if err != nil { - f.t.Fatal(err) - } - err = os.Symlink(linkContents, fullDestPath) - if err != nil { - f.t.Fatal(err) - } -} - -func (f *TempDirFixture) MkdirAll(path string) { - fullPath := f.JoinPath(path) - err := os.MkdirAll(fullPath, os.FileMode(0o777)) - if err != nil { - f.t.Fatal(err) - } -} - -func (f *TempDirFixture) TouchFiles(paths []string) { - for _, p := range paths { - f.WriteFile(p, "") - } -} - -func (f *TempDirFixture) Rm(pathInRepo string) { - fullPath := f.JoinPath(pathInRepo) - err := os.RemoveAll(fullPath) - if err != nil { - f.t.Fatal(err) - } -} - -func (f *TempDirFixture) NewFile(prefix string) (*os.File, error) { - return os.CreateTemp(f.dir.Path(), prefix) -} - -func (f *TempDirFixture) TempDir(prefix string) string { - name, err := os.MkdirTemp(f.dir.Path(), prefix) - if err != nil { - f.t.Fatal(err) - } - return name -} - -func (f *TempDirFixture) tearDown() { - if f.oldDir != "" { - err := os.Chdir(f.oldDir) - if err != nil { - f.t.Fatal(err) - } - } - - err := f.dir.TearDown() - if err != nil && runtime.GOOS == "windows" && - (strings.Contains(err.Error(), "The process cannot access the file") || - strings.Contains(err.Error(), "Access is denied")) { - // NOTE(nick): I'm not convinced that this is a real problem. - // I think it might just be clean up of file notification I/O. - } else if err != nil { - f.t.Fatal(err) - } -} diff --git a/vendor/github.com/docker/compose/v2/pkg/watch/watcher_darwin.go b/vendor/github.com/docker/compose/v2/pkg/watch/watcher_darwin.go deleted file mode 100644 index d1a2a9c20..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/watch/watcher_darwin.go +++ /dev/null @@ -1,147 +0,0 @@ -//go:build darwin -// +build darwin - -/* - Copyright 2020 Docker Compose CLI 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 watch - -import ( - "os" - "path/filepath" - "time" - - "github.com/fsnotify/fsevents" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" -) - -// A file watcher optimized for Darwin. -// Uses FSEvents to avoid the terrible perf characteristics of kqueue. Requires CGO -type fseventNotify struct { - stream *fsevents.EventStream - events chan FileEvent - errors chan error - stop chan struct{} - - pathsWereWatching map[string]interface{} - ignore PathMatcher -} - -func (d *fseventNotify) loop() { - for { - select { - case <-d.stop: - return - case events, ok := <-d.stream.Events: - if !ok { - return - } - - for _, e := range events { - e.Path = filepath.Join(string(os.PathSeparator), e.Path) - - _, isPathWereWatching := d.pathsWereWatching[e.Path] - if e.Flags&fsevents.ItemIsDir == fsevents.ItemIsDir && e.Flags&fsevents.ItemCreated == fsevents.ItemCreated && isPathWereWatching { - // This is the first create for the path that we're watching. We always get exactly one of these - // even after we get the HistoryDone event. Skip it. - continue - } - - ignore, err := d.ignore.Matches(e.Path) - if err != nil { - logrus.Infof("Error matching path %q: %v", e.Path, err) - } else if ignore { - logrus.Tracef("Ignoring event for path: %v", e.Path) - continue - } - - d.events <- NewFileEvent(e.Path) - } - } - } -} - -// Add a path to be watched. Should only be called during initialization. -func (d *fseventNotify) initAdd(name string) { - d.stream.Paths = append(d.stream.Paths, name) - - if d.pathsWereWatching == nil { - d.pathsWereWatching = make(map[string]interface{}) - } - d.pathsWereWatching[name] = struct{}{} -} - -func (d *fseventNotify) Start() error { - if len(d.stream.Paths) == 0 { - return nil - } - - numberOfWatches.Add(int64(len(d.stream.Paths))) - - d.stream.Start() - - go d.loop() - - return nil -} - -func (d *fseventNotify) Close() error { - numberOfWatches.Add(int64(-len(d.stream.Paths))) - - d.stream.Stop() - close(d.errors) - close(d.stop) - - return nil -} - -func (d *fseventNotify) Events() chan FileEvent { - return d.events -} - -func (d *fseventNotify) Errors() chan error { - return d.errors -} - -func newWatcher(paths []string, ignore PathMatcher) (Notify, error) { - dw := &fseventNotify{ - ignore: ignore, - stream: &fsevents.EventStream{ - Latency: 50 * time.Millisecond, - Flags: fsevents.FileEvents | fsevents.IgnoreSelf, - // NOTE(dmiller): this corresponds to the `sinceWhen` parameter in FSEventStreamCreate - // https://developer.apple.com/documentation/coreservices/1443980-fseventstreamcreate - EventID: fsevents.LatestEventID(), - }, - events: make(chan FileEvent), - errors: make(chan error), - stop: make(chan struct{}), - } - - paths = dedupePathsForRecursiveWatcher(paths) - for _, path := range paths { - path, err := filepath.Abs(path) - if err != nil { - return nil, errors.Wrap(err, "newWatcher") - } - dw.initAdd(path) - } - - return dw, nil -} - -var _ Notify = &fseventNotify{} diff --git a/vendor/github.com/docker/compose/v2/pkg/watch/watcher_naive.go b/vendor/github.com/docker/compose/v2/pkg/watch/watcher_naive.go deleted file mode 100644 index e8c7e855f..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/watch/watcher_naive.go +++ /dev/null @@ -1,359 +0,0 @@ -//go:build !darwin -// +build !darwin - -/* - Copyright 2020 Docker Compose CLI 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 watch - -import ( - "fmt" - "io/fs" - "os" - "path/filepath" - "runtime" - "strings" - - "github.com/pkg/errors" - "github.com/sirupsen/logrus" - - "github.com/tilt-dev/fsnotify" -) - -// A naive file watcher that uses the plain fsnotify API. -// Used on all non-Darwin systems (including Windows & Linux). -// -// All OS-specific codepaths are handled by fsnotify. -type naiveNotify struct { - // Paths that we're watching that should be passed up to the caller. - // Note that we may have to watch ancestors of these paths - // in order to fulfill the API promise. - // - // We often need to check if paths are a child of a path in - // the notify list. It might be better to store this in a tree - // structure, so we can filter the list quickly. - notifyList map[string]bool - - ignore PathMatcher - - isWatcherRecursive bool - watcher *fsnotify.Watcher - events chan fsnotify.Event - wrappedEvents chan FileEvent - errors chan error - numWatches int64 -} - -func (d *naiveNotify) Start() error { - if len(d.notifyList) == 0 { - return nil - } - - pathsToWatch := []string{} - for path := range d.notifyList { - pathsToWatch = append(pathsToWatch, path) - } - - pathsToWatch, err := greatestExistingAncestors(pathsToWatch) - if err != nil { - return err - } - if d.isWatcherRecursive { - pathsToWatch = dedupePathsForRecursiveWatcher(pathsToWatch) - } - - for _, name := range pathsToWatch { - fi, err := os.Stat(name) - if err != nil && !os.IsNotExist(err) { - return errors.Wrapf(err, "notify.Add(%q)", name) - } - - // if it's a file that doesn't exist, - // we should have caught that above, let's just skip it. - if os.IsNotExist(err) { - continue - } - - if fi.IsDir() { - err = d.watchRecursively(name) - if err != nil { - return errors.Wrapf(err, "notify.Add(%q)", name) - } - } else { - err = d.add(filepath.Dir(name)) - if err != nil { - return errors.Wrapf(err, "notify.Add(%q)", filepath.Dir(name)) - } - } - } - - go d.loop() - - return nil -} - -func (d *naiveNotify) watchRecursively(dir string) error { - if d.isWatcherRecursive { - err := d.add(dir) - if err == nil || os.IsNotExist(err) { - return nil - } - return errors.Wrapf(err, "watcher.Add(%q)", dir) - } - - return filepath.WalkDir(dir, func(path string, info fs.DirEntry, err error) error { - if err != nil { - return err - } - - if !info.IsDir() { - return nil - } - - shouldSkipDir, err := d.shouldSkipDir(path) - if err != nil { - return err - } - - if shouldSkipDir { - logrus.Debugf("Ignoring directory and its contents (recursively): %s", path) - return filepath.SkipDir - } - - err = d.add(path) - if err != nil { - if os.IsNotExist(err) { - return nil - } - return errors.Wrapf(err, "watcher.Add(%q)", path) - } - return nil - }) -} - -func (d *naiveNotify) Close() error { - numberOfWatches.Add(-d.numWatches) - d.numWatches = 0 - return d.watcher.Close() -} - -func (d *naiveNotify) Events() chan FileEvent { - return d.wrappedEvents -} - -func (d *naiveNotify) Errors() chan error { - return d.errors -} - -func (d *naiveNotify) loop() { //nolint:gocyclo - defer close(d.wrappedEvents) - for e := range d.events { - // The Windows fsnotify event stream sometimes gets events with empty names - // that are also sent to the error stream. Hmmmm... - if e.Name == "" { - continue - } - - if e.Op&fsnotify.Create != fsnotify.Create { - if d.shouldNotify(e.Name) { - d.wrappedEvents <- FileEvent{e.Name} - } - continue - } - - if d.isWatcherRecursive { - if d.shouldNotify(e.Name) { - d.wrappedEvents <- FileEvent{e.Name} - } - continue - } - - // If the watcher is not recursive, we have to walk the tree - // and add watches manually. We fire the event while we're walking the tree. - // because it's a bit more elegant that way. - // - // TODO(dbentley): if there's a delete should we call d.watcher.Remove to prevent leaking? - err := filepath.WalkDir(e.Name, func(path string, info fs.DirEntry, err error) error { - if err != nil { - return err - } - - if d.shouldNotify(path) { - d.wrappedEvents <- FileEvent{path} - } - - // TODO(dmiller): symlinks 😭 - - shouldWatch := false - if info.IsDir() { - // watch directories unless we can skip them entirely - shouldSkipDir, err := d.shouldSkipDir(path) - if err != nil { - return err - } - if shouldSkipDir { - return filepath.SkipDir - } - - shouldWatch = true - } else { - // watch files that are explicitly named, but don't watch others - _, ok := d.notifyList[path] - if ok { - shouldWatch = true - } - } - if shouldWatch { - err := d.add(path) - if err != nil && !os.IsNotExist(err) { - logrus.Infof("Error watching path %s: %s", e.Name, err) - } - } - return nil - }) - if err != nil && !os.IsNotExist(err) { - logrus.Infof("Error walking directory %s: %s", e.Name, err) - } - } -} - -func (d *naiveNotify) shouldNotify(path string) bool { - ignore, err := d.ignore.Matches(path) - if err != nil { - logrus.Infof("Error matching path %q: %v", path, err) - } else if ignore { - logrus.Tracef("Ignoring event for path: %v", path) - return false - } - - if _, ok := d.notifyList[path]; ok { - // We generally don't care when directories change at the root of an ADD - stat, err := os.Lstat(path) - isDir := err == nil && stat.IsDir() - return !isDir - } - - for root := range d.notifyList { - if IsChild(root, path) { - return true - } - } - return false -} - -func (d *naiveNotify) shouldSkipDir(path string) (bool, error) { - // If path is directly in the notifyList, we should always watch it. - if d.notifyList[path] { - return false, nil - } - - skip, err := d.ignore.MatchesEntireDir(path) - if err != nil { - return false, errors.Wrap(err, "shouldSkipDir") - } - - if skip { - return true, nil - } - - // Suppose we're watching - // /src/.tiltignore - // but the .tiltignore file doesn't exist. - // - // Our watcher will create an inotify watch on /src/. - // - // But then we want to make sure we don't recurse from /src/ down to /src/node_modules. - // - // To handle this case, we only want to traverse dirs that are: - // - A child of a directory that's in our notify list, or - // - A parent of a directory that's in our notify list - // (i.e., to cover the "path doesn't exist" case). - for root := range d.notifyList { - if IsChild(root, path) || IsChild(path, root) { - return false, nil - } - } - return true, nil -} - -func (d *naiveNotify) add(path string) error { - err := d.watcher.Add(path) - if err != nil { - return err - } - d.numWatches++ - numberOfWatches.Add(1) - return nil -} - -func newWatcher(paths []string, ignore PathMatcher) (Notify, error) { - if ignore == nil { - return nil, fmt.Errorf("newWatcher: ignore is nil") - } - - fsw, err := fsnotify.NewWatcher() - if err != nil { - if strings.Contains(err.Error(), "too many open files") && runtime.GOOS == "linux" { - return nil, fmt.Errorf("Hit OS limits creating a watcher.\n" + - "Run 'sysctl fs.inotify.max_user_instances' to check your inotify limits.\n" + - "To raise them, run 'sudo sysctl fs.inotify.max_user_instances=1024'") - } - return nil, errors.Wrap(err, "creating file watcher") - } - MaybeIncreaseBufferSize(fsw) - - err = fsw.SetRecursive() - isWatcherRecursive := err == nil - - wrappedEvents := make(chan FileEvent) - notifyList := make(map[string]bool, len(paths)) - if isWatcherRecursive { - paths = dedupePathsForRecursiveWatcher(paths) - } - for _, path := range paths { - path, err := filepath.Abs(path) - if err != nil { - return nil, errors.Wrap(err, "newWatcher") - } - notifyList[path] = true - } - - wmw := &naiveNotify{ - notifyList: notifyList, - ignore: ignore, - watcher: fsw, - events: fsw.Events, - wrappedEvents: wrappedEvents, - errors: fsw.Errors, - isWatcherRecursive: isWatcherRecursive, - } - - return wmw, nil -} - -var _ Notify = &naiveNotify{} - -func greatestExistingAncestors(paths []string) ([]string, error) { - result := []string{} - for _, p := range paths { - newP, err := greatestExistingAncestor(p) - if err != nil { - return nil, fmt.Errorf("Finding ancestor of %s: %v", p, err) - } - result = append(result, newP) - } - return result, nil -} diff --git a/vendor/github.com/docker/compose/v2/pkg/watch/watcher_nonwin.go b/vendor/github.com/docker/compose/v2/pkg/watch/watcher_nonwin.go deleted file mode 100644 index 360713318..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/watch/watcher_nonwin.go +++ /dev/null @@ -1,26 +0,0 @@ -//go:build !windows -// +build !windows - -/* - Copyright 2020 Docker Compose CLI 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 watch - -import "github.com/tilt-dev/fsnotify" - -func MaybeIncreaseBufferSize(w *fsnotify.Watcher) { - // Not needed on non-windows -} diff --git a/vendor/github.com/docker/compose/v2/pkg/watch/watcher_windows.go b/vendor/github.com/docker/compose/v2/pkg/watch/watcher_windows.go deleted file mode 100644 index 69af1ea5d..000000000 --- a/vendor/github.com/docker/compose/v2/pkg/watch/watcher_windows.go +++ /dev/null @@ -1,36 +0,0 @@ -//go:build windows -// +build windows - -/* - Copyright 2020 Docker Compose CLI 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 watch - -import ( - "github.com/tilt-dev/fsnotify" -) - -// TODO(nick): I think the ideal API would be to automatically increase the -// size of the buffer when we exceed capacity. But this gets messy, -// because each time we get a short read error, we need to invalidate -// everything we know about the currently changed files. So for now, -// we just provide a way for people to increase the buffer ourselves. -// -// It might also pay to be clever about sizing the buffer -// relative the number of files in the directory we're watching. -func MaybeIncreaseBufferSize(w *fsnotify.Watcher) { - w.SetBufferSize(DesiredWindowsBufferSize()) -} diff --git a/vendor/github.com/docker/distribution/.dockerignore b/vendor/github.com/docker/distribution/.dockerignore deleted file mode 100644 index e660fd93d..000000000 --- a/vendor/github.com/docker/distribution/.dockerignore +++ /dev/null @@ -1 +0,0 @@ -bin/ diff --git a/vendor/github.com/docker/distribution/.gitignore b/vendor/github.com/docker/distribution/.gitignore deleted file mode 100644 index 4cf7888e9..000000000 --- a/vendor/github.com/docker/distribution/.gitignore +++ /dev/null @@ -1,38 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof - -# never checkin from the bin file (for now) -bin/* - -# Test key files -*.pem - -# Cover profiles -*.out - -# Editor/IDE specific files. -*.sublime-project -*.sublime-workspace -.idea/* diff --git a/vendor/github.com/docker/distribution/.golangci.yml b/vendor/github.com/docker/distribution/.golangci.yml deleted file mode 100644 index 61dd0e00e..000000000 --- a/vendor/github.com/docker/distribution/.golangci.yml +++ /dev/null @@ -1,33 +0,0 @@ -linters: - enable: - - staticcheck - - unconvert - - gofmt - - goimports - - golint - - ineffassign - - vet - - unused - - misspell - disable: - - errcheck - -linters-settings: - revive: - rules: - # TODO(thaJeztah): temporarily disabled the "unused-parameter" check. - # It produces many warnings, and some of those may need to be looked at. - - name: unused-parameter - disabled: true - -run: - deadline: 2m - skip-dirs: - - vendor - -issues: - exclude-rules: - # io/ioutil is deprecated, but won't be removed until Go v2. It's safe to ignore for the release/2.8 branch. - - text: "SA1019: \"io/ioutil\" has been deprecated since Go 1.16" - linters: - - staticcheck diff --git a/vendor/github.com/docker/distribution/.mailmap b/vendor/github.com/docker/distribution/.mailmap deleted file mode 100644 index d7b832d9e..000000000 --- a/vendor/github.com/docker/distribution/.mailmap +++ /dev/null @@ -1,54 +0,0 @@ -Stephen J Day Stephen Day -Stephen J Day Stephen Day -Olivier Gambier Olivier Gambier -Brian Bland Brian Bland -Brian Bland Brian Bland -Josh Hawn Josh Hawn -Richard Scothern Richard -Richard Scothern Richard Scothern -Andrew Meredith Andrew Meredith -harche harche -Jessie Frazelle -Sharif Nassar Sharif Nassar -Sven Dowideit Sven Dowideit -Vincent Giersch Vincent Giersch -davidli davidli -Omer Cohen Omer Cohen -Eric Yang Eric Yang -Nikita Tarasov Nikita -Yu Wang yuwaMSFT2 -Yu Wang Yu Wang (UC) -Olivier Gambier dmp -Olivier Gambier Olivier -Olivier Gambier Olivier -Elsan Li 李楠 elsanli(李楠) -Rui Cao ruicao -Gwendolynne Barr gbarr01 -Haibing Zhou 周海兵 zhouhaibing089 -Feng Honglin tifayuki -Helen Xie Helen-xie -Mike Brown Mike Brown -Manish Tomar Manish Tomar -Sakeven Jiang sakeven -Milos Gajdos Milos Gajdos -Derek McGowan Derek McGowa -Adrian Plata Adrian Plata <@users.noreply.github.com> -Sebastiaan van Stijn Sebastiaan van Stijn -Vishesh Jindal Vishesh Jindal -Wang Yan Wang Yan -Chris Patterson Chris Patterson -Eohyung Lee Eohyung Lee -João Pereira <484633+joaodrp@users.noreply.github.com> -Smasherr Smasherr -Thomas Berger Thomas Berger -Samuel Karp Samuel Karp -Justin Cormack -sayboras -CrazyMax <1951866+crazy-max@users.noreply.github.com> -Hayley Swimelar -Jose D. Gomez R -Shengjing Zhu -Silvin Lubecki <31478878+silvin-lubecki@users.noreply.github.com> -James Hewitt -Marcus Pettersen Irgens -Ben Manuel diff --git a/vendor/github.com/docker/distribution/BUILDING.md b/vendor/github.com/docker/distribution/BUILDING.md deleted file mode 100644 index 4c43b03cb..000000000 --- a/vendor/github.com/docker/distribution/BUILDING.md +++ /dev/null @@ -1,117 +0,0 @@ - -# Building the registry source - -## Use-case - -This is useful if you intend to actively work on the registry. - -### Alternatives - -Most people should use the [official Registry docker image](https://hub.docker.com/r/library/registry/). - -People looking for advanced operational use cases might consider rolling their own image with a custom Dockerfile inheriting `FROM registry:2`. - -OS X users who want to run natively can do so following [the instructions here](https://github.com/docker/docker.github.io/blob/master/registry/recipes/osx-setup-guide.md). - -### Gotchas - -You are expected to know your way around with go & git. - -If you are a casual user with no development experience, and no preliminary knowledge of go, building from source is probably not a good solution for you. - -## Build the development environment - -The first prerequisite of properly building distribution targets is to have a Go -development environment setup. Please follow [How to Write Go Code](https://golang.org/doc/code.html) -for proper setup. If done correctly, you should have a GOROOT and GOPATH set in the -environment. - -If a Go development environment is setup, one can use `go get` to install the -`registry` command from the current latest: - - go get github.com/docker/distribution/cmd/registry - -The above will install the source repository into the `GOPATH`. - -Now create the directory for the registry data (this might require you to set permissions properly) - - mkdir -p /var/lib/registry - -... or alternatively `export REGISTRY_STORAGE_FILESYSTEM_ROOTDIRECTORY=/somewhere` if you want to store data into another location. - -The `registry` -binary can then be run with the following: - - $ $GOPATH/bin/registry --version - $GOPATH/bin/registry github.com/docker/distribution v2.0.0-alpha.1+unknown - -> __NOTE:__ While you do not need to use `go get` to checkout the distribution -> project, for these build instructions to work, the project must be checked -> out in the correct location in the `GOPATH`. This should almost always be -> `$GOPATH/src/github.com/docker/distribution`. - -The registry can be run with the default config using the following -incantation: - - $ $GOPATH/bin/registry serve $GOPATH/src/github.com/docker/distribution/cmd/registry/config-example.yml - INFO[0000] endpoint local-5003 disabled, skipping app.id=34bbec38-a91a-494a-9a3f-b72f9010081f version=v2.0.0-alpha.1+unknown - INFO[0000] endpoint local-8083 disabled, skipping app.id=34bbec38-a91a-494a-9a3f-b72f9010081f version=v2.0.0-alpha.1+unknown - INFO[0000] listening on :5000 app.id=34bbec38-a91a-494a-9a3f-b72f9010081f version=v2.0.0-alpha.1+unknown - INFO[0000] debug server listening localhost:5001 - -If it is working, one should see the above log messages. - -### Repeatable Builds - -For the full development experience, one should `cd` into -`$GOPATH/src/github.com/docker/distribution`. From there, the regular `go` -commands, such as `go test`, should work per package (please see -[Developing](#developing) if they don't work). - -A `Makefile` has been provided as a convenience to support repeatable builds. -Please install the following into `GOPATH` for it to work: - - go get github.com/golang/lint/golint - -Once these commands are available in the `GOPATH`, run `make` to get a full -build: - - $ make - + clean - + fmt - + vet - + lint - + build - github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar - github.com/sirupsen/logrus - github.com/docker/libtrust - ... - github.com/yvasiyarov/gorelic - github.com/docker/distribution/registry/handlers - github.com/docker/distribution/cmd/registry - + test - ... - ok github.com/docker/distribution/digest 7.875s - ok github.com/docker/distribution/manifest 0.028s - ok github.com/docker/distribution/notifications 17.322s - ? github.com/docker/distribution/registry [no test files] - ok github.com/docker/distribution/registry/api/v2 0.101s - ? github.com/docker/distribution/registry/auth [no test files] - ok github.com/docker/distribution/registry/auth/silly 0.011s - ... - + /Users/sday/go/src/github.com/docker/distribution/bin/registry - + /Users/sday/go/src/github.com/docker/distribution/bin/registry-api-descriptor-template - + binaries - -The above provides a repeatable build using the contents of the vendor -directory. This includes formatting, vetting, linting, building, -testing and generating tagged binaries. We can verify this worked by running -the registry binary generated in the "./bin" directory: - - $ ./bin/registry --version - ./bin/registry github.com/docker/distribution v2.0.0-alpha.2-80-g16d8b2c.m - -### Optional build tags - -Optional [build tags](http://golang.org/pkg/go/build/) can be provided using -the environment variable `BUILDTAGS`. diff --git a/vendor/github.com/docker/distribution/CONTRIBUTING.md b/vendor/github.com/docker/distribution/CONTRIBUTING.md deleted file mode 100644 index 4c067d9e7..000000000 --- a/vendor/github.com/docker/distribution/CONTRIBUTING.md +++ /dev/null @@ -1,148 +0,0 @@ -# Contributing to the registry - -## Before reporting an issue... - -### If your problem is with... - - - automated builds - - your account on the [Docker Hub](https://hub.docker.com/) - - any other [Docker Hub](https://hub.docker.com/) issue - -Then please do not report your issue here - you should instead report it to [https://support.docker.com](https://support.docker.com) - -### If you... - - - need help setting up your registry - - can't figure out something - - are not sure what's going on or what your problem is - -Then please do not open an issue here yet - you should first try one of the following support forums: - - - irc: #docker-distribution on freenode - - mailing-list: or https://groups.google.com/a/dockerproject.org/forum/#!forum/distribution - -### Reporting security issues - -The Docker maintainers take security seriously. If you discover a security -issue, please bring it to their attention right away! - -Please **DO NOT** file a public issue, instead send your report privately to -[security@docker.com](mailto:security@docker.com). - -## Reporting an issue properly - -By following these simple rules you will get better and faster feedback on your issue. - - - search the bugtracker for an already reported issue - -### If you found an issue that describes your problem: - - - please read other user comments first, and confirm this is the same issue: a given error condition might be indicative of different problems - you may also find a workaround in the comments - - please refrain from adding "same thing here" or "+1" comments - - you don't need to comment on an issue to get notified of updates: just hit the "subscribe" button - - comment if you have some new, technical and relevant information to add to the case - - __DO NOT__ comment on closed issues or merged PRs. If you think you have a related problem, open up a new issue and reference the PR or issue. - -### If you have not found an existing issue that describes your problem: - - 1. create a new issue, with a succinct title that describes your issue: - - bad title: "It doesn't work with my docker" - - good title: "Private registry push fail: 400 error with E_INVALID_DIGEST" - 2. copy the output of: - - `docker version` - - `docker info` - - `docker exec registry --version` - 3. copy the command line you used to launch your Registry - 4. restart your docker daemon in debug mode (add `-D` to the daemon launch arguments) - 5. reproduce your problem and get your docker daemon logs showing the error - 6. if relevant, copy your registry logs that show the error - 7. provide any relevant detail about your specific Registry configuration (e.g., storage backend used) - 8. indicate if you are using an enterprise proxy, Nginx, or anything else between you and your Registry - -## Contributing a patch for a known bug, or a small correction - -You should follow the basic GitHub workflow: - - 1. fork - 2. commit a change - 3. make sure the tests pass - 4. PR - -Additionally, you must [sign your commits](https://github.com/docker/docker/blob/master/CONTRIBUTING.md#sign-your-work). It's very simple: - - - configure your name with git: `git config user.name "Real Name" && git config user.email mail@example.com` - - sign your commits using `-s`: `git commit -s -m "My commit"` - -Some simple rules to ensure quick merge: - - - clearly point to the issue(s) you want to fix in your PR comment (e.g., `closes #12345`) - - prefer multiple (smaller) PRs addressing individual issues over a big one trying to address multiple issues at once - - if you need to amend your PR following comments, please squash instead of adding more commits - -## Contributing new features - -You are heavily encouraged to first discuss what you want to do. You can do so on the irc channel, or by opening an issue that clearly describes the use case you want to fulfill, or the problem you are trying to solve. - -If this is a major new feature, you should then submit a proposal that describes your technical solution and reasoning. -If you did discuss it first, this will likely be greenlighted very fast. It's advisable to address all feedback on this proposal before starting actual work. - -Then you should submit your implementation, clearly linking to the issue (and possible proposal). - -Your PR will be reviewed by the community, then ultimately by the project maintainers, before being merged. - -It's mandatory to: - - - interact respectfully with other community members and maintainers - more generally, you are expected to abide by the [Docker community rules](https://github.com/docker/docker/blob/master/CONTRIBUTING.md#docker-community-guidelines) - - address maintainers' comments and modify your submission accordingly - - write tests for any new code - -Complying to these simple rules will greatly accelerate the review process, and will ensure you have a pleasant experience in contributing code to the Registry. - -Have a look at a great, successful contribution: the [Swift driver PR](https://github.com/docker/distribution/pull/493) - -## Coding Style - -Unless explicitly stated, we follow all coding guidelines from the Go -community. While some of these standards may seem arbitrary, they somehow seem -to result in a solid, consistent codebase. - -It is possible that the code base does not currently comply with these -guidelines. We are not looking for a massive PR that fixes this, since that -goes against the spirit of the guidelines. All new contributions should make a -best effort to clean up and make the code base better than they left it. -Obviously, apply your best judgement. Remember, the goal here is to make the -code base easier for humans to navigate and understand. Always keep that in -mind when nudging others to comply. - -The rules: - -1. All code should be formatted with `gofmt -s`. -2. All code should pass the default levels of - [`golint`](https://github.com/golang/lint). -3. All code should follow the guidelines covered in [Effective - Go](http://golang.org/doc/effective_go.html) and [Go Code Review - Comments](https://github.com/golang/go/wiki/CodeReviewComments). -4. Comment the code. Tell us the why, the history and the context. -5. Document _all_ declarations and methods, even private ones. Declare - expectations, caveats and anything else that may be important. If a type - gets exported, having the comments already there will ensure it's ready. -6. Variable name length should be proportional to its context and no longer. - `noCommaALongVariableNameLikeThisIsNotMoreClearWhenASimpleCommentWouldDo`. - In practice, short methods will have short variable names and globals will - have longer names. -7. No underscores in package names. If you need a compound name, step back, - and re-examine why you need a compound name. If you still think you need a - compound name, lose the underscore. -8. No utils or helpers packages. If a function is not general enough to - warrant its own package, it has not been written generally enough to be a - part of a util package. Just leave it unexported and well-documented. -9. All tests should run with `go test` and outside tooling should not be - required. No, we don't need another unit testing framework. Assertion - packages are acceptable if they provide _real_ incremental value. -10. Even though we call these "rules" above, they are actually just - guidelines. Since you've read all the rules, you now know that. - -If you are having trouble getting into the mood of idiomatic Go, we recommend -reading through [Effective Go](http://golang.org/doc/effective_go.html). The -[Go Blog](http://blog.golang.org/) is also a great resource. Drinking the -kool-aid is a lot easier than going thirsty. diff --git a/vendor/github.com/docker/distribution/Dockerfile b/vendor/github.com/docker/distribution/Dockerfile deleted file mode 100644 index ebd42c242..000000000 --- a/vendor/github.com/docker/distribution/Dockerfile +++ /dev/null @@ -1,60 +0,0 @@ -# syntax=docker/dockerfile:1 - -ARG GO_VERSION=1.20.8 -ARG ALPINE_VERSION=3.18 -ARG XX_VERSION=1.2.1 - -FROM --platform=$BUILDPLATFORM tonistiigi/xx:${XX_VERSION} AS xx -FROM --platform=$BUILDPLATFORM golang:${GO_VERSION}-alpine${ALPINE_VERSION} AS base -COPY --from=xx / / -RUN apk add --no-cache bash coreutils file git -ENV GO111MODULE=auto -ENV CGO_ENABLED=0 -WORKDIR /go/src/github.com/docker/distribution - -FROM base AS version -ARG PKG="github.com/docker/distribution" -RUN --mount=target=. \ - VERSION=$(git describe --match 'v[0-9]*' --dirty='.m' --always --tags) REVISION=$(git rev-parse HEAD)$(if ! git diff --no-ext-diff --quiet --exit-code; then echo .m; fi); \ - echo "-X ${PKG}/version.Version=${VERSION#v} -X ${PKG}/version.Revision=${REVISION} -X ${PKG}/version.Package=${PKG}" | tee /tmp/.ldflags; \ - echo -n "${VERSION}" | tee /tmp/.version; - -FROM base AS build -ARG TARGETPLATFORM -ARG LDFLAGS="-s -w" -ARG BUILDTAGS="include_oss,include_gcs" -RUN --mount=type=bind,target=/go/src/github.com/docker/distribution,rw \ - --mount=type=cache,target=/root/.cache/go-build \ - --mount=target=/go/pkg/mod,type=cache \ - --mount=type=bind,source=/tmp/.ldflags,target=/tmp/.ldflags,from=version \ - set -x ; xx-go build -tags "${BUILDTAGS}" -trimpath -ldflags "$(cat /tmp/.ldflags) ${LDFLAGS}" -o /usr/bin/registry ./cmd/registry \ - && xx-verify --static /usr/bin/registry - -FROM scratch AS binary -COPY --from=build /usr/bin/registry / - -FROM base AS releaser -ARG TARGETOS -ARG TARGETARCH -ARG TARGETVARIANT -WORKDIR /work -RUN --mount=from=binary,target=/build \ - --mount=type=bind,target=/src \ - --mount=type=bind,source=/tmp/.version,target=/tmp/.version,from=version \ - VERSION=$(cat /tmp/.version) \ - && mkdir -p /out \ - && cp /build/registry /src/README.md /src/LICENSE . \ - && tar -czvf "/out/registry_${VERSION#v}_${TARGETOS}_${TARGETARCH}${TARGETVARIANT}.tar.gz" * \ - && sha256sum -z "/out/registry_${VERSION#v}_${TARGETOS}_${TARGETARCH}${TARGETVARIANT}.tar.gz" | awk '{ print $1 }' > "/out/registry_${VERSION#v}_${TARGETOS}_${TARGETARCH}${TARGETVARIANT}.tar.gz.sha256" - -FROM scratch AS artifact -COPY --from=releaser /out / - -FROM alpine:${ALPINE_VERSION} -RUN apk add --no-cache ca-certificates -COPY cmd/registry/config-dev.yml /etc/docker/registry/config.yml -COPY --from=binary /registry /bin/registry -VOLUME ["/var/lib/registry"] -EXPOSE 5000 -ENTRYPOINT ["registry"] -CMD ["serve", "/etc/docker/registry/config.yml"] diff --git a/vendor/github.com/docker/distribution/LICENSE b/vendor/github.com/docker/distribution/LICENSE deleted file mode 100644 index e06d20818..000000000 --- a/vendor/github.com/docker/distribution/LICENSE +++ /dev/null @@ -1,202 +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/docker/distribution/MAINTAINERS b/vendor/github.com/docker/distribution/MAINTAINERS deleted file mode 100644 index 3183620c5..000000000 --- a/vendor/github.com/docker/distribution/MAINTAINERS +++ /dev/null @@ -1,243 +0,0 @@ -# Distribution maintainers file -# -# This file describes who runs the docker/distribution project and how. -# This is a living document - if you see something out of date or missing, speak up! -# -# It is structured to be consumable by both humans and programs. -# To extract its contents programmatically, use any TOML-compliant parser. -# - -[Rules] - - [Rules.maintainers] - - title = "What is a maintainer?" - - text = """ -There are different types of maintainers, with different responsibilities, but -all maintainers have 3 things in common: - -1) They share responsibility in the project's success. -2) They have made a long-term, recurring time investment to improve the project. -3) They spend that time doing whatever needs to be done, not necessarily what -is the most interesting or fun. - -Maintainers are often under-appreciated, because their work is harder to appreciate. -It's easy to appreciate a really cool and technically advanced feature. It's harder -to appreciate the absence of bugs, the slow but steady improvement in stability, -or the reliability of a release process. But those things distinguish a good -project from a great one. -""" - - [Rules.reviewer] - - title = "What is a reviewer?" - - text = """ -A reviewer is a core role within the project. -They share in reviewing issues and pull requests and their LGTM count towards the -required LGTM count to merge a code change into the project. - -Reviewers are part of the organization but do not have write access. -Becoming a reviewer is a core aspect in the journey to becoming a maintainer. -""" - - [Rules.adding-maintainers] - - title = "How are maintainers added?" - - text = """ -Maintainers are first and foremost contributors that have shown they are -committed to the long term success of a project. Contributors wanting to become -maintainers are expected to be deeply involved in contributing code, pull -request review, and triage of issues in the project for more than three months. - -Just contributing does not make you a maintainer, it is about building trust -with the current maintainers of the project and being a person that they can -depend on and trust to make decisions in the best interest of the project. - -Periodically, the existing maintainers curate a list of contributors that have -shown regular activity on the project over the prior months. From this list, -maintainer candidates are selected and proposed on the maintainers mailing list. - -After a candidate has been announced on the maintainers mailing list, the -existing maintainers are given five business days to discuss the candidate, -raise objections and cast their vote. Candidates must be approved by at least 66% of the current maintainers by adding their vote on the mailing -list. Only maintainers of the repository that the candidate is proposed for are -allowed to vote. - -If a candidate is approved, a maintainer will contact the candidate to invite -the candidate to open a pull request that adds the contributor to the -MAINTAINERS file. The candidate becomes a maintainer once the pull request is -merged. -""" - - [Rules.stepping-down-policy] - - title = "Stepping down policy" - - text = """ -Life priorities, interests, and passions can change. If you're a maintainer but -feel you must remove yourself from the list, inform other maintainers that you -intend to step down, and if possible, help find someone to pick up your work. -At the very least, ensure your work can be continued where you left off. - -After you've informed other maintainers, create a pull request to remove -yourself from the MAINTAINERS file. -""" - - [Rules.inactive-maintainers] - - title = "Removal of inactive maintainers" - - text = """ -Similar to the procedure for adding new maintainers, existing maintainers can -be removed from the list if they do not show significant activity on the -project. Periodically, the maintainers review the list of maintainers and their -activity over the last three months. - -If a maintainer has shown insufficient activity over this period, a neutral -person will contact the maintainer to ask if they want to continue being -a maintainer. If the maintainer decides to step down as a maintainer, they -open a pull request to be removed from the MAINTAINERS file. - -If the maintainer wants to remain a maintainer, but is unable to perform the -required duties they can be removed with a vote of at least 66% of -the current maintainers. An e-mail is sent to the -mailing list, inviting maintainers of the project to vote. The voting period is -five business days. Issues related to a maintainer's performance should be -discussed with them among the other maintainers so that they are not surprised -by a pull request removing them. -""" - - [Rules.decisions] - - title = "How are decisions made?" - - text = """ -Short answer: EVERYTHING IS A PULL REQUEST. - -distribution is an open-source project with an open design philosophy. This means -that the repository is the source of truth for EVERY aspect of the project, -including its philosophy, design, road map, and APIs. *If it's part of the -project, it's in the repo. If it's in the repo, it's part of the project.* - -As a result, all decisions can be expressed as changes to the repository. An -implementation change is a change to the source code. An API change is a change -to the API specification. A philosophy change is a change to the philosophy -manifesto, and so on. - -All decisions affecting distribution, big and small, follow the same 3 steps: - -* Step 1: Open a pull request. Anyone can do this. - -* Step 2: Discuss the pull request. Anyone can do this. - -* Step 3: Merge or refuse the pull request. Who does this depends on the nature -of the pull request and which areas of the project it affects. -""" - - [Rules.DCO] - - title = "Helping contributors with the DCO" - - text = """ -The [DCO or `Sign your work`]( -https://github.com/moby/moby/blob/master/CONTRIBUTING.md#sign-your-work) -requirement is not intended as a roadblock or speed bump. - -Some distribution contributors are not as familiar with `git`, or have used a web -based editor, and thus asking them to `git commit --amend -s` is not the best -way forward. - -In this case, maintainers can update the commits based on clause (c) of the DCO. -The most trivial way for a contributor to allow the maintainer to do this, is to -add a DCO signature in a pull requests's comment, or a maintainer can simply -note that the change is sufficiently trivial that it does not substantially -change the existing contribution - i.e., a spelling change. - -When you add someone's DCO, please also add your own to keep a log. -""" - - [Rules."no direct push"] - - title = "I'm a maintainer. Should I make pull requests too?" - - text = """ -Yes. Nobody should ever push to master directly. All changes should be -made through a pull request. -""" - - [Rules.tsc] - - title = "Conflict Resolution and technical disputes" - - text = """ -distribution defers to the [Technical Steering Committee](https://github.com/moby/tsc) for escalations and resolution on disputes for technical matters." - """ - - [Rules.meta] - - title = "How is this process changed?" - - text = "Just like everything else: by making a pull request :)" - -# Current project organization -[Org] - - [Org.Maintainers] - people = [ - "dmcgowan", - "dmp42", - "stevvooe", - ] - [Org.Reviewers] - people = [ - "manishtomar", - "caervs", - "davidswu", - "RobbKistler" - ] - -[people] - -# A reference list of all people associated with the project. -# All other sections should refer to people by their canonical key -# in the people section. - - # ADD YOURSELF HERE IN ALPHABETICAL ORDER - - [people.caervs] - Name = "Ryan Abrams" - Email = "rdabrams@gmail.com" - GitHub = "caervs" - - [people.davidswu] - Name = "David Wu" - Email = "dwu7401@gmail.com" - GitHub = "davidswu" - - [people.dmcgowan] - Name = "Derek McGowan" - Email = "derek@mcgstyle.net" - GitHub = "dmcgowan" - - [people.dmp42] - Name = "Olivier Gambier" - Email = "olivier@docker.com" - GitHub = "dmp42" - - [people.manishtomar] - Name = "Manish Tomar" - Email = "manish.tomar@docker.com" - GitHub = "manishtomar" - - [people.RobbKistler] - Name = "Robb Kistler" - Email = "robb.kistler@docker.com" - GitHub = "RobbKistler" - - [people.stevvooe] - Name = "Stephen Day" - Email = "stephen.day@docker.com" - GitHub = "stevvooe" diff --git a/vendor/github.com/docker/distribution/Makefile b/vendor/github.com/docker/distribution/Makefile deleted file mode 100644 index dcdbcb547..000000000 --- a/vendor/github.com/docker/distribution/Makefile +++ /dev/null @@ -1,102 +0,0 @@ -# Root directory of the project (absolute path). -ROOTDIR=$(dir $(abspath $(lastword $(MAKEFILE_LIST)))) - -# Used to populate version variable in main package. -VERSION=$(shell git describe --match 'v[0-9]*' --dirty='.m' --always) -REVISION=$(shell git rev-parse HEAD)$(shell if ! git diff --no-ext-diff --quiet --exit-code; then echo .m; fi) - - -PKG=github.com/docker/distribution - -# Project packages. -PACKAGES=$(shell go list -tags "${BUILDTAGS}" ./... | grep -v /vendor/) -INTEGRATION_PACKAGE=${PKG} -COVERAGE_PACKAGES=$(filter-out ${PKG}/registry/storage/driver/%,${PACKAGES}) - - -# Project binaries. -COMMANDS=registry digest registry-api-descriptor-template - -# Allow turning off function inlining and variable registerization -ifeq (${DISABLE_OPTIMIZATION},true) - GO_GCFLAGS=-gcflags "-N -l" - VERSION:="$(VERSION)-noopt" -endif - -WHALE = "+" - -# Go files -# -TESTFLAGS_RACE= -GOFILES=$(shell find . -type f -name '*.go') -GO_TAGS=$(if $(BUILDTAGS),-tags "$(BUILDTAGS)",) -GO_LDFLAGS=-ldflags '-s -w -X $(PKG)/version.Version=$(VERSION) -X $(PKG)/version.Revision=$(REVISION) -X $(PKG)/version.Package=$(PKG) $(EXTRA_LDFLAGS)' - -BINARIES=$(addprefix bin/,$(COMMANDS)) - -# Flags passed to `go test` -TESTFLAGS ?= -v $(TESTFLAGS_RACE) -TESTFLAGS_PARALLEL ?= 8 - -.PHONY: all build binaries check clean test test-race test-full integration coverage -.DEFAULT: all - -all: binaries - -# This only needs to be generated by hand when cutting full releases. -version/version.go: - @echo "$(WHALE) $@" - ./version/version.sh > $@ - -check: ## run all linters (TODO: enable "unused", "varcheck", "ineffassign", "unconvert", "staticheck", "goimports", "structcheck") - @echo "$(WHALE) $@" - @GO111MODULE=off golangci-lint --build-tags "${BUILDTAGS}" run - -test: ## run tests, except integration test with test.short - @echo "$(WHALE) $@" - @go test ${GO_TAGS} -test.short ${TESTFLAGS} $(filter-out ${INTEGRATION_PACKAGE},${PACKAGES}) - -test-race: ## run tests, except integration test with test.short and race - @echo "$(WHALE) $@" - @go test ${GO_TAGS} -race -test.short ${TESTFLAGS} $(filter-out ${INTEGRATION_PACKAGE},${PACKAGES}) - -test-full: ## run tests, except integration tests - @echo "$(WHALE) $@" - @go test ${GO_TAGS} ${TESTFLAGS} $(filter-out ${INTEGRATION_PACKAGE},${PACKAGES}) - -integration: ## run integration tests - @echo "$(WHALE) $@" - @go test ${TESTFLAGS} -parallel ${TESTFLAGS_PARALLEL} ${INTEGRATION_PACKAGE} - -coverage: ## generate coverprofiles from the unit tests - @echo "$(WHALE) $@" - @rm -f coverage.txt - @go test ${GO_TAGS} -i ${TESTFLAGS} $(filter-out ${INTEGRATION_PACKAGE},${COVERAGE_PACKAGES}) 2> /dev/null - @( for pkg in $(filter-out ${INTEGRATION_PACKAGE},${COVERAGE_PACKAGES}); do \ - go test ${GO_TAGS} ${TESTFLAGS} \ - -cover \ - -coverprofile=profile.out \ - -covermode=atomic $$pkg || exit; \ - if [ -f profile.out ]; then \ - cat profile.out >> coverage.txt; \ - rm profile.out; \ - fi; \ - done ) - -FORCE: - -# Build a binary from a cmd. -bin/%: cmd/% FORCE - @echo "$(WHALE) $@${BINARY_SUFFIX}" - @go build ${GO_GCFLAGS} ${GO_BUILD_FLAGS} -o $@${BINARY_SUFFIX} ${GO_LDFLAGS} ${GO_TAGS} ./$< - -binaries: $(BINARIES) ## build binaries - @echo "$(WHALE) $@" - -build: - @echo "$(WHALE) $@" - @go build ${GO_GCFLAGS} ${GO_BUILD_FLAGS} ${GO_LDFLAGS} ${GO_TAGS} $(PACKAGES) - -clean: ## clean up binaries - @echo "$(WHALE) $@" - @rm -f $(BINARIES) diff --git a/vendor/github.com/docker/distribution/README.md b/vendor/github.com/docker/distribution/README.md deleted file mode 100644 index e513c18e9..000000000 --- a/vendor/github.com/docker/distribution/README.md +++ /dev/null @@ -1,130 +0,0 @@ -# Distribution - -The Docker toolset to pack, ship, store, and deliver content. - -This repository provides the Docker Registry 2.0 implementation -for storing and distributing Docker images. It supersedes the -[docker/docker-registry](https://github.com/docker/docker-registry) -project with a new API design, focused around security and performance. - - - -[![Circle CI](https://circleci.com/gh/docker/distribution/tree/master.svg?style=svg)](https://circleci.com/gh/docker/distribution/tree/master) -[![GoDoc](https://godoc.org/github.com/docker/distribution?status.svg)](https://godoc.org/github.com/docker/distribution) - -This repository contains the following components: - -|**Component** |Description | -|--------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| **registry** | An implementation of the [Docker Registry HTTP API V2](docs/spec/api.md) for use with docker 1.6+. | -| **libraries** | A rich set of libraries for interacting with distribution components. Please see [godoc](https://godoc.org/github.com/docker/distribution) for details. **Note**: These libraries are **unstable**. | -| **specifications** | _Distribution_ related specifications are available in [docs/spec](docs/spec) | -| **documentation** | Docker's full documentation set is available at [docs.docker.com](https://docs.docker.com). This repository [contains the subset](docs/) related just to the registry. | - -### How does this integrate with Docker engine? - -This project should provide an implementation to a V2 API for use in the [Docker -core project](https://github.com/docker/docker). The API should be embeddable -and simplify the process of securely pulling and pushing content from `docker` -daemons. - -### What are the long term goals of the Distribution project? - -The _Distribution_ project has the further long term goal of providing a -secure tool chain for distributing content. The specifications, APIs and tools -should be as useful with Docker as they are without. - -Our goal is to design a professional grade and extensible content distribution -system that allow users to: - -* Enjoy an efficient, secured and reliable way to store, manage, package and - exchange content -* Hack/roll their own on top of healthy open-source components -* Implement their own home made solution through good specs, and solid - extensions mechanism. - -## More about Registry 2.0 - -The new registry implementation provides the following benefits: - -- faster push and pull -- new, more efficient implementation -- simplified deployment -- pluggable storage backend -- webhook notifications - -For information on upcoming functionality, please see [ROADMAP.md](ROADMAP.md). - -### Who needs to deploy a registry? - -By default, Docker users pull images from Docker's public registry instance. -[Installing Docker](https://docs.docker.com/engine/installation/) gives users this -ability. Users can also push images to a repository on Docker's public registry, -if they have a [Docker Hub](https://hub.docker.com/) account. - -For some users and even companies, this default behavior is sufficient. For -others, it is not. - -For example, users with their own software products may want to maintain a -registry for private, company images. Also, you may wish to deploy your own -image repository for images used to test or in continuous integration. For these -use cases and others, [deploying your own registry instance](https://github.com/docker/docker.github.io/blob/master/registry/deploying.md) -may be the better choice. - -### Migration to Registry 2.0 - -For those who have previously deployed their own registry based on the Registry -1.0 implementation and wish to deploy a Registry 2.0 while retaining images, -data migration is required. A tool to assist with migration efforts has been -created. For more information see [docker/migrator](https://github.com/docker/migrator). - -## Contribute - -Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details on how to contribute -issues, fixes, and patches to this project. If you are contributing code, see -the instructions for [building a development environment](BUILDING.md). - -## Support - -If any issues are encountered while using the _Distribution_ project, several -avenues are available for support: - - - - - - - - - - - - - - - - - - -
- IRC - - #docker-distribution on FreeNode -
- Issue Tracker - - github.com/docker/distribution/issues -
- Google Groups - - https://groups.google.com/a/dockerproject.org/forum/#!forum/distribution -
- Mailing List - - docker@dockerproject.org -
- - -## License - -This project is distributed under [Apache License, Version 2.0](LICENSE). diff --git a/vendor/github.com/docker/distribution/ROADMAP.md b/vendor/github.com/docker/distribution/ROADMAP.md deleted file mode 100644 index 701127afe..000000000 --- a/vendor/github.com/docker/distribution/ROADMAP.md +++ /dev/null @@ -1,267 +0,0 @@ -# Roadmap - -The Distribution Project consists of several components, some of which are -still being defined. This document defines the high-level goals of the -project, identifies the current components, and defines the release- -relationship to the Docker Platform. - -* [Distribution Goals](#distribution-goals) -* [Distribution Components](#distribution-components) -* [Project Planning](#project-planning): release-relationship to the Docker Platform. - -This road map is a living document, providing an overview of the goals and -considerations made in respect of the future of the project. - -## Distribution Goals - -- Replace the existing [docker registry](github.com/docker/docker-registry) - implementation as the primary implementation. -- Replace the existing push and pull code in the docker engine with the - distribution package. -- Define a strong data model for distributing docker images -- Provide a flexible distribution tool kit for use in the docker platform -- Unlock new distribution models - -## Distribution Components - -Components of the Distribution Project are managed via github [milestones](https://github.com/docker/distribution/milestones). Upcoming -features and bugfixes for a component will be added to the relevant milestone. If a feature or -bugfix is not part of a milestone, it is currently unscheduled for -implementation. - -* [Registry](#registry) -* [Distribution Package](#distribution-package) - -*** - -### Registry - -The new Docker registry is the main portion of the distribution repository. -Registry 2.0 is the first release of the next-generation registry. This was -primarily focused on implementing the [new registry -API](https://github.com/docker/distribution/blob/master/docs/spec/api.md), -with a focus on security and performance. - -Following from the Distribution project goals above, we have a set of goals -for registry v2 that we would like to follow in the design. New features -should be compared against these goals. - -#### Data Storage and Distribution First - -The registry's first goal is to provide a reliable, consistent storage -location for Docker images. The registry should only provide the minimal -amount of indexing required to fetch image data and no more. - -This means we should be selective in new features and API additions, including -those that may require expensive, ever growing indexes. Requests should be -servable in "constant time". - -#### Content Addressability - -All data objects used in the registry API should be content addressable. -Content identifiers should be secure and verifiable. This provides a secure, -reliable base from which to build more advanced content distribution systems. - -#### Content Agnostic - -In the past, changes to the image format would require large changes in Docker -and the Registry. By decoupling the distribution and image format, we can -allow the formats to progress without having to coordinate between the two. -This means that we should be focused on decoupling Docker from the registry -just as much as decoupling the registry from Docker. Such an approach will -allow us to unlock new distribution models that haven't been possible before. - -We can take this further by saying that the new registry should be content -agnostic. The registry provides a model of names, tags, manifests and content -addresses and that model can be used to work with content. - -#### Simplicity - -The new registry should be closer to a microservice component than its -predecessor. This means it should have a narrower API and a low number of -service dependencies. It should be easy to deploy. - -This means that other solutions should be explored before changing the API or -adding extra dependencies. If functionality is required, can it be added as an -extension or companion service. - -#### Extensibility - -The registry should provide extension points to add functionality. By keeping -the scope narrow, but providing the ability to add functionality. - -Features like search, indexing, synchronization and registry explorers fall -into this category. No such feature should be added unless we've found it -impossible to do through an extension. - -#### Active Feature Discussions - -The following are feature discussions that are currently active. - -If you don't see your favorite, unimplemented feature, feel free to contact us -via IRC or the mailing list and we can talk about adding it. The goal here is -to make sure that new features go through a rigid design process before -landing in the registry. - -##### Proxying to other Registries - -A _pull-through caching_ mode exists for the registry, but is restricted from -within the docker client to only mirror the official Docker Hub. This functionality -can be expanded when image provenance has been specified and implemented in the -distribution project. - -##### Metadata storage - -Metadata for the registry is currently stored with the manifest and layer data on -the storage backend. While this is a big win for simplicity and reliably maintaining -state, it comes with the cost of consistency and high latency. The mutable registry -metadata operations should be abstracted behind an API which will allow ACID compliant -storage systems to handle metadata. - -##### Peer to Peer transfer - -Discussion has started here: https://docs.google.com/document/d/1rYDpSpJiQWmCQy8Cuiaa3NH-Co33oK_SC9HeXYo87QA/edit - -##### Indexing, Search and Discovery - -The original registry provided some implementation of search for use with -private registries. Support has been elided from V2 since we'd like to both -decouple search functionality from the registry. The makes the registry -simpler to deploy, especially in use cases where search is not needed, and -let's us decouple the image format from the registry. - -There are explorations into using the catalog API and notification system to -build external indexes. The current line of thought is that we will define a -common search API to index and query docker images. Such a system could be run -as a companion to a registry or set of registries to power discovery. - -The main issue with search and discovery is that there are so many ways to -accomplish it. There are two aspects to this project. The first is deciding on -how it will be done, including an API definition that can work with changing -data formats. The second is the process of integrating with `docker search`. -We expect that someone attempts to address the problem with the existing tools -and propose it as a standard search API or uses it to inform a standardization -process. Once this has been explored, we integrate with the docker client. - -Please see the following for more detail: - -- https://github.com/docker/distribution/issues/206 - -##### Deletes - -> __NOTE:__ Deletes are a much asked for feature. Before requesting this -feature or participating in discussion, we ask that you read this section in -full and understand the problems behind deletes. - -While, at first glance, implementing deleting seems simple, there are a number -mitigating factors that make many solutions not ideal or even pathological in -the context of a registry. The following paragraph discuss the background and -approaches that could be applied to arrive at a solution. - -The goal of deletes in any system is to remove unused or unneeded data. Only -data requested for deletion should be removed and no other data. Removing -unintended data is worse than _not_ removing data that was requested for -removal but ideally, both are supported. Generally, according to this rule, we -err on holding data longer than needed, ensuring that it is only removed when -we can be certain that it can be removed. With the current behavior, we opt to -hold onto the data forever, ensuring that data cannot be incorrectly removed. - -To understand the problems with implementing deletes, one must understand the -data model. All registry data is stored in a filesystem layout, implemented on -a "storage driver", effectively a _virtual file system_ (VFS). The storage -system must assume that this VFS layer will be eventually consistent and has -poor read- after-write consistency, since this is the lower common denominator -among the storage drivers. This is mitigated by writing values in reverse- -dependent order, but makes wider transactional operations unsafe. - -Layered on the VFS model is a content-addressable _directed, acyclic graph_ -(DAG) made up of blobs. Manifests reference layers. Tags reference manifests. -Since the same data can be referenced by multiple manifests, we only store -data once, even if it is in different repositories. Thus, we have a set of -blobs, referenced by tags and manifests. If we want to delete a blob we need -to be certain that it is no longer referenced by another manifest or tag. When -we delete a manifest, we also can try to delete the referenced blobs. Deciding -whether or not a blob has an active reference is the crux of the problem. - -Conceptually, deleting a manifest and its resources is quite simple. Just find -all the manifests, enumerate the referenced blobs and delete the blobs not in -that set. An astute observer will recognize this as a garbage collection -problem. As with garbage collection in programming languages, this is very -simple when one always has a consistent view. When one adds parallelism and an -inconsistent view of data, it becomes very challenging. - -A simple example can demonstrate this. Let's say we are deleting a manifest -_A_ in one process. We scan the manifest and decide that all the blobs are -ready for deletion. Concurrently, we have another process accepting a new -manifest _B_ referencing one or more blobs from the manifest _A_. Manifest _B_ -is accepted and all the blobs are considered present, so the operation -proceeds. The original process then deletes the referenced blobs, assuming -they were unreferenced. The manifest _B_, which we thought had all of its data -present, can no longer be served by the registry, since the dependent data has -been deleted. - -Deleting data from the registry safely requires some way to coordinate this -operation. The following approaches are being considered: - -- _Reference Counting_ - Maintain a count of references to each blob. This is - challenging for a number of reasons: 1. maintaining a consistent consensus - of reference counts across a set of Registries and 2. Building the initial - list of reference counts for an existing registry. These challenges can be - met with a consensus protocol like Paxos or Raft in the first case and a - necessary but simple scan in the second.. -- _Lock the World GC_ - Halt all writes to the data store. Walk the data store - and find all blob references. Delete all unreferenced blobs. This approach - is very simple but requires disabling writes for a period of time while the - service reads all data. This is slow and expensive but very accurate and - effective. -- _Generational GC_ - Do something similar to above but instead of blocking - writes, writes are sent to another storage backend while reads are broadcast - to the new and old backends. GC is then performed on the read-only portion. - Because writes land in the new backend, the data in the read-only section - can be safely deleted. The main drawbacks of this approach are complexity - and coordination. -- _Centralized Oracle_ - Using a centralized, transactional database, we can - know exactly which data is referenced at any given time. This avoids - coordination problem by managing this data in a single location. We trade - off metadata scalability for simplicity and performance. This is a very good - option for most registry deployments. This would create a bottleneck for - registry metadata. However, metadata is generally not the main bottleneck - when serving images. - -Please let us know if other solutions exist that we have yet to enumerate. -Note that for any approach, implementation is a massive consideration. For -example, a mark-sweep based solution may seem simple but the amount of work in -coordination offset the extra work it might take to build a _Centralized -Oracle_. We'll accept proposals for any solution but please coordinate with us -before dropping code. - -At this time, we have traded off simplicity and ease of deployment for disk -space. Simplicity and ease of deployment tend to reduce developer involvement, -which is currently the most expensive resource in software engineering. Taking -on any solution for deletes will greatly effect these factors, trading off -very cheap disk space for a complex deployment and operational story. - -Please see the following issues for more detail: - -- https://github.com/docker/distribution/issues/422 -- https://github.com/docker/distribution/issues/461 -- https://github.com/docker/distribution/issues/462 - -### Distribution Package - -At its core, the Distribution Project is a set of Go packages that make up -Distribution Components. At this time, most of these packages make up the -Registry implementation. - -The package itself is considered unstable. If you're using it, please take care to vendor the dependent version. - -For feature additions, please see the Registry section. In the future, we may break out a -separate Roadmap for distribution-specific features that apply to more than -just the registry. - -*** - -### Project Planning - -An [Open-Source Planning Process](https://github.com/docker/distribution/wiki/Open-Source-Planning-Process) is used to define the Roadmap. [Project Pages](https://github.com/docker/distribution/wiki) define the goals for each Milestone and identify current progress. - diff --git a/vendor/github.com/docker/distribution/blobs.go b/vendor/github.com/docker/distribution/blobs.go deleted file mode 100644 index 671372abf..000000000 --- a/vendor/github.com/docker/distribution/blobs.go +++ /dev/null @@ -1,265 +0,0 @@ -package distribution - -import ( - "context" - "errors" - "fmt" - "io" - "net/http" - "time" - - "github.com/distribution/reference" - "github.com/opencontainers/go-digest" - v1 "github.com/opencontainers/image-spec/specs-go/v1" -) - -var ( - // ErrBlobExists returned when blob already exists - ErrBlobExists = errors.New("blob exists") - - // ErrBlobDigestUnsupported when blob digest is an unsupported version. - ErrBlobDigestUnsupported = errors.New("unsupported blob digest") - - // ErrBlobUnknown when blob is not found. - ErrBlobUnknown = errors.New("unknown blob") - - // ErrBlobUploadUnknown returned when upload is not found. - ErrBlobUploadUnknown = errors.New("blob upload unknown") - - // ErrBlobInvalidLength returned when the blob has an expected length on - // commit, meaning mismatched with the descriptor or an invalid value. - ErrBlobInvalidLength = errors.New("blob invalid length") -) - -// ErrBlobInvalidDigest returned when digest check fails. -type ErrBlobInvalidDigest struct { - Digest digest.Digest - Reason error -} - -func (err ErrBlobInvalidDigest) Error() string { - return fmt.Sprintf("invalid digest for referenced layer: %v, %v", - err.Digest, err.Reason) -} - -// ErrBlobMounted returned when a blob is mounted from another repository -// instead of initiating an upload session. -type ErrBlobMounted struct { - From reference.Canonical - Descriptor Descriptor -} - -func (err ErrBlobMounted) Error() string { - return fmt.Sprintf("blob mounted from: %v to: %v", - err.From, err.Descriptor) -} - -// Descriptor describes targeted content. Used in conjunction with a blob -// store, a descriptor can be used to fetch, store and target any kind of -// blob. The struct also describes the wire protocol format. Fields should -// only be added but never changed. -type Descriptor struct { - // MediaType describe the type of the content. All text based formats are - // encoded as utf-8. - MediaType string `json:"mediaType,omitempty"` - - // Size in bytes of content. - Size int64 `json:"size,omitempty"` - - // Digest uniquely identifies the content. A byte stream can be verified - // against this digest. - Digest digest.Digest `json:"digest,omitempty"` - - // URLs contains the source URLs of this content. - URLs []string `json:"urls,omitempty"` - - // Annotations contains arbitrary metadata relating to the targeted content. - Annotations map[string]string `json:"annotations,omitempty"` - - // Platform describes the platform which the image in the manifest runs on. - // This should only be used when referring to a manifest. - Platform *v1.Platform `json:"platform,omitempty"` - - // NOTE: Before adding a field here, please ensure that all - // other options have been exhausted. Much of the type relationships - // depend on the simplicity of this type. -} - -// Descriptor returns the descriptor, to make it satisfy the Describable -// interface. Note that implementations of Describable are generally objects -// which can be described, not simply descriptors; this exception is in place -// to make it more convenient to pass actual descriptors to functions that -// expect Describable objects. -func (d Descriptor) Descriptor() Descriptor { - return d -} - -// BlobStatter makes blob descriptors available by digest. The service may -// provide a descriptor of a different digest if the provided digest is not -// canonical. -type BlobStatter interface { - // Stat provides metadata about a blob identified by the digest. If the - // blob is unknown to the describer, ErrBlobUnknown will be returned. - Stat(ctx context.Context, dgst digest.Digest) (Descriptor, error) -} - -// BlobDeleter enables deleting blobs from storage. -type BlobDeleter interface { - Delete(ctx context.Context, dgst digest.Digest) error -} - -// BlobEnumerator enables iterating over blobs from storage -type BlobEnumerator interface { - Enumerate(ctx context.Context, ingester func(dgst digest.Digest) error) error -} - -// BlobDescriptorService manages metadata about a blob by digest. Most -// implementations will not expose such an interface explicitly. Such mappings -// should be maintained by interacting with the BlobIngester. Hence, this is -// left off of BlobService and BlobStore. -type BlobDescriptorService interface { - BlobStatter - - // SetDescriptor assigns the descriptor to the digest. The provided digest and - // the digest in the descriptor must map to identical content but they may - // differ on their algorithm. The descriptor must have the canonical - // digest of the content and the digest algorithm must match the - // annotators canonical algorithm. - // - // Such a facility can be used to map blobs between digest domains, with - // the restriction that the algorithm of the descriptor must match the - // canonical algorithm (ie sha256) of the annotator. - SetDescriptor(ctx context.Context, dgst digest.Digest, desc Descriptor) error - - // Clear enables descriptors to be unlinked - Clear(ctx context.Context, dgst digest.Digest) error -} - -// BlobDescriptorServiceFactory creates middleware for BlobDescriptorService. -type BlobDescriptorServiceFactory interface { - BlobAccessController(svc BlobDescriptorService) BlobDescriptorService -} - -// ReadSeekCloser is the primary reader type for blob data, combining -// io.ReadSeeker with io.Closer. -type ReadSeekCloser interface { - io.ReadSeeker - io.Closer -} - -// BlobProvider describes operations for getting blob data. -type BlobProvider interface { - // Get returns the entire blob identified by digest along with the descriptor. - Get(ctx context.Context, dgst digest.Digest) ([]byte, error) - - // Open provides a ReadSeekCloser to the blob identified by the provided - // descriptor. If the blob is not known to the service, an error will be - // returned. - Open(ctx context.Context, dgst digest.Digest) (ReadSeekCloser, error) -} - -// BlobServer can serve blobs via http. -type BlobServer interface { - // ServeBlob attempts to serve the blob, identified by dgst, via http. The - // service may decide to redirect the client elsewhere or serve the data - // directly. - // - // This handler only issues successful responses, such as 2xx or 3xx, - // meaning it serves data or issues a redirect. If the blob is not - // available, an error will be returned and the caller may still issue a - // response. - // - // The implementation may serve the same blob from a different digest - // domain. The appropriate headers will be set for the blob, unless they - // have already been set by the caller. - ServeBlob(ctx context.Context, w http.ResponseWriter, r *http.Request, dgst digest.Digest) error -} - -// BlobIngester ingests blob data. -type BlobIngester interface { - // Put inserts the content p into the blob service, returning a descriptor - // or an error. - Put(ctx context.Context, mediaType string, p []byte) (Descriptor, error) - - // Create allocates a new blob writer to add a blob to this service. The - // returned handle can be written to and later resumed using an opaque - // identifier. With this approach, one can Close and Resume a BlobWriter - // multiple times until the BlobWriter is committed or cancelled. - Create(ctx context.Context, options ...BlobCreateOption) (BlobWriter, error) - - // Resume attempts to resume a write to a blob, identified by an id. - Resume(ctx context.Context, id string) (BlobWriter, error) -} - -// BlobCreateOption is a general extensible function argument for blob creation -// methods. A BlobIngester may choose to honor any or none of the given -// BlobCreateOptions, which can be specific to the implementation of the -// BlobIngester receiving them. -// TODO (brianbland): unify this with ManifestServiceOption in the future -type BlobCreateOption interface { - Apply(interface{}) error -} - -// CreateOptions is a collection of blob creation modifiers relevant to general -// blob storage intended to be configured by the BlobCreateOption.Apply method. -type CreateOptions struct { - Mount struct { - ShouldMount bool - From reference.Canonical - // Stat allows to pass precalculated descriptor to link and return. - // Blob access check will be skipped if set. - Stat *Descriptor - } -} - -// BlobWriter provides a handle for inserting data into a blob store. -// Instances should be obtained from BlobWriteService.Writer and -// BlobWriteService.Resume. If supported by the store, a writer can be -// recovered with the id. -type BlobWriter interface { - io.WriteCloser - io.ReaderFrom - - // Size returns the number of bytes written to this blob. - Size() int64 - - // ID returns the identifier for this writer. The ID can be used with the - // Blob service to later resume the write. - ID() string - - // StartedAt returns the time this blob write was started. - StartedAt() time.Time - - // Commit completes the blob writer process. The content is verified - // against the provided provisional descriptor, which may result in an - // error. Depending on the implementation, written data may be validated - // against the provisional descriptor fields. If MediaType is not present, - // the implementation may reject the commit or assign "application/octet- - // stream" to the blob. The returned descriptor may have a different - // digest depending on the blob store, referred to as the canonical - // descriptor. - Commit(ctx context.Context, provisional Descriptor) (canonical Descriptor, err error) - - // Cancel ends the blob write without storing any data and frees any - // associated resources. Any data written thus far will be lost. Cancel - // implementations should allow multiple calls even after a commit that - // result in a no-op. This allows use of Cancel in a defer statement, - // increasing the assurance that it is correctly called. - Cancel(ctx context.Context) error -} - -// BlobService combines the operations to access, read and write blobs. This -// can be used to describe remote blob services. -type BlobService interface { - BlobStatter - BlobProvider - BlobIngester -} - -// BlobStore represent the entire suite of blob related operations. Such an -// implementation can access, read, write, delete and serve blobs. -type BlobStore interface { - BlobService - BlobServer - BlobDeleter -} diff --git a/vendor/github.com/docker/distribution/doc.go b/vendor/github.com/docker/distribution/doc.go deleted file mode 100644 index bdd8cb708..000000000 --- a/vendor/github.com/docker/distribution/doc.go +++ /dev/null @@ -1,7 +0,0 @@ -// Package distribution will define the interfaces for the components of -// docker distribution. The goal is to allow users to reliably package, ship -// and store content related to docker images. -// -// This is currently a work in progress. More details are available in the -// README.md. -package distribution diff --git a/vendor/github.com/docker/distribution/docker-bake.hcl b/vendor/github.com/docker/distribution/docker-bake.hcl deleted file mode 100644 index 91686e608..000000000 --- a/vendor/github.com/docker/distribution/docker-bake.hcl +++ /dev/null @@ -1,56 +0,0 @@ -group "default" { - targets = ["image-local"] -} - -// Special target: https://github.com/docker/metadata-action#bake-definition -target "docker-metadata-action" { - tags = ["registry:local"] -} - -target "binary" { - target = "binary" - output = ["./bin"] -} - -target "artifact" { - target = "artifact" - output = ["./bin"] -} - -target "artifact-all" { - inherits = ["artifact"] - platforms = [ - "linux/amd64", - "linux/arm/v6", - "linux/arm/v7", - "linux/arm64", - "linux/ppc64le", - "linux/s390x" - ] -} - -// Special target: https://github.com/docker/metadata-action#bake-definition -target "docker-metadata-action" { - tags = ["registry:local"] -} - -target "image" { - inherits = ["docker-metadata-action"] -} - -target "image-local" { - inherits = ["image"] - output = ["type=docker"] -} - -target "image-all" { - inherits = ["image"] - platforms = [ - "linux/amd64", - "linux/arm/v6", - "linux/arm/v7", - "linux/arm64", - "linux/ppc64le", - "linux/s390x" - ] -} diff --git a/vendor/github.com/docker/distribution/errors.go b/vendor/github.com/docker/distribution/errors.go deleted file mode 100644 index 8e0b788d6..000000000 --- a/vendor/github.com/docker/distribution/errors.go +++ /dev/null @@ -1,119 +0,0 @@ -package distribution - -import ( - "errors" - "fmt" - "strings" - - "github.com/opencontainers/go-digest" -) - -// ErrAccessDenied is returned when an access to a requested resource is -// denied. -var ErrAccessDenied = errors.New("access denied") - -// ErrManifestNotModified is returned when a conditional manifest GetByTag -// returns nil due to the client indicating it has the latest version -var ErrManifestNotModified = errors.New("manifest not modified") - -// ErrUnsupported is returned when an unimplemented or unsupported action is -// performed -var ErrUnsupported = errors.New("operation unsupported") - -// ErrSchemaV1Unsupported is returned when a client tries to upload a schema v1 -// manifest but the registry is configured to reject it -var ErrSchemaV1Unsupported = errors.New("manifest schema v1 unsupported") - -// ErrTagUnknown is returned if the given tag is not known by the tag service -type ErrTagUnknown struct { - Tag string -} - -func (err ErrTagUnknown) Error() string { - return fmt.Sprintf("unknown tag=%s", err.Tag) -} - -// ErrRepositoryUnknown is returned if the named repository is not known by -// the registry. -type ErrRepositoryUnknown struct { - Name string -} - -func (err ErrRepositoryUnknown) Error() string { - return fmt.Sprintf("unknown repository name=%s", err.Name) -} - -// ErrRepositoryNameInvalid should be used to denote an invalid repository -// name. Reason may set, indicating the cause of invalidity. -type ErrRepositoryNameInvalid struct { - Name string - Reason error -} - -func (err ErrRepositoryNameInvalid) Error() string { - return fmt.Sprintf("repository name %q invalid: %v", err.Name, err.Reason) -} - -// ErrManifestUnknown is returned if the manifest is not known by the -// registry. -type ErrManifestUnknown struct { - Name string - Tag string -} - -func (err ErrManifestUnknown) Error() string { - return fmt.Sprintf("unknown manifest name=%s tag=%s", err.Name, err.Tag) -} - -// ErrManifestUnknownRevision is returned when a manifest cannot be found by -// revision within a repository. -type ErrManifestUnknownRevision struct { - Name string - Revision digest.Digest -} - -func (err ErrManifestUnknownRevision) Error() string { - return fmt.Sprintf("unknown manifest name=%s revision=%s", err.Name, err.Revision) -} - -// ErrManifestUnverified is returned when the registry is unable to verify -// the manifest. -type ErrManifestUnverified struct{} - -func (ErrManifestUnverified) Error() string { - return "unverified manifest" -} - -// ErrManifestVerification provides a type to collect errors encountered -// during manifest verification. Currently, it accepts errors of all types, -// but it may be narrowed to those involving manifest verification. -type ErrManifestVerification []error - -func (errs ErrManifestVerification) Error() string { - var parts []string - for _, err := range errs { - parts = append(parts, err.Error()) - } - - return fmt.Sprintf("errors verifying manifest: %v", strings.Join(parts, ",")) -} - -// ErrManifestBlobUnknown returned when a referenced blob cannot be found. -type ErrManifestBlobUnknown struct { - Digest digest.Digest -} - -func (err ErrManifestBlobUnknown) Error() string { - return fmt.Sprintf("unknown blob %v on manifest", err.Digest) -} - -// ErrManifestNameInvalid should be used to denote an invalid manifest -// name. Reason may set, indicating the cause of invalidity. -type ErrManifestNameInvalid struct { - Name string - Reason error -} - -func (err ErrManifestNameInvalid) Error() string { - return fmt.Sprintf("manifest name %q invalid: %v", err.Name, err.Reason) -} diff --git a/vendor/github.com/docker/distribution/manifest/doc.go b/vendor/github.com/docker/distribution/manifest/doc.go deleted file mode 100644 index 88367b0a0..000000000 --- a/vendor/github.com/docker/distribution/manifest/doc.go +++ /dev/null @@ -1 +0,0 @@ -package manifest diff --git a/vendor/github.com/docker/distribution/manifest/manifestlist/manifestlist.go b/vendor/github.com/docker/distribution/manifest/manifestlist/manifestlist.go deleted file mode 100644 index bea2341c7..000000000 --- a/vendor/github.com/docker/distribution/manifest/manifestlist/manifestlist.go +++ /dev/null @@ -1,239 +0,0 @@ -package manifestlist - -import ( - "encoding/json" - "errors" - "fmt" - - "github.com/docker/distribution" - "github.com/docker/distribution/manifest" - "github.com/opencontainers/go-digest" - v1 "github.com/opencontainers/image-spec/specs-go/v1" -) - -const ( - // MediaTypeManifestList specifies the mediaType for manifest lists. - MediaTypeManifestList = "application/vnd.docker.distribution.manifest.list.v2+json" -) - -// SchemaVersion provides a pre-initialized version structure for this -// packages version of the manifest. -var SchemaVersion = manifest.Versioned{ - SchemaVersion: 2, - MediaType: MediaTypeManifestList, -} - -// OCISchemaVersion provides a pre-initialized version structure for this -// packages OCIschema version of the manifest. -var OCISchemaVersion = manifest.Versioned{ - SchemaVersion: 2, - MediaType: v1.MediaTypeImageIndex, -} - -func init() { - manifestListFunc := func(b []byte) (distribution.Manifest, distribution.Descriptor, error) { - m := new(DeserializedManifestList) - err := m.UnmarshalJSON(b) - if err != nil { - return nil, distribution.Descriptor{}, err - } - - if m.MediaType != MediaTypeManifestList { - err = fmt.Errorf("mediaType in manifest list should be '%s' not '%s'", - MediaTypeManifestList, m.MediaType) - - return nil, distribution.Descriptor{}, err - } - - dgst := digest.FromBytes(b) - return m, distribution.Descriptor{Digest: dgst, Size: int64(len(b)), MediaType: MediaTypeManifestList}, err - } - err := distribution.RegisterManifestSchema(MediaTypeManifestList, manifestListFunc) - if err != nil { - panic(fmt.Sprintf("Unable to register manifest: %s", err)) - } - - imageIndexFunc := func(b []byte) (distribution.Manifest, distribution.Descriptor, error) { - if err := validateIndex(b); err != nil { - return nil, distribution.Descriptor{}, err - } - m := new(DeserializedManifestList) - err := m.UnmarshalJSON(b) - if err != nil { - return nil, distribution.Descriptor{}, err - } - - if m.MediaType != "" && m.MediaType != v1.MediaTypeImageIndex { - err = fmt.Errorf("if present, mediaType in image index should be '%s' not '%s'", - v1.MediaTypeImageIndex, m.MediaType) - - return nil, distribution.Descriptor{}, err - } - - dgst := digest.FromBytes(b) - return m, distribution.Descriptor{Digest: dgst, Size: int64(len(b)), MediaType: v1.MediaTypeImageIndex}, err - } - err = distribution.RegisterManifestSchema(v1.MediaTypeImageIndex, imageIndexFunc) - if err != nil { - panic(fmt.Sprintf("Unable to register OCI Image Index: %s", err)) - } -} - -// PlatformSpec specifies a platform where a particular image manifest is -// applicable. -type PlatformSpec struct { - // Architecture field specifies the CPU architecture, for example - // `amd64` or `ppc64`. - Architecture string `json:"architecture"` - - // OS specifies the operating system, for example `linux` or `windows`. - OS string `json:"os"` - - // OSVersion is an optional field specifying the operating system - // version, for example `10.0.10586`. - OSVersion string `json:"os.version,omitempty"` - - // OSFeatures is an optional field specifying an array of strings, - // each listing a required OS feature (for example on Windows `win32k`). - OSFeatures []string `json:"os.features,omitempty"` - - // Variant is an optional field specifying a variant of the CPU, for - // example `ppc64le` to specify a little-endian version of a PowerPC CPU. - Variant string `json:"variant,omitempty"` - - // Features is an optional field specifying an array of strings, each - // listing a required CPU feature (for example `sse4` or `aes`). - Features []string `json:"features,omitempty"` -} - -// A ManifestDescriptor references a platform-specific manifest. -type ManifestDescriptor struct { - distribution.Descriptor - - // Platform specifies which platform the manifest pointed to by the - // descriptor runs on. - Platform PlatformSpec `json:"platform"` -} - -// ManifestList references manifests for various platforms. -type ManifestList struct { - manifest.Versioned - - // Config references the image configuration as a blob. - Manifests []ManifestDescriptor `json:"manifests"` -} - -// References returns the distribution descriptors for the referenced image -// manifests. -func (m ManifestList) References() []distribution.Descriptor { - dependencies := make([]distribution.Descriptor, len(m.Manifests)) - for i := range m.Manifests { - dependencies[i] = m.Manifests[i].Descriptor - } - - return dependencies -} - -// DeserializedManifestList wraps ManifestList with a copy of the original -// JSON. -type DeserializedManifestList struct { - ManifestList - - // canonical is the canonical byte representation of the Manifest. - canonical []byte -} - -// FromDescriptors takes a slice of descriptors, and returns a -// DeserializedManifestList which contains the resulting manifest list -// and its JSON representation. -func FromDescriptors(descriptors []ManifestDescriptor) (*DeserializedManifestList, error) { - var mediaType string - if len(descriptors) > 0 && descriptors[0].Descriptor.MediaType == v1.MediaTypeImageManifest { - mediaType = v1.MediaTypeImageIndex - } else { - mediaType = MediaTypeManifestList - } - - return FromDescriptorsWithMediaType(descriptors, mediaType) -} - -// FromDescriptorsWithMediaType is for testing purposes, it's useful to be able to specify the media type explicitly -func FromDescriptorsWithMediaType(descriptors []ManifestDescriptor, mediaType string) (*DeserializedManifestList, error) { - m := ManifestList{ - Versioned: manifest.Versioned{ - SchemaVersion: 2, - MediaType: mediaType, - }, - } - - m.Manifests = make([]ManifestDescriptor, len(descriptors)) - copy(m.Manifests, descriptors) - - deserialized := DeserializedManifestList{ - ManifestList: m, - } - - var err error - deserialized.canonical, err = json.MarshalIndent(&m, "", " ") - return &deserialized, err -} - -// UnmarshalJSON populates a new ManifestList struct from JSON data. -func (m *DeserializedManifestList) UnmarshalJSON(b []byte) error { - m.canonical = make([]byte, len(b)) - // store manifest list in canonical - copy(m.canonical, b) - - // Unmarshal canonical JSON into ManifestList object - var manifestList ManifestList - if err := json.Unmarshal(m.canonical, &manifestList); err != nil { - return err - } - - m.ManifestList = manifestList - - return nil -} - -// MarshalJSON returns the contents of canonical. If canonical is empty, -// marshals the inner contents. -func (m *DeserializedManifestList) MarshalJSON() ([]byte, error) { - if len(m.canonical) > 0 { - return m.canonical, nil - } - - return nil, errors.New("JSON representation not initialized in DeserializedManifestList") -} - -// Payload returns the raw content of the manifest list. The contents can be -// used to calculate the content identifier. -func (m DeserializedManifestList) Payload() (string, []byte, error) { - var mediaType string - if m.MediaType == "" { - mediaType = v1.MediaTypeImageIndex - } else { - mediaType = m.MediaType - } - - return mediaType, m.canonical, nil -} - -// unknownDocument represents a manifest, manifest list, or index that has not -// yet been validated -type unknownDocument struct { - Config interface{} `json:"config,omitempty"` - Layers interface{} `json:"layers,omitempty"` -} - -// validateIndex returns an error if the byte slice is invalid JSON or if it -// contains fields that belong to a manifest -func validateIndex(b []byte) error { - var doc unknownDocument - if err := json.Unmarshal(b, &doc); err != nil { - return err - } - if doc.Config != nil || doc.Layers != nil { - return errors.New("index: expected index but found manifest") - } - return nil -} diff --git a/vendor/github.com/docker/distribution/manifest/ocischema/builder.go b/vendor/github.com/docker/distribution/manifest/ocischema/builder.go deleted file mode 100644 index b89bf5b71..000000000 --- a/vendor/github.com/docker/distribution/manifest/ocischema/builder.go +++ /dev/null @@ -1,107 +0,0 @@ -package ocischema - -import ( - "context" - "errors" - - "github.com/docker/distribution" - "github.com/docker/distribution/manifest" - "github.com/opencontainers/go-digest" - v1 "github.com/opencontainers/image-spec/specs-go/v1" -) - -// Builder is a type for constructing manifests. -type Builder struct { - // bs is a BlobService used to publish the configuration blob. - bs distribution.BlobService - - // configJSON references - configJSON []byte - - // layers is a list of layer descriptors that gets built by successive - // calls to AppendReference. - layers []distribution.Descriptor - - // Annotations contains arbitrary metadata relating to the targeted content. - annotations map[string]string - - // For testing purposes - mediaType string -} - -// NewManifestBuilder is used to build new manifests for the current schema -// version. It takes a BlobService so it can publish the configuration blob -// as part of the Build process, and annotations. -func NewManifestBuilder(bs distribution.BlobService, configJSON []byte, annotations map[string]string) distribution.ManifestBuilder { - mb := &Builder{ - bs: bs, - configJSON: make([]byte, len(configJSON)), - annotations: annotations, - mediaType: v1.MediaTypeImageManifest, - } - copy(mb.configJSON, configJSON) - - return mb -} - -// SetMediaType assigns the passed mediatype or error if the mediatype is not a -// valid media type for oci image manifests currently: "" or "application/vnd.oci.image.manifest.v1+json" -func (mb *Builder) SetMediaType(mediaType string) error { - if mediaType != "" && mediaType != v1.MediaTypeImageManifest { - return errors.New("invalid media type for OCI image manifest") - } - - mb.mediaType = mediaType - return nil -} - -// Build produces a final manifest from the given references. -func (mb *Builder) Build(ctx context.Context) (distribution.Manifest, error) { - m := Manifest{ - Versioned: manifest.Versioned{ - SchemaVersion: 2, - MediaType: mb.mediaType, - }, - Layers: make([]distribution.Descriptor, len(mb.layers)), - Annotations: mb.annotations, - } - copy(m.Layers, mb.layers) - - configDigest := digest.FromBytes(mb.configJSON) - - var err error - m.Config, err = mb.bs.Stat(ctx, configDigest) - switch err { - case nil: - // Override MediaType, since Put always replaces the specified media - // type with application/octet-stream in the descriptor it returns. - m.Config.MediaType = v1.MediaTypeImageConfig - return FromStruct(m) - case distribution.ErrBlobUnknown: - // nop - default: - return nil, err - } - - // Add config to the blob store - m.Config, err = mb.bs.Put(ctx, v1.MediaTypeImageConfig, mb.configJSON) - // Override MediaType, since Put always replaces the specified media - // type with application/octet-stream in the descriptor it returns. - m.Config.MediaType = v1.MediaTypeImageConfig - if err != nil { - return nil, err - } - - return FromStruct(m) -} - -// AppendReference adds a reference to the current ManifestBuilder. -func (mb *Builder) AppendReference(d distribution.Describable) error { - mb.layers = append(mb.layers, d.Descriptor()) - return nil -} - -// References returns the current references added to this builder. -func (mb *Builder) References() []distribution.Descriptor { - return mb.layers -} diff --git a/vendor/github.com/docker/distribution/manifest/ocischema/manifest.go b/vendor/github.com/docker/distribution/manifest/ocischema/manifest.go deleted file mode 100644 index d51f8debb..000000000 --- a/vendor/github.com/docker/distribution/manifest/ocischema/manifest.go +++ /dev/null @@ -1,146 +0,0 @@ -package ocischema - -import ( - "encoding/json" - "errors" - "fmt" - - "github.com/docker/distribution" - "github.com/docker/distribution/manifest" - "github.com/opencontainers/go-digest" - v1 "github.com/opencontainers/image-spec/specs-go/v1" -) - -var ( - // SchemaVersion provides a pre-initialized version structure for this - // packages version of the manifest. - SchemaVersion = manifest.Versioned{ - SchemaVersion: 2, // historical value here.. does not pertain to OCI or docker version - MediaType: v1.MediaTypeImageManifest, - } -) - -func init() { - ocischemaFunc := func(b []byte) (distribution.Manifest, distribution.Descriptor, error) { - if err := validateManifest(b); err != nil { - return nil, distribution.Descriptor{}, err - } - m := new(DeserializedManifest) - err := m.UnmarshalJSON(b) - if err != nil { - return nil, distribution.Descriptor{}, err - } - - dgst := digest.FromBytes(b) - return m, distribution.Descriptor{Digest: dgst, Size: int64(len(b)), MediaType: v1.MediaTypeImageManifest}, err - } - err := distribution.RegisterManifestSchema(v1.MediaTypeImageManifest, ocischemaFunc) - if err != nil { - panic(fmt.Sprintf("Unable to register manifest: %s", err)) - } -} - -// Manifest defines a ocischema manifest. -type Manifest struct { - manifest.Versioned - - // Config references the image configuration as a blob. - Config distribution.Descriptor `json:"config"` - - // Layers lists descriptors for the layers referenced by the - // configuration. - Layers []distribution.Descriptor `json:"layers"` - - // Annotations contains arbitrary metadata for the image manifest. - Annotations map[string]string `json:"annotations,omitempty"` -} - -// References returns the descriptors of this manifests references. -func (m Manifest) References() []distribution.Descriptor { - references := make([]distribution.Descriptor, 0, 1+len(m.Layers)) - references = append(references, m.Config) - references = append(references, m.Layers...) - return references -} - -// Target returns the target of this manifest. -func (m Manifest) Target() distribution.Descriptor { - return m.Config -} - -// DeserializedManifest wraps Manifest with a copy of the original JSON. -// It satisfies the distribution.Manifest interface. -type DeserializedManifest struct { - Manifest - - // canonical is the canonical byte representation of the Manifest. - canonical []byte -} - -// FromStruct takes a Manifest structure, marshals it to JSON, and returns a -// DeserializedManifest which contains the manifest and its JSON representation. -func FromStruct(m Manifest) (*DeserializedManifest, error) { - var deserialized DeserializedManifest - deserialized.Manifest = m - - var err error - deserialized.canonical, err = json.MarshalIndent(&m, "", " ") - return &deserialized, err -} - -// UnmarshalJSON populates a new Manifest struct from JSON data. -func (m *DeserializedManifest) UnmarshalJSON(b []byte) error { - m.canonical = make([]byte, len(b)) - // store manifest in canonical - copy(m.canonical, b) - - // Unmarshal canonical JSON into Manifest object - var manifest Manifest - if err := json.Unmarshal(m.canonical, &manifest); err != nil { - return err - } - - if manifest.MediaType != "" && manifest.MediaType != v1.MediaTypeImageManifest { - return fmt.Errorf("if present, mediaType in manifest should be '%s' not '%s'", - v1.MediaTypeImageManifest, manifest.MediaType) - } - - m.Manifest = manifest - - return nil -} - -// MarshalJSON returns the contents of canonical. If canonical is empty, -// marshals the inner contents. -func (m *DeserializedManifest) MarshalJSON() ([]byte, error) { - if len(m.canonical) > 0 { - return m.canonical, nil - } - - return nil, errors.New("JSON representation not initialized in DeserializedManifest") -} - -// Payload returns the raw content of the manifest. The contents can be used to -// calculate the content identifier. -func (m DeserializedManifest) Payload() (string, []byte, error) { - return v1.MediaTypeImageManifest, m.canonical, nil -} - -// unknownDocument represents a manifest, manifest list, or index that has not -// yet been validated -type unknownDocument struct { - Manifests interface{} `json:"manifests,omitempty"` -} - -// validateManifest returns an error if the byte slice is invalid JSON or if it -// contains fields that belong to a index -func validateManifest(b []byte) error { - var doc unknownDocument - if err := json.Unmarshal(b, &doc); err != nil { - return err - } - if doc.Manifests != nil { - return errors.New("ocimanifest: expected manifest but found index") - } - return nil -} diff --git a/vendor/github.com/docker/distribution/manifest/schema2/builder.go b/vendor/github.com/docker/distribution/manifest/schema2/builder.go deleted file mode 100644 index 3facaae62..000000000 --- a/vendor/github.com/docker/distribution/manifest/schema2/builder.go +++ /dev/null @@ -1,85 +0,0 @@ -package schema2 - -import ( - "context" - - "github.com/docker/distribution" - "github.com/opencontainers/go-digest" -) - -// builder is a type for constructing manifests. -type builder struct { - // bs is a BlobService used to publish the configuration blob. - bs distribution.BlobService - - // configMediaType is media type used to describe configuration - configMediaType string - - // configJSON references - configJSON []byte - - // dependencies is a list of descriptors that gets built by successive - // calls to AppendReference. In case of image configuration these are layers. - dependencies []distribution.Descriptor -} - -// NewManifestBuilder is used to build new manifests for the current schema -// version. It takes a BlobService so it can publish the configuration blob -// as part of the Build process. -func NewManifestBuilder(bs distribution.BlobService, configMediaType string, configJSON []byte) distribution.ManifestBuilder { - mb := &builder{ - bs: bs, - configMediaType: configMediaType, - configJSON: make([]byte, len(configJSON)), - } - copy(mb.configJSON, configJSON) - - return mb -} - -// Build produces a final manifest from the given references. -func (mb *builder) Build(ctx context.Context) (distribution.Manifest, error) { - m := Manifest{ - Versioned: SchemaVersion, - Layers: make([]distribution.Descriptor, len(mb.dependencies)), - } - copy(m.Layers, mb.dependencies) - - configDigest := digest.FromBytes(mb.configJSON) - - var err error - m.Config, err = mb.bs.Stat(ctx, configDigest) - switch err { - case nil: - // Override MediaType, since Put always replaces the specified media - // type with application/octet-stream in the descriptor it returns. - m.Config.MediaType = mb.configMediaType - return FromStruct(m) - case distribution.ErrBlobUnknown: - // nop - default: - return nil, err - } - - // Add config to the blob store - m.Config, err = mb.bs.Put(ctx, mb.configMediaType, mb.configJSON) - // Override MediaType, since Put always replaces the specified media - // type with application/octet-stream in the descriptor it returns. - m.Config.MediaType = mb.configMediaType - if err != nil { - return nil, err - } - - return FromStruct(m) -} - -// AppendReference adds a reference to the current ManifestBuilder. -func (mb *builder) AppendReference(d distribution.Describable) error { - mb.dependencies = append(mb.dependencies, d.Descriptor()) - return nil -} - -// References returns the current references added to this builder. -func (mb *builder) References() []distribution.Descriptor { - return mb.dependencies -} diff --git a/vendor/github.com/docker/distribution/manifest/schema2/manifest.go b/vendor/github.com/docker/distribution/manifest/schema2/manifest.go deleted file mode 100644 index 41f480292..000000000 --- a/vendor/github.com/docker/distribution/manifest/schema2/manifest.go +++ /dev/null @@ -1,144 +0,0 @@ -package schema2 - -import ( - "encoding/json" - "errors" - "fmt" - - "github.com/docker/distribution" - "github.com/docker/distribution/manifest" - "github.com/opencontainers/go-digest" -) - -const ( - // MediaTypeManifest specifies the mediaType for the current version. - MediaTypeManifest = "application/vnd.docker.distribution.manifest.v2+json" - - // MediaTypeImageConfig specifies the mediaType for the image configuration. - MediaTypeImageConfig = "application/vnd.docker.container.image.v1+json" - - // MediaTypePluginConfig specifies the mediaType for plugin configuration. - MediaTypePluginConfig = "application/vnd.docker.plugin.v1+json" - - // MediaTypeLayer is the mediaType used for layers referenced by the - // manifest. - MediaTypeLayer = "application/vnd.docker.image.rootfs.diff.tar.gzip" - - // MediaTypeForeignLayer is the mediaType used for layers that must be - // downloaded from foreign URLs. - MediaTypeForeignLayer = "application/vnd.docker.image.rootfs.foreign.diff.tar.gzip" - - // MediaTypeUncompressedLayer is the mediaType used for layers which - // are not compressed. - MediaTypeUncompressedLayer = "application/vnd.docker.image.rootfs.diff.tar" -) - -var ( - // SchemaVersion provides a pre-initialized version structure for this - // packages version of the manifest. - SchemaVersion = manifest.Versioned{ - SchemaVersion: 2, - MediaType: MediaTypeManifest, - } -) - -func init() { - schema2Func := func(b []byte) (distribution.Manifest, distribution.Descriptor, error) { - m := new(DeserializedManifest) - err := m.UnmarshalJSON(b) - if err != nil { - return nil, distribution.Descriptor{}, err - } - - dgst := digest.FromBytes(b) - return m, distribution.Descriptor{Digest: dgst, Size: int64(len(b)), MediaType: MediaTypeManifest}, err - } - err := distribution.RegisterManifestSchema(MediaTypeManifest, schema2Func) - if err != nil { - panic(fmt.Sprintf("Unable to register manifest: %s", err)) - } -} - -// Manifest defines a schema2 manifest. -type Manifest struct { - manifest.Versioned - - // Config references the image configuration as a blob. - Config distribution.Descriptor `json:"config"` - - // Layers lists descriptors for the layers referenced by the - // configuration. - Layers []distribution.Descriptor `json:"layers"` -} - -// References returns the descriptors of this manifests references. -func (m Manifest) References() []distribution.Descriptor { - references := make([]distribution.Descriptor, 0, 1+len(m.Layers)) - references = append(references, m.Config) - references = append(references, m.Layers...) - return references -} - -// Target returns the target of this manifest. -func (m Manifest) Target() distribution.Descriptor { - return m.Config -} - -// DeserializedManifest wraps Manifest with a copy of the original JSON. -// It satisfies the distribution.Manifest interface. -type DeserializedManifest struct { - Manifest - - // canonical is the canonical byte representation of the Manifest. - canonical []byte -} - -// FromStruct takes a Manifest structure, marshals it to JSON, and returns a -// DeserializedManifest which contains the manifest and its JSON representation. -func FromStruct(m Manifest) (*DeserializedManifest, error) { - var deserialized DeserializedManifest - deserialized.Manifest = m - - var err error - deserialized.canonical, err = json.MarshalIndent(&m, "", " ") - return &deserialized, err -} - -// UnmarshalJSON populates a new Manifest struct from JSON data. -func (m *DeserializedManifest) UnmarshalJSON(b []byte) error { - m.canonical = make([]byte, len(b)) - // store manifest in canonical - copy(m.canonical, b) - - // Unmarshal canonical JSON into Manifest object - var manifest Manifest - if err := json.Unmarshal(m.canonical, &manifest); err != nil { - return err - } - - if manifest.MediaType != MediaTypeManifest { - return fmt.Errorf("mediaType in manifest should be '%s' not '%s'", - MediaTypeManifest, manifest.MediaType) - - } - - m.Manifest = manifest - - return nil -} - -// MarshalJSON returns the contents of canonical. If canonical is empty, -// marshals the inner contents. -func (m *DeserializedManifest) MarshalJSON() ([]byte, error) { - if len(m.canonical) > 0 { - return m.canonical, nil - } - - return nil, errors.New("JSON representation not initialized in DeserializedManifest") -} - -// Payload returns the raw content of the manifest. The contents can be used to -// calculate the content identifier. -func (m DeserializedManifest) Payload() (string, []byte, error) { - return m.MediaType, m.canonical, nil -} diff --git a/vendor/github.com/docker/distribution/manifest/versioned.go b/vendor/github.com/docker/distribution/manifest/versioned.go deleted file mode 100644 index caa6b14e8..000000000 --- a/vendor/github.com/docker/distribution/manifest/versioned.go +++ /dev/null @@ -1,12 +0,0 @@ -package manifest - -// Versioned provides a struct with the manifest schemaVersion and mediaType. -// Incoming content with unknown schema version can be decoded against this -// struct to check the version. -type Versioned struct { - // SchemaVersion is the image manifest schema that this image follows - SchemaVersion int `json:"schemaVersion"` - - // MediaType is the media type of this schema. - MediaType string `json:"mediaType,omitempty"` -} diff --git a/vendor/github.com/docker/distribution/manifests.go b/vendor/github.com/docker/distribution/manifests.go deleted file mode 100644 index 8f84a220a..000000000 --- a/vendor/github.com/docker/distribution/manifests.go +++ /dev/null @@ -1,125 +0,0 @@ -package distribution - -import ( - "context" - "fmt" - "mime" - - "github.com/opencontainers/go-digest" -) - -// Manifest represents a registry object specifying a set of -// references and an optional target -type Manifest interface { - // References returns a list of objects which make up this manifest. - // A reference is anything which can be represented by a - // distribution.Descriptor. These can consist of layers, resources or other - // manifests. - // - // While no particular order is required, implementations should return - // them from highest to lowest priority. For example, one might want to - // return the base layer before the top layer. - References() []Descriptor - - // Payload provides the serialized format of the manifest, in addition to - // the media type. - Payload() (mediaType string, payload []byte, err error) -} - -// ManifestBuilder creates a manifest allowing one to include dependencies. -// Instances can be obtained from a version-specific manifest package. Manifest -// specific data is passed into the function which creates the builder. -type ManifestBuilder interface { - // Build creates the manifest from his builder. - Build(ctx context.Context) (Manifest, error) - - // References returns a list of objects which have been added to this - // builder. The dependencies are returned in the order they were added, - // which should be from base to head. - References() []Descriptor - - // AppendReference includes the given object in the manifest after any - // existing dependencies. If the add fails, such as when adding an - // unsupported dependency, an error may be returned. - // - // The destination of the reference is dependent on the manifest type and - // the dependency type. - AppendReference(dependency Describable) error -} - -// ManifestService describes operations on image manifests. -type ManifestService interface { - // Exists returns true if the manifest exists. - Exists(ctx context.Context, dgst digest.Digest) (bool, error) - - // Get retrieves the manifest specified by the given digest - Get(ctx context.Context, dgst digest.Digest, options ...ManifestServiceOption) (Manifest, error) - - // Put creates or updates the given manifest returning the manifest digest - Put(ctx context.Context, manifest Manifest, options ...ManifestServiceOption) (digest.Digest, error) - - // Delete removes the manifest specified by the given digest. Deleting - // a manifest that doesn't exist will return ErrManifestNotFound - Delete(ctx context.Context, dgst digest.Digest) error -} - -// ManifestEnumerator enables iterating over manifests -type ManifestEnumerator interface { - // Enumerate calls ingester for each manifest. - Enumerate(ctx context.Context, ingester func(digest.Digest) error) error -} - -// Describable is an interface for descriptors -type Describable interface { - Descriptor() Descriptor -} - -// ManifestMediaTypes returns the supported media types for manifests. -func ManifestMediaTypes() (mediaTypes []string) { - for t := range mappings { - if t != "" { - mediaTypes = append(mediaTypes, t) - } - } - return -} - -// UnmarshalFunc implements manifest unmarshalling a given MediaType -type UnmarshalFunc func([]byte) (Manifest, Descriptor, error) - -var mappings = make(map[string]UnmarshalFunc) - -// UnmarshalManifest looks up manifest unmarshal functions based on -// MediaType -func UnmarshalManifest(ctHeader string, p []byte) (Manifest, Descriptor, error) { - // Need to look up by the actual media type, not the raw contents of - // the header. Strip semicolons and anything following them. - var mediaType string - if ctHeader != "" { - var err error - mediaType, _, err = mime.ParseMediaType(ctHeader) - if err != nil { - return nil, Descriptor{}, err - } - } - - unmarshalFunc, ok := mappings[mediaType] - if !ok { - unmarshalFunc, ok = mappings[""] - if !ok { - return nil, Descriptor{}, fmt.Errorf("unsupported manifest media type and no default available: %s", mediaType) - } - } - - return unmarshalFunc(p) -} - -// RegisterManifestSchema registers an UnmarshalFunc for a given schema type. This -// should be called from specific -func RegisterManifestSchema(mediaType string, u UnmarshalFunc) error { - if _, ok := mappings[mediaType]; ok { - return fmt.Errorf("manifest media type registration would overwrite existing: %s", mediaType) - } - mappings[mediaType] = u - return nil -} diff --git a/vendor/github.com/docker/distribution/metrics/prometheus.go b/vendor/github.com/docker/distribution/metrics/prometheus.go deleted file mode 100644 index b5a532144..000000000 --- a/vendor/github.com/docker/distribution/metrics/prometheus.go +++ /dev/null @@ -1,13 +0,0 @@ -package metrics - -import "github.com/docker/go-metrics" - -const ( - // NamespacePrefix is the namespace of prometheus metrics - NamespacePrefix = "registry" -) - -var ( - // StorageNamespace is the prometheus namespace of blob/cache related operations - StorageNamespace = metrics.NewNamespace(NamespacePrefix, "storage", nil) -) diff --git a/vendor/github.com/docker/distribution/reference/helpers_deprecated.go b/vendor/github.com/docker/distribution/reference/helpers_deprecated.go deleted file mode 100644 index cbd119250..000000000 --- a/vendor/github.com/docker/distribution/reference/helpers_deprecated.go +++ /dev/null @@ -1,34 +0,0 @@ -package reference - -import "github.com/distribution/reference" - -// IsNameOnly returns true if reference only contains a repo name. -// -// Deprecated: use [reference.IsNameOnly]. -func IsNameOnly(ref reference.Named) bool { - return reference.IsNameOnly(ref) -} - -// FamiliarName returns the familiar name string -// for the given named, familiarizing if needed. -// -// Deprecated: use [reference.FamiliarName]. -func FamiliarName(ref reference.Named) string { - return reference.FamiliarName(ref) -} - -// FamiliarString returns the familiar string representation -// for the given reference, familiarizing if needed. -// -// Deprecated: use [reference.FamiliarString]. -func FamiliarString(ref reference.Reference) string { - return reference.FamiliarString(ref) -} - -// FamiliarMatch reports whether ref matches the specified pattern. -// See [path.Match] for supported patterns. -// -// Deprecated: use [reference.FamiliarMatch]. -func FamiliarMatch(pattern string, ref reference.Reference) (bool, error) { - return reference.FamiliarMatch(pattern, ref) -} diff --git a/vendor/github.com/docker/distribution/reference/normalize_deprecated.go b/vendor/github.com/docker/distribution/reference/normalize_deprecated.go deleted file mode 100644 index 1b4a459d7..000000000 --- a/vendor/github.com/docker/distribution/reference/normalize_deprecated.go +++ /dev/null @@ -1,92 +0,0 @@ -package reference - -import ( - "regexp" - - "github.com/distribution/reference" - "github.com/opencontainers/go-digest" - "github.com/opencontainers/go-digest/digestset" -) - -// ParseNormalizedNamed parses a string into a named reference -// transforming a familiar name from Docker UI to a fully -// qualified reference. If the value may be an identifier -// use ParseAnyReference. -// -// Deprecated: use [reference.ParseNormalizedNamed]. -func ParseNormalizedNamed(s string) (reference.Named, error) { - return reference.ParseNormalizedNamed(s) -} - -// ParseDockerRef normalizes the image reference following the docker convention, -// which allows for references to contain both a tag and a digest. -// -// Deprecated: use [reference.ParseDockerRef]. -func ParseDockerRef(ref string) (reference.Named, error) { - return reference.ParseDockerRef(ref) -} - -// TagNameOnly adds the default tag "latest" to a reference if it only has -// a repo name. -// -// Deprecated: use [reference.TagNameOnly]. -func TagNameOnly(ref reference.Named) reference.Named { - return reference.TagNameOnly(ref) -} - -// ParseAnyReference parses a reference string as a possible identifier, -// full digest, or familiar name. -// -// Deprecated: use [reference.ParseAnyReference]. -func ParseAnyReference(ref string) (reference.Reference, error) { - return reference.ParseAnyReference(ref) -} - -// Functions and types below have been removed in distribution v3 and -// have not been ported to github.com/distribution/reference. See -// https://github.com/distribution/distribution/pull/3774 - -var ( - // ShortIdentifierRegexp is the format used to represent a prefix - // of an identifier. A prefix may be used to match a sha256 identifier - // within a list of trusted identifiers. - // - // Deprecated: support for short-identifiers is deprecated, and will be removed in v3. - ShortIdentifierRegexp = regexp.MustCompile(shortIdentifier) - - shortIdentifier = `([a-f0-9]{6,64})` - - // anchoredShortIdentifierRegexp is used to check if a value - // is a possible identifier prefix, anchored at start and end - // of string. - anchoredShortIdentifierRegexp = regexp.MustCompile(`^` + shortIdentifier + `$`) -) - -type digestReference digest.Digest - -func (d digestReference) String() string { - return digest.Digest(d).String() -} - -func (d digestReference) Digest() digest.Digest { - return digest.Digest(d) -} - -// ParseAnyReferenceWithSet parses a reference string as a possible short -// identifier to be matched in a digest set, a full digest, or familiar name. -// -// Deprecated: support for short-identifiers is deprecated, and will be removed in v3. -func ParseAnyReferenceWithSet(ref string, ds *digestset.Set) (Reference, error) { - if ok := anchoredShortIdentifierRegexp.MatchString(ref); ok { - dgst, err := ds.Lookup(ref) - if err == nil { - return digestReference(dgst), nil - } - } else { - if dgst, err := digest.Parse(ref); err == nil { - return digestReference(dgst), nil - } - } - - return reference.ParseNormalizedNamed(ref) -} diff --git a/vendor/github.com/docker/distribution/reference/reference_deprecated.go b/vendor/github.com/docker/distribution/reference/reference_deprecated.go deleted file mode 100644 index 5b732498e..000000000 --- a/vendor/github.com/docker/distribution/reference/reference_deprecated.go +++ /dev/null @@ -1,172 +0,0 @@ -// Package reference is deprecated, and has moved to github.com/distribution/reference. -// -// Deprecated: use github.com/distribution/reference instead. -package reference - -import ( - "github.com/distribution/reference" - "github.com/opencontainers/go-digest" -) - -const ( - // NameTotalLengthMax is the maximum total number of characters in a repository name. - // - // Deprecated: use [reference.NameTotalLengthMax]. - NameTotalLengthMax = reference.NameTotalLengthMax -) - -var ( - // ErrReferenceInvalidFormat represents an error while trying to parse a string as a reference. - // - // Deprecated: use [reference.ErrReferenceInvalidFormat]. - ErrReferenceInvalidFormat = reference.ErrReferenceInvalidFormat - - // ErrTagInvalidFormat represents an error while trying to parse a string as a tag. - // - // Deprecated: use [reference.ErrTagInvalidFormat]. - ErrTagInvalidFormat = reference.ErrTagInvalidFormat - - // ErrDigestInvalidFormat represents an error while trying to parse a string as a tag. - // - // Deprecated: use [reference.ErrDigestInvalidFormat]. - ErrDigestInvalidFormat = reference.ErrDigestInvalidFormat - - // ErrNameContainsUppercase is returned for invalid repository names that contain uppercase characters. - // - // Deprecated: use [reference.ErrNameContainsUppercase]. - ErrNameContainsUppercase = reference.ErrNameContainsUppercase - - // ErrNameEmpty is returned for empty, invalid repository names. - // - // Deprecated: use [reference.ErrNameEmpty]. - ErrNameEmpty = reference.ErrNameEmpty - - // ErrNameTooLong is returned when a repository name is longer than NameTotalLengthMax. - // - // Deprecated: use [reference.ErrNameTooLong]. - ErrNameTooLong = reference.ErrNameTooLong - - // ErrNameNotCanonical is returned when a name is not canonical. - // - // Deprecated: use [reference.ErrNameNotCanonical]. - ErrNameNotCanonical = reference.ErrNameNotCanonical -) - -// Reference is an opaque object reference identifier that may include -// modifiers such as a hostname, name, tag, and digest. -// -// Deprecated: use [reference.Reference]. -type Reference = reference.Reference - -// Field provides a wrapper type for resolving correct reference types when -// working with encoding. -// -// Deprecated: use [reference.Field]. -type Field = reference.Field - -// AsField wraps a reference in a Field for encoding. -// -// Deprecated: use [reference.AsField]. -func AsField(ref reference.Reference) reference.Field { - return reference.AsField(ref) -} - -// Named is an object with a full name -// -// Deprecated: use [reference.Named]. -type Named = reference.Named - -// Tagged is an object which has a tag -// -// Deprecated: use [reference.Tagged]. -type Tagged = reference.Tagged - -// NamedTagged is an object including a name and tag. -// -// Deprecated: use [reference.NamedTagged]. -type NamedTagged reference.NamedTagged - -// Digested is an object which has a digest -// in which it can be referenced by -// -// Deprecated: use [reference.Digested]. -type Digested reference.Digested - -// Canonical reference is an object with a fully unique -// name including a name with domain and digest -// -// Deprecated: use [reference.Canonical]. -type Canonical reference.Canonical - -// Domain returns the domain part of the [Named] reference. -// -// Deprecated: use [reference.Domain]. -func Domain(named reference.Named) string { - return reference.Domain(named) -} - -// Path returns the name without the domain part of the [Named] reference. -// -// Deprecated: use [reference.Path]. -func Path(named reference.Named) (name string) { - return reference.Path(named) -} - -// SplitHostname splits a named reference into a -// hostname and name string. If no valid hostname is -// found, the hostname is empty and the full value -// is returned as name -// -// Deprecated: Use [reference.Domain] or [reference.Path]. -func SplitHostname(named reference.Named) (string, string) { - return reference.SplitHostname(named) -} - -// Parse parses s and returns a syntactically valid Reference. -// If an error was encountered it is returned, along with a nil Reference. -// -// Deprecated: use [reference.Parse]. -func Parse(s string) (reference.Reference, error) { - return reference.Parse(s) -} - -// ParseNamed parses s and returns a syntactically valid reference implementing -// the Named interface. The reference must have a name and be in the canonical -// form, otherwise an error is returned. -// If an error was encountered it is returned, along with a nil Reference. -// -// Deprecated: use [reference.ParseNamed]. -func ParseNamed(s string) (reference.Named, error) { - return reference.ParseNamed(s) -} - -// WithName returns a named object representing the given string. If the input -// is invalid ErrReferenceInvalidFormat will be returned. -// -// Deprecated: use [reference.WithName]. -func WithName(name string) (reference.Named, error) { - return reference.WithName(name) -} - -// WithTag combines the name from "name" and the tag from "tag" to form a -// reference incorporating both the name and the tag. -// -// Deprecated: use [reference.WithTag]. -func WithTag(name reference.Named, tag string) (reference.NamedTagged, error) { - return reference.WithTag(name, tag) -} - -// WithDigest combines the name from "name" and the digest from "digest" to form -// a reference incorporating both the name and the digest. -// -// Deprecated: use [reference.WithDigest]. -func WithDigest(name reference.Named, digest digest.Digest) (reference.Canonical, error) { - return reference.WithDigest(name, digest) -} - -// TrimNamed removes any tag or digest from the named reference. -// -// Deprecated: use [reference.TrimNamed]. -func TrimNamed(ref reference.Named) reference.Named { - return reference.TrimNamed(ref) -} diff --git a/vendor/github.com/docker/distribution/reference/regexp_deprecated.go b/vendor/github.com/docker/distribution/reference/regexp_deprecated.go deleted file mode 100644 index 4b9c1b58e..000000000 --- a/vendor/github.com/docker/distribution/reference/regexp_deprecated.go +++ /dev/null @@ -1,50 +0,0 @@ -package reference - -import ( - "github.com/distribution/reference" -) - -// DigestRegexp matches well-formed digests, including algorithm (e.g. "sha256:"). -// -// Deprecated: use [reference.DigestRegexp]. -var DigestRegexp = reference.DigestRegexp - -// DomainRegexp matches hostname or IP-addresses, optionally including a port -// number. It defines the structure of potential domain components that may be -// part of image names. This is purposely a subset of what is allowed by DNS to -// ensure backwards compatibility with Docker image names. It may be a subset of -// DNS domain name, an IPv4 address in decimal format, or an IPv6 address between -// square brackets (excluding zone identifiers as defined by [RFC 6874] or special -// addresses such as IPv4-Mapped). -// -// Deprecated: use [reference.DomainRegexp]. -// -// [RFC 6874]: https://www.rfc-editor.org/rfc/rfc6874. -var DomainRegexp = reference.DigestRegexp - -// IdentifierRegexp is the format for string identifier used as a -// content addressable identifier using sha256. These identifiers -// are like digests without the algorithm, since sha256 is used. -// -// Deprecated: use [reference.IdentifierRegexp]. -var IdentifierRegexp = reference.IdentifierRegexp - -// NameRegexp is the format for the name component of references, including -// an optional domain and port, but without tag or digest suffix. -// -// Deprecated: use [reference.NameRegexp]. -var NameRegexp = reference.NameRegexp - -// ReferenceRegexp is the full supported format of a reference. The regexp -// is anchored and has capturing groups for name, tag, and digest -// components. -// -// Deprecated: use [reference.ReferenceRegexp]. -var ReferenceRegexp = reference.ReferenceRegexp - -// TagRegexp matches valid tag names. From [docker/docker:graph/tags.go]. -// -// Deprecated: use [reference.TagRegexp]. -// -// [docker/docker:graph/tags.go]: https://github.com/moby/moby/blob/v1.6.0/graph/tags.go#L26-L28 -var TagRegexp = reference.TagRegexp diff --git a/vendor/github.com/docker/distribution/reference/sort_deprecated.go b/vendor/github.com/docker/distribution/reference/sort_deprecated.go deleted file mode 100644 index a73251b6f..000000000 --- a/vendor/github.com/docker/distribution/reference/sort_deprecated.go +++ /dev/null @@ -1,10 +0,0 @@ -package reference - -import "github.com/distribution/reference" - -// Sort sorts string references preferring higher information references. -// -// Deprecated: use [reference.Sort]. -func Sort(references []string) []string { - return reference.Sort(references) -} diff --git a/vendor/github.com/docker/distribution/registry.go b/vendor/github.com/docker/distribution/registry.go deleted file mode 100644 index d0deee65d..000000000 --- a/vendor/github.com/docker/distribution/registry.go +++ /dev/null @@ -1,118 +0,0 @@ -package distribution - -import ( - "context" - - "github.com/distribution/reference" -) - -// Scope defines the set of items that match a namespace. -type Scope interface { - // Contains returns true if the name belongs to the namespace. - Contains(name string) bool -} - -type fullScope struct{} - -func (f fullScope) Contains(string) bool { - return true -} - -// GlobalScope represents the full namespace scope which contains -// all other scopes. -var GlobalScope = Scope(fullScope{}) - -// Namespace represents a collection of repositories, addressable by name. -// Generally, a namespace is backed by a set of one or more services, -// providing facilities such as registry access, trust, and indexing. -type Namespace interface { - // Scope describes the names that can be used with this Namespace. The - // global namespace will have a scope that matches all names. The scope - // effectively provides an identity for the namespace. - Scope() Scope - - // Repository should return a reference to the named repository. The - // registry may or may not have the repository but should always return a - // reference. - Repository(ctx context.Context, name reference.Named) (Repository, error) - - // Repositories fills 'repos' with a lexicographically sorted catalog of repositories - // up to the size of 'repos' and returns the value 'n' for the number of entries - // which were filled. 'last' contains an offset in the catalog, and 'err' will be - // set to io.EOF if there are no more entries to obtain. - Repositories(ctx context.Context, repos []string, last string) (n int, err error) - - // Blobs returns a blob enumerator to access all blobs - Blobs() BlobEnumerator - - // BlobStatter returns a BlobStatter to control - BlobStatter() BlobStatter -} - -// RepositoryEnumerator describes an operation to enumerate repositories -type RepositoryEnumerator interface { - Enumerate(ctx context.Context, ingester func(string) error) error -} - -// RepositoryRemover removes given repository -type RepositoryRemover interface { - Remove(ctx context.Context, name reference.Named) error -} - -// ManifestServiceOption is a function argument for Manifest Service methods -type ManifestServiceOption interface { - Apply(ManifestService) error -} - -// WithTag allows a tag to be passed into Put -func WithTag(tag string) ManifestServiceOption { - return WithTagOption{tag} -} - -// WithTagOption holds a tag -type WithTagOption struct{ Tag string } - -// Apply conforms to the ManifestServiceOption interface -func (o WithTagOption) Apply(m ManifestService) error { - // no implementation - return nil -} - -// WithManifestMediaTypes lists the media types the client wishes -// the server to provide. -func WithManifestMediaTypes(mediaTypes []string) ManifestServiceOption { - return WithManifestMediaTypesOption{mediaTypes} -} - -// WithManifestMediaTypesOption holds a list of accepted media types -type WithManifestMediaTypesOption struct{ MediaTypes []string } - -// Apply conforms to the ManifestServiceOption interface -func (o WithManifestMediaTypesOption) Apply(m ManifestService) error { - // no implementation - return nil -} - -// Repository is a named collection of manifests and layers. -type Repository interface { - // Named returns the name of the repository. - Named() reference.Named - - // Manifests returns a reference to this repository's manifest service. - // with the supplied options applied. - Manifests(ctx context.Context, options ...ManifestServiceOption) (ManifestService, error) - - // Blobs returns a reference to this repository's blob service. - Blobs(ctx context.Context) BlobStore - - // TODO(stevvooe): The above BlobStore return can probably be relaxed to - // be a BlobService for use with clients. This will allow such - // implementations to avoid implementing ServeBlob. - - // Tags returns a reference to this repositories tag service - Tags(ctx context.Context) TagService -} - -// TODO(stevvooe): Must add close methods to all these. May want to change the -// way instances are created to better reflect internal dependency -// relationships. diff --git a/vendor/github.com/docker/distribution/registry/api/errcode/errors.go b/vendor/github.com/docker/distribution/registry/api/errcode/errors.go deleted file mode 100644 index 4c35b879a..000000000 --- a/vendor/github.com/docker/distribution/registry/api/errcode/errors.go +++ /dev/null @@ -1,267 +0,0 @@ -package errcode - -import ( - "encoding/json" - "fmt" - "strings" -) - -// ErrorCoder is the base interface for ErrorCode and Error allowing -// users of each to just call ErrorCode to get the real ID of each -type ErrorCoder interface { - ErrorCode() ErrorCode -} - -// ErrorCode represents the error type. The errors are serialized via strings -// and the integer format may change and should *never* be exported. -type ErrorCode int - -var _ error = ErrorCode(0) - -// ErrorCode just returns itself -func (ec ErrorCode) ErrorCode() ErrorCode { - return ec -} - -// Error returns the ID/Value -func (ec ErrorCode) Error() string { - // NOTE(stevvooe): Cannot use message here since it may have unpopulated args. - return strings.ToLower(strings.Replace(ec.String(), "_", " ", -1)) -} - -// Descriptor returns the descriptor for the error code. -func (ec ErrorCode) Descriptor() ErrorDescriptor { - d, ok := errorCodeToDescriptors[ec] - - if !ok { - return ErrorCodeUnknown.Descriptor() - } - - return d -} - -// String returns the canonical identifier for this error code. -func (ec ErrorCode) String() string { - return ec.Descriptor().Value -} - -// Message returned the human-readable error message for this error code. -func (ec ErrorCode) Message() string { - return ec.Descriptor().Message -} - -// MarshalText encodes the receiver into UTF-8-encoded text and returns the -// result. -func (ec ErrorCode) MarshalText() (text []byte, err error) { - return []byte(ec.String()), nil -} - -// UnmarshalText decodes the form generated by MarshalText. -func (ec *ErrorCode) UnmarshalText(text []byte) error { - desc, ok := idToDescriptors[string(text)] - - if !ok { - desc = ErrorCodeUnknown.Descriptor() - } - - *ec = desc.Code - - return nil -} - -// WithMessage creates a new Error struct based on the passed-in info and -// overrides the Message property. -func (ec ErrorCode) WithMessage(message string) Error { - return Error{ - Code: ec, - Message: message, - } -} - -// WithDetail creates a new Error struct based on the passed-in info and -// set the Detail property appropriately -func (ec ErrorCode) WithDetail(detail interface{}) Error { - return Error{ - Code: ec, - Message: ec.Message(), - }.WithDetail(detail) -} - -// WithArgs creates a new Error struct and sets the Args slice -func (ec ErrorCode) WithArgs(args ...interface{}) Error { - return Error{ - Code: ec, - Message: ec.Message(), - }.WithArgs(args...) -} - -// Error provides a wrapper around ErrorCode with extra Details provided. -type Error struct { - Code ErrorCode `json:"code"` - Message string `json:"message"` - Detail interface{} `json:"detail,omitempty"` - - // TODO(duglin): See if we need an "args" property so we can do the - // variable substitution right before showing the message to the user -} - -var _ error = Error{} - -// ErrorCode returns the ID/Value of this Error -func (e Error) ErrorCode() ErrorCode { - return e.Code -} - -// Error returns a human readable representation of the error. -func (e Error) Error() string { - return fmt.Sprintf("%s: %s", e.Code.Error(), e.Message) -} - -// WithDetail will return a new Error, based on the current one, but with -// some Detail info added -func (e Error) WithDetail(detail interface{}) Error { - return Error{ - Code: e.Code, - Message: e.Message, - Detail: detail, - } -} - -// WithArgs uses the passed-in list of interface{} as the substitution -// variables in the Error's Message string, but returns a new Error -func (e Error) WithArgs(args ...interface{}) Error { - return Error{ - Code: e.Code, - Message: fmt.Sprintf(e.Code.Message(), args...), - Detail: e.Detail, - } -} - -// ErrorDescriptor provides relevant information about a given error code. -type ErrorDescriptor struct { - // Code is the error code that this descriptor describes. - Code ErrorCode - - // Value provides a unique, string key, often captilized with - // underscores, to identify the error code. This value is used as the - // keyed value when serializing api errors. - Value string - - // Message is a short, human readable decription of the error condition - // included in API responses. - Message string - - // Description provides a complete account of the errors purpose, suitable - // for use in documentation. - Description string - - // HTTPStatusCode provides the http status code that is associated with - // this error condition. - HTTPStatusCode int -} - -// ParseErrorCode returns the value by the string error code. -// `ErrorCodeUnknown` will be returned if the error is not known. -func ParseErrorCode(value string) ErrorCode { - ed, ok := idToDescriptors[value] - if ok { - return ed.Code - } - - return ErrorCodeUnknown -} - -// Errors provides the envelope for multiple errors and a few sugar methods -// for use within the application. -type Errors []error - -var _ error = Errors{} - -func (errs Errors) Error() string { - switch len(errs) { - case 0: - return "" - case 1: - return errs[0].Error() - default: - msg := "errors:\n" - for _, err := range errs { - msg += err.Error() + "\n" - } - return msg - } -} - -// Len returns the current number of errors. -func (errs Errors) Len() int { - return len(errs) -} - -// MarshalJSON converts slice of error, ErrorCode or Error into a -// slice of Error - then serializes -func (errs Errors) MarshalJSON() ([]byte, error) { - var tmpErrs struct { - Errors []Error `json:"errors,omitempty"` - } - - for _, daErr := range errs { - var err Error - - switch daErr := daErr.(type) { - case ErrorCode: - err = daErr.WithDetail(nil) - case Error: - err = daErr - default: - err = ErrorCodeUnknown.WithDetail(daErr) - - } - - // If the Error struct was setup and they forgot to set the - // Message field (meaning its "") then grab it from the ErrCode - msg := err.Message - if msg == "" { - msg = err.Code.Message() - } - - tmpErrs.Errors = append(tmpErrs.Errors, Error{ - Code: err.Code, - Message: msg, - Detail: err.Detail, - }) - } - - return json.Marshal(tmpErrs) -} - -// UnmarshalJSON deserializes []Error and then converts it into slice of -// Error or ErrorCode -func (errs *Errors) UnmarshalJSON(data []byte) error { - var tmpErrs struct { - Errors []Error - } - - if err := json.Unmarshal(data, &tmpErrs); err != nil { - return err - } - - var newErrs Errors - for _, daErr := range tmpErrs.Errors { - // If Message is empty or exactly matches the Code's message string - // then just use the Code, no need for a full Error struct - if daErr.Detail == nil && (daErr.Message == "" || daErr.Message == daErr.Code.Message()) { - // Error's w/o details get converted to ErrorCode - newErrs = append(newErrs, daErr.Code) - } else { - // Error's w/ details are untouched - newErrs = append(newErrs, Error{ - Code: daErr.Code, - Message: daErr.Message, - Detail: daErr.Detail, - }) - } - } - - *errs = newErrs - return nil -} diff --git a/vendor/github.com/docker/distribution/registry/api/errcode/handler.go b/vendor/github.com/docker/distribution/registry/api/errcode/handler.go deleted file mode 100644 index d77e70473..000000000 --- a/vendor/github.com/docker/distribution/registry/api/errcode/handler.go +++ /dev/null @@ -1,40 +0,0 @@ -package errcode - -import ( - "encoding/json" - "net/http" -) - -// ServeJSON attempts to serve the errcode in a JSON envelope. It marshals err -// and sets the content-type header to 'application/json'. It will handle -// ErrorCoder and Errors, and if necessary will create an envelope. -func ServeJSON(w http.ResponseWriter, err error) error { - w.Header().Set("Content-Type", "application/json; charset=utf-8") - var sc int - - switch errs := err.(type) { - case Errors: - if len(errs) < 1 { - break - } - - if err, ok := errs[0].(ErrorCoder); ok { - sc = err.ErrorCode().Descriptor().HTTPStatusCode - } - case ErrorCoder: - sc = errs.ErrorCode().Descriptor().HTTPStatusCode - err = Errors{err} // create an envelope. - default: - // We just have an unhandled error type, so just place in an envelope - // and move along. - err = Errors{err} - } - - if sc == 0 { - sc = http.StatusInternalServerError - } - - w.WriteHeader(sc) - - return json.NewEncoder(w).Encode(err) -} diff --git a/vendor/github.com/docker/distribution/registry/api/errcode/register.go b/vendor/github.com/docker/distribution/registry/api/errcode/register.go deleted file mode 100644 index d1e8826c6..000000000 --- a/vendor/github.com/docker/distribution/registry/api/errcode/register.go +++ /dev/null @@ -1,138 +0,0 @@ -package errcode - -import ( - "fmt" - "net/http" - "sort" - "sync" -) - -var ( - errorCodeToDescriptors = map[ErrorCode]ErrorDescriptor{} - idToDescriptors = map[string]ErrorDescriptor{} - groupToDescriptors = map[string][]ErrorDescriptor{} -) - -var ( - // ErrorCodeUnknown is a generic error that can be used as a last - // resort if there is no situation-specific error message that can be used - ErrorCodeUnknown = Register("errcode", ErrorDescriptor{ - Value: "UNKNOWN", - Message: "unknown error", - Description: `Generic error returned when the error does not have an - API classification.`, - HTTPStatusCode: http.StatusInternalServerError, - }) - - // ErrorCodeUnsupported is returned when an operation is not supported. - ErrorCodeUnsupported = Register("errcode", ErrorDescriptor{ - Value: "UNSUPPORTED", - Message: "The operation is unsupported.", - Description: `The operation was unsupported due to a missing - implementation or invalid set of parameters.`, - HTTPStatusCode: http.StatusMethodNotAllowed, - }) - - // ErrorCodeUnauthorized is returned if a request requires - // authentication. - ErrorCodeUnauthorized = Register("errcode", ErrorDescriptor{ - Value: "UNAUTHORIZED", - Message: "authentication required", - Description: `The access controller was unable to authenticate - the client. Often this will be accompanied by a - Www-Authenticate HTTP response header indicating how to - authenticate.`, - HTTPStatusCode: http.StatusUnauthorized, - }) - - // ErrorCodeDenied is returned if a client does not have sufficient - // permission to perform an action. - ErrorCodeDenied = Register("errcode", ErrorDescriptor{ - Value: "DENIED", - Message: "requested access to the resource is denied", - Description: `The access controller denied access for the - operation on a resource.`, - HTTPStatusCode: http.StatusForbidden, - }) - - // ErrorCodeUnavailable provides a common error to report unavailability - // of a service or endpoint. - ErrorCodeUnavailable = Register("errcode", ErrorDescriptor{ - Value: "UNAVAILABLE", - Message: "service unavailable", - Description: "Returned when a service is not available", - HTTPStatusCode: http.StatusServiceUnavailable, - }) - - // ErrorCodeTooManyRequests is returned if a client attempts too many - // times to contact a service endpoint. - ErrorCodeTooManyRequests = Register("errcode", ErrorDescriptor{ - Value: "TOOMANYREQUESTS", - Message: "too many requests", - Description: `Returned when a client attempts to contact a - service too many times`, - HTTPStatusCode: http.StatusTooManyRequests, - }) -) - -var nextCode = 1000 -var registerLock sync.Mutex - -// Register will make the passed-in error known to the environment and -// return a new ErrorCode -func Register(group string, descriptor ErrorDescriptor) ErrorCode { - registerLock.Lock() - defer registerLock.Unlock() - - descriptor.Code = ErrorCode(nextCode) - - if _, ok := idToDescriptors[descriptor.Value]; ok { - panic(fmt.Sprintf("ErrorValue %q is already registered", descriptor.Value)) - } - if _, ok := errorCodeToDescriptors[descriptor.Code]; ok { - panic(fmt.Sprintf("ErrorCode %v is already registered", descriptor.Code)) - } - - groupToDescriptors[group] = append(groupToDescriptors[group], descriptor) - errorCodeToDescriptors[descriptor.Code] = descriptor - idToDescriptors[descriptor.Value] = descriptor - - nextCode++ - return descriptor.Code -} - -type byValue []ErrorDescriptor - -func (a byValue) Len() int { return len(a) } -func (a byValue) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a byValue) Less(i, j int) bool { return a[i].Value < a[j].Value } - -// GetGroupNames returns the list of Error group names that are registered -func GetGroupNames() []string { - keys := []string{} - - for k := range groupToDescriptors { - keys = append(keys, k) - } - sort.Strings(keys) - return keys -} - -// GetErrorCodeGroup returns the named group of error descriptors -func GetErrorCodeGroup(name string) []ErrorDescriptor { - desc := groupToDescriptors[name] - sort.Sort(byValue(desc)) - return desc -} - -// GetErrorAllDescriptors returns a slice of all ErrorDescriptors that are -// registered, irrespective of what group they're in -func GetErrorAllDescriptors() []ErrorDescriptor { - result := []ErrorDescriptor{} - - for _, group := range GetGroupNames() { - result = append(result, GetErrorCodeGroup(group)...) - } - sort.Sort(byValue(result)) - return result -} diff --git a/vendor/github.com/docker/distribution/registry/api/v2/descriptors.go b/vendor/github.com/docker/distribution/registry/api/v2/descriptors.go deleted file mode 100644 index 7fceefbc6..000000000 --- a/vendor/github.com/docker/distribution/registry/api/v2/descriptors.go +++ /dev/null @@ -1,1613 +0,0 @@ -package v2 - -import ( - "net/http" - "regexp" - - "github.com/distribution/reference" - "github.com/docker/distribution/registry/api/errcode" - "github.com/opencontainers/go-digest" -) - -var ( - nameParameterDescriptor = ParameterDescriptor{ - Name: "name", - Type: "string", - Format: reference.NameRegexp.String(), - Required: true, - Description: `Name of the target repository.`, - } - - referenceParameterDescriptor = ParameterDescriptor{ - Name: "reference", - Type: "string", - Format: reference.TagRegexp.String(), - Required: true, - Description: `Tag or digest of the target manifest.`, - } - - uuidParameterDescriptor = ParameterDescriptor{ - Name: "uuid", - Type: "opaque", - Required: true, - Description: "A uuid identifying the upload. This field can accept characters that match `[a-zA-Z0-9-_.=]+`.", - } - - digestPathParameter = ParameterDescriptor{ - Name: "digest", - Type: "path", - Required: true, - Format: digest.DigestRegexp.String(), - Description: `Digest of desired blob.`, - } - - hostHeader = ParameterDescriptor{ - Name: "Host", - Type: "string", - Description: "Standard HTTP Host Header. Should be set to the registry host.", - Format: "", - Examples: []string{"registry-1.docker.io"}, - } - - authHeader = ParameterDescriptor{ - Name: "Authorization", - Type: "string", - Description: "An RFC7235 compliant authorization header.", - Format: " ", - Examples: []string{"Bearer dGhpcyBpcyBhIGZha2UgYmVhcmVyIHRva2VuIQ=="}, - } - - authChallengeHeader = ParameterDescriptor{ - Name: "WWW-Authenticate", - Type: "string", - Description: "An RFC7235 compliant authentication challenge header.", - Format: ` realm="", ..."`, - Examples: []string{ - `Bearer realm="https://auth.docker.com/", service="registry.docker.com", scopes="repository:library/ubuntu:pull"`, - }, - } - - contentLengthZeroHeader = ParameterDescriptor{ - Name: "Content-Length", - Description: "The `Content-Length` header must be zero and the body must be empty.", - Type: "integer", - Format: "0", - } - - dockerUploadUUIDHeader = ParameterDescriptor{ - Name: "Docker-Upload-UUID", - Description: "Identifies the docker upload uuid for the current request.", - Type: "uuid", - Format: "", - } - - digestHeader = ParameterDescriptor{ - Name: "Docker-Content-Digest", - Description: "Digest of the targeted content for the request.", - Type: "digest", - Format: "", - } - - linkHeader = ParameterDescriptor{ - Name: "Link", - Type: "link", - Description: "RFC5988 compliant rel='next' with URL to next result set, if available", - Format: `<?n=&last=>; rel="next"`, - } - - paginationParameters = []ParameterDescriptor{ - { - Name: "n", - Type: "integer", - Description: "Limit the number of entries in each response. It not present, all entries will be returned.", - Format: "", - Required: false, - }, - { - Name: "last", - Type: "string", - Description: "Result set will include values lexically after last.", - Format: "", - Required: false, - }, - } - - unauthorizedResponseDescriptor = ResponseDescriptor{ - Name: "Authentication Required", - StatusCode: http.StatusUnauthorized, - Description: "The client is not authenticated.", - Headers: []ParameterDescriptor{ - authChallengeHeader, - { - Name: "Content-Length", - Type: "integer", - Description: "Length of the JSON response body.", - Format: "", - }, - }, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: errorsBody, - }, - ErrorCodes: []errcode.ErrorCode{ - errcode.ErrorCodeUnauthorized, - }, - } - - invalidPaginationResponseDescriptor = ResponseDescriptor{ - Name: "Invalid pagination number", - Description: "The received parameter n was invalid in some way, as described by the error code. The client should resolve the issue and retry the request.", - StatusCode: http.StatusBadRequest, - Body: BodyDescriptor{ - ContentType: "application/json", - Format: errorsBody, - }, - ErrorCodes: []errcode.ErrorCode{ - ErrorCodePaginationNumberInvalid, - }, - } - - repositoryNotFoundResponseDescriptor = ResponseDescriptor{ - Name: "No Such Repository Error", - StatusCode: http.StatusNotFound, - Description: "The repository is not known to the registry.", - Headers: []ParameterDescriptor{ - { - Name: "Content-Length", - Type: "integer", - Description: "Length of the JSON response body.", - Format: "", - }, - }, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: errorsBody, - }, - ErrorCodes: []errcode.ErrorCode{ - ErrorCodeNameUnknown, - }, - } - - deniedResponseDescriptor = ResponseDescriptor{ - Name: "Access Denied", - StatusCode: http.StatusForbidden, - Description: "The client does not have required access to the repository.", - Headers: []ParameterDescriptor{ - { - Name: "Content-Length", - Type: "integer", - Description: "Length of the JSON response body.", - Format: "", - }, - }, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: errorsBody, - }, - ErrorCodes: []errcode.ErrorCode{ - errcode.ErrorCodeDenied, - }, - } - - tooManyRequestsDescriptor = ResponseDescriptor{ - Name: "Too Many Requests", - StatusCode: http.StatusTooManyRequests, - Description: "The client made too many requests within a time interval.", - Headers: []ParameterDescriptor{ - { - Name: "Content-Length", - Type: "integer", - Description: "Length of the JSON response body.", - Format: "", - }, - }, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: errorsBody, - }, - ErrorCodes: []errcode.ErrorCode{ - errcode.ErrorCodeTooManyRequests, - }, - } -) - -const ( - manifestBody = `{ - "name": , - "tag": , - "fsLayers": [ - { - "blobSum": "" - }, - ... - ] - ], - "history": , - "signature": -}` - - errorsBody = `{ - "errors:" [ - { - "code": , - "message": "", - "detail": ... - }, - ... - ] -}` -) - -// APIDescriptor exports descriptions of the layout of the v2 registry API. -var APIDescriptor = struct { - // RouteDescriptors provides a list of the routes available in the API. - RouteDescriptors []RouteDescriptor -}{ - RouteDescriptors: routeDescriptors, -} - -// RouteDescriptor describes a route specified by name. -type RouteDescriptor struct { - // Name is the name of the route, as specified in RouteNameXXX exports. - // These names a should be considered a unique reference for a route. If - // the route is registered with gorilla, this is the name that will be - // used. - Name string - - // Path is a gorilla/mux-compatible regexp that can be used to match the - // route. For any incoming method and path, only one route descriptor - // should match. - Path string - - // Entity should be a short, human-readalbe description of the object - // targeted by the endpoint. - Entity string - - // Description should provide an accurate overview of the functionality - // provided by the route. - Description string - - // Methods should describe the various HTTP methods that may be used on - // this route, including request and response formats. - Methods []MethodDescriptor -} - -// MethodDescriptor provides a description of the requests that may be -// conducted with the target method. -type MethodDescriptor struct { - - // Method is an HTTP method, such as GET, PUT or POST. - Method string - - // Description should provide an overview of the functionality provided by - // the covered method, suitable for use in documentation. Use of markdown - // here is encouraged. - Description string - - // Requests is a slice of request descriptors enumerating how this - // endpoint may be used. - Requests []RequestDescriptor -} - -// RequestDescriptor covers a particular set of headers and parameters that -// can be carried out with the parent method. Its most helpful to have one -// RequestDescriptor per API use case. -type RequestDescriptor struct { - // Name provides a short identifier for the request, usable as a title or - // to provide quick context for the particular request. - Name string - - // Description should cover the requests purpose, covering any details for - // this particular use case. - Description string - - // Headers describes headers that must be used with the HTTP request. - Headers []ParameterDescriptor - - // PathParameters enumerate the parameterized path components for the - // given request, as defined in the route's regular expression. - PathParameters []ParameterDescriptor - - // QueryParameters provides a list of query parameters for the given - // request. - QueryParameters []ParameterDescriptor - - // Body describes the format of the request body. - Body BodyDescriptor - - // Successes enumerates the possible responses that are considered to be - // the result of a successful request. - Successes []ResponseDescriptor - - // Failures covers the possible failures from this particular request. - Failures []ResponseDescriptor -} - -// ResponseDescriptor describes the components of an API response. -type ResponseDescriptor struct { - // Name provides a short identifier for the response, usable as a title or - // to provide quick context for the particular response. - Name string - - // Description should provide a brief overview of the role of the - // response. - Description string - - // StatusCode specifies the status received by this particular response. - StatusCode int - - // Headers covers any headers that may be returned from the response. - Headers []ParameterDescriptor - - // Fields describes any fields that may be present in the response. - Fields []ParameterDescriptor - - // ErrorCodes enumerates the error codes that may be returned along with - // the response. - ErrorCodes []errcode.ErrorCode - - // Body describes the body of the response, if any. - Body BodyDescriptor -} - -// BodyDescriptor describes a request body and its expected content type. For -// the most part, it should be example json or some placeholder for body -// data in documentation. -type BodyDescriptor struct { - ContentType string - Format string -} - -// ParameterDescriptor describes the format of a request parameter, which may -// be a header, path parameter or query parameter. -type ParameterDescriptor struct { - // Name is the name of the parameter, either of the path component or - // query parameter. - Name string - - // Type specifies the type of the parameter, such as string, integer, etc. - Type string - - // Description provides a human-readable description of the parameter. - Description string - - // Required means the field is required when set. - Required bool - - // Format is a specifying the string format accepted by this parameter. - Format string - - // Regexp is a compiled regular expression that can be used to validate - // the contents of the parameter. - Regexp *regexp.Regexp - - // Examples provides multiple examples for the values that might be valid - // for this parameter. - Examples []string -} - -var routeDescriptors = []RouteDescriptor{ - { - Name: RouteNameBase, - Path: "/v2/", - Entity: "Base", - Description: `Base V2 API route. Typically, this can be used for lightweight version checks and to validate registry authentication.`, - Methods: []MethodDescriptor{ - { - Method: "GET", - Description: "Check that the endpoint implements Docker Registry API V2.", - Requests: []RequestDescriptor{ - { - Headers: []ParameterDescriptor{ - hostHeader, - authHeader, - }, - Successes: []ResponseDescriptor{ - { - Description: "The API implements V2 protocol and is accessible.", - StatusCode: http.StatusOK, - }, - }, - Failures: []ResponseDescriptor{ - { - Description: "The registry does not implement the V2 API.", - StatusCode: http.StatusNotFound, - }, - unauthorizedResponseDescriptor, - tooManyRequestsDescriptor, - }, - }, - }, - }, - }, - }, - { - Name: RouteNameTags, - Path: "/v2/{name:" + reference.NameRegexp.String() + "}/tags/list", - Entity: "Tags", - Description: "Retrieve information about tags.", - Methods: []MethodDescriptor{ - { - Method: "GET", - Description: "Fetch the tags under the repository identified by `name`.", - Requests: []RequestDescriptor{ - { - Name: "Tags", - Description: "Return all tags for the repository", - Headers: []ParameterDescriptor{ - hostHeader, - authHeader, - }, - PathParameters: []ParameterDescriptor{ - nameParameterDescriptor, - }, - Successes: []ResponseDescriptor{ - { - StatusCode: http.StatusOK, - Description: "A list of tags for the named repository.", - Headers: []ParameterDescriptor{ - { - Name: "Content-Length", - Type: "integer", - Description: "Length of the JSON response body.", - Format: "", - }, - }, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: `{ - "name": , - "tags": [ - , - ... - ] -}`, - }, - }, - }, - Failures: []ResponseDescriptor{ - unauthorizedResponseDescriptor, - repositoryNotFoundResponseDescriptor, - deniedResponseDescriptor, - tooManyRequestsDescriptor, - }, - }, - { - Name: "Tags Paginated", - Description: "Return a portion of the tags for the specified repository.", - PathParameters: []ParameterDescriptor{nameParameterDescriptor}, - QueryParameters: paginationParameters, - Successes: []ResponseDescriptor{ - { - StatusCode: http.StatusOK, - Description: "A list of tags for the named repository.", - Headers: []ParameterDescriptor{ - { - Name: "Content-Length", - Type: "integer", - Description: "Length of the JSON response body.", - Format: "", - }, - linkHeader, - }, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: `{ - "name": , - "tags": [ - , - ... - ], -}`, - }, - }, - }, - Failures: []ResponseDescriptor{ - invalidPaginationResponseDescriptor, - unauthorizedResponseDescriptor, - repositoryNotFoundResponseDescriptor, - deniedResponseDescriptor, - tooManyRequestsDescriptor, - }, - }, - }, - }, - }, - }, - { - Name: RouteNameManifest, - Path: "/v2/{name:" + reference.NameRegexp.String() + "}/manifests/{reference:" + reference.TagRegexp.String() + "|" + digest.DigestRegexp.String() + "}", - Entity: "Manifest", - Description: "Create, update, delete and retrieve manifests.", - Methods: []MethodDescriptor{ - { - Method: "GET", - Description: "Fetch the manifest identified by `name` and `reference` where `reference` can be a tag or digest. A `HEAD` request can also be issued to this endpoint to obtain resource information without receiving all data.", - Requests: []RequestDescriptor{ - { - Headers: []ParameterDescriptor{ - hostHeader, - authHeader, - }, - PathParameters: []ParameterDescriptor{ - nameParameterDescriptor, - referenceParameterDescriptor, - }, - Successes: []ResponseDescriptor{ - { - Description: "The manifest identified by `name` and `reference`. The contents can be used to identify and resolve resources required to run the specified image.", - StatusCode: http.StatusOK, - Headers: []ParameterDescriptor{ - digestHeader, - }, - Body: BodyDescriptor{ - ContentType: "", - Format: manifestBody, - }, - }, - }, - Failures: []ResponseDescriptor{ - { - Description: "The name or reference was invalid.", - StatusCode: http.StatusBadRequest, - ErrorCodes: []errcode.ErrorCode{ - ErrorCodeNameInvalid, - ErrorCodeTagInvalid, - }, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: errorsBody, - }, - }, - unauthorizedResponseDescriptor, - repositoryNotFoundResponseDescriptor, - deniedResponseDescriptor, - tooManyRequestsDescriptor, - }, - }, - }, - }, - { - Method: "PUT", - Description: "Put the manifest identified by `name` and `reference` where `reference` can be a tag or digest.", - Requests: []RequestDescriptor{ - { - Headers: []ParameterDescriptor{ - hostHeader, - authHeader, - }, - PathParameters: []ParameterDescriptor{ - nameParameterDescriptor, - referenceParameterDescriptor, - }, - Body: BodyDescriptor{ - ContentType: "", - Format: manifestBody, - }, - Successes: []ResponseDescriptor{ - { - Description: "The manifest has been accepted by the registry and is stored under the specified `name` and `tag`.", - StatusCode: http.StatusCreated, - Headers: []ParameterDescriptor{ - { - Name: "Location", - Type: "url", - Description: "The canonical location url of the uploaded manifest.", - Format: "", - }, - contentLengthZeroHeader, - digestHeader, - }, - }, - }, - Failures: []ResponseDescriptor{ - { - Name: "Invalid Manifest", - Description: "The received manifest was invalid in some way, as described by the error codes. The client should resolve the issue and retry the request.", - StatusCode: http.StatusBadRequest, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: errorsBody, - }, - ErrorCodes: []errcode.ErrorCode{ - ErrorCodeNameInvalid, - ErrorCodeTagInvalid, - ErrorCodeManifestInvalid, - ErrorCodeManifestUnverified, - ErrorCodeBlobUnknown, - }, - }, - unauthorizedResponseDescriptor, - repositoryNotFoundResponseDescriptor, - deniedResponseDescriptor, - tooManyRequestsDescriptor, - { - Name: "Missing Layer(s)", - Description: "One or more layers may be missing during a manifest upload. If so, the missing layers will be enumerated in the error response.", - StatusCode: http.StatusBadRequest, - ErrorCodes: []errcode.ErrorCode{ - ErrorCodeBlobUnknown, - }, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: `{ - "errors:" [{ - "code": "BLOB_UNKNOWN", - "message": "blob unknown to registry", - "detail": { - "digest": "" - } - }, - ... - ] -}`, - }, - }, - { - Name: "Not allowed", - Description: "Manifest put is not allowed because the registry is configured as a pull-through cache or for some other reason", - StatusCode: http.StatusMethodNotAllowed, - ErrorCodes: []errcode.ErrorCode{ - errcode.ErrorCodeUnsupported, - }, - }, - }, - }, - }, - }, - { - Method: "DELETE", - Description: "Delete the manifest identified by `name` and `reference`. Note that a manifest can _only_ be deleted by `digest`.", - Requests: []RequestDescriptor{ - { - Headers: []ParameterDescriptor{ - hostHeader, - authHeader, - }, - PathParameters: []ParameterDescriptor{ - nameParameterDescriptor, - referenceParameterDescriptor, - }, - Successes: []ResponseDescriptor{ - { - StatusCode: http.StatusAccepted, - }, - }, - Failures: []ResponseDescriptor{ - { - Name: "Invalid Name or Reference", - Description: "The specified `name` or `reference` were invalid and the delete was unable to proceed.", - StatusCode: http.StatusBadRequest, - ErrorCodes: []errcode.ErrorCode{ - ErrorCodeNameInvalid, - ErrorCodeTagInvalid, - }, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: errorsBody, - }, - }, - unauthorizedResponseDescriptor, - repositoryNotFoundResponseDescriptor, - deniedResponseDescriptor, - tooManyRequestsDescriptor, - { - Name: "Unknown Manifest", - Description: "The specified `name` or `reference` are unknown to the registry and the delete was unable to proceed. Clients can assume the manifest was already deleted if this response is returned.", - StatusCode: http.StatusNotFound, - ErrorCodes: []errcode.ErrorCode{ - ErrorCodeNameUnknown, - ErrorCodeManifestUnknown, - }, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: errorsBody, - }, - }, - { - Name: "Not allowed", - Description: "Manifest delete is not allowed because the registry is configured as a pull-through cache or `delete` has been disabled.", - StatusCode: http.StatusMethodNotAllowed, - ErrorCodes: []errcode.ErrorCode{ - errcode.ErrorCodeUnsupported, - }, - }, - }, - }, - }, - }, - }, - }, - - { - Name: RouteNameBlob, - Path: "/v2/{name:" + reference.NameRegexp.String() + "}/blobs/{digest:" + digest.DigestRegexp.String() + "}", - Entity: "Blob", - Description: "Operations on blobs identified by `name` and `digest`. Used to fetch or delete layers by digest.", - Methods: []MethodDescriptor{ - { - Method: "GET", - Description: "Retrieve the blob from the registry identified by `digest`. A `HEAD` request can also be issued to this endpoint to obtain resource information without receiving all data.", - Requests: []RequestDescriptor{ - { - Name: "Fetch Blob", - Headers: []ParameterDescriptor{ - hostHeader, - authHeader, - }, - PathParameters: []ParameterDescriptor{ - nameParameterDescriptor, - digestPathParameter, - }, - Successes: []ResponseDescriptor{ - { - Description: "The blob identified by `digest` is available. The blob content will be present in the body of the request.", - StatusCode: http.StatusOK, - Headers: []ParameterDescriptor{ - { - Name: "Content-Length", - Type: "integer", - Description: "The length of the requested blob content.", - Format: "", - }, - digestHeader, - }, - Body: BodyDescriptor{ - ContentType: "application/octet-stream", - Format: "", - }, - }, - { - Description: "The blob identified by `digest` is available at the provided location.", - StatusCode: http.StatusTemporaryRedirect, - Headers: []ParameterDescriptor{ - { - Name: "Location", - Type: "url", - Description: "The location where the layer should be accessible.", - Format: "", - }, - digestHeader, - }, - }, - }, - Failures: []ResponseDescriptor{ - { - Description: "There was a problem with the request that needs to be addressed by the client, such as an invalid `name` or `tag`.", - StatusCode: http.StatusBadRequest, - ErrorCodes: []errcode.ErrorCode{ - ErrorCodeNameInvalid, - ErrorCodeDigestInvalid, - }, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: errorsBody, - }, - }, - { - Description: "The blob, identified by `name` and `digest`, is unknown to the registry.", - StatusCode: http.StatusNotFound, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: errorsBody, - }, - ErrorCodes: []errcode.ErrorCode{ - ErrorCodeNameUnknown, - ErrorCodeBlobUnknown, - }, - }, - unauthorizedResponseDescriptor, - repositoryNotFoundResponseDescriptor, - deniedResponseDescriptor, - tooManyRequestsDescriptor, - }, - }, - { - Name: "Fetch Blob Part", - Description: "This endpoint may also support RFC7233 compliant range requests. Support can be detected by issuing a HEAD request. If the header `Accept-Range: bytes` is returned, range requests can be used to fetch partial content.", - Headers: []ParameterDescriptor{ - hostHeader, - authHeader, - { - Name: "Range", - Type: "string", - Description: "HTTP Range header specifying blob chunk.", - Format: "bytes=-", - }, - }, - PathParameters: []ParameterDescriptor{ - nameParameterDescriptor, - digestPathParameter, - }, - Successes: []ResponseDescriptor{ - { - Description: "The blob identified by `digest` is available. The specified chunk of blob content will be present in the body of the request.", - StatusCode: http.StatusPartialContent, - Headers: []ParameterDescriptor{ - { - Name: "Content-Length", - Type: "integer", - Description: "The length of the requested blob chunk.", - Format: "", - }, - { - Name: "Content-Range", - Type: "byte range", - Description: "Content range of blob chunk.", - Format: "bytes -/", - }, - }, - Body: BodyDescriptor{ - ContentType: "application/octet-stream", - Format: "", - }, - }, - }, - Failures: []ResponseDescriptor{ - { - Description: "There was a problem with the request that needs to be addressed by the client, such as an invalid `name` or `tag`.", - StatusCode: http.StatusBadRequest, - ErrorCodes: []errcode.ErrorCode{ - ErrorCodeNameInvalid, - ErrorCodeDigestInvalid, - }, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: errorsBody, - }, - }, - { - StatusCode: http.StatusNotFound, - ErrorCodes: []errcode.ErrorCode{ - ErrorCodeNameUnknown, - ErrorCodeBlobUnknown, - }, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: errorsBody, - }, - }, - { - Description: "The range specification cannot be satisfied for the requested content. This can happen when the range is not formatted correctly or if the range is outside of the valid size of the content.", - StatusCode: http.StatusRequestedRangeNotSatisfiable, - }, - unauthorizedResponseDescriptor, - repositoryNotFoundResponseDescriptor, - deniedResponseDescriptor, - tooManyRequestsDescriptor, - }, - }, - }, - }, - { - Method: "DELETE", - Description: "Delete the blob identified by `name` and `digest`", - Requests: []RequestDescriptor{ - { - Headers: []ParameterDescriptor{ - hostHeader, - authHeader, - }, - PathParameters: []ParameterDescriptor{ - nameParameterDescriptor, - digestPathParameter, - }, - Successes: []ResponseDescriptor{ - { - StatusCode: http.StatusAccepted, - Headers: []ParameterDescriptor{ - { - Name: "Content-Length", - Type: "integer", - Description: "0", - Format: "0", - }, - digestHeader, - }, - }, - }, - Failures: []ResponseDescriptor{ - { - Name: "Invalid Name or Digest", - StatusCode: http.StatusBadRequest, - ErrorCodes: []errcode.ErrorCode{ - ErrorCodeDigestInvalid, - ErrorCodeNameInvalid, - }, - }, - { - Description: "The blob, identified by `name` and `digest`, is unknown to the registry.", - StatusCode: http.StatusNotFound, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: errorsBody, - }, - ErrorCodes: []errcode.ErrorCode{ - ErrorCodeNameUnknown, - ErrorCodeBlobUnknown, - }, - }, - { - Description: "Blob delete is not allowed because the registry is configured as a pull-through cache or `delete` has been disabled", - StatusCode: http.StatusMethodNotAllowed, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: errorsBody, - }, - ErrorCodes: []errcode.ErrorCode{ - errcode.ErrorCodeUnsupported, - }, - }, - unauthorizedResponseDescriptor, - repositoryNotFoundResponseDescriptor, - deniedResponseDescriptor, - tooManyRequestsDescriptor, - }, - }, - }, - }, - - // TODO(stevvooe): We may want to add a PUT request here to - // kickoff an upload of a blob, integrated with the blob upload - // API. - }, - }, - - { - Name: RouteNameBlobUpload, - Path: "/v2/{name:" + reference.NameRegexp.String() + "}/blobs/uploads/", - Entity: "Initiate Blob Upload", - Description: "Initiate a blob upload. This endpoint can be used to create resumable uploads or monolithic uploads.", - Methods: []MethodDescriptor{ - { - Method: "POST", - Description: "Initiate a resumable blob upload. If successful, an upload location will be provided to complete the upload. Optionally, if the `digest` parameter is present, the request body will be used to complete the upload in a single request.", - Requests: []RequestDescriptor{ - { - Name: "Initiate Monolithic Blob Upload", - Description: "Upload a blob identified by the `digest` parameter in single request. This upload will not be resumable unless a recoverable error is returned.", - Headers: []ParameterDescriptor{ - hostHeader, - authHeader, - { - Name: "Content-Length", - Type: "integer", - Format: "", - }, - }, - PathParameters: []ParameterDescriptor{ - nameParameterDescriptor, - }, - QueryParameters: []ParameterDescriptor{ - { - Name: "digest", - Type: "query", - Format: "", - Regexp: digest.DigestRegexp, - Description: `Digest of uploaded blob. If present, the upload will be completed, in a single request, with contents of the request body as the resulting blob.`, - }, - }, - Body: BodyDescriptor{ - ContentType: "application/octect-stream", - Format: "", - }, - Successes: []ResponseDescriptor{ - { - Description: "The blob has been created in the registry and is available at the provided location.", - StatusCode: http.StatusCreated, - Headers: []ParameterDescriptor{ - { - Name: "Location", - Type: "url", - Format: "", - }, - contentLengthZeroHeader, - dockerUploadUUIDHeader, - }, - }, - }, - Failures: []ResponseDescriptor{ - { - Name: "Invalid Name or Digest", - StatusCode: http.StatusBadRequest, - ErrorCodes: []errcode.ErrorCode{ - ErrorCodeDigestInvalid, - ErrorCodeNameInvalid, - }, - }, - { - Name: "Not allowed", - Description: "Blob upload is not allowed because the registry is configured as a pull-through cache or for some other reason", - StatusCode: http.StatusMethodNotAllowed, - ErrorCodes: []errcode.ErrorCode{ - errcode.ErrorCodeUnsupported, - }, - }, - unauthorizedResponseDescriptor, - repositoryNotFoundResponseDescriptor, - deniedResponseDescriptor, - tooManyRequestsDescriptor, - }, - }, - { - Name: "Initiate Resumable Blob Upload", - Description: "Initiate a resumable blob upload with an empty request body.", - Headers: []ParameterDescriptor{ - hostHeader, - authHeader, - contentLengthZeroHeader, - }, - PathParameters: []ParameterDescriptor{ - nameParameterDescriptor, - }, - Successes: []ResponseDescriptor{ - { - Description: "The upload has been created. The `Location` header must be used to complete the upload. The response should be identical to a `GET` request on the contents of the returned `Location` header.", - StatusCode: http.StatusAccepted, - Headers: []ParameterDescriptor{ - contentLengthZeroHeader, - { - Name: "Location", - Type: "url", - Format: "/v2//blobs/uploads/", - Description: "The location of the created upload. Clients should use the contents verbatim to complete the upload, adding parameters where required.", - }, - { - Name: "Range", - Format: "0-0", - Description: "Range header indicating the progress of the upload. When starting an upload, it will return an empty range, since no content has been received.", - }, - dockerUploadUUIDHeader, - }, - }, - }, - Failures: []ResponseDescriptor{ - { - Name: "Invalid Name or Digest", - StatusCode: http.StatusBadRequest, - ErrorCodes: []errcode.ErrorCode{ - ErrorCodeDigestInvalid, - ErrorCodeNameInvalid, - }, - }, - unauthorizedResponseDescriptor, - repositoryNotFoundResponseDescriptor, - deniedResponseDescriptor, - tooManyRequestsDescriptor, - }, - }, - { - Name: "Mount Blob", - Description: "Mount a blob identified by the `mount` parameter from another repository.", - Headers: []ParameterDescriptor{ - hostHeader, - authHeader, - contentLengthZeroHeader, - }, - PathParameters: []ParameterDescriptor{ - nameParameterDescriptor, - }, - QueryParameters: []ParameterDescriptor{ - { - Name: "mount", - Type: "query", - Format: "", - Regexp: digest.DigestRegexp, - Description: `Digest of blob to mount from the source repository.`, - }, - { - Name: "from", - Type: "query", - Format: "", - Regexp: reference.NameRegexp, - Description: `Name of the source repository.`, - }, - }, - Successes: []ResponseDescriptor{ - { - Description: "The blob has been mounted in the repository and is available at the provided location.", - StatusCode: http.StatusCreated, - Headers: []ParameterDescriptor{ - { - Name: "Location", - Type: "url", - Format: "", - }, - contentLengthZeroHeader, - dockerUploadUUIDHeader, - }, - }, - }, - Failures: []ResponseDescriptor{ - { - Name: "Invalid Name or Digest", - StatusCode: http.StatusBadRequest, - ErrorCodes: []errcode.ErrorCode{ - ErrorCodeDigestInvalid, - ErrorCodeNameInvalid, - }, - }, - { - Name: "Not allowed", - Description: "Blob mount is not allowed because the registry is configured as a pull-through cache or for some other reason", - StatusCode: http.StatusMethodNotAllowed, - ErrorCodes: []errcode.ErrorCode{ - errcode.ErrorCodeUnsupported, - }, - }, - unauthorizedResponseDescriptor, - repositoryNotFoundResponseDescriptor, - deniedResponseDescriptor, - tooManyRequestsDescriptor, - }, - }, - }, - }, - }, - }, - - { - Name: RouteNameBlobUploadChunk, - Path: "/v2/{name:" + reference.NameRegexp.String() + "}/blobs/uploads/{uuid:[a-zA-Z0-9-_.=]+}", - Entity: "Blob Upload", - Description: "Interact with blob uploads. Clients should never assemble URLs for this endpoint and should only take it through the `Location` header on related API requests. The `Location` header and its parameters should be preserved by clients, using the latest value returned via upload related API calls.", - Methods: []MethodDescriptor{ - { - Method: "GET", - Description: "Retrieve status of upload identified by `uuid`. The primary purpose of this endpoint is to resolve the current status of a resumable upload.", - Requests: []RequestDescriptor{ - { - Description: "Retrieve the progress of the current upload, as reported by the `Range` header.", - Headers: []ParameterDescriptor{ - hostHeader, - authHeader, - }, - PathParameters: []ParameterDescriptor{ - nameParameterDescriptor, - uuidParameterDescriptor, - }, - Successes: []ResponseDescriptor{ - { - Name: "Upload Progress", - Description: "The upload is known and in progress. The last received offset is available in the `Range` header.", - StatusCode: http.StatusNoContent, - Headers: []ParameterDescriptor{ - { - Name: "Range", - Type: "header", - Format: "0-", - Description: "Range indicating the current progress of the upload.", - }, - contentLengthZeroHeader, - dockerUploadUUIDHeader, - }, - }, - }, - Failures: []ResponseDescriptor{ - { - Description: "There was an error processing the upload and it must be restarted.", - StatusCode: http.StatusBadRequest, - ErrorCodes: []errcode.ErrorCode{ - ErrorCodeDigestInvalid, - ErrorCodeNameInvalid, - ErrorCodeBlobUploadInvalid, - }, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: errorsBody, - }, - }, - { - Description: "The upload is unknown to the registry. The upload must be restarted.", - StatusCode: http.StatusNotFound, - ErrorCodes: []errcode.ErrorCode{ - ErrorCodeBlobUploadUnknown, - }, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: errorsBody, - }, - }, - unauthorizedResponseDescriptor, - repositoryNotFoundResponseDescriptor, - deniedResponseDescriptor, - tooManyRequestsDescriptor, - }, - }, - }, - }, - { - Method: "PATCH", - Description: "Upload a chunk of data for the specified upload.", - Requests: []RequestDescriptor{ - { - Name: "Stream upload", - Description: "Upload a stream of data to upload without completing the upload.", - PathParameters: []ParameterDescriptor{ - nameParameterDescriptor, - uuidParameterDescriptor, - }, - Headers: []ParameterDescriptor{ - hostHeader, - authHeader, - }, - Body: BodyDescriptor{ - ContentType: "application/octet-stream", - Format: "", - }, - Successes: []ResponseDescriptor{ - { - Name: "Data Accepted", - Description: "The stream of data has been accepted and the current progress is available in the range header. The updated upload location is available in the `Location` header.", - StatusCode: http.StatusNoContent, - Headers: []ParameterDescriptor{ - { - Name: "Location", - Type: "url", - Format: "/v2//blobs/uploads/", - Description: "The location of the upload. Clients should assume this changes after each request. Clients should use the contents verbatim to complete the upload, adding parameters where required.", - }, - { - Name: "Range", - Type: "header", - Format: "0-", - Description: "Range indicating the current progress of the upload.", - }, - contentLengthZeroHeader, - dockerUploadUUIDHeader, - }, - }, - }, - Failures: []ResponseDescriptor{ - { - Description: "There was an error processing the upload and it must be restarted.", - StatusCode: http.StatusBadRequest, - ErrorCodes: []errcode.ErrorCode{ - ErrorCodeDigestInvalid, - ErrorCodeNameInvalid, - ErrorCodeBlobUploadInvalid, - }, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: errorsBody, - }, - }, - { - Description: "The upload is unknown to the registry. The upload must be restarted.", - StatusCode: http.StatusNotFound, - ErrorCodes: []errcode.ErrorCode{ - ErrorCodeBlobUploadUnknown, - }, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: errorsBody, - }, - }, - unauthorizedResponseDescriptor, - repositoryNotFoundResponseDescriptor, - deniedResponseDescriptor, - tooManyRequestsDescriptor, - }, - }, - { - Name: "Chunked upload", - Description: "Upload a chunk of data to specified upload without completing the upload. The data will be uploaded to the specified Content Range.", - PathParameters: []ParameterDescriptor{ - nameParameterDescriptor, - uuidParameterDescriptor, - }, - Headers: []ParameterDescriptor{ - hostHeader, - authHeader, - { - Name: "Content-Range", - Type: "header", - Format: "-", - Required: true, - Description: "Range of bytes identifying the desired block of content represented by the body. Start must the end offset retrieved via status check plus one. Note that this is a non-standard use of the `Content-Range` header.", - }, - { - Name: "Content-Length", - Type: "integer", - Format: "", - Description: "Length of the chunk being uploaded, corresponding the length of the request body.", - }, - }, - Body: BodyDescriptor{ - ContentType: "application/octet-stream", - Format: "", - }, - Successes: []ResponseDescriptor{ - { - Name: "Chunk Accepted", - Description: "The chunk of data has been accepted and the current progress is available in the range header. The updated upload location is available in the `Location` header.", - StatusCode: http.StatusNoContent, - Headers: []ParameterDescriptor{ - { - Name: "Location", - Type: "url", - Format: "/v2//blobs/uploads/", - Description: "The location of the upload. Clients should assume this changes after each request. Clients should use the contents verbatim to complete the upload, adding parameters where required.", - }, - { - Name: "Range", - Type: "header", - Format: "0-", - Description: "Range indicating the current progress of the upload.", - }, - contentLengthZeroHeader, - dockerUploadUUIDHeader, - }, - }, - }, - Failures: []ResponseDescriptor{ - { - Description: "There was an error processing the upload and it must be restarted.", - StatusCode: http.StatusBadRequest, - ErrorCodes: []errcode.ErrorCode{ - ErrorCodeDigestInvalid, - ErrorCodeNameInvalid, - ErrorCodeBlobUploadInvalid, - }, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: errorsBody, - }, - }, - { - Description: "The upload is unknown to the registry. The upload must be restarted.", - StatusCode: http.StatusNotFound, - ErrorCodes: []errcode.ErrorCode{ - ErrorCodeBlobUploadUnknown, - }, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: errorsBody, - }, - }, - { - Description: "The `Content-Range` specification cannot be accepted, either because it does not overlap with the current progress or it is invalid.", - StatusCode: http.StatusRequestedRangeNotSatisfiable, - }, - unauthorizedResponseDescriptor, - repositoryNotFoundResponseDescriptor, - deniedResponseDescriptor, - tooManyRequestsDescriptor, - }, - }, - }, - }, - { - Method: "PUT", - Description: "Complete the upload specified by `uuid`, optionally appending the body as the final chunk.", - Requests: []RequestDescriptor{ - { - Description: "Complete the upload, providing all the data in the body, if necessary. A request without a body will just complete the upload with previously uploaded content.", - Headers: []ParameterDescriptor{ - hostHeader, - authHeader, - { - Name: "Content-Length", - Type: "integer", - Format: "", - Description: "Length of the data being uploaded, corresponding to the length of the request body. May be zero if no data is provided.", - }, - }, - PathParameters: []ParameterDescriptor{ - nameParameterDescriptor, - uuidParameterDescriptor, - }, - QueryParameters: []ParameterDescriptor{ - { - Name: "digest", - Type: "string", - Format: "", - Regexp: digest.DigestRegexp, - Required: true, - Description: `Digest of uploaded blob.`, - }, - }, - Body: BodyDescriptor{ - ContentType: "application/octet-stream", - Format: "", - }, - Successes: []ResponseDescriptor{ - { - Name: "Upload Complete", - Description: "The upload has been completed and accepted by the registry. The canonical location will be available in the `Location` header.", - StatusCode: http.StatusNoContent, - Headers: []ParameterDescriptor{ - { - Name: "Location", - Type: "url", - Format: "", - Description: "The canonical location of the blob for retrieval", - }, - { - Name: "Content-Range", - Type: "header", - Format: "-", - Description: "Range of bytes identifying the desired block of content represented by the body. Start must match the end of offset retrieved via status check. Note that this is a non-standard use of the `Content-Range` header.", - }, - contentLengthZeroHeader, - digestHeader, - }, - }, - }, - Failures: []ResponseDescriptor{ - { - Description: "There was an error processing the upload and it must be restarted.", - StatusCode: http.StatusBadRequest, - ErrorCodes: []errcode.ErrorCode{ - ErrorCodeDigestInvalid, - ErrorCodeNameInvalid, - ErrorCodeBlobUploadInvalid, - errcode.ErrorCodeUnsupported, - }, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: errorsBody, - }, - }, - { - Description: "The upload is unknown to the registry. The upload must be restarted.", - StatusCode: http.StatusNotFound, - ErrorCodes: []errcode.ErrorCode{ - ErrorCodeBlobUploadUnknown, - }, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: errorsBody, - }, - }, - unauthorizedResponseDescriptor, - repositoryNotFoundResponseDescriptor, - deniedResponseDescriptor, - tooManyRequestsDescriptor, - }, - }, - }, - }, - { - Method: "DELETE", - Description: "Cancel outstanding upload processes, releasing associated resources. If this is not called, the unfinished uploads will eventually timeout.", - Requests: []RequestDescriptor{ - { - Description: "Cancel the upload specified by `uuid`.", - PathParameters: []ParameterDescriptor{ - nameParameterDescriptor, - uuidParameterDescriptor, - }, - Headers: []ParameterDescriptor{ - hostHeader, - authHeader, - contentLengthZeroHeader, - }, - Successes: []ResponseDescriptor{ - { - Name: "Upload Deleted", - Description: "The upload has been successfully deleted.", - StatusCode: http.StatusNoContent, - Headers: []ParameterDescriptor{ - contentLengthZeroHeader, - }, - }, - }, - Failures: []ResponseDescriptor{ - { - Description: "An error was encountered processing the delete. The client may ignore this error.", - StatusCode: http.StatusBadRequest, - ErrorCodes: []errcode.ErrorCode{ - ErrorCodeNameInvalid, - ErrorCodeBlobUploadInvalid, - }, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: errorsBody, - }, - }, - { - Description: "The upload is unknown to the registry. The client may ignore this error and assume the upload has been deleted.", - StatusCode: http.StatusNotFound, - ErrorCodes: []errcode.ErrorCode{ - ErrorCodeBlobUploadUnknown, - }, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: errorsBody, - }, - }, - unauthorizedResponseDescriptor, - repositoryNotFoundResponseDescriptor, - deniedResponseDescriptor, - tooManyRequestsDescriptor, - }, - }, - }, - }, - }, - }, - { - Name: RouteNameCatalog, - Path: "/v2/_catalog", - Entity: "Catalog", - Description: "List a set of available repositories in the local registry cluster. Does not provide any indication of what may be available upstream. Applications can only determine if a repository is available but not if it is not available.", - Methods: []MethodDescriptor{ - { - Method: "GET", - Description: "Retrieve a sorted, json list of repositories available in the registry.", - Requests: []RequestDescriptor{ - { - Name: "Catalog Fetch", - Description: "Request an unabridged list of repositories available. The implementation may impose a maximum limit and return a partial set with pagination links.", - Successes: []ResponseDescriptor{ - { - Description: "Returns the unabridged list of repositories as a json response.", - StatusCode: http.StatusOK, - Headers: []ParameterDescriptor{ - { - Name: "Content-Length", - Type: "integer", - Description: "Length of the JSON response body.", - Format: "", - }, - }, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: `{ - "repositories": [ - , - ... - ] -}`, - }, - }, - }, - }, - { - Name: "Catalog Fetch Paginated", - Description: "Return the specified portion of repositories.", - QueryParameters: paginationParameters, - Successes: []ResponseDescriptor{ - { - StatusCode: http.StatusOK, - Body: BodyDescriptor{ - ContentType: "application/json; charset=utf-8", - Format: `{ - "repositories": [ - , - ... - ] - "next": "?last=&n=" -}`, - }, - Headers: []ParameterDescriptor{ - { - Name: "Content-Length", - Type: "integer", - Description: "Length of the JSON response body.", - Format: "", - }, - linkHeader, - }, - }, - }, - Failures: []ResponseDescriptor{ - invalidPaginationResponseDescriptor, - }, - }, - }, - }, - }, - }, -} - -var routeDescriptorsMap map[string]RouteDescriptor - -func init() { - routeDescriptorsMap = make(map[string]RouteDescriptor, len(routeDescriptors)) - - for _, descriptor := range routeDescriptors { - routeDescriptorsMap[descriptor.Name] = descriptor - } -} diff --git a/vendor/github.com/docker/distribution/registry/api/v2/doc.go b/vendor/github.com/docker/distribution/registry/api/v2/doc.go deleted file mode 100644 index cde011959..000000000 --- a/vendor/github.com/docker/distribution/registry/api/v2/doc.go +++ /dev/null @@ -1,9 +0,0 @@ -// Package v2 describes routes, urls and the error codes used in the Docker -// Registry JSON HTTP API V2. In addition to declarations, descriptors are -// provided for routes and error codes that can be used for implementation and -// automatically generating documentation. -// -// Definitions here are considered to be locked down for the V2 registry api. -// Any changes must be considered carefully and should not proceed without a -// change proposal in docker core. -package v2 diff --git a/vendor/github.com/docker/distribution/registry/api/v2/errors.go b/vendor/github.com/docker/distribution/registry/api/v2/errors.go deleted file mode 100644 index 87e9f3c14..000000000 --- a/vendor/github.com/docker/distribution/registry/api/v2/errors.go +++ /dev/null @@ -1,145 +0,0 @@ -package v2 - -import ( - "net/http" - - "github.com/docker/distribution/registry/api/errcode" -) - -const errGroup = "registry.api.v2" - -var ( - // ErrorCodeDigestInvalid is returned when uploading a blob if the - // provided digest does not match the blob contents. - ErrorCodeDigestInvalid = errcode.Register(errGroup, errcode.ErrorDescriptor{ - Value: "DIGEST_INVALID", - Message: "provided digest did not match uploaded content", - Description: `When a blob is uploaded, the registry will check that - the content matches the digest provided by the client. The error may - include a detail structure with the key "digest", including the - invalid digest string. This error may also be returned when a manifest - includes an invalid layer digest.`, - HTTPStatusCode: http.StatusBadRequest, - }) - - // ErrorCodeSizeInvalid is returned when uploading a blob if the provided - ErrorCodeSizeInvalid = errcode.Register(errGroup, errcode.ErrorDescriptor{ - Value: "SIZE_INVALID", - Message: "provided length did not match content length", - Description: `When a layer is uploaded, the provided size will be - checked against the uploaded content. If they do not match, this error - will be returned.`, - HTTPStatusCode: http.StatusBadRequest, - }) - - // ErrorCodeNameInvalid is returned when the name in the manifest does not - // match the provided name. - ErrorCodeNameInvalid = errcode.Register(errGroup, errcode.ErrorDescriptor{ - Value: "NAME_INVALID", - Message: "invalid repository name", - Description: `Invalid repository name encountered either during - manifest validation or any API operation.`, - HTTPStatusCode: http.StatusBadRequest, - }) - - // ErrorCodeTagInvalid is returned when the tag in the manifest does not - // match the provided tag. - ErrorCodeTagInvalid = errcode.Register(errGroup, errcode.ErrorDescriptor{ - Value: "TAG_INVALID", - Message: "manifest tag did not match URI", - Description: `During a manifest upload, if the tag in the manifest - does not match the uri tag, this error will be returned.`, - HTTPStatusCode: http.StatusBadRequest, - }) - - // ErrorCodeNameUnknown when the repository name is not known. - ErrorCodeNameUnknown = errcode.Register(errGroup, errcode.ErrorDescriptor{ - Value: "NAME_UNKNOWN", - Message: "repository name not known to registry", - Description: `This is returned if the name used during an operation is - unknown to the registry.`, - HTTPStatusCode: http.StatusNotFound, - }) - - // ErrorCodeManifestUnknown returned when image manifest is unknown. - ErrorCodeManifestUnknown = errcode.Register(errGroup, errcode.ErrorDescriptor{ - Value: "MANIFEST_UNKNOWN", - Message: "manifest unknown", - Description: `This error is returned when the manifest, identified by - name and tag is unknown to the repository.`, - HTTPStatusCode: http.StatusNotFound, - }) - - // ErrorCodeManifestInvalid returned when an image manifest is invalid, - // typically during a PUT operation. This error encompasses all errors - // encountered during manifest validation that aren't signature errors. - ErrorCodeManifestInvalid = errcode.Register(errGroup, errcode.ErrorDescriptor{ - Value: "MANIFEST_INVALID", - Message: "manifest invalid", - Description: `During upload, manifests undergo several checks ensuring - validity. If those checks fail, this error may be returned, unless a - more specific error is included. The detail will contain information - the failed validation.`, - HTTPStatusCode: http.StatusBadRequest, - }) - - // ErrorCodeManifestUnverified is returned when the manifest fails - // signature verification. - ErrorCodeManifestUnverified = errcode.Register(errGroup, errcode.ErrorDescriptor{ - Value: "MANIFEST_UNVERIFIED", - Message: "manifest failed signature verification", - Description: `During manifest upload, if the manifest fails signature - verification, this error will be returned.`, - HTTPStatusCode: http.StatusBadRequest, - }) - - // ErrorCodeManifestBlobUnknown is returned when a manifest blob is - // unknown to the registry. - ErrorCodeManifestBlobUnknown = errcode.Register(errGroup, errcode.ErrorDescriptor{ - Value: "MANIFEST_BLOB_UNKNOWN", - Message: "blob unknown to registry", - Description: `This error may be returned when a manifest blob is - unknown to the registry.`, - HTTPStatusCode: http.StatusBadRequest, - }) - - // ErrorCodeBlobUnknown is returned when a blob is unknown to the - // registry. This can happen when the manifest references a nonexistent - // layer or the result is not found by a blob fetch. - ErrorCodeBlobUnknown = errcode.Register(errGroup, errcode.ErrorDescriptor{ - Value: "BLOB_UNKNOWN", - Message: "blob unknown to registry", - Description: `This error may be returned when a blob is unknown to the - registry in a specified repository. This can be returned with a - standard get or if a manifest references an unknown layer during - upload.`, - HTTPStatusCode: http.StatusNotFound, - }) - - // ErrorCodeBlobUploadUnknown is returned when an upload is unknown. - ErrorCodeBlobUploadUnknown = errcode.Register(errGroup, errcode.ErrorDescriptor{ - Value: "BLOB_UPLOAD_UNKNOWN", - Message: "blob upload unknown to registry", - Description: `If a blob upload has been cancelled or was never - started, this error code may be returned.`, - HTTPStatusCode: http.StatusNotFound, - }) - - // ErrorCodeBlobUploadInvalid is returned when an upload is invalid. - ErrorCodeBlobUploadInvalid = errcode.Register(errGroup, errcode.ErrorDescriptor{ - Value: "BLOB_UPLOAD_INVALID", - Message: "blob upload invalid", - Description: `The blob upload encountered an error and can no - longer proceed.`, - HTTPStatusCode: http.StatusNotFound, - }) - - ErrorCodePaginationNumberInvalid = errcode.Register(errGroup, errcode.ErrorDescriptor{ - Value: "PAGINATION_NUMBER_INVALID", - Message: "invalid number of results requested", - Description: `Returned when the "n" parameter (number of results - to return) is not an integer, "n" is negative or "n" is bigger than - the maximum allowed.`, - HTTPStatusCode: http.StatusBadRequest, - }) -) diff --git a/vendor/github.com/docker/distribution/registry/api/v2/headerparser.go b/vendor/github.com/docker/distribution/registry/api/v2/headerparser.go deleted file mode 100644 index 9bc41a3a6..000000000 --- a/vendor/github.com/docker/distribution/registry/api/v2/headerparser.go +++ /dev/null @@ -1,161 +0,0 @@ -package v2 - -import ( - "fmt" - "regexp" - "strings" - "unicode" -) - -var ( - // according to rfc7230 - reToken = regexp.MustCompile(`^[^"(),/:;<=>?@[\]{}[:space:][:cntrl:]]+`) - reQuotedValue = regexp.MustCompile(`^[^\\"]+`) - reEscapedCharacter = regexp.MustCompile(`^[[:blank:][:graph:]]`) -) - -// parseForwardedHeader is a benevolent parser of Forwarded header defined in rfc7239. The header contains -// a comma-separated list of forwarding key-value pairs. Each list element is set by single proxy. The -// function parses only the first element of the list, which is set by the very first proxy. It returns a map -// of corresponding key-value pairs and an unparsed slice of the input string. -// -// Examples of Forwarded header values: -// -// 1. Forwarded: For=192.0.2.43; Proto=https,For="[2001:db8:cafe::17]",For=unknown -// 2. Forwarded: for="192.0.2.43:443"; host="registry.example.org", for="10.10.05.40:80" -// -// The first will be parsed into {"for": "192.0.2.43", "proto": "https"} while the second into -// {"for": "192.0.2.43:443", "host": "registry.example.org"}. -func parseForwardedHeader(forwarded string) (map[string]string, string, error) { - // Following are states of forwarded header parser. Any state could transition to a failure. - const ( - // terminating state; can transition to Parameter - stateElement = iota - // terminating state; can transition to KeyValueDelimiter - stateParameter - // can transition to Value - stateKeyValueDelimiter - // can transition to one of { QuotedValue, PairEnd } - stateValue - // can transition to one of { EscapedCharacter, PairEnd } - stateQuotedValue - // can transition to one of { QuotedValue } - stateEscapedCharacter - // terminating state; can transition to one of { Parameter, Element } - statePairEnd - ) - - var ( - parameter string - value string - parse = forwarded[:] - res = map[string]string{} - state = stateElement - ) - -Loop: - for { - // skip spaces unless in quoted value - if state != stateQuotedValue && state != stateEscapedCharacter { - parse = strings.TrimLeftFunc(parse, unicode.IsSpace) - } - - if len(parse) == 0 { - if state != stateElement && state != statePairEnd && state != stateParameter { - return nil, parse, fmt.Errorf("unexpected end of input") - } - // terminating - break - } - - switch state { - // terminate at list element delimiter - case stateElement: - if parse[0] == ',' { - parse = parse[1:] - break Loop - } - state = stateParameter - - // parse parameter (the key of key-value pair) - case stateParameter: - match := reToken.FindString(parse) - if len(match) == 0 { - return nil, parse, fmt.Errorf("failed to parse token at position %d", len(forwarded)-len(parse)) - } - parameter = strings.ToLower(match) - parse = parse[len(match):] - state = stateKeyValueDelimiter - - // parse '=' - case stateKeyValueDelimiter: - if parse[0] != '=' { - return nil, parse, fmt.Errorf("expected '=', not '%c' at position %d", parse[0], len(forwarded)-len(parse)) - } - parse = parse[1:] - state = stateValue - - // parse value or quoted value - case stateValue: - if parse[0] == '"' { - parse = parse[1:] - state = stateQuotedValue - } else { - value = reToken.FindString(parse) - if len(value) == 0 { - return nil, parse, fmt.Errorf("failed to parse value at position %d", len(forwarded)-len(parse)) - } - if _, exists := res[parameter]; exists { - return nil, parse, fmt.Errorf("duplicate parameter %q at position %d", parameter, len(forwarded)-len(parse)) - } - res[parameter] = value - parse = parse[len(value):] - value = "" - state = statePairEnd - } - - // parse a part of quoted value until the first backslash - case stateQuotedValue: - match := reQuotedValue.FindString(parse) - value += match - parse = parse[len(match):] - switch { - case len(parse) == 0: - return nil, parse, fmt.Errorf("unterminated quoted string") - case parse[0] == '"': - res[parameter] = value - value = "" - parse = parse[1:] - state = statePairEnd - case parse[0] == '\\': - parse = parse[1:] - state = stateEscapedCharacter - } - - // parse escaped character in a quoted string, ignore the backslash - // transition back to QuotedValue state - case stateEscapedCharacter: - c := reEscapedCharacter.FindString(parse) - if len(c) == 0 { - return nil, parse, fmt.Errorf("invalid escape sequence at position %d", len(forwarded)-len(parse)-1) - } - value += c - parse = parse[1:] - state = stateQuotedValue - - // expect either a new key-value pair, new list or end of input - case statePairEnd: - switch parse[0] { - case ';': - parse = parse[1:] - state = stateParameter - case ',': - state = stateElement - default: - return nil, parse, fmt.Errorf("expected ',' or ';', not %c at position %d", parse[0], len(forwarded)-len(parse)) - } - } - } - - return res, parse, nil -} diff --git a/vendor/github.com/docker/distribution/registry/api/v2/routes.go b/vendor/github.com/docker/distribution/registry/api/v2/routes.go deleted file mode 100644 index 9612ac2e5..000000000 --- a/vendor/github.com/docker/distribution/registry/api/v2/routes.go +++ /dev/null @@ -1,40 +0,0 @@ -package v2 - -import "github.com/gorilla/mux" - -// The following are definitions of the name under which all V2 routes are -// registered. These symbols can be used to look up a route based on the name. -const ( - RouteNameBase = "base" - RouteNameManifest = "manifest" - RouteNameTags = "tags" - RouteNameBlob = "blob" - RouteNameBlobUpload = "blob-upload" - RouteNameBlobUploadChunk = "blob-upload-chunk" - RouteNameCatalog = "catalog" -) - -// Router builds a gorilla router with named routes for the various API -// methods. This can be used directly by both server implementations and -// clients. -func Router() *mux.Router { - return RouterWithPrefix("") -} - -// RouterWithPrefix builds a gorilla router with a configured prefix -// on all routes. -func RouterWithPrefix(prefix string) *mux.Router { - rootRouter := mux.NewRouter() - router := rootRouter - if prefix != "" { - router = router.PathPrefix(prefix).Subrouter() - } - - router.StrictSlash(true) - - for _, descriptor := range routeDescriptors { - router.Path(descriptor.Path).Name(descriptor.Name) - } - - return rootRouter -} diff --git a/vendor/github.com/docker/distribution/registry/api/v2/urls.go b/vendor/github.com/docker/distribution/registry/api/v2/urls.go deleted file mode 100644 index ab6406335..000000000 --- a/vendor/github.com/docker/distribution/registry/api/v2/urls.go +++ /dev/null @@ -1,254 +0,0 @@ -package v2 - -import ( - "fmt" - "net/http" - "net/url" - "strings" - - "github.com/distribution/reference" - "github.com/gorilla/mux" -) - -// URLBuilder creates registry API urls from a single base endpoint. It can be -// used to create urls for use in a registry client or server. -// -// All urls will be created from the given base, including the api version. -// For example, if a root of "/foo/" is provided, urls generated will be fall -// under "/foo/v2/...". Most application will only provide a schema, host and -// port, such as "https://localhost:5000/". -type URLBuilder struct { - root *url.URL // url root (ie http://localhost/) - router *mux.Router - relative bool -} - -// NewURLBuilder creates a URLBuilder with provided root url object. -func NewURLBuilder(root *url.URL, relative bool) *URLBuilder { - return &URLBuilder{ - root: root, - router: Router(), - relative: relative, - } -} - -// NewURLBuilderFromString workes identically to NewURLBuilder except it takes -// a string argument for the root, returning an error if it is not a valid -// url. -func NewURLBuilderFromString(root string, relative bool) (*URLBuilder, error) { - u, err := url.Parse(root) - if err != nil { - return nil, err - } - - return NewURLBuilder(u, relative), nil -} - -// NewURLBuilderFromRequest uses information from an *http.Request to -// construct the root url. -func NewURLBuilderFromRequest(r *http.Request, relative bool) *URLBuilder { - var ( - scheme = "http" - host = r.Host - ) - - if r.TLS != nil { - scheme = "https" - } else if len(r.URL.Scheme) > 0 { - scheme = r.URL.Scheme - } - - // Handle fowarded headers - // Prefer "Forwarded" header as defined by rfc7239 if given - // see https://tools.ietf.org/html/rfc7239 - if forwarded := r.Header.Get("Forwarded"); len(forwarded) > 0 { - forwardedHeader, _, err := parseForwardedHeader(forwarded) - if err == nil { - if fproto := forwardedHeader["proto"]; len(fproto) > 0 { - scheme = fproto - } - if fhost := forwardedHeader["host"]; len(fhost) > 0 { - host = fhost - } - } - } else { - if forwardedProto := r.Header.Get("X-Forwarded-Proto"); len(forwardedProto) > 0 { - scheme = forwardedProto - } - if forwardedHost := r.Header.Get("X-Forwarded-Host"); len(forwardedHost) > 0 { - // According to the Apache mod_proxy docs, X-Forwarded-Host can be a - // comma-separated list of hosts, to which each proxy appends the - // requested host. We want to grab the first from this comma-separated - // list. - hosts := strings.SplitN(forwardedHost, ",", 2) - host = strings.TrimSpace(hosts[0]) - } - } - - basePath := routeDescriptorsMap[RouteNameBase].Path - - requestPath := r.URL.Path - index := strings.Index(requestPath, basePath) - - u := &url.URL{ - Scheme: scheme, - Host: host, - } - - if index > 0 { - // N.B. index+1 is important because we want to include the trailing / - u.Path = requestPath[0 : index+1] - } - - return NewURLBuilder(u, relative) -} - -// BuildBaseURL constructs a base url for the API, typically just "/v2/". -func (ub *URLBuilder) BuildBaseURL() (string, error) { - route := ub.cloneRoute(RouteNameBase) - - baseURL, err := route.URL() - if err != nil { - return "", err - } - - return baseURL.String(), nil -} - -// BuildCatalogURL constructs a url get a catalog of repositories -func (ub *URLBuilder) BuildCatalogURL(values ...url.Values) (string, error) { - route := ub.cloneRoute(RouteNameCatalog) - - catalogURL, err := route.URL() - if err != nil { - return "", err - } - - return appendValuesURL(catalogURL, values...).String(), nil -} - -// BuildTagsURL constructs a url to list the tags in the named repository. -func (ub *URLBuilder) BuildTagsURL(name reference.Named) (string, error) { - route := ub.cloneRoute(RouteNameTags) - - tagsURL, err := route.URL("name", name.Name()) - if err != nil { - return "", err - } - - return tagsURL.String(), nil -} - -// BuildManifestURL constructs a url for the manifest identified by name and -// reference. The argument reference may be either a tag or digest. -func (ub *URLBuilder) BuildManifestURL(ref reference.Named) (string, error) { - route := ub.cloneRoute(RouteNameManifest) - - tagOrDigest := "" - switch v := ref.(type) { - case reference.Tagged: - tagOrDigest = v.Tag() - case reference.Digested: - tagOrDigest = v.Digest().String() - default: - return "", fmt.Errorf("reference must have a tag or digest") - } - - manifestURL, err := route.URL("name", ref.Name(), "reference", tagOrDigest) - if err != nil { - return "", err - } - - return manifestURL.String(), nil -} - -// BuildBlobURL constructs the url for the blob identified by name and dgst. -func (ub *URLBuilder) BuildBlobURL(ref reference.Canonical) (string, error) { - route := ub.cloneRoute(RouteNameBlob) - - layerURL, err := route.URL("name", ref.Name(), "digest", ref.Digest().String()) - if err != nil { - return "", err - } - - return layerURL.String(), nil -} - -// BuildBlobUploadURL constructs a url to begin a blob upload in the -// repository identified by name. -func (ub *URLBuilder) BuildBlobUploadURL(name reference.Named, values ...url.Values) (string, error) { - route := ub.cloneRoute(RouteNameBlobUpload) - - uploadURL, err := route.URL("name", name.Name()) - if err != nil { - return "", err - } - - return appendValuesURL(uploadURL, values...).String(), nil -} - -// BuildBlobUploadChunkURL constructs a url for the upload identified by uuid, -// including any url values. This should generally not be used by clients, as -// this url is provided by server implementations during the blob upload -// process. -func (ub *URLBuilder) BuildBlobUploadChunkURL(name reference.Named, uuid string, values ...url.Values) (string, error) { - route := ub.cloneRoute(RouteNameBlobUploadChunk) - - uploadURL, err := route.URL("name", name.Name(), "uuid", uuid) - if err != nil { - return "", err - } - - return appendValuesURL(uploadURL, values...).String(), nil -} - -// clondedRoute returns a clone of the named route from the router. Routes -// must be cloned to avoid modifying them during url generation. -func (ub *URLBuilder) cloneRoute(name string) clonedRoute { - route := new(mux.Route) - root := new(url.URL) - - *route = *ub.router.GetRoute(name) // clone the route - *root = *ub.root - - return clonedRoute{Route: route, root: root, relative: ub.relative} -} - -type clonedRoute struct { - *mux.Route - root *url.URL - relative bool -} - -func (cr clonedRoute) URL(pairs ...string) (*url.URL, error) { - routeURL, err := cr.Route.URL(pairs...) - if err != nil { - return nil, err - } - - if cr.relative { - return routeURL, nil - } - - if routeURL.Scheme == "" && routeURL.User == nil && routeURL.Host == "" { - routeURL.Path = routeURL.Path[1:] - } - - url := cr.root.ResolveReference(routeURL) - url.Scheme = cr.root.Scheme - return url, nil -} - -// appendValuesURL appends the parameters to the url. -func appendValuesURL(u *url.URL, values ...url.Values) *url.URL { - merged := u.Query() - - for _, v := range values { - for k, vv := range v { - merged[k] = append(merged[k], vv...) - } - } - - u.RawQuery = merged.Encode() - return u -} diff --git a/vendor/github.com/docker/distribution/registry/client/auth/api_version.go b/vendor/github.com/docker/distribution/registry/client/auth/api_version.go deleted file mode 100644 index 7d8f1d957..000000000 --- a/vendor/github.com/docker/distribution/registry/client/auth/api_version.go +++ /dev/null @@ -1,58 +0,0 @@ -package auth - -import ( - "net/http" - "strings" -) - -// APIVersion represents a version of an API including its -// type and version number. -type APIVersion struct { - // Type refers to the name of a specific API specification - // such as "registry" - Type string - - // Version is the version of the API specification implemented, - // This may omit the revision number and only include - // the major and minor version, such as "2.0" - Version string -} - -// String returns the string formatted API Version -func (v APIVersion) String() string { - return v.Type + "/" + v.Version -} - -// APIVersions gets the API versions out of an HTTP response using the provided -// version header as the key for the HTTP header. -func APIVersions(resp *http.Response, versionHeader string) []APIVersion { - versions := []APIVersion{} - if versionHeader != "" { - for _, supportedVersions := range resp.Header[http.CanonicalHeaderKey(versionHeader)] { - for _, version := range strings.Fields(supportedVersions) { - versions = append(versions, ParseAPIVersion(version)) - } - } - } - return versions -} - -// ParseAPIVersion parses an API version string into an APIVersion -// Format (Expected, not enforced): -// API version string = '/' -// API type = [a-z][a-z0-9]* -// API version = [0-9]+(\.[0-9]+)? -// TODO(dmcgowan): Enforce format, add error condition, remove unknown type -func ParseAPIVersion(versionStr string) APIVersion { - idx := strings.IndexRune(versionStr, '/') - if idx == -1 { - return APIVersion{ - Type: "unknown", - Version: versionStr, - } - } - return APIVersion{ - Type: strings.ToLower(versionStr[:idx]), - Version: versionStr[idx+1:], - } -} diff --git a/vendor/github.com/docker/distribution/registry/client/auth/challenge/addr.go b/vendor/github.com/docker/distribution/registry/client/auth/challenge/addr.go deleted file mode 100644 index 2c3ebe165..000000000 --- a/vendor/github.com/docker/distribution/registry/client/auth/challenge/addr.go +++ /dev/null @@ -1,27 +0,0 @@ -package challenge - -import ( - "net/url" - "strings" -) - -// FROM: https://golang.org/src/net/http/http.go -// Given a string of the form "host", "host:port", or "[ipv6::address]:port", -// return true if the string includes a port. -func hasPort(s string) bool { return strings.LastIndex(s, ":") > strings.LastIndex(s, "]") } - -// FROM: http://golang.org/src/net/http/transport.go -var portMap = map[string]string{ - "http": "80", - "https": "443", -} - -// canonicalAddr returns url.Host but always with a ":port" suffix -// FROM: http://golang.org/src/net/http/transport.go -func canonicalAddr(url *url.URL) string { - addr := url.Host - if !hasPort(addr) { - return addr + ":" + portMap[url.Scheme] - } - return addr -} diff --git a/vendor/github.com/docker/distribution/registry/client/auth/challenge/authchallenge.go b/vendor/github.com/docker/distribution/registry/client/auth/challenge/authchallenge.go deleted file mode 100644 index fe238210c..000000000 --- a/vendor/github.com/docker/distribution/registry/client/auth/challenge/authchallenge.go +++ /dev/null @@ -1,237 +0,0 @@ -package challenge - -import ( - "fmt" - "net/http" - "net/url" - "strings" - "sync" -) - -// Challenge carries information from a WWW-Authenticate response header. -// See RFC 2617. -type Challenge struct { - // Scheme is the auth-scheme according to RFC 2617 - Scheme string - - // Parameters are the auth-params according to RFC 2617 - Parameters map[string]string -} - -// Manager manages the challenges for endpoints. -// The challenges are pulled out of HTTP responses. Only -// responses which expect challenges should be added to -// the manager, since a non-unauthorized request will be -// viewed as not requiring challenges. -type Manager interface { - // GetChallenges returns the challenges for the given - // endpoint URL. - GetChallenges(endpoint url.URL) ([]Challenge, error) - - // AddResponse adds the response to the challenge - // manager. The challenges will be parsed out of - // the WWW-Authenicate headers and added to the - // URL which was produced the response. If the - // response was authorized, any challenges for the - // endpoint will be cleared. - AddResponse(resp *http.Response) error -} - -// NewSimpleManager returns an instance of -// Manger which only maps endpoints to challenges -// based on the responses which have been added the -// manager. The simple manager will make no attempt to -// perform requests on the endpoints or cache the responses -// to a backend. -func NewSimpleManager() Manager { - return &simpleManager{ - Challenges: make(map[string][]Challenge), - } -} - -type simpleManager struct { - sync.RWMutex - Challenges map[string][]Challenge -} - -func normalizeURL(endpoint *url.URL) { - endpoint.Host = strings.ToLower(endpoint.Host) - endpoint.Host = canonicalAddr(endpoint) -} - -func (m *simpleManager) GetChallenges(endpoint url.URL) ([]Challenge, error) { - normalizeURL(&endpoint) - - m.RLock() - defer m.RUnlock() - challenges := m.Challenges[endpoint.String()] - return challenges, nil -} - -func (m *simpleManager) AddResponse(resp *http.Response) error { - challenges := ResponseChallenges(resp) - if resp.Request == nil { - return fmt.Errorf("missing request reference") - } - urlCopy := url.URL{ - Path: resp.Request.URL.Path, - Host: resp.Request.URL.Host, - Scheme: resp.Request.URL.Scheme, - } - normalizeURL(&urlCopy) - - m.Lock() - defer m.Unlock() - m.Challenges[urlCopy.String()] = challenges - return nil -} - -// Octet types from RFC 2616. -type octetType byte - -var octetTypes [256]octetType - -const ( - isToken octetType = 1 << iota - isSpace -) - -func init() { - // OCTET = - // CHAR = - // CTL = - // CR = - // LF = - // SP = - // HT = - // <"> = - // CRLF = CR LF - // LWS = [CRLF] 1*( SP | HT ) - // TEXT = - // separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <"> - // | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT - // token = 1* - // qdtext = > - - for c := 0; c < 256; c++ { - var t octetType - isCtl := c <= 31 || c == 127 - isChar := 0 <= c && c <= 127 - isSeparator := strings.ContainsRune(" \t\"(),/:;<=>?@[]\\{}", rune(c)) - if strings.ContainsRune(" \t\r\n", rune(c)) { - t |= isSpace - } - if isChar && !isCtl && !isSeparator { - t |= isToken - } - octetTypes[c] = t - } -} - -// ResponseChallenges returns a list of authorization challenges -// for the given http Response. Challenges are only checked if -// the response status code was a 401. -func ResponseChallenges(resp *http.Response) []Challenge { - if resp.StatusCode == http.StatusUnauthorized { - // Parse the WWW-Authenticate Header and store the challenges - // on this endpoint object. - return parseAuthHeader(resp.Header) - } - - return nil -} - -func parseAuthHeader(header http.Header) []Challenge { - challenges := []Challenge{} - for _, h := range header[http.CanonicalHeaderKey("WWW-Authenticate")] { - v, p := parseValueAndParams(h) - if v != "" { - challenges = append(challenges, Challenge{Scheme: v, Parameters: p}) - } - } - return challenges -} - -func parseValueAndParams(header string) (value string, params map[string]string) { - params = make(map[string]string) - value, s := expectToken(header) - if value == "" { - return - } - value = strings.ToLower(value) - s = "," + skipSpace(s) - for strings.HasPrefix(s, ",") { - var pkey string - pkey, s = expectToken(skipSpace(s[1:])) - if pkey == "" { - return - } - if !strings.HasPrefix(s, "=") { - return - } - var pvalue string - pvalue, s = expectTokenOrQuoted(s[1:]) - if pvalue == "" { - return - } - pkey = strings.ToLower(pkey) - params[pkey] = pvalue - s = skipSpace(s) - } - return -} - -func skipSpace(s string) (rest string) { - i := 0 - for ; i < len(s); i++ { - if octetTypes[s[i]]&isSpace == 0 { - break - } - } - return s[i:] -} - -func expectToken(s string) (token, rest string) { - i := 0 - for ; i < len(s); i++ { - if octetTypes[s[i]]&isToken == 0 { - break - } - } - return s[:i], s[i:] -} - -func expectTokenOrQuoted(s string) (value string, rest string) { - if !strings.HasPrefix(s, "\"") { - return expectToken(s) - } - s = s[1:] - for i := 0; i < len(s); i++ { - switch s[i] { - case '"': - return s[:i], s[i+1:] - case '\\': - p := make([]byte, len(s)-1) - j := copy(p, s[:i]) - escape := true - for i = i + 1; i < len(s); i++ { - b := s[i] - switch { - case escape: - escape = false - p[j] = b - j++ - case b == '\\': - escape = true - case b == '"': - return string(p[:j]), s[i+1:] - default: - p[j] = b - j++ - } - } - return "", "" - } - } - return "", "" -} diff --git a/vendor/github.com/docker/distribution/registry/client/auth/session.go b/vendor/github.com/docker/distribution/registry/client/auth/session.go deleted file mode 100644 index aad8a0e6f..000000000 --- a/vendor/github.com/docker/distribution/registry/client/auth/session.go +++ /dev/null @@ -1,530 +0,0 @@ -package auth - -import ( - "encoding/json" - "errors" - "fmt" - "net/http" - "net/url" - "strings" - "sync" - "time" - - "github.com/docker/distribution/registry/client" - "github.com/docker/distribution/registry/client/auth/challenge" - "github.com/docker/distribution/registry/client/transport" -) - -var ( - // ErrNoBasicAuthCredentials is returned if a request can't be authorized with - // basic auth due to lack of credentials. - ErrNoBasicAuthCredentials = errors.New("no basic auth credentials") - - // ErrNoToken is returned if a request is successful but the body does not - // contain an authorization token. - ErrNoToken = errors.New("authorization server did not include a token in the response") -) - -const defaultClientID = "registry-client" - -// AuthenticationHandler is an interface for authorizing a request from -// params from a "WWW-Authenicate" header for a single scheme. -type AuthenticationHandler interface { - // Scheme returns the scheme as expected from the "WWW-Authenicate" header. - Scheme() string - - // AuthorizeRequest adds the authorization header to a request (if needed) - // using the parameters from "WWW-Authenticate" method. The parameters - // values depend on the scheme. - AuthorizeRequest(req *http.Request, params map[string]string) error -} - -// CredentialStore is an interface for getting credentials for -// a given URL -type CredentialStore interface { - // Basic returns basic auth for the given URL - Basic(*url.URL) (string, string) - - // RefreshToken returns a refresh token for the - // given URL and service - RefreshToken(*url.URL, string) string - - // SetRefreshToken sets the refresh token if none - // is provided for the given url and service - SetRefreshToken(realm *url.URL, service, token string) -} - -// NewAuthorizer creates an authorizer which can handle multiple authentication -// schemes. The handlers are tried in order, the higher priority authentication -// methods should be first. The challengeMap holds a list of challenges for -// a given root API endpoint (for example "https://registry-1.docker.io/v2/"). -func NewAuthorizer(manager challenge.Manager, handlers ...AuthenticationHandler) transport.RequestModifier { - return &endpointAuthorizer{ - challenges: manager, - handlers: handlers, - } -} - -type endpointAuthorizer struct { - challenges challenge.Manager - handlers []AuthenticationHandler -} - -func (ea *endpointAuthorizer) ModifyRequest(req *http.Request) error { - pingPath := req.URL.Path - if v2Root := strings.Index(req.URL.Path, "/v2/"); v2Root != -1 { - pingPath = pingPath[:v2Root+4] - } else if v1Root := strings.Index(req.URL.Path, "/v1/"); v1Root != -1 { - pingPath = pingPath[:v1Root] + "/v2/" - } else { - return nil - } - - ping := url.URL{ - Host: req.URL.Host, - Scheme: req.URL.Scheme, - Path: pingPath, - } - - challenges, err := ea.challenges.GetChallenges(ping) - if err != nil { - return err - } - - if len(challenges) > 0 { - for _, handler := range ea.handlers { - for _, c := range challenges { - if c.Scheme != handler.Scheme() { - continue - } - if err := handler.AuthorizeRequest(req, c.Parameters); err != nil { - return err - } - } - } - } - - return nil -} - -// This is the minimum duration a token can last (in seconds). -// A token must not live less than 60 seconds because older versions -// of the Docker client didn't read their expiration from the token -// response and assumed 60 seconds. So to remain compatible with -// those implementations, a token must live at least this long. -const minimumTokenLifetimeSeconds = 60 - -// Private interface for time used by this package to enable tests to provide their own implementation. -type clock interface { - Now() time.Time -} - -type tokenHandler struct { - creds CredentialStore - transport http.RoundTripper - clock clock - - offlineAccess bool - forceOAuth bool - clientID string - scopes []Scope - - tokenLock sync.Mutex - tokenCache string - tokenExpiration time.Time - - logger Logger -} - -// Scope is a type which is serializable to a string -// using the allow scope grammar. -type Scope interface { - String() string -} - -// RepositoryScope represents a token scope for access -// to a repository. -type RepositoryScope struct { - Repository string - Class string - Actions []string -} - -// String returns the string representation of the repository -// using the scope grammar -func (rs RepositoryScope) String() string { - repoType := "repository" - // Keep existing format for image class to maintain backwards compatibility - // with authorization servers which do not support the expanded grammar. - if rs.Class != "" && rs.Class != "image" { - repoType = fmt.Sprintf("%s(%s)", repoType, rs.Class) - } - return fmt.Sprintf("%s:%s:%s", repoType, rs.Repository, strings.Join(rs.Actions, ",")) -} - -// RegistryScope represents a token scope for access -// to resources in the registry. -type RegistryScope struct { - Name string - Actions []string -} - -// String returns the string representation of the user -// using the scope grammar -func (rs RegistryScope) String() string { - return fmt.Sprintf("registry:%s:%s", rs.Name, strings.Join(rs.Actions, ",")) -} - -// Logger defines the injectable logging interface, used on TokenHandlers. -type Logger interface { - Debugf(format string, args ...interface{}) -} - -func logDebugf(logger Logger, format string, args ...interface{}) { - if logger == nil { - return - } - logger.Debugf(format, args...) -} - -// TokenHandlerOptions is used to configure a new token handler -type TokenHandlerOptions struct { - Transport http.RoundTripper - Credentials CredentialStore - - OfflineAccess bool - ForceOAuth bool - ClientID string - Scopes []Scope - Logger Logger -} - -// An implementation of clock for providing real time data. -type realClock struct{} - -// Now implements clock -func (realClock) Now() time.Time { return time.Now() } - -// NewTokenHandler creates a new AuthenicationHandler which supports -// fetching tokens from a remote token server. -func NewTokenHandler(transport http.RoundTripper, creds CredentialStore, scope string, actions ...string) AuthenticationHandler { - // Create options... - return NewTokenHandlerWithOptions(TokenHandlerOptions{ - Transport: transport, - Credentials: creds, - Scopes: []Scope{ - RepositoryScope{ - Repository: scope, - Actions: actions, - }, - }, - }) -} - -// NewTokenHandlerWithOptions creates a new token handler using the provided -// options structure. -func NewTokenHandlerWithOptions(options TokenHandlerOptions) AuthenticationHandler { - handler := &tokenHandler{ - transport: options.Transport, - creds: options.Credentials, - offlineAccess: options.OfflineAccess, - forceOAuth: options.ForceOAuth, - clientID: options.ClientID, - scopes: options.Scopes, - clock: realClock{}, - logger: options.Logger, - } - - return handler -} - -func (th *tokenHandler) client() *http.Client { - return &http.Client{ - Transport: th.transport, - Timeout: 15 * time.Second, - } -} - -func (th *tokenHandler) Scheme() string { - return "bearer" -} - -func (th *tokenHandler) AuthorizeRequest(req *http.Request, params map[string]string) error { - var additionalScopes []string - if fromParam := req.URL.Query().Get("from"); fromParam != "" { - additionalScopes = append(additionalScopes, RepositoryScope{ - Repository: fromParam, - Actions: []string{"pull"}, - }.String()) - } - - token, err := th.getToken(params, additionalScopes...) - if err != nil { - return err - } - - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) - - return nil -} - -func (th *tokenHandler) getToken(params map[string]string, additionalScopes ...string) (string, error) { - th.tokenLock.Lock() - defer th.tokenLock.Unlock() - scopes := make([]string, 0, len(th.scopes)+len(additionalScopes)) - for _, scope := range th.scopes { - scopes = append(scopes, scope.String()) - } - var addedScopes bool - for _, scope := range additionalScopes { - if hasScope(scopes, scope) { - continue - } - scopes = append(scopes, scope) - addedScopes = true - } - - now := th.clock.Now() - if now.After(th.tokenExpiration) || addedScopes { - token, expiration, err := th.fetchToken(params, scopes) - if err != nil { - return "", err - } - - // do not update cache for added scope tokens - if !addedScopes { - th.tokenCache = token - th.tokenExpiration = expiration - } - - return token, nil - } - - return th.tokenCache, nil -} - -func hasScope(scopes []string, scope string) bool { - for _, s := range scopes { - if s == scope { - return true - } - } - return false -} - -type postTokenResponse struct { - AccessToken string `json:"access_token"` - RefreshToken string `json:"refresh_token"` - ExpiresIn int `json:"expires_in"` - IssuedAt time.Time `json:"issued_at"` - Scope string `json:"scope"` -} - -func (th *tokenHandler) fetchTokenWithOAuth(realm *url.URL, refreshToken, service string, scopes []string) (token string, expiration time.Time, err error) { - form := url.Values{} - form.Set("scope", strings.Join(scopes, " ")) - form.Set("service", service) - - clientID := th.clientID - if clientID == "" { - // Use default client, this is a required field - clientID = defaultClientID - } - form.Set("client_id", clientID) - - if refreshToken != "" { - form.Set("grant_type", "refresh_token") - form.Set("refresh_token", refreshToken) - } else if th.creds != nil { - form.Set("grant_type", "password") - username, password := th.creds.Basic(realm) - form.Set("username", username) - form.Set("password", password) - - // attempt to get a refresh token - form.Set("access_type", "offline") - } else { - // refuse to do oauth without a grant type - return "", time.Time{}, fmt.Errorf("no supported grant type") - } - - resp, err := th.client().PostForm(realm.String(), form) - if err != nil { - return "", time.Time{}, err - } - defer resp.Body.Close() - - if !client.SuccessStatus(resp.StatusCode) { - err := client.HandleErrorResponse(resp) - return "", time.Time{}, err - } - - decoder := json.NewDecoder(resp.Body) - - var tr postTokenResponse - if err = decoder.Decode(&tr); err != nil { - return "", time.Time{}, fmt.Errorf("unable to decode token response: %s", err) - } - - if tr.RefreshToken != "" && tr.RefreshToken != refreshToken { - th.creds.SetRefreshToken(realm, service, tr.RefreshToken) - } - - if tr.ExpiresIn < minimumTokenLifetimeSeconds { - // The default/minimum lifetime. - tr.ExpiresIn = minimumTokenLifetimeSeconds - logDebugf(th.logger, "Increasing token expiration to: %d seconds", tr.ExpiresIn) - } - - if tr.IssuedAt.IsZero() { - // issued_at is optional in the token response. - tr.IssuedAt = th.clock.Now().UTC() - } - - return tr.AccessToken, tr.IssuedAt.Add(time.Duration(tr.ExpiresIn) * time.Second), nil -} - -type getTokenResponse struct { - Token string `json:"token"` - AccessToken string `json:"access_token"` - ExpiresIn int `json:"expires_in"` - IssuedAt time.Time `json:"issued_at"` - RefreshToken string `json:"refresh_token"` -} - -func (th *tokenHandler) fetchTokenWithBasicAuth(realm *url.URL, service string, scopes []string) (token string, expiration time.Time, err error) { - - req, err := http.NewRequest("GET", realm.String(), nil) - if err != nil { - return "", time.Time{}, err - } - - reqParams := req.URL.Query() - - if service != "" { - reqParams.Add("service", service) - } - - for _, scope := range scopes { - reqParams.Add("scope", scope) - } - - if th.offlineAccess { - reqParams.Add("offline_token", "true") - clientID := th.clientID - if clientID == "" { - clientID = defaultClientID - } - reqParams.Add("client_id", clientID) - } - - if th.creds != nil { - username, password := th.creds.Basic(realm) - if username != "" && password != "" { - reqParams.Add("account", username) - req.SetBasicAuth(username, password) - } - } - - req.URL.RawQuery = reqParams.Encode() - - resp, err := th.client().Do(req) - if err != nil { - return "", time.Time{}, err - } - defer resp.Body.Close() - - if !client.SuccessStatus(resp.StatusCode) { - err := client.HandleErrorResponse(resp) - return "", time.Time{}, err - } - - decoder := json.NewDecoder(resp.Body) - - var tr getTokenResponse - if err = decoder.Decode(&tr); err != nil { - return "", time.Time{}, fmt.Errorf("unable to decode token response: %s", err) - } - - if tr.RefreshToken != "" && th.creds != nil { - th.creds.SetRefreshToken(realm, service, tr.RefreshToken) - } - - // `access_token` is equivalent to `token` and if both are specified - // the choice is undefined. Canonicalize `access_token` by sticking - // things in `token`. - if tr.AccessToken != "" { - tr.Token = tr.AccessToken - } - - if tr.Token == "" { - return "", time.Time{}, ErrNoToken - } - - if tr.ExpiresIn < minimumTokenLifetimeSeconds { - // The default/minimum lifetime. - tr.ExpiresIn = minimumTokenLifetimeSeconds - logDebugf(th.logger, "Increasing token expiration to: %d seconds", tr.ExpiresIn) - } - - if tr.IssuedAt.IsZero() { - // issued_at is optional in the token response. - tr.IssuedAt = th.clock.Now().UTC() - } - - return tr.Token, tr.IssuedAt.Add(time.Duration(tr.ExpiresIn) * time.Second), nil -} - -func (th *tokenHandler) fetchToken(params map[string]string, scopes []string) (token string, expiration time.Time, err error) { - realm, ok := params["realm"] - if !ok { - return "", time.Time{}, errors.New("no realm specified for token auth challenge") - } - - // TODO(dmcgowan): Handle empty scheme and relative realm - realmURL, err := url.Parse(realm) - if err != nil { - return "", time.Time{}, fmt.Errorf("invalid token auth challenge realm: %s", err) - } - - service := params["service"] - - var refreshToken string - - if th.creds != nil { - refreshToken = th.creds.RefreshToken(realmURL, service) - } - - if refreshToken != "" || th.forceOAuth { - return th.fetchTokenWithOAuth(realmURL, refreshToken, service, scopes) - } - - return th.fetchTokenWithBasicAuth(realmURL, service, scopes) -} - -type basicHandler struct { - creds CredentialStore -} - -// NewBasicHandler creaters a new authentiation handler which adds -// basic authentication credentials to a request. -func NewBasicHandler(creds CredentialStore) AuthenticationHandler { - return &basicHandler{ - creds: creds, - } -} - -func (*basicHandler) Scheme() string { - return "basic" -} - -func (bh *basicHandler) AuthorizeRequest(req *http.Request, params map[string]string) error { - if bh.creds != nil { - username, password := bh.creds.Basic(req.URL) - if username != "" && password != "" { - req.SetBasicAuth(username, password) - return nil - } - } - return ErrNoBasicAuthCredentials -} diff --git a/vendor/github.com/docker/distribution/registry/client/blob_writer.go b/vendor/github.com/docker/distribution/registry/client/blob_writer.go deleted file mode 100644 index dac030c73..000000000 --- a/vendor/github.com/docker/distribution/registry/client/blob_writer.go +++ /dev/null @@ -1,164 +0,0 @@ -package client - -import ( - "bytes" - "context" - "fmt" - "io" - "io/ioutil" - "net/http" - "time" - - "github.com/docker/distribution" -) - -type httpBlobUpload struct { - statter distribution.BlobStatter - client *http.Client - - uuid string - startedAt time.Time - - location string // always the last value of the location header. - offset int64 - closed bool -} - -func (hbu *httpBlobUpload) Reader() (io.ReadCloser, error) { - panic("Not implemented") -} - -func (hbu *httpBlobUpload) handleErrorResponse(resp *http.Response) error { - if resp.StatusCode == http.StatusNotFound { - return distribution.ErrBlobUploadUnknown - } - return HandleErrorResponse(resp) -} - -func (hbu *httpBlobUpload) ReadFrom(r io.Reader) (n int64, err error) { - req, err := http.NewRequest("PATCH", hbu.location, ioutil.NopCloser(r)) - if err != nil { - return 0, err - } - defer req.Body.Close() - - req.Header.Set("Content-Type", "application/octet-stream") - - resp, err := hbu.client.Do(req) - if err != nil { - return 0, err - } - - if !SuccessStatus(resp.StatusCode) { - return 0, hbu.handleErrorResponse(resp) - } - - hbu.uuid = resp.Header.Get("Docker-Upload-UUID") - hbu.location, err = sanitizeLocation(resp.Header.Get("Location"), hbu.location) - if err != nil { - return 0, err - } - rng := resp.Header.Get("Range") - var start, end int64 - if n, err := fmt.Sscanf(rng, "%d-%d", &start, &end); err != nil { - return 0, err - } else if n != 2 || end < start { - return 0, fmt.Errorf("bad range format: %s", rng) - } - - return (end - start + 1), nil - -} - -func (hbu *httpBlobUpload) Write(p []byte) (n int, err error) { - req, err := http.NewRequest("PATCH", hbu.location, bytes.NewReader(p)) - if err != nil { - return 0, err - } - req.Header.Set("Content-Range", fmt.Sprintf("%d-%d", hbu.offset, hbu.offset+int64(len(p)-1))) - req.Header.Set("Content-Length", fmt.Sprintf("%d", len(p))) - req.Header.Set("Content-Type", "application/octet-stream") - - resp, err := hbu.client.Do(req) - if err != nil { - return 0, err - } - - if !SuccessStatus(resp.StatusCode) { - return 0, hbu.handleErrorResponse(resp) - } - - hbu.uuid = resp.Header.Get("Docker-Upload-UUID") - hbu.location, err = sanitizeLocation(resp.Header.Get("Location"), hbu.location) - if err != nil { - return 0, err - } - rng := resp.Header.Get("Range") - var start, end int - if n, err := fmt.Sscanf(rng, "%d-%d", &start, &end); err != nil { - return 0, err - } else if n != 2 || end < start { - return 0, fmt.Errorf("bad range format: %s", rng) - } - - return (end - start + 1), nil - -} - -func (hbu *httpBlobUpload) Size() int64 { - return hbu.offset -} - -func (hbu *httpBlobUpload) ID() string { - return hbu.uuid -} - -func (hbu *httpBlobUpload) StartedAt() time.Time { - return hbu.startedAt -} - -func (hbu *httpBlobUpload) Commit(ctx context.Context, desc distribution.Descriptor) (distribution.Descriptor, error) { - // TODO(dmcgowan): Check if already finished, if so just fetch - req, err := http.NewRequest("PUT", hbu.location, nil) - if err != nil { - return distribution.Descriptor{}, err - } - - values := req.URL.Query() - values.Set("digest", desc.Digest.String()) - req.URL.RawQuery = values.Encode() - - resp, err := hbu.client.Do(req) - if err != nil { - return distribution.Descriptor{}, err - } - defer resp.Body.Close() - - if !SuccessStatus(resp.StatusCode) { - return distribution.Descriptor{}, hbu.handleErrorResponse(resp) - } - - return hbu.statter.Stat(ctx, desc.Digest) -} - -func (hbu *httpBlobUpload) Cancel(ctx context.Context) error { - req, err := http.NewRequest("DELETE", hbu.location, nil) - if err != nil { - return err - } - resp, err := hbu.client.Do(req) - if err != nil { - return err - } - defer resp.Body.Close() - - if resp.StatusCode == http.StatusNotFound || SuccessStatus(resp.StatusCode) { - return nil - } - return hbu.handleErrorResponse(resp) -} - -func (hbu *httpBlobUpload) Close() error { - hbu.closed = true - return nil -} diff --git a/vendor/github.com/docker/distribution/registry/client/errors.go b/vendor/github.com/docker/distribution/registry/client/errors.go deleted file mode 100644 index ce9902034..000000000 --- a/vendor/github.com/docker/distribution/registry/client/errors.go +++ /dev/null @@ -1,160 +0,0 @@ -package client - -import ( - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "mime" - "net/http" - - "github.com/docker/distribution/registry/api/errcode" - "github.com/docker/distribution/registry/client/auth/challenge" -) - -// ErrNoErrorsInBody is returned when an HTTP response body parses to an empty -// errcode.Errors slice. -var ErrNoErrorsInBody = errors.New("no error details found in HTTP response body") - -// UnexpectedHTTPStatusError is returned when an unexpected HTTP status is -// returned when making a registry api call. -type UnexpectedHTTPStatusError struct { - Status string -} - -func (e *UnexpectedHTTPStatusError) Error() string { - return fmt.Sprintf("received unexpected HTTP status: %s", e.Status) -} - -// UnexpectedHTTPResponseError is returned when an expected HTTP status code -// is returned, but the content was unexpected and failed to be parsed. -type UnexpectedHTTPResponseError struct { - ParseErr error - StatusCode int - Response []byte -} - -func (e *UnexpectedHTTPResponseError) Error() string { - return fmt.Sprintf("error parsing HTTP %d response body: %s: %q", e.StatusCode, e.ParseErr.Error(), string(e.Response)) -} - -func parseHTTPErrorResponse(resp *http.Response) error { - var errors errcode.Errors - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - - statusCode := resp.StatusCode - ctHeader := resp.Header.Get("Content-Type") - - if ctHeader == "" { - return makeError(statusCode, string(body)) - } - - contentType, _, err := mime.ParseMediaType(ctHeader) - if err != nil { - return fmt.Errorf("failed parsing content-type: %w", err) - } - - if contentType != "application/json" && contentType != "application/vnd.api+json" { - return makeError(statusCode, string(body)) - } - - // For backward compatibility, handle irregularly formatted - // messages that contain a "details" field. - var detailsErr struct { - Details string `json:"details"` - } - err = json.Unmarshal(body, &detailsErr) - if err == nil && detailsErr.Details != "" { - return makeError(statusCode, detailsErr.Details) - } - - if err := json.Unmarshal(body, &errors); err != nil { - return &UnexpectedHTTPResponseError{ - ParseErr: err, - StatusCode: statusCode, - Response: body, - } - } - - if len(errors) == 0 { - // If there was no error specified in the body, return - // UnexpectedHTTPResponseError. - return &UnexpectedHTTPResponseError{ - ParseErr: ErrNoErrorsInBody, - StatusCode: statusCode, - Response: body, - } - } - - return errors -} - -func makeError(statusCode int, details string) error { - switch statusCode { - case http.StatusUnauthorized: - return errcode.ErrorCodeUnauthorized.WithMessage(details) - case http.StatusForbidden: - return errcode.ErrorCodeDenied.WithMessage(details) - case http.StatusTooManyRequests: - return errcode.ErrorCodeTooManyRequests.WithMessage(details) - default: - return errcode.ErrorCodeUnknown.WithMessage(details) - } -} - -func makeErrorList(err error) []error { - if errL, ok := err.(errcode.Errors); ok { - return []error(errL) - } - return []error{err} -} - -func mergeErrors(err1, err2 error) error { - return errcode.Errors(append(makeErrorList(err1), makeErrorList(err2)...)) -} - -// HandleErrorResponse returns error parsed from HTTP response for an -// unsuccessful HTTP response code (in the range 400 - 499 inclusive). An -// UnexpectedHTTPStatusError returned for response code outside of expected -// range. -func HandleErrorResponse(resp *http.Response) error { - if resp.StatusCode >= 400 && resp.StatusCode < 500 { - // Check for OAuth errors within the `WWW-Authenticate` header first - // See https://tools.ietf.org/html/rfc6750#section-3 - for _, c := range challenge.ResponseChallenges(resp) { - if c.Scheme == "bearer" { - var err errcode.Error - // codes defined at https://tools.ietf.org/html/rfc6750#section-3.1 - switch c.Parameters["error"] { - case "invalid_token": - err.Code = errcode.ErrorCodeUnauthorized - case "insufficient_scope": - err.Code = errcode.ErrorCodeDenied - default: - continue - } - if description := c.Parameters["error_description"]; description != "" { - err.Message = description - } else { - err.Message = err.Code.Message() - } - return mergeErrors(err, parseHTTPErrorResponse(resp)) - } - } - err := parseHTTPErrorResponse(resp) - if uErr, ok := err.(*UnexpectedHTTPResponseError); ok && resp.StatusCode == 401 { - return errcode.ErrorCodeUnauthorized.WithDetail(uErr.Response) - } - return err - } - return &UnexpectedHTTPStatusError{Status: resp.Status} -} - -// SuccessStatus returns true if the argument is a successful HTTP response -// code (in the range 200 - 399 inclusive). -func SuccessStatus(status int) bool { - return status >= 200 && status <= 399 -} diff --git a/vendor/github.com/docker/distribution/registry/client/repository.go b/vendor/github.com/docker/distribution/registry/client/repository.go deleted file mode 100644 index fd42a1e66..000000000 --- a/vendor/github.com/docker/distribution/registry/client/repository.go +++ /dev/null @@ -1,870 +0,0 @@ -package client - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "strconv" - "strings" - "time" - - "github.com/distribution/reference" - "github.com/docker/distribution" - v2 "github.com/docker/distribution/registry/api/v2" - "github.com/docker/distribution/registry/client/transport" - "github.com/docker/distribution/registry/storage/cache" - "github.com/docker/distribution/registry/storage/cache/memory" - "github.com/opencontainers/go-digest" -) - -// Registry provides an interface for calling Repositories, which returns a catalog of repositories. -type Registry interface { - Repositories(ctx context.Context, repos []string, last string) (n int, err error) -} - -// checkHTTPRedirect is a callback that can manipulate redirected HTTP -// requests. It is used to preserve Accept and Range headers. -func checkHTTPRedirect(req *http.Request, via []*http.Request) error { - if len(via) >= 10 { - return errors.New("stopped after 10 redirects") - } - - if len(via) > 0 { - for headerName, headerVals := range via[0].Header { - if headerName != "Accept" && headerName != "Range" { - continue - } - for _, val := range headerVals { - // Don't add to redirected request if redirected - // request already has a header with the same - // name and value. - hasValue := false - for _, existingVal := range req.Header[headerName] { - if existingVal == val { - hasValue = true - break - } - } - if !hasValue { - req.Header.Add(headerName, val) - } - } - } - } - - return nil -} - -// NewRegistry creates a registry namespace which can be used to get a listing of repositories -func NewRegistry(baseURL string, transport http.RoundTripper) (Registry, error) { - ub, err := v2.NewURLBuilderFromString(baseURL, false) - if err != nil { - return nil, err - } - - client := &http.Client{ - Transport: transport, - Timeout: 1 * time.Minute, - CheckRedirect: checkHTTPRedirect, - } - - return ®istry{ - client: client, - ub: ub, - }, nil -} - -type registry struct { - client *http.Client - ub *v2.URLBuilder -} - -// Repositories returns a lexigraphically sorted catalog given a base URL. The 'entries' slice will be filled up to the size -// of the slice, starting at the value provided in 'last'. The number of entries will be returned along with io.EOF if there -// are no more entries -func (r *registry) Repositories(ctx context.Context, entries []string, last string) (int, error) { - var numFilled int - var returnErr error - - values := buildCatalogValues(len(entries), last) - u, err := r.ub.BuildCatalogURL(values) - if err != nil { - return 0, err - } - - resp, err := r.client.Get(u) - if err != nil { - return 0, err - } - defer resp.Body.Close() - - if SuccessStatus(resp.StatusCode) { - var ctlg struct { - Repositories []string `json:"repositories"` - } - decoder := json.NewDecoder(resp.Body) - - if err := decoder.Decode(&ctlg); err != nil { - return 0, err - } - - copy(entries, ctlg.Repositories) - numFilled = len(ctlg.Repositories) - - link := resp.Header.Get("Link") - if link == "" { - returnErr = io.EOF - } - } else { - return 0, HandleErrorResponse(resp) - } - - return numFilled, returnErr -} - -// NewRepository creates a new Repository for the given repository name and base URL. -func NewRepository(name reference.Named, baseURL string, transport http.RoundTripper) (distribution.Repository, error) { - ub, err := v2.NewURLBuilderFromString(baseURL, false) - if err != nil { - return nil, err - } - - client := &http.Client{ - Transport: transport, - CheckRedirect: checkHTTPRedirect, - // TODO(dmcgowan): create cookie jar - } - - return &repository{ - client: client, - ub: ub, - name: name, - }, nil -} - -type repository struct { - client *http.Client - ub *v2.URLBuilder - name reference.Named -} - -func (r *repository) Named() reference.Named { - return r.name -} - -func (r *repository) Blobs(ctx context.Context) distribution.BlobStore { - statter := &blobStatter{ - name: r.name, - ub: r.ub, - client: r.client, - } - return &blobs{ - name: r.name, - ub: r.ub, - client: r.client, - statter: cache.NewCachedBlobStatter(memory.NewInMemoryBlobDescriptorCacheProvider(), statter), - } -} - -func (r *repository) Manifests(ctx context.Context, options ...distribution.ManifestServiceOption) (distribution.ManifestService, error) { - // todo(richardscothern): options should be sent over the wire - return &manifests{ - name: r.name, - ub: r.ub, - client: r.client, - etags: make(map[string]string), - }, nil -} - -func (r *repository) Tags(ctx context.Context) distribution.TagService { - return &tags{ - client: r.client, - ub: r.ub, - name: r.Named(), - } -} - -// tags implements remote tagging operations. -type tags struct { - client *http.Client - ub *v2.URLBuilder - name reference.Named -} - -// All returns all tags -func (t *tags) All(ctx context.Context) ([]string, error) { - var tags []string - - listURLStr, err := t.ub.BuildTagsURL(t.name) - if err != nil { - return tags, err - } - - listURL, err := url.Parse(listURLStr) - if err != nil { - return tags, err - } - - for { - resp, err := t.client.Get(listURL.String()) - if err != nil { - return tags, err - } - defer resp.Body.Close() - - if SuccessStatus(resp.StatusCode) { - b, err := ioutil.ReadAll(resp.Body) - if err != nil { - return tags, err - } - - tagsResponse := struct { - Tags []string `json:"tags"` - }{} - if err := json.Unmarshal(b, &tagsResponse); err != nil { - return tags, err - } - tags = append(tags, tagsResponse.Tags...) - if link := resp.Header.Get("Link"); link != "" { - linkURLStr := strings.Trim(strings.Split(link, ";")[0], "<>") - linkURL, err := url.Parse(linkURLStr) - if err != nil { - return tags, err - } - - listURL = listURL.ResolveReference(linkURL) - } else { - return tags, nil - } - } else { - return tags, HandleErrorResponse(resp) - } - } -} - -func descriptorFromResponse(response *http.Response) (distribution.Descriptor, error) { - desc := distribution.Descriptor{} - headers := response.Header - - ctHeader := headers.Get("Content-Type") - if ctHeader == "" { - return distribution.Descriptor{}, errors.New("missing or empty Content-Type header") - } - desc.MediaType = ctHeader - - digestHeader := headers.Get("Docker-Content-Digest") - if digestHeader == "" { - bytes, err := ioutil.ReadAll(response.Body) - if err != nil { - return distribution.Descriptor{}, err - } - _, desc, err := distribution.UnmarshalManifest(ctHeader, bytes) - if err != nil { - return distribution.Descriptor{}, err - } - return desc, nil - } - - dgst, err := digest.Parse(digestHeader) - if err != nil { - return distribution.Descriptor{}, err - } - desc.Digest = dgst - - lengthHeader := headers.Get("Content-Length") - if lengthHeader == "" { - return distribution.Descriptor{}, errors.New("missing or empty Content-Length header") - } - length, err := strconv.ParseInt(lengthHeader, 10, 64) - if err != nil { - return distribution.Descriptor{}, err - } - desc.Size = length - - return desc, nil - -} - -// Get issues a HEAD request for a Manifest against its named endpoint in order -// to construct a descriptor for the tag. If the registry doesn't support HEADing -// a manifest, fallback to GET. -func (t *tags) Get(ctx context.Context, tag string) (distribution.Descriptor, error) { - ref, err := reference.WithTag(t.name, tag) - if err != nil { - return distribution.Descriptor{}, err - } - u, err := t.ub.BuildManifestURL(ref) - if err != nil { - return distribution.Descriptor{}, err - } - - newRequest := func(method string) (*http.Response, error) { - req, err := http.NewRequest(method, u, nil) - if err != nil { - return nil, err - } - - for _, t := range distribution.ManifestMediaTypes() { - req.Header.Add("Accept", t) - } - resp, err := t.client.Do(req) - return resp, err - } - - resp, err := newRequest("HEAD") - if err != nil { - return distribution.Descriptor{}, err - } - defer resp.Body.Close() - - switch { - case resp.StatusCode >= 200 && resp.StatusCode < 400 && len(resp.Header.Get("Docker-Content-Digest")) > 0: - // if the response is a success AND a Docker-Content-Digest can be retrieved from the headers - return descriptorFromResponse(resp) - default: - // if the response is an error - there will be no body to decode. - // Issue a GET request: - // - for data from a server that does not handle HEAD - // - to get error details in case of a failure - resp, err = newRequest("GET") - if err != nil { - return distribution.Descriptor{}, err - } - defer resp.Body.Close() - - if resp.StatusCode >= 200 && resp.StatusCode < 400 { - return descriptorFromResponse(resp) - } - return distribution.Descriptor{}, HandleErrorResponse(resp) - } -} - -func (t *tags) Lookup(ctx context.Context, digest distribution.Descriptor) ([]string, error) { - panic("not implemented") -} - -func (t *tags) Tag(ctx context.Context, tag string, desc distribution.Descriptor) error { - panic("not implemented") -} - -func (t *tags) Untag(ctx context.Context, tag string) error { - panic("not implemented") -} - -type manifests struct { - name reference.Named - ub *v2.URLBuilder - client *http.Client - etags map[string]string -} - -func (ms *manifests) Exists(ctx context.Context, dgst digest.Digest) (bool, error) { - ref, err := reference.WithDigest(ms.name, dgst) - if err != nil { - return false, err - } - u, err := ms.ub.BuildManifestURL(ref) - if err != nil { - return false, err - } - - resp, err := ms.client.Head(u) - if err != nil { - return false, err - } - - if SuccessStatus(resp.StatusCode) { - return true, nil - } else if resp.StatusCode == http.StatusNotFound { - return false, nil - } - return false, HandleErrorResponse(resp) -} - -// AddEtagToTag allows a client to supply an eTag to Get which will be -// used for a conditional HTTP request. If the eTag matches, a nil manifest -// and ErrManifestNotModified error will be returned. etag is automatically -// quoted when added to this map. -func AddEtagToTag(tag, etag string) distribution.ManifestServiceOption { - return etagOption{tag, etag} -} - -type etagOption struct{ tag, etag string } - -func (o etagOption) Apply(ms distribution.ManifestService) error { - if ms, ok := ms.(*manifests); ok { - ms.etags[o.tag] = fmt.Sprintf(`"%s"`, o.etag) - return nil - } - return fmt.Errorf("etag options is a client-only option") -} - -// ReturnContentDigest allows a client to set a the content digest on -// a successful request from the 'Docker-Content-Digest' header. This -// returned digest is represents the digest which the registry uses -// to refer to the content and can be used to delete the content. -func ReturnContentDigest(dgst *digest.Digest) distribution.ManifestServiceOption { - return contentDigestOption{dgst} -} - -type contentDigestOption struct{ digest *digest.Digest } - -func (o contentDigestOption) Apply(ms distribution.ManifestService) error { - return nil -} - -func (ms *manifests) Get(ctx context.Context, dgst digest.Digest, options ...distribution.ManifestServiceOption) (distribution.Manifest, error) { - var ( - digestOrTag string - ref reference.Named - err error - contentDgst *digest.Digest - mediaTypes []string - ) - - for _, option := range options { - switch opt := option.(type) { - case distribution.WithTagOption: - digestOrTag = opt.Tag - ref, err = reference.WithTag(ms.name, opt.Tag) - if err != nil { - return nil, err - } - case contentDigestOption: - contentDgst = opt.digest - case distribution.WithManifestMediaTypesOption: - mediaTypes = opt.MediaTypes - default: - err := option.Apply(ms) - if err != nil { - return nil, err - } - } - } - - if digestOrTag == "" { - digestOrTag = dgst.String() - ref, err = reference.WithDigest(ms.name, dgst) - if err != nil { - return nil, err - } - } - - if len(mediaTypes) == 0 { - mediaTypes = distribution.ManifestMediaTypes() - } - - u, err := ms.ub.BuildManifestURL(ref) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("GET", u, nil) - if err != nil { - return nil, err - } - - for _, t := range mediaTypes { - req.Header.Add("Accept", t) - } - - if _, ok := ms.etags[digestOrTag]; ok { - req.Header.Set("If-None-Match", ms.etags[digestOrTag]) - } - - resp, err := ms.client.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - if resp.StatusCode == http.StatusNotModified { - return nil, distribution.ErrManifestNotModified - } else if SuccessStatus(resp.StatusCode) { - if contentDgst != nil { - dgst, err := digest.Parse(resp.Header.Get("Docker-Content-Digest")) - if err == nil { - *contentDgst = dgst - } - } - mt := resp.Header.Get("Content-Type") - body, err := ioutil.ReadAll(resp.Body) - - if err != nil { - return nil, err - } - m, _, err := distribution.UnmarshalManifest(mt, body) - if err != nil { - return nil, err - } - return m, nil - } - return nil, HandleErrorResponse(resp) -} - -// Put puts a manifest. A tag can be specified using an options parameter which uses some shared state to hold the -// tag name in order to build the correct upload URL. -func (ms *manifests) Put(ctx context.Context, m distribution.Manifest, options ...distribution.ManifestServiceOption) (digest.Digest, error) { - ref := ms.name - var tagged bool - - for _, option := range options { - if opt, ok := option.(distribution.WithTagOption); ok { - var err error - ref, err = reference.WithTag(ref, opt.Tag) - if err != nil { - return "", err - } - tagged = true - } else { - err := option.Apply(ms) - if err != nil { - return "", err - } - } - } - mediaType, p, err := m.Payload() - if err != nil { - return "", err - } - - if !tagged { - // generate a canonical digest and Put by digest - _, d, err := distribution.UnmarshalManifest(mediaType, p) - if err != nil { - return "", err - } - ref, err = reference.WithDigest(ref, d.Digest) - if err != nil { - return "", err - } - } - - manifestURL, err := ms.ub.BuildManifestURL(ref) - if err != nil { - return "", err - } - - putRequest, err := http.NewRequest("PUT", manifestURL, bytes.NewReader(p)) - if err != nil { - return "", err - } - - putRequest.Header.Set("Content-Type", mediaType) - - resp, err := ms.client.Do(putRequest) - if err != nil { - return "", err - } - defer resp.Body.Close() - - if SuccessStatus(resp.StatusCode) { - dgstHeader := resp.Header.Get("Docker-Content-Digest") - dgst, err := digest.Parse(dgstHeader) - if err != nil { - return "", err - } - - return dgst, nil - } - - return "", HandleErrorResponse(resp) -} - -func (ms *manifests) Delete(ctx context.Context, dgst digest.Digest) error { - ref, err := reference.WithDigest(ms.name, dgst) - if err != nil { - return err - } - u, err := ms.ub.BuildManifestURL(ref) - if err != nil { - return err - } - req, err := http.NewRequest("DELETE", u, nil) - if err != nil { - return err - } - - resp, err := ms.client.Do(req) - if err != nil { - return err - } - defer resp.Body.Close() - - if SuccessStatus(resp.StatusCode) { - return nil - } - return HandleErrorResponse(resp) -} - -// todo(richardscothern): Restore interface and implementation with merge of #1050 -/*func (ms *manifests) Enumerate(ctx context.Context, manifests []distribution.Manifest, last distribution.Manifest) (n int, err error) { - panic("not supported") -}*/ - -type blobs struct { - name reference.Named - ub *v2.URLBuilder - client *http.Client - - statter distribution.BlobDescriptorService - distribution.BlobDeleter -} - -func sanitizeLocation(location, base string) (string, error) { - baseURL, err := url.Parse(base) - if err != nil { - return "", err - } - - locationURL, err := url.Parse(location) - if err != nil { - return "", err - } - - return baseURL.ResolveReference(locationURL).String(), nil -} - -func (bs *blobs) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) { - return bs.statter.Stat(ctx, dgst) - -} - -func (bs *blobs) Get(ctx context.Context, dgst digest.Digest) ([]byte, error) { - reader, err := bs.Open(ctx, dgst) - if err != nil { - return nil, err - } - defer reader.Close() - - return ioutil.ReadAll(reader) -} - -func (bs *blobs) Open(ctx context.Context, dgst digest.Digest) (distribution.ReadSeekCloser, error) { - ref, err := reference.WithDigest(bs.name, dgst) - if err != nil { - return nil, err - } - blobURL, err := bs.ub.BuildBlobURL(ref) - if err != nil { - return nil, err - } - - return transport.NewHTTPReadSeeker(bs.client, blobURL, - func(resp *http.Response) error { - if resp.StatusCode == http.StatusNotFound { - return distribution.ErrBlobUnknown - } - return HandleErrorResponse(resp) - }), nil -} - -func (bs *blobs) ServeBlob(ctx context.Context, w http.ResponseWriter, r *http.Request, dgst digest.Digest) error { - panic("not implemented") -} - -func (bs *blobs) Put(ctx context.Context, mediaType string, p []byte) (distribution.Descriptor, error) { - writer, err := bs.Create(ctx) - if err != nil { - return distribution.Descriptor{}, err - } - dgstr := digest.Canonical.Digester() - n, err := io.Copy(writer, io.TeeReader(bytes.NewReader(p), dgstr.Hash())) - if err != nil { - return distribution.Descriptor{}, err - } - if n < int64(len(p)) { - return distribution.Descriptor{}, fmt.Errorf("short copy: wrote %d of %d", n, len(p)) - } - - desc := distribution.Descriptor{ - MediaType: mediaType, - Size: int64(len(p)), - Digest: dgstr.Digest(), - } - - return writer.Commit(ctx, desc) -} - -type optionFunc func(interface{}) error - -func (f optionFunc) Apply(v interface{}) error { - return f(v) -} - -// WithMountFrom returns a BlobCreateOption which designates that the blob should be -// mounted from the given canonical reference. -func WithMountFrom(ref reference.Canonical) distribution.BlobCreateOption { - return optionFunc(func(v interface{}) error { - opts, ok := v.(*distribution.CreateOptions) - if !ok { - return fmt.Errorf("unexpected options type: %T", v) - } - - opts.Mount.ShouldMount = true - opts.Mount.From = ref - - return nil - }) -} - -func (bs *blobs) Create(ctx context.Context, options ...distribution.BlobCreateOption) (distribution.BlobWriter, error) { - var opts distribution.CreateOptions - - for _, option := range options { - err := option.Apply(&opts) - if err != nil { - return nil, err - } - } - - var values []url.Values - - if opts.Mount.ShouldMount { - values = append(values, url.Values{"from": {opts.Mount.From.Name()}, "mount": {opts.Mount.From.Digest().String()}}) - } - - u, err := bs.ub.BuildBlobUploadURL(bs.name, values...) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", u, nil) - if err != nil { - return nil, err - } - - resp, err := bs.client.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - switch resp.StatusCode { - case http.StatusCreated: - desc, err := bs.statter.Stat(ctx, opts.Mount.From.Digest()) - if err != nil { - return nil, err - } - return nil, distribution.ErrBlobMounted{From: opts.Mount.From, Descriptor: desc} - case http.StatusAccepted: - // TODO(dmcgowan): Check for invalid UUID - uuid := resp.Header.Get("Docker-Upload-UUID") - location, err := sanitizeLocation(resp.Header.Get("Location"), u) - if err != nil { - return nil, err - } - - return &httpBlobUpload{ - statter: bs.statter, - client: bs.client, - uuid: uuid, - startedAt: time.Now(), - location: location, - }, nil - default: - return nil, HandleErrorResponse(resp) - } -} - -func (bs *blobs) Resume(ctx context.Context, id string) (distribution.BlobWriter, error) { - panic("not implemented") -} - -func (bs *blobs) Delete(ctx context.Context, dgst digest.Digest) error { - return bs.statter.Clear(ctx, dgst) -} - -type blobStatter struct { - name reference.Named - ub *v2.URLBuilder - client *http.Client -} - -func (bs *blobStatter) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) { - ref, err := reference.WithDigest(bs.name, dgst) - if err != nil { - return distribution.Descriptor{}, err - } - u, err := bs.ub.BuildBlobURL(ref) - if err != nil { - return distribution.Descriptor{}, err - } - - resp, err := bs.client.Head(u) - if err != nil { - return distribution.Descriptor{}, err - } - defer resp.Body.Close() - - if SuccessStatus(resp.StatusCode) { - lengthHeader := resp.Header.Get("Content-Length") - if lengthHeader == "" { - return distribution.Descriptor{}, fmt.Errorf("missing content-length header for request: %s", u) - } - - length, err := strconv.ParseInt(lengthHeader, 10, 64) - if err != nil { - return distribution.Descriptor{}, fmt.Errorf("error parsing content-length: %v", err) - } - - return distribution.Descriptor{ - MediaType: resp.Header.Get("Content-Type"), - Size: length, - Digest: dgst, - }, nil - } else if resp.StatusCode == http.StatusNotFound { - return distribution.Descriptor{}, distribution.ErrBlobUnknown - } - return distribution.Descriptor{}, HandleErrorResponse(resp) -} - -func buildCatalogValues(maxEntries int, last string) url.Values { - values := url.Values{} - - if maxEntries > 0 { - values.Add("n", strconv.Itoa(maxEntries)) - } - - if last != "" { - values.Add("last", last) - } - - return values -} - -func (bs *blobStatter) Clear(ctx context.Context, dgst digest.Digest) error { - ref, err := reference.WithDigest(bs.name, dgst) - if err != nil { - return err - } - blobURL, err := bs.ub.BuildBlobURL(ref) - if err != nil { - return err - } - - req, err := http.NewRequest("DELETE", blobURL, nil) - if err != nil { - return err - } - - resp, err := bs.client.Do(req) - if err != nil { - return err - } - defer resp.Body.Close() - - if SuccessStatus(resp.StatusCode) { - return nil - } - return HandleErrorResponse(resp) -} - -func (bs *blobStatter) SetDescriptor(ctx context.Context, dgst digest.Digest, desc distribution.Descriptor) error { - return nil -} diff --git a/vendor/github.com/docker/distribution/registry/client/transport/http_reader.go b/vendor/github.com/docker/distribution/registry/client/transport/http_reader.go deleted file mode 100644 index 9120dbed6..000000000 --- a/vendor/github.com/docker/distribution/registry/client/transport/http_reader.go +++ /dev/null @@ -1,249 +0,0 @@ -package transport - -import ( - "errors" - "fmt" - "io" - "net/http" - "regexp" - "strconv" -) - -var ( - contentRangeRegexp = regexp.MustCompile(`bytes ([0-9]+)-([0-9]+)/([0-9]+|\\*)`) - - // ErrWrongCodeForByteRange is returned if the client sends a request - // with a Range header but the server returns a 2xx or 3xx code other - // than 206 Partial Content. - ErrWrongCodeForByteRange = errors.New("expected HTTP 206 from byte range request") -) - -// ReadSeekCloser combines io.ReadSeeker with io.Closer. -type ReadSeekCloser interface { - io.ReadSeeker - io.Closer -} - -// NewHTTPReadSeeker handles reading from an HTTP endpoint using a GET -// request. When seeking and starting a read from a non-zero offset -// the a "Range" header will be added which sets the offset. -// TODO(dmcgowan): Move this into a separate utility package -func NewHTTPReadSeeker(client *http.Client, url string, errorHandler func(*http.Response) error) ReadSeekCloser { - return &httpReadSeeker{ - client: client, - url: url, - errorHandler: errorHandler, - } -} - -type httpReadSeeker struct { - client *http.Client - url string - - // errorHandler creates an error from an unsuccessful HTTP response. - // This allows the error to be created with the HTTP response body - // without leaking the body through a returned error. - errorHandler func(*http.Response) error - - size int64 - - // rc is the remote read closer. - rc io.ReadCloser - // readerOffset tracks the offset as of the last read. - readerOffset int64 - // seekOffset allows Seek to override the offset. Seek changes - // seekOffset instead of changing readOffset directly so that - // connection resets can be delayed and possibly avoided if the - // seek is undone (i.e. seeking to the end and then back to the - // beginning). - seekOffset int64 - err error -} - -func (hrs *httpReadSeeker) Read(p []byte) (n int, err error) { - if hrs.err != nil { - return 0, hrs.err - } - - // If we sought to a different position, we need to reset the - // connection. This logic is here instead of Seek so that if - // a seek is undone before the next read, the connection doesn't - // need to be closed and reopened. A common example of this is - // seeking to the end to determine the length, and then seeking - // back to the original position. - if hrs.readerOffset != hrs.seekOffset { - hrs.reset() - } - - hrs.readerOffset = hrs.seekOffset - - rd, err := hrs.reader() - if err != nil { - return 0, err - } - - n, err = rd.Read(p) - hrs.seekOffset += int64(n) - hrs.readerOffset += int64(n) - - return n, err -} - -func (hrs *httpReadSeeker) Seek(offset int64, whence int) (int64, error) { - if hrs.err != nil { - return 0, hrs.err - } - - lastReaderOffset := hrs.readerOffset - - if whence == io.SeekStart && hrs.rc == nil { - // If no request has been made yet, and we are seeking to an - // absolute position, set the read offset as well to avoid an - // unnecessary request. - hrs.readerOffset = offset - } - - _, err := hrs.reader() - if err != nil { - hrs.readerOffset = lastReaderOffset - return 0, err - } - - newOffset := hrs.seekOffset - - switch whence { - case io.SeekCurrent: - newOffset += offset - case io.SeekEnd: - if hrs.size < 0 { - return 0, errors.New("content length not known") - } - newOffset = hrs.size + offset - case io.SeekStart: - newOffset = offset - } - - if newOffset < 0 { - err = errors.New("cannot seek to negative position") - } else { - hrs.seekOffset = newOffset - } - - return hrs.seekOffset, err -} - -func (hrs *httpReadSeeker) Close() error { - if hrs.err != nil { - return hrs.err - } - - // close and release reader chain - if hrs.rc != nil { - hrs.rc.Close() - } - - hrs.rc = nil - - hrs.err = errors.New("httpLayer: closed") - - return nil -} - -func (hrs *httpReadSeeker) reset() { - if hrs.err != nil { - return - } - if hrs.rc != nil { - hrs.rc.Close() - hrs.rc = nil - } -} - -func (hrs *httpReadSeeker) reader() (io.Reader, error) { - if hrs.err != nil { - return nil, hrs.err - } - - if hrs.rc != nil { - return hrs.rc, nil - } - - req, err := http.NewRequest("GET", hrs.url, nil) - if err != nil { - return nil, err - } - - if hrs.readerOffset > 0 { - // If we are at different offset, issue a range request from there. - req.Header.Add("Range", fmt.Sprintf("bytes=%d-", hrs.readerOffset)) - // TODO: get context in here - // context.GetLogger(hrs.context).Infof("Range: %s", req.Header.Get("Range")) - } - - resp, err := hrs.client.Do(req) - if err != nil { - return nil, err - } - - // Normally would use client.SuccessStatus, but that would be a cyclic - // import - if resp.StatusCode >= 200 && resp.StatusCode <= 399 { - if hrs.readerOffset > 0 { - if resp.StatusCode != http.StatusPartialContent { - return nil, ErrWrongCodeForByteRange - } - - contentRange := resp.Header.Get("Content-Range") - if contentRange == "" { - return nil, errors.New("no Content-Range header found in HTTP 206 response") - } - - submatches := contentRangeRegexp.FindStringSubmatch(contentRange) - if len(submatches) < 4 { - return nil, fmt.Errorf("could not parse Content-Range header: %s", contentRange) - } - - startByte, err := strconv.ParseUint(submatches[1], 10, 64) - if err != nil { - return nil, fmt.Errorf("could not parse start of range in Content-Range header: %s", contentRange) - } - - if startByte != uint64(hrs.readerOffset) { - return nil, fmt.Errorf("received Content-Range starting at offset %d instead of requested %d", startByte, hrs.readerOffset) - } - - endByte, err := strconv.ParseUint(submatches[2], 10, 64) - if err != nil { - return nil, fmt.Errorf("could not parse end of range in Content-Range header: %s", contentRange) - } - - if submatches[3] == "*" { - hrs.size = -1 - } else { - size, err := strconv.ParseUint(submatches[3], 10, 64) - if err != nil { - return nil, fmt.Errorf("could not parse total size in Content-Range header: %s", contentRange) - } - - if endByte+1 != size { - return nil, fmt.Errorf("range in Content-Range stops before the end of the content: %s", contentRange) - } - - hrs.size = int64(size) - } - } else if resp.StatusCode == http.StatusOK { - hrs.size = resp.ContentLength - } else { - hrs.size = -1 - } - hrs.rc = resp.Body - } else { - defer resp.Body.Close() - if hrs.errorHandler != nil { - return nil, hrs.errorHandler(resp) - } - return nil, fmt.Errorf("unexpected status resolving reader: %v", resp.Status) - } - - return hrs.rc, nil -} diff --git a/vendor/github.com/docker/distribution/registry/client/transport/transport.go b/vendor/github.com/docker/distribution/registry/client/transport/transport.go deleted file mode 100644 index 30e45fab0..000000000 --- a/vendor/github.com/docker/distribution/registry/client/transport/transport.go +++ /dev/null @@ -1,147 +0,0 @@ -package transport - -import ( - "io" - "net/http" - "sync" -) - -// RequestModifier represents an object which will do an inplace -// modification of an HTTP request. -type RequestModifier interface { - ModifyRequest(*http.Request) error -} - -type headerModifier http.Header - -// NewHeaderRequestModifier returns a new RequestModifier which will -// add the given headers to a request. -func NewHeaderRequestModifier(header http.Header) RequestModifier { - return headerModifier(header) -} - -func (h headerModifier) ModifyRequest(req *http.Request) error { - for k, s := range http.Header(h) { - req.Header[k] = append(req.Header[k], s...) - } - - return nil -} - -// NewTransport creates a new transport which will apply modifiers to -// the request on a RoundTrip call. -func NewTransport(base http.RoundTripper, modifiers ...RequestModifier) http.RoundTripper { - return &transport{ - Modifiers: modifiers, - Base: base, - } -} - -// transport is an http.RoundTripper that makes HTTP requests after -// copying and modifying the request -type transport struct { - Modifiers []RequestModifier - Base http.RoundTripper - - mu sync.Mutex // guards modReq - modReq map[*http.Request]*http.Request // original -> modified -} - -// RoundTrip authorizes and authenticates the request with an -// access token. If no token exists or token is expired, -// tries to refresh/fetch a new token. -func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) { - req2 := cloneRequest(req) - for _, modifier := range t.Modifiers { - if err := modifier.ModifyRequest(req2); err != nil { - return nil, err - } - } - - t.setModReq(req, req2) - res, err := t.base().RoundTrip(req2) - 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 -} - -// CancelRequest cancels an in-flight request by closing its connection. -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) - } -} - -func (t *transport) base() http.RoundTripper { - if t.Base != nil { - return t.Base - } - 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 { - // shallow copy of the struct - r2 := new(http.Request) - *r2 = *r - // deep copy of the Header - r2.Header = make(http.Header, len(r.Header)) - for k, s := range r.Header { - r2.Header[k] = append([]string(nil), s...) - } - - 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/github.com/docker/distribution/registry/storage/cache/cache.go b/vendor/github.com/docker/distribution/registry/storage/cache/cache.go deleted file mode 100644 index 10a390919..000000000 --- a/vendor/github.com/docker/distribution/registry/storage/cache/cache.go +++ /dev/null @@ -1,35 +0,0 @@ -// Package cache provides facilities to speed up access to the storage -// backend. -package cache - -import ( - "fmt" - - "github.com/docker/distribution" -) - -// BlobDescriptorCacheProvider provides repository scoped -// BlobDescriptorService cache instances and a global descriptor cache. -type BlobDescriptorCacheProvider interface { - distribution.BlobDescriptorService - - RepositoryScoped(repo string) (distribution.BlobDescriptorService, error) -} - -// ValidateDescriptor provides a helper function to ensure that caches have -// common criteria for admitting descriptors. -func ValidateDescriptor(desc distribution.Descriptor) error { - if err := desc.Digest.Validate(); err != nil { - return err - } - - if desc.Size < 0 { - return fmt.Errorf("cache: invalid length in descriptor: %v < 0", desc.Size) - } - - if desc.MediaType == "" { - return fmt.Errorf("cache: empty mediatype on descriptor: %v", desc) - } - - return nil -} diff --git a/vendor/github.com/docker/distribution/registry/storage/cache/cachedblobdescriptorstore.go b/vendor/github.com/docker/distribution/registry/storage/cache/cachedblobdescriptorstore.go deleted file mode 100644 index ac4c45211..000000000 --- a/vendor/github.com/docker/distribution/registry/storage/cache/cachedblobdescriptorstore.go +++ /dev/null @@ -1,129 +0,0 @@ -package cache - -import ( - "context" - - "github.com/docker/distribution" - prometheus "github.com/docker/distribution/metrics" - "github.com/opencontainers/go-digest" -) - -// Metrics is used to hold metric counters -// related to the number of times a cache was -// hit or missed. -type Metrics struct { - Requests uint64 - Hits uint64 - Misses uint64 -} - -// Logger can be provided on the MetricsTracker to log errors. -// -// Usually, this is just a proxy to dcontext.GetLogger. -type Logger interface { - Errorf(format string, args ...interface{}) -} - -// MetricsTracker represents a metric tracker -// which simply counts the number of hits and misses. -type MetricsTracker interface { - Hit() - Miss() - Metrics() Metrics - Logger(context.Context) Logger -} - -type cachedBlobStatter struct { - cache distribution.BlobDescriptorService - backend distribution.BlobDescriptorService - tracker MetricsTracker -} - -var ( - // cacheCount is the number of total cache request received/hits/misses - cacheCount = prometheus.StorageNamespace.NewLabeledCounter("cache", "The number of cache request received", "type") -) - -// NewCachedBlobStatter creates a new statter which prefers a cache and -// falls back to a backend. -func NewCachedBlobStatter(cache distribution.BlobDescriptorService, backend distribution.BlobDescriptorService) distribution.BlobDescriptorService { - return &cachedBlobStatter{ - cache: cache, - backend: backend, - } -} - -// NewCachedBlobStatterWithMetrics creates a new statter which prefers a cache and -// falls back to a backend. Hits and misses will send to the tracker. -func NewCachedBlobStatterWithMetrics(cache distribution.BlobDescriptorService, backend distribution.BlobDescriptorService, tracker MetricsTracker) distribution.BlobStatter { - return &cachedBlobStatter{ - cache: cache, - backend: backend, - tracker: tracker, - } -} - -func (cbds *cachedBlobStatter) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) { - cacheCount.WithValues("Request").Inc(1) - desc, err := cbds.cache.Stat(ctx, dgst) - if err != nil { - if err != distribution.ErrBlobUnknown { - logErrorf(ctx, cbds.tracker, "error retrieving descriptor from cache: %v", err) - } - - goto fallback - } - cacheCount.WithValues("Hit").Inc(1) - if cbds.tracker != nil { - cbds.tracker.Hit() - } - return desc, nil -fallback: - cacheCount.WithValues("Miss").Inc(1) - if cbds.tracker != nil { - cbds.tracker.Miss() - } - desc, err = cbds.backend.Stat(ctx, dgst) - if err != nil { - return desc, err - } - - if err := cbds.cache.SetDescriptor(ctx, dgst, desc); err != nil { - logErrorf(ctx, cbds.tracker, "error adding descriptor %v to cache: %v", desc.Digest, err) - } - - return desc, err - -} - -func (cbds *cachedBlobStatter) Clear(ctx context.Context, dgst digest.Digest) error { - err := cbds.cache.Clear(ctx, dgst) - if err != nil { - return err - } - - err = cbds.backend.Clear(ctx, dgst) - if err != nil { - return err - } - return nil -} - -func (cbds *cachedBlobStatter) SetDescriptor(ctx context.Context, dgst digest.Digest, desc distribution.Descriptor) error { - if err := cbds.cache.SetDescriptor(ctx, dgst, desc); err != nil { - logErrorf(ctx, cbds.tracker, "error adding descriptor %v to cache: %v", desc.Digest, err) - } - return nil -} - -func logErrorf(ctx context.Context, tracker MetricsTracker, format string, args ...interface{}) { - if tracker == nil { - return - } - - logger := tracker.Logger(ctx) - if logger == nil { - return - } - logger.Errorf(format, args...) -} diff --git a/vendor/github.com/docker/distribution/registry/storage/cache/memory/memory.go b/vendor/github.com/docker/distribution/registry/storage/cache/memory/memory.go deleted file mode 100644 index f2953b02c..000000000 --- a/vendor/github.com/docker/distribution/registry/storage/cache/memory/memory.go +++ /dev/null @@ -1,179 +0,0 @@ -package memory - -import ( - "context" - "sync" - - "github.com/distribution/reference" - "github.com/docker/distribution" - "github.com/docker/distribution/registry/storage/cache" - "github.com/opencontainers/go-digest" -) - -type inMemoryBlobDescriptorCacheProvider struct { - global *mapBlobDescriptorCache - repositories map[string]*mapBlobDescriptorCache - mu sync.RWMutex -} - -// NewInMemoryBlobDescriptorCacheProvider returns a new mapped-based cache for -// storing blob descriptor data. -func NewInMemoryBlobDescriptorCacheProvider() cache.BlobDescriptorCacheProvider { - return &inMemoryBlobDescriptorCacheProvider{ - global: newMapBlobDescriptorCache(), - repositories: make(map[string]*mapBlobDescriptorCache), - } -} - -func (imbdcp *inMemoryBlobDescriptorCacheProvider) RepositoryScoped(repo string) (distribution.BlobDescriptorService, error) { - if _, err := reference.ParseNormalizedNamed(repo); err != nil { - return nil, err - } - - imbdcp.mu.RLock() - defer imbdcp.mu.RUnlock() - - return &repositoryScopedInMemoryBlobDescriptorCache{ - repo: repo, - parent: imbdcp, - repository: imbdcp.repositories[repo], - }, nil -} - -func (imbdcp *inMemoryBlobDescriptorCacheProvider) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) { - return imbdcp.global.Stat(ctx, dgst) -} - -func (imbdcp *inMemoryBlobDescriptorCacheProvider) Clear(ctx context.Context, dgst digest.Digest) error { - return imbdcp.global.Clear(ctx, dgst) -} - -func (imbdcp *inMemoryBlobDescriptorCacheProvider) SetDescriptor(ctx context.Context, dgst digest.Digest, desc distribution.Descriptor) error { - _, err := imbdcp.Stat(ctx, dgst) - if err == distribution.ErrBlobUnknown { - - if dgst.Algorithm() != desc.Digest.Algorithm() && dgst != desc.Digest { - // if the digests differ, set the other canonical mapping - if err := imbdcp.global.SetDescriptor(ctx, desc.Digest, desc); err != nil { - return err - } - } - - // unknown, just set it - return imbdcp.global.SetDescriptor(ctx, dgst, desc) - } - - // we already know it, do nothing - return err -} - -// repositoryScopedInMemoryBlobDescriptorCache provides the request scoped -// repository cache. Instances are not thread-safe but the delegated -// operations are. -type repositoryScopedInMemoryBlobDescriptorCache struct { - repo string - parent *inMemoryBlobDescriptorCacheProvider // allows lazy allocation of repo's map - repository *mapBlobDescriptorCache -} - -func (rsimbdcp *repositoryScopedInMemoryBlobDescriptorCache) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) { - rsimbdcp.parent.mu.Lock() - repo := rsimbdcp.repository - rsimbdcp.parent.mu.Unlock() - - if repo == nil { - return distribution.Descriptor{}, distribution.ErrBlobUnknown - } - - return repo.Stat(ctx, dgst) -} - -func (rsimbdcp *repositoryScopedInMemoryBlobDescriptorCache) Clear(ctx context.Context, dgst digest.Digest) error { - rsimbdcp.parent.mu.Lock() - repo := rsimbdcp.repository - rsimbdcp.parent.mu.Unlock() - - if repo == nil { - return distribution.ErrBlobUnknown - } - - return repo.Clear(ctx, dgst) -} - -func (rsimbdcp *repositoryScopedInMemoryBlobDescriptorCache) SetDescriptor(ctx context.Context, dgst digest.Digest, desc distribution.Descriptor) error { - rsimbdcp.parent.mu.Lock() - repo := rsimbdcp.repository - if repo == nil { - // allocate map since we are setting it now. - var ok bool - // have to read back value since we may have allocated elsewhere. - repo, ok = rsimbdcp.parent.repositories[rsimbdcp.repo] - if !ok { - repo = newMapBlobDescriptorCache() - rsimbdcp.parent.repositories[rsimbdcp.repo] = repo - } - rsimbdcp.repository = repo - } - rsimbdcp.parent.mu.Unlock() - - if err := repo.SetDescriptor(ctx, dgst, desc); err != nil { - return err - } - - return rsimbdcp.parent.SetDescriptor(ctx, dgst, desc) -} - -// mapBlobDescriptorCache provides a simple map-based implementation of the -// descriptor cache. -type mapBlobDescriptorCache struct { - descriptors map[digest.Digest]distribution.Descriptor - mu sync.RWMutex -} - -var _ distribution.BlobDescriptorService = &mapBlobDescriptorCache{} - -func newMapBlobDescriptorCache() *mapBlobDescriptorCache { - return &mapBlobDescriptorCache{ - descriptors: make(map[digest.Digest]distribution.Descriptor), - } -} - -func (mbdc *mapBlobDescriptorCache) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) { - if err := dgst.Validate(); err != nil { - return distribution.Descriptor{}, err - } - - mbdc.mu.RLock() - defer mbdc.mu.RUnlock() - - desc, ok := mbdc.descriptors[dgst] - if !ok { - return distribution.Descriptor{}, distribution.ErrBlobUnknown - } - - return desc, nil -} - -func (mbdc *mapBlobDescriptorCache) Clear(ctx context.Context, dgst digest.Digest) error { - mbdc.mu.Lock() - defer mbdc.mu.Unlock() - - delete(mbdc.descriptors, dgst) - return nil -} - -func (mbdc *mapBlobDescriptorCache) SetDescriptor(ctx context.Context, dgst digest.Digest, desc distribution.Descriptor) error { - if err := dgst.Validate(); err != nil { - return err - } - - if err := cache.ValidateDescriptor(desc); err != nil { - return err - } - - mbdc.mu.Lock() - defer mbdc.mu.Unlock() - - mbdc.descriptors[dgst] = desc - return nil -} diff --git a/vendor/github.com/docker/distribution/tags.go b/vendor/github.com/docker/distribution/tags.go deleted file mode 100644 index f22df2b85..000000000 --- a/vendor/github.com/docker/distribution/tags.go +++ /dev/null @@ -1,27 +0,0 @@ -package distribution - -import ( - "context" -) - -// TagService provides access to information about tagged objects. -type TagService interface { - // Get retrieves the descriptor identified by the tag. Some - // implementations may differentiate between "trusted" tags and - // "untrusted" tags. If a tag is "untrusted", the mapping will be returned - // as an ErrTagUntrusted error, with the target descriptor. - Get(ctx context.Context, tag string) (Descriptor, error) - - // Tag associates the tag with the provided descriptor, updating the - // current association, if needed. - Tag(ctx context.Context, tag string, desc Descriptor) error - - // Untag removes the given tag association - Untag(ctx context.Context, tag string) error - - // All returns the set of tags managed by this tag service - All(ctx context.Context) ([]string, error) - - // Lookup returns the set of tags referencing the given digest. - Lookup(ctx context.Context, digest Descriptor) ([]string, error) -} diff --git a/vendor/github.com/docker/distribution/uuid/uuid.go b/vendor/github.com/docker/distribution/uuid/uuid.go deleted file mode 100644 index d433ccaf5..000000000 --- a/vendor/github.com/docker/distribution/uuid/uuid.go +++ /dev/null @@ -1,126 +0,0 @@ -// Package uuid provides simple UUID generation. Only version 4 style UUIDs -// can be generated. -// -// Please see http://tools.ietf.org/html/rfc4122 for details on UUIDs. -package uuid - -import ( - "crypto/rand" - "fmt" - "io" - "os" - "syscall" - "time" -) - -const ( - // Bits is the number of bits in a UUID - Bits = 128 - - // Size is the number of bytes in a UUID - Size = Bits / 8 - - format = "%08x-%04x-%04x-%04x-%012x" -) - -var ( - // ErrUUIDInvalid indicates a parsed string is not a valid uuid. - ErrUUIDInvalid = fmt.Errorf("invalid uuid") - - // Loggerf can be used to override the default logging destination. Such - // log messages in this library should be logged at warning or higher. - Loggerf = func(format string, args ...interface{}) {} -) - -// UUID represents a UUID value. UUIDs can be compared and set to other values -// and accessed by byte. -type UUID [Size]byte - -// Generate creates a new, version 4 uuid. -func Generate() (u UUID) { - const ( - // ensures we backoff for less than 450ms total. Use the following to - // select new value, in units of 10ms: - // n*(n+1)/2 = d -> n^2 + n - 2d -> n = (sqrt(8d + 1) - 1)/2 - maxretries = 9 - backoff = time.Millisecond * 10 - ) - - var ( - totalBackoff time.Duration - count int - retries int - ) - - for { - // This should never block but the read may fail. Because of this, - // we just try to read the random number generator until we get - // something. This is a very rare condition but may happen. - b := time.Duration(retries) * backoff - time.Sleep(b) - totalBackoff += b - - n, err := io.ReadFull(rand.Reader, u[count:]) - if err != nil { - if retryOnError(err) && retries < maxretries { - count += n - retries++ - Loggerf("error generating version 4 uuid, retrying: %v", err) - continue - } - - // Any other errors represent a system problem. What did someone - // do to /dev/urandom? - panic(fmt.Errorf("error reading random number generator, retried for %v: %v", totalBackoff.String(), err)) - } - - break - } - - u[6] = (u[6] & 0x0f) | 0x40 // set version byte - u[8] = (u[8] & 0x3f) | 0x80 // set high order byte 0b10{8,9,a,b} - - return u -} - -// Parse attempts to extract a uuid from the string or returns an error. -func Parse(s string) (u UUID, err error) { - if len(s) != 36 { - return UUID{}, ErrUUIDInvalid - } - - // create stack addresses for each section of the uuid. - p := make([][]byte, 5) - - if _, err := fmt.Sscanf(s, format, &p[0], &p[1], &p[2], &p[3], &p[4]); err != nil { - return u, err - } - - copy(u[0:4], p[0]) - copy(u[4:6], p[1]) - copy(u[6:8], p[2]) - copy(u[8:10], p[3]) - copy(u[10:16], p[4]) - - return -} - -func (u UUID) String() string { - return fmt.Sprintf(format, u[:4], u[4:6], u[6:8], u[8:10], u[10:]) -} - -// retryOnError tries to detect whether or not retrying would be fruitful. -func retryOnError(err error) bool { - switch err := err.(type) { - case *os.PathError: - return retryOnError(err.Err) // unpack the target error - case syscall.Errno: - if err == syscall.EPERM { - // EPERM represents an entropy pool exhaustion, a condition under - // which we backoff and retry. - return true - } - } - - return false -} diff --git a/vendor/github.com/docker/distribution/vendor.conf b/vendor/github.com/docker/distribution/vendor.conf deleted file mode 100644 index 20818428f..000000000 --- a/vendor/github.com/docker/distribution/vendor.conf +++ /dev/null @@ -1,52 +0,0 @@ -github.com/Azure/azure-sdk-for-go 4650843026a7fdec254a8d9cf893693a254edd0b -github.com/Azure/go-autorest eaa7994b2278094c904d31993d26f56324db3052 -github.com/sirupsen/logrus 3d4380f53a34dcdc95f0c1db702615992b38d9a4 -github.com/aws/aws-sdk-go f831d5a0822a1ad72420ab18c6269bca1ddaf490 -github.com/bshuster-repo/logrus-logstash-hook d2c0ecc1836d91814e15e23bb5dc309c3ef51f4a -github.com/beorn7/perks 4c0e84591b9aa9e6dcfdf3e020114cd81f89d5f9 -github.com/bugsnag/bugsnag-go b1d153021fcd90ca3f080db36bec96dc690fb274 -github.com/bugsnag/osext 0dd3f918b21bec95ace9dc86c7e70266cfc5c702 -github.com/bugsnag/panicwrap e2c28503fcd0675329da73bf48b33404db873782 -github.com/denverdino/aliyungo afedced274aa9a7fcdd47ac97018f0f8db4e5de2 -github.com/dgrijalva/jwt-go 4bbdd8ac624fc7a9ef7aec841c43d99b5fe65a29 https://github.com/golang-jwt/jwt.git # v3.2.2 -github.com/distribution/reference 49c28499d219290c3226822e9cfcd4ede6d75379 # v0.5.0 -github.com/docker/go-metrics 399ea8c73916000c64c2c76e8da00ca82f8387ab -github.com/docker/libtrust fa567046d9b14f6aa788882a950d69651d230b21 -github.com/garyburd/redigo 535138d7bcd717d6531c701ef5933d98b1866257 -github.com/go-ini/ini 2ba15ac2dc9cdf88c110ec2dc0ced7fa45f5678c -github.com/golang/protobuf 8d92cf5fc15a4382f8964b08e1f42a75c0591aa3 -github.com/gorilla/handlers 60c7bfde3e33c201519a200a4507a158cc03a17b -github.com/gorilla/mux 599cba5e7b6137d46ddf58fb1765f5d928e69604 -github.com/inconshreveable/mousetrap 76626ae9c91c4f2a10f34cad8ce83ea42c93bb75 -github.com/jmespath/go-jmespath bd40a432e4c76585ef6b72d3fd96fb9b6dc7b68d -github.com/marstr/guid 8bd9a64bf37eb297b492a4101fb28e80ac0b290f -github.com/satori/go.uuid f58768cc1a7a7e77a3bd49e98cdd21419399b6a3 -github.com/matttproud/golang_protobuf_extensions c12348ce28de40eed0136aa2b644d0ee0650e56c -github.com/miekg/dns 271c58e0c14f552178ea321a545ff9af38930f39 -github.com/mitchellh/mapstructure 482a9fd5fa83e8c4e7817413b80f3eb8feec03ef -github.com/ncw/swift a0320860b16212c2b59b4912bb6508cda1d7cee6 -github.com/prometheus/client_golang c332b6f63c0658a65eca15c0e5247ded801cf564 -github.com/prometheus/client_model 99fa1f4be8e564e8a6b613da7fa6f46c9edafc6c -github.com/prometheus/common 89604d197083d4781071d3c65855d24ecfb0a563 -github.com/prometheus/procfs cb4147076ac75738c9a7d279075a253c0cc5acbd -github.com/Shopify/logrus-bugsnag 577dee27f20dd8f1a529f82210094af593be12bd -github.com/spf13/cobra 312092086bed4968099259622145a0c9ae280064 -github.com/spf13/pflag 5644820622454e71517561946e3d94b9f9db6842 -github.com/xenolf/lego a9d8cec0e6563575e5868a005359ac97911b5985 -github.com/yvasiyarov/go-metrics 57bccd1ccd43f94bb17fdd8bf3007059b802f85e -github.com/yvasiyarov/gorelic a9bba5b9ab508a086f9a12b8c51fab68478e2128 -github.com/yvasiyarov/newrelic_platform_go b21fdbd4370f3717f3bbd2bf41c223bc273068e6 -golang.org/x/crypto c10c31b5e94b6f7a0283272dc2bb27163dcea24b -golang.org/x/net 4876518f9e71663000c348837735820161a42df7 -golang.org/x/oauth2 045497edb6234273d67dbc25da3f2ddbc4c4cacf -golang.org/x/time a4bde12657593d5e90d0533a3e4fd95e635124cb -google.golang.org/api 9bf6e6e569ff057f75d9604a46c52928f17d2b54 -google.golang.org/appengine 12d5545dc1cfa6047a286d5e853841b6471f4c19 -google.golang.org/cloud 975617b05ea8a58727e6c1a06b6161ff4185a9f2 -google.golang.org/grpc d3ddb4469d5a1b949fc7a7da7c1d6a0d1b6de994 -gopkg.in/check.v1 64131543e7896d5bcc6bd5a76287eb75ea96c673 -gopkg.in/square/go-jose.v1 40d457b439244b546f023d056628e5184136899b -gopkg.in/yaml.v2 v2.2.1 -rsc.io/letsencrypt e770c10b0f1a64775ae91d240407ce00d1a5bdeb https://github.com/dmcgowan/letsencrypt.git -github.com/opencontainers/go-digest ea51bea511f75cfa3ef6098cc253c5c3609b037a # v1.0.0 -github.com/opencontainers/image-spec 67d2d5658fe0476ab9bf414cec164077ebff3920 # v1.0.2 diff --git a/vendor/github.com/docker/docker-credential-helpers/LICENSE b/vendor/github.com/docker/docker-credential-helpers/LICENSE deleted file mode 100644 index 1ea555e2a..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2016 David Calavera - -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/docker/docker-credential-helpers/client/client.go b/vendor/github.com/docker/docker-credential-helpers/client/client.go deleted file mode 100644 index 7ca5ab722..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/client/client.go +++ /dev/null @@ -1,114 +0,0 @@ -package client - -import ( - "bytes" - "encoding/json" - "fmt" - "strings" - - "github.com/docker/docker-credential-helpers/credentials" -) - -// isValidCredsMessage checks if 'msg' contains invalid credentials error message. -// It returns whether the logs are free of invalid credentials errors and the error if it isn't. -// error values can be errCredentialsMissingServerURL or errCredentialsMissingUsername. -func isValidCredsMessage(msg string) error { - if credentials.IsCredentialsMissingServerURLMessage(msg) { - return credentials.NewErrCredentialsMissingServerURL() - } - if credentials.IsCredentialsMissingUsernameMessage(msg) { - return credentials.NewErrCredentialsMissingUsername() - } - return nil -} - -// Store uses an external program to save credentials. -func Store(program ProgramFunc, creds *credentials.Credentials) error { - cmd := program(credentials.ActionStore) - - buffer := new(bytes.Buffer) - if err := json.NewEncoder(buffer).Encode(creds); err != nil { - return err - } - cmd.Input(buffer) - - out, err := cmd.Output() - if err != nil { - if isValidErr := isValidCredsMessage(string(out)); isValidErr != nil { - err = isValidErr - } - return fmt.Errorf("error storing credentials - err: %v, out: `%s`", err, strings.TrimSpace(string(out))) - } - - return nil -} - -// Get executes an external program to get the credentials from a native store. -func Get(program ProgramFunc, serverURL string) (*credentials.Credentials, error) { - cmd := program(credentials.ActionGet) - cmd.Input(strings.NewReader(serverURL)) - - out, err := cmd.Output() - if err != nil { - if credentials.IsErrCredentialsNotFoundMessage(string(out)) { - return nil, credentials.NewErrCredentialsNotFound() - } - - if isValidErr := isValidCredsMessage(string(out)); isValidErr != nil { - err = isValidErr - } - - return nil, fmt.Errorf("error getting credentials - err: %v, out: `%s`", err, strings.TrimSpace(string(out))) - } - - resp := &credentials.Credentials{ - ServerURL: serverURL, - } - - if err := json.NewDecoder(bytes.NewReader(out)).Decode(resp); err != nil { - return nil, err - } - - return resp, nil -} - -// Erase executes a program to remove the server credentials from the native store. -func Erase(program ProgramFunc, serverURL string) error { - cmd := program(credentials.ActionErase) - cmd.Input(strings.NewReader(serverURL)) - out, err := cmd.Output() - if err != nil { - t := strings.TrimSpace(string(out)) - - if isValidErr := isValidCredsMessage(t); isValidErr != nil { - err = isValidErr - } - - return fmt.Errorf("error erasing credentials - err: %v, out: `%s`", err, t) - } - - return nil -} - -// List executes a program to list server credentials in the native store. -func List(program ProgramFunc) (map[string]string, error) { - cmd := program(credentials.ActionList) - cmd.Input(strings.NewReader("unused")) - out, err := cmd.Output() - if err != nil { - t := strings.TrimSpace(string(out)) - - if isValidErr := isValidCredsMessage(t); isValidErr != nil { - err = isValidErr - } - - return nil, fmt.Errorf("error listing credentials - err: %v, out: `%s`", err, t) - } - - var resp map[string]string - if err = json.NewDecoder(bytes.NewReader(out)).Decode(&resp); err != nil { - return nil, err - } - - return resp, nil -} diff --git a/vendor/github.com/docker/docker-credential-helpers/client/command.go b/vendor/github.com/docker/docker-credential-helpers/client/command.go deleted file mode 100644 index 1936234be..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/client/command.go +++ /dev/null @@ -1,54 +0,0 @@ -package client - -import ( - "io" - "os" - "os/exec" -) - -// Program is an interface to execute external programs. -type Program interface { - Output() ([]byte, error) - Input(in io.Reader) -} - -// ProgramFunc is a type of function that initializes programs based on arguments. -type ProgramFunc func(args ...string) Program - -// NewShellProgramFunc creates programs that are executed in a Shell. -func NewShellProgramFunc(name string) ProgramFunc { - return NewShellProgramFuncWithEnv(name, nil) -} - -// NewShellProgramFuncWithEnv creates programs that are executed in a Shell with environment variables -func NewShellProgramFuncWithEnv(name string, env *map[string]string) ProgramFunc { - return func(args ...string) Program { - return &Shell{cmd: createProgramCmdRedirectErr(name, args, env)} - } -} - -func createProgramCmdRedirectErr(commandName string, args []string, env *map[string]string) *exec.Cmd { - programCmd := exec.Command(commandName, args...) - if env != nil { - for k, v := range *env { - programCmd.Env = append(programCmd.Environ(), k+"="+v) - } - } - programCmd.Stderr = os.Stderr - return programCmd -} - -// Shell invokes shell commands to talk with a remote credentials-helper. -type Shell struct { - cmd *exec.Cmd -} - -// Output returns responses from the remote credentials-helper. -func (s *Shell) Output() ([]byte, error) { - return s.cmd.Output() -} - -// Input sets the input to send to a remote credentials-helper. -func (s *Shell) Input(in io.Reader) { - s.cmd.Stdin = in -} diff --git a/vendor/github.com/docker/docker-credential-helpers/credentials/credentials.go b/vendor/github.com/docker/docker-credential-helpers/credentials/credentials.go deleted file mode 100644 index eac551884..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/credentials/credentials.go +++ /dev/null @@ -1,209 +0,0 @@ -package credentials - -import ( - "bufio" - "bytes" - "encoding/json" - "fmt" - "io" - "os" - "strings" -) - -// Action defines the name of an action (sub-command) supported by a -// credential-helper binary. It is an alias for "string", and mostly -// for convenience. -type Action = string - -// List of actions (sub-commands) supported by credential-helper binaries. -const ( - ActionStore Action = "store" - ActionGet Action = "get" - ActionErase Action = "erase" - ActionList Action = "list" - ActionVersion Action = "version" -) - -// Credentials holds the information shared between docker and the credentials store. -type Credentials struct { - ServerURL string - Username string - Secret string -} - -// isValid checks the integrity of Credentials object such that no credentials lack -// a server URL or a username. -// It returns whether the credentials are valid and the error if it isn't. -// error values can be errCredentialsMissingServerURL or errCredentialsMissingUsername -func (c *Credentials) isValid() (bool, error) { - if len(c.ServerURL) == 0 { - return false, NewErrCredentialsMissingServerURL() - } - - if len(c.Username) == 0 { - return false, NewErrCredentialsMissingUsername() - } - - return true, nil -} - -// CredsLabel holds the way Docker credentials should be labeled as such in credentials stores that allow labelling. -// That label allows to filter out non-Docker credentials too at lookup/search in macOS keychain, -// Windows credentials manager and Linux libsecret. Default value is "Docker Credentials" -var CredsLabel = "Docker Credentials" - -// SetCredsLabel is a simple setter for CredsLabel -func SetCredsLabel(label string) { - CredsLabel = label -} - -// Serve initializes the credentials-helper and parses the action argument. -// This function is designed to be called from a command line interface. -// It uses os.Args[1] as the key for the action. -// It uses os.Stdin as input and os.Stdout as output. -// This function terminates the program with os.Exit(1) if there is an error. -func Serve(helper Helper) { - if len(os.Args) != 2 { - _, _ = fmt.Fprintln(os.Stdout, usage()) - os.Exit(1) - } - - switch os.Args[1] { - case "--version", "-v": - _ = PrintVersion(os.Stdout) - os.Exit(0) - case "--help", "-h": - _, _ = fmt.Fprintln(os.Stdout, usage()) - os.Exit(0) - } - - if err := HandleCommand(helper, os.Args[1], os.Stdin, os.Stdout); err != nil { - _, _ = fmt.Fprintln(os.Stdout, err) - os.Exit(1) - } -} - -func usage() string { - return fmt.Sprintf("Usage: %s ", Name) -} - -// HandleCommand runs a helper to execute a credential action. -func HandleCommand(helper Helper, action Action, in io.Reader, out io.Writer) error { - switch action { - case ActionStore: - return Store(helper, in) - case ActionGet: - return Get(helper, in, out) - case ActionErase: - return Erase(helper, in) - case ActionList: - return List(helper, out) - case ActionVersion: - return PrintVersion(out) - default: - return fmt.Errorf("%s: unknown action: %s", Name, action) - } -} - -// Store uses a helper and an input reader to save credentials. -// The reader must contain the JSON serialization of a Credentials struct. -func Store(helper Helper, reader io.Reader) error { - scanner := bufio.NewScanner(reader) - - buffer := new(bytes.Buffer) - for scanner.Scan() { - buffer.Write(scanner.Bytes()) - } - - if err := scanner.Err(); err != nil && err != io.EOF { - return err - } - - var creds Credentials - if err := json.NewDecoder(buffer).Decode(&creds); err != nil { - return err - } - - if ok, err := creds.isValid(); !ok { - return err - } - - return helper.Add(&creds) -} - -// Get retrieves the credentials for a given server url. -// The reader must contain the server URL to search. -// The writer is used to write the JSON serialization of the credentials. -func Get(helper Helper, reader io.Reader, writer io.Writer) error { - scanner := bufio.NewScanner(reader) - - buffer := new(bytes.Buffer) - for scanner.Scan() { - buffer.Write(scanner.Bytes()) - } - - if err := scanner.Err(); err != nil && err != io.EOF { - return err - } - - serverURL := strings.TrimSpace(buffer.String()) - if len(serverURL) == 0 { - return NewErrCredentialsMissingServerURL() - } - - username, secret, err := helper.Get(serverURL) - if err != nil { - return err - } - - buffer.Reset() - err = json.NewEncoder(buffer).Encode(Credentials{ - ServerURL: serverURL, - Username: username, - Secret: secret, - }) - if err != nil { - return err - } - - _, _ = fmt.Fprint(writer, buffer.String()) - return nil -} - -// Erase removes credentials from the store. -// The reader must contain the server URL to remove. -func Erase(helper Helper, reader io.Reader) error { - scanner := bufio.NewScanner(reader) - - buffer := new(bytes.Buffer) - for scanner.Scan() { - buffer.Write(scanner.Bytes()) - } - - if err := scanner.Err(); err != nil && err != io.EOF { - return err - } - - serverURL := strings.TrimSpace(buffer.String()) - if len(serverURL) == 0 { - return NewErrCredentialsMissingServerURL() - } - - return helper.Delete(serverURL) -} - -// List returns all the serverURLs of keys in -// the OS store as a list of strings -func List(helper Helper, writer io.Writer) error { - accts, err := helper.List() - if err != nil { - return err - } - return json.NewEncoder(writer).Encode(accts) -} - -// PrintVersion outputs the current version. -func PrintVersion(writer io.Writer) error { - _, _ = fmt.Fprintf(writer, "%s (%s) %s\n", Name, Package, Version) - return nil -} diff --git a/vendor/github.com/docker/docker-credential-helpers/credentials/error.go b/vendor/github.com/docker/docker-credential-helpers/credentials/error.go deleted file mode 100644 index 2283d5a44..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/credentials/error.go +++ /dev/null @@ -1,124 +0,0 @@ -package credentials - -import ( - "errors" - "strings" -) - -const ( - // ErrCredentialsNotFound standardizes the not found error, so every helper returns - // the same message and docker can handle it properly. - errCredentialsNotFoundMessage = "credentials not found in native keychain" - - // ErrCredentialsMissingServerURL and ErrCredentialsMissingUsername standardize - // invalid credentials or credentials management operations - errCredentialsMissingServerURLMessage = "no credentials server URL" - errCredentialsMissingUsernameMessage = "no credentials username" -) - -// errCredentialsNotFound represents an error -// raised when credentials are not in the store. -type errCredentialsNotFound struct{} - -// Error returns the standard error message -// for when the credentials are not in the store. -func (errCredentialsNotFound) Error() string { - return errCredentialsNotFoundMessage -} - -// NotFound implements the [ErrNotFound][errdefs.ErrNotFound] interface. -// -// [errdefs.ErrNotFound]: https://pkg.go.dev/github.com/docker/docker@v24.0.1+incompatible/errdefs#ErrNotFound -func (errCredentialsNotFound) NotFound() {} - -// NewErrCredentialsNotFound creates a new error -// for when the credentials are not in the store. -func NewErrCredentialsNotFound() error { - return errCredentialsNotFound{} -} - -// IsErrCredentialsNotFound returns true if the error -// was caused by not having a set of credentials in a store. -func IsErrCredentialsNotFound(err error) bool { - var target errCredentialsNotFound - return errors.As(err, &target) -} - -// IsErrCredentialsNotFoundMessage returns true if the error -// was caused by not having a set of credentials in a store. -// -// This function helps to check messages returned by an -// external program via its standard output. -func IsErrCredentialsNotFoundMessage(err string) bool { - return strings.TrimSpace(err) == errCredentialsNotFoundMessage -} - -// errCredentialsMissingServerURL represents an error raised -// when the credentials object has no server URL or when no -// server URL is provided to a credentials operation requiring -// one. -type errCredentialsMissingServerURL struct{} - -func (errCredentialsMissingServerURL) Error() string { - return errCredentialsMissingServerURLMessage -} - -// InvalidParameter implements the [ErrInvalidParameter][errdefs.ErrInvalidParameter] -// interface. -// -// [errdefs.ErrInvalidParameter]: https://pkg.go.dev/github.com/docker/docker@v24.0.1+incompatible/errdefs#ErrInvalidParameter -func (errCredentialsMissingServerURL) InvalidParameter() {} - -// errCredentialsMissingUsername represents an error raised -// when the credentials object has no username or when no -// username is provided to a credentials operation requiring -// one. -type errCredentialsMissingUsername struct{} - -func (errCredentialsMissingUsername) Error() string { - return errCredentialsMissingUsernameMessage -} - -// InvalidParameter implements the [ErrInvalidParameter][errdefs.ErrInvalidParameter] -// interface. -// -// [errdefs.ErrInvalidParameter]: https://pkg.go.dev/github.com/docker/docker@v24.0.1+incompatible/errdefs#ErrInvalidParameter -func (errCredentialsMissingUsername) InvalidParameter() {} - -// NewErrCredentialsMissingServerURL creates a new error for -// errCredentialsMissingServerURL. -func NewErrCredentialsMissingServerURL() error { - return errCredentialsMissingServerURL{} -} - -// NewErrCredentialsMissingUsername creates a new error for -// errCredentialsMissingUsername. -func NewErrCredentialsMissingUsername() error { - return errCredentialsMissingUsername{} -} - -// IsCredentialsMissingServerURL returns true if the error -// was an errCredentialsMissingServerURL. -func IsCredentialsMissingServerURL(err error) bool { - var target errCredentialsMissingServerURL - return errors.As(err, &target) -} - -// IsCredentialsMissingServerURLMessage checks for an -// errCredentialsMissingServerURL in the error message. -func IsCredentialsMissingServerURLMessage(err string) bool { - return strings.TrimSpace(err) == errCredentialsMissingServerURLMessage -} - -// IsCredentialsMissingUsername returns true if the error -// was an errCredentialsMissingUsername. -func IsCredentialsMissingUsername(err error) bool { - var target errCredentialsMissingUsername - return errors.As(err, &target) -} - -// IsCredentialsMissingUsernameMessage checks for an -// errCredentialsMissingUsername in the error message. -func IsCredentialsMissingUsernameMessage(err string) bool { - return strings.TrimSpace(err) == errCredentialsMissingUsernameMessage -} diff --git a/vendor/github.com/docker/docker-credential-helpers/credentials/helper.go b/vendor/github.com/docker/docker-credential-helpers/credentials/helper.go deleted file mode 100644 index 135acd254..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/credentials/helper.go +++ /dev/null @@ -1,14 +0,0 @@ -package credentials - -// Helper is the interface a credentials store helper must implement. -type Helper interface { - // Add appends credentials to the store. - Add(*Credentials) error - // Delete removes credentials from the store. - Delete(serverURL string) error - // Get retrieves credentials from the store. - // It returns username and secret as strings. - Get(serverURL string) (string, string, error) - // List returns the stored serverURLs and their associated usernames. - List() (map[string]string, error) -} diff --git a/vendor/github.com/docker/docker-credential-helpers/credentials/version.go b/vendor/github.com/docker/docker-credential-helpers/credentials/version.go deleted file mode 100644 index 84377c263..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/credentials/version.go +++ /dev/null @@ -1,16 +0,0 @@ -package credentials - -var ( - // Name is filled at linking time - Name = "" - - // Package is filled at linking time - Package = "github.com/docker/docker-credential-helpers" - - // Version holds the complete version number. Filled in at linking time. - Version = "v0.0.0+unknown" - - // Revision is filled with the VCS (e.g. git) revision being used to build - // the program at linking time. - Revision = "" -) diff --git a/vendor/github.com/docker/docker/AUTHORS b/vendor/github.com/docker/docker/AUTHORS deleted file mode 100644 index b31418192..000000000 --- a/vendor/github.com/docker/docker/AUTHORS +++ /dev/null @@ -1,2390 +0,0 @@ -# File @generated by hack/generate-authors.sh. DO NOT EDIT. -# This file lists all contributors to the repository. -# See hack/generate-authors.sh to make modifications. - -Aanand Prasad -Aaron Davidson -Aaron Feng -Aaron Hnatiw -Aaron Huslage -Aaron L. Xu -Aaron Lehmann -Aaron Welch -Abel Muiño -Abhijeet Kasurde -Abhinandan Prativadi -Abhinav Ajgaonkar -Abhishek Chanda -Abhishek Sharma -Abin Shahab -Abirdcfly -Ada Mancini -Adam Avilla -Adam Dobrawy -Adam Eijdenberg -Adam Kunk -Adam Miller -Adam Mills -Adam Pointer -Adam Singer -Adam Walz -Adam Williams -AdamKorcz -Addam Hardy -Aditi Rajagopal -Aditya -Adnan Khan -Adolfo Ochagavía -Adria Casas -Adrian Moisey -Adrian Mouat -Adrian Oprea -Adrien Folie -Adrien Gallouët -Ahmed Kamal -Ahmet Alp Balkan -Aidan Feldman -Aidan Hobson Sayers -AJ Bowen -Ajey Charantimath -ajneu -Akash Gupta -Akhil Mohan -Akihiro Matsushima -Akihiro Suda -Akim Demaille -Akira Koyasu -Akshay Karle -Akshay Moghe -Al Tobey -alambike -Alan Hoyle -Alan Scherger -Alan Thompson -Albert Callarisa -Albert Zhang -Albin Kerouanton -Alec Benson -Alejandro González Hevia -Aleksa Sarai -Aleksandr Chebotov -Aleksandrs Fadins -Alena Prokharchyk -Alessandro Boch -Alessio Biancalana -Alex Chan -Alex Chen -Alex Coventry -Alex Crawford -Alex Ellis -Alex Gaynor -Alex Goodman -Alex Nordlund -Alex Olshansky -Alex Samorukov -Alex Stockinger -Alex Warhawk -Alexander Artemenko -Alexander Boyd -Alexander Larsson -Alexander Midlash -Alexander Morozov -Alexander Polakov -Alexander Shopov -Alexandre Beslic -Alexandre Garnier -Alexandre González -Alexandre Jomin -Alexandru Sfirlogea -Alexei Margasov -Alexey Guskov -Alexey Kotlyarov -Alexey Shamrin -Alexis Ries -Alexis Thomas -Alfred Landrum -Ali Dehghani -Alicia Lauerman -Alihan Demir -Allen Madsen -Allen Sun -almoehi -Alvaro Saurin -Alvin Deng -Alvin Richards -amangoel -Amen Belayneh -Ameya Gawde -Amir Goldstein -Amit Bakshi -Amit Krishnan -Amit Shukla -Amr Gawish -Amy Lindburg -Anand Patil -AnandkumarPatel -Anatoly Borodin -Anca Iordache -Anchal Agrawal -Anda Xu -Anders Janmyr -Andre Dublin <81dublin@gmail.com> -Andre Granovsky -Andrea Denisse Gómez -Andrea Luzzardi -Andrea Turli -Andreas Elvers -Andreas Köhler -Andreas Savvides -Andreas Tiefenthaler -Andrei Gherzan -Andrei Ushakov -Andrei Vagin -Andrew C. Bodine -Andrew Clay Shafer -Andrew Duckworth -Andrew France -Andrew Gerrand -Andrew Guenther -Andrew He -Andrew Hsu -Andrew Kim -Andrew Kuklewicz -Andrew Macgregor -Andrew Macpherson -Andrew Martin -Andrew McDonnell -Andrew Munsell -Andrew Pennebaker -Andrew Po -Andrew Weiss -Andrew Williams -Andrews Medina -Andrey Kolomentsev -Andrey Petrov -Andrey Stolbovsky -André Martins -Andy Chambers -andy diller -Andy Goldstein -Andy Kipp -Andy Lindeman -Andy Rothfusz -Andy Smith -Andy Wilson -Andy Zhang -Anes Hasicic -Angel Velazquez -Anil Belur -Anil Madhavapeddy -Ankit Jain -Ankush Agarwal -Anonmily -Anran Qiao -Anshul Pundir -Anthon van der Neut -Anthony Baire -Anthony Bishopric -Anthony Dahanne -Anthony Sottile -Anton Löfgren -Anton Nikitin -Anton Polonskiy -Anton Tiurin -Antonio Murdaca -Antonis Kalipetis -Antony Messerli -Anuj Bahuguna -Anuj Varma -Anusha Ragunathan -Anyu Wang -apocas -Arash Deshmeh -arcosx -ArikaChen -Arko Dasgupta -Arnaud Lefebvre -Arnaud Porterie -Arnaud Rebillout -Artem Khramov -Arthur Barr -Arthur Gautier -Artur Meyster -Arun Gupta -Asad Saeeduddin -Asbjørn Enge -Austin Vazquez -averagehuman -Avi Das -Avi Kivity -Avi Miller -Avi Vaid -ayoshitake -Azat Khuyiyakhmetov -Bao Yonglei -Bardia Keyoumarsi -Barnaby Gray -Barry Allard -Bartłomiej Piotrowski -Bastiaan Bakker -Bastien Pascard -bdevloed -Bearice Ren -Ben Bonnefoy -Ben Firshman -Ben Golub -Ben Gould -Ben Hall -Ben Langfeld -Ben Sargent -Ben Severson -Ben Toews -Ben Wiklund -Benjamin Atkin -Benjamin Baker -Benjamin Boudreau -Benjamin Böhmke -Benjamin Wang -Benjamin Yolken -Benny Ng -Benoit Chesneau -Bernerd Schaefer -Bernhard M. Wiedemann -Bert Goethals -Bertrand Roussel -Bevisy Zhang -Bharath Thiruveedula -Bhiraj Butala -Bhumika Bayani -Bilal Amarni -Bill Wang -Billy Ridgway -Bily Zhang -Bin Liu -Bingshen Wang -Bjorn Neergaard -Blake Geno -Boaz Shuster -bobby abbott -Bojun Zhu -Boqin Qin -Boris Pruessmann -Boshi Lian -Bouke Haarsma -Boyd Hemphill -boynux -Bradley Cicenas -Bradley Wright -Brandon Liu -Brandon Philips -Brandon Rhodes -Brendan Dixon -Brent Salisbury -Brett Higgins -Brett Kochendorfer -Brett Milford -Brett Randall -Brian (bex) Exelbierd -Brian Bland -Brian DeHamer -Brian Dorsey -Brian Flad -Brian Goff -Brian McCallister -Brian Olsen -Brian Schwind -Brian Shumate -Brian Torres-Gil -Brian Trump -Brice Jaglin -Briehan Lombaard -Brielle Broder -Bruno Bigras -Bruno Binet -Bruno Gazzera -Bruno Renié -Bruno Tavares -Bryan Bess -Bryan Boreham -Bryan Matsuo -Bryan Murphy -Burke Libbey -Byung Kang -Caleb Spare -Calen Pennington -Cameron Boehmer -Cameron Sparr -Cameron Spear -Campbell Allen -Candid Dauth -Cao Weiwei -Carl Henrik Lunde -Carl Loa Odin -Carl X. Su -Carlo Mion -Carlos Alexandro Becker -Carlos de Paula -Carlos Sanchez -Carol Fager-Higgins -Cary -Casey Bisson -Catalin Pirvu -Ce Gao -Cedric Davies -Cezar Sa Espinola -Chad Swenson -Chance Zibolski -Chander Govindarajan -Chanhun Jeong -Chao Wang -Charles Chan -Charles Hooper -Charles Law -Charles Lindsay -Charles Merriam -Charles Sarrazin -Charles Smith -Charlie Drage -Charlie Lewis -Chase Bolt -ChaYoung You -Chee Hau Lim -Chen Chao -Chen Chuanliang -Chen Hanxiao -Chen Min -Chen Mingjie -Chen Qiu -Cheng-mean Liu -Chengfei Shang -Chengguang Xu -Chenyang Yan -chenyuzhu -Chetan Birajdar -Chewey -Chia-liang Kao -chli -Cholerae Hu -Chris Alfonso -Chris Armstrong -Chris Dias -Chris Dituri -Chris Fordham -Chris Gavin -Chris Gibson -Chris Khoo -Chris Kreussling (Flatbush Gardener) -Chris McKinnel -Chris McKinnel -Chris Price -Chris Seto -Chris Snow -Chris St. Pierre -Chris Stivers -Chris Swan -Chris Telfer -Chris Wahl -Chris Weyl -Chris White -Christian Becker -Christian Berendt -Christian Brauner -Christian Böhme -Christian Muehlhaeuser -Christian Persson -Christian Rotzoll -Christian Simon -Christian Stefanescu -Christoph Ziebuhr -Christophe Mehay -Christophe Troestler -Christophe Vidal -Christopher Biscardi -Christopher Crone -Christopher Currie -Christopher Jones -Christopher Latham -Christopher Rigor -Christy Norman -Chun Chen -Ciro S. Costa -Clayton Coleman -Clint Armstrong -Clinton Kitson -clubby789 -Cody Roseborough -Coenraad Loubser -Colin Dunklau -Colin Hebert -Colin Panisset -Colin Rice -Colin Walters -Collin Guarino -Colm Hally -companycy -Conor Evans -Corbin Coleman -Corey Farrell -Cory Forsyth -Cory Snider -cressie176 -Cristian Ariza -Cristian Staretu -cristiano balducci -Cristina Yenyxe Gonzalez Garcia -Cruceru Calin-Cristian -CUI Wei -cuishuang -Cuong Manh Le -Cyprian Gracz -Cyril F -Da McGrady -Daan van Berkel -Daehyeok Mun -Dafydd Crosby -dalanlan -Damian Smyth -Damien Nadé -Damien Nozay -Damjan Georgievski -Dan Anolik -Dan Buch -Dan Cotora -Dan Feldman -Dan Griffin -Dan Hirsch -Dan Keder -Dan Levy -Dan McPherson -Dan Plamadeala -Dan Stine -Dan Williams -Dani Hodovic -Dani Louca -Daniel Antlinger -Daniel Black -Daniel Dao -Daniel Exner -Daniel Farrell -Daniel Garcia -Daniel Gasienica -Daniel Grunwell -Daniel Helfand -Daniel Hiltgen -Daniel J Walsh -Daniel Menet -Daniel Mizyrycki -Daniel Nephin -Daniel Norberg -Daniel Nordberg -Daniel P. Berrangé -Daniel Robinson -Daniel S -Daniel Sweet -Daniel Von Fange -Daniel Watkins -Daniel X Moore -Daniel YC Lin -Daniel Zhang -Daniele Rondina -Danny Berger -Danny Milosavljevic -Danny Yates -Danyal Khaliq -Darren Coxall -Darren Shepherd -Darren Stahl -Dattatraya Kumbhar -Davanum Srinivas -Dave Barboza -Dave Goodchild -Dave Henderson -Dave MacDonald -Dave Tucker -David Anderson -David Bellotti -David Calavera -David Chung -David Corking -David Cramer -David Currie -David Davis -David Dooling -David Gageot -David Gebler -David Glasser -David Lawrence -David Lechner -David M. Karr -David Mackey -David Manouchehri -David Mat -David Mcanulty -David McKay -David O'Rourke -David P Hilton -David Pelaez -David R. Jenni -David Röthlisberger -David Sheets -David Sissitka -David Trott -David Wang <00107082@163.com> -David Williamson -David Xia -David Young -Davide Ceretti -Dawn Chen -dbdd -dcylabs -Debayan De -Deborah Gertrude Digges -deed02392 -Deep Debroy -Deng Guangxing -Deni Bertovic -Denis Defreyne -Denis Gladkikh -Denis Ollier -Dennis Chen -Dennis Chen -Dennis Docter -Derek -Derek -Derek Ch -Derek McGowan -Deric Crago -Deshi Xiao -Devon Estes -Devvyn Murphy -Dharmit Shah -Dhawal Yogesh Bhanushali -Dhilip Kumars -Diego Romero -Diego Siqueira -Dieter Reuter -Dillon Dixon -Dima Stopel -Dimitri John Ledkov -Dimitris Mandalidis -Dimitris Rozakis -Dimitry Andric -Dinesh Subhraveti -Ding Fei -dingwei -Diogo Monica -DiuDiugirl -Djibril Koné -Djordje Lukic -dkumor -Dmitri Logvinenko -Dmitri Shuralyov -Dmitry Demeshchuk -Dmitry Gusev -Dmitry Kononenko -Dmitry Sharshakov -Dmitry Shyshkin -Dmitry Smirnov -Dmitry V. Krivenok -Dmitry Vorobev -Dmytro Iakovliev -docker-unir[bot] -Dolph Mathews -Dominic Tubach -Dominic Yin -Dominik Dingel -Dominik Finkbeiner -Dominik Honnef -Don Kirkby -Don Kjer -Don Spaulding -Donald Huang -Dong Chen -Donghwa Kim -Donovan Jones -Doron Podoleanu -Doug Davis -Doug MacEachern -Doug Tangren -Douglas Curtis -Dr Nic Williams -dragon788 -Dražen Lučanin -Drew Erny -Drew Hubl -Dustin Sallings -Ed Costello -Edmund Wagner -Eiichi Tsukata -Eike Herzbach -Eivin Giske Skaaren -Eivind Uggedal -Elan Ruusamäe -Elango Sivanandam -Elena Morozova -Eli Uriegas -Elias Faxö -Elias Koromilas -Elias Probst -Elijah Zupancic -eluck -Elvir Kuric -Emil Davtyan -Emil Hernvall -Emily Maier -Emily Rose -Emir Ozer -Eng Zer Jun -Enguerran -Eohyung Lee -epeterso -er0k -Eric Barch -Eric Curtin -Eric G. Noriega -Eric Hanchrow -Eric Lee -Eric Mountain -Eric Myhre -Eric Paris -Eric Rafaloff -Eric Rosenberg -Eric Sage -Eric Soderstrom -Eric Yang -Eric-Olivier Lamey -Erica Windisch -Erich Cordoba -Erik Bray -Erik Dubbelboer -Erik Hollensbe -Erik Inge Bolsø -Erik Kristensen -Erik Sipsma -Erik St. Martin -Erik Weathers -Erno Hopearuoho -Erwin van der Koogh -Espen Suenson -Ethan Bell -Ethan Mosbaugh -Euan Harris -Euan Kemp -Eugen Krizo -Eugene Yakubovich -Evan Allrich -Evan Carmi -Evan Hazlett -Evan Krall -Evan Phoenix -Evan Wies -Evelyn Xu -Everett Toews -Evgeniy Makhrov -Evgeny Shmarnev -Evgeny Vereshchagin -Ewa Czechowska -Eystein Måløy Stenberg -ezbercih -Ezra Silvera -Fabian Kramm -Fabian Lauer -Fabian Raetz -Fabiano Rosas -Fabio Falci -Fabio Kung -Fabio Rapposelli -Fabio Rehm -Fabrizio Regini -Fabrizio Soppelsa -Faiz Khan -falmp -Fangming Fang -Fangyuan Gao <21551127@zju.edu.cn> -fanjiyun -Fareed Dudhia -Fathi Boudra -Federico Gimenez -Felipe Oliveira -Felipe Ruhland -Felix Abecassis -Felix Geisendörfer -Felix Hupfeld -Felix Rabe -Felix Ruess -Felix Schindler -Feng Yan -Fengtu Wang -Ferenc Szabo -Fernando -Fero Volar -Feroz Salam -Ferran Rodenas -Filipe Brandenburger -Filipe Oliveira -Flavio Castelli -Flavio Crisciani -Florian -Florian Klein -Florian Maier -Florian Noeding -Florian Schmaus -Florian Weingarten -Florin Asavoaie -Florin Patan -fonglh -Foysal Iqbal -Francesc Campoy -Francesco Degrassi -Francesco Mari -Francis Chuang -Francisco Carriedo -Francisco Souza -Frank Groeneveld -Frank Herrmann -Frank Macreery -Frank Rosquin -Frank Yang -Fred Lifton -Frederick F. Kautz IV -Frederico F. de Oliveira -Frederik Loeffert -Frederik Nordahl Jul Sabroe -Freek Kalter -Frieder Bluemle -frobnicaty <92033765+frobnicaty@users.noreply.github.com> -Frédéric Dalleau -Fu JinLin -Félix Baylac-Jacqué -Félix Cantournet -Gabe Rosenhouse -Gabor Nagy -Gabriel Adrian Samfira -Gabriel Goller -Gabriel L. Somlo -Gabriel Linder -Gabriel Monroy -Gabriel Nicolas Avellaneda -Gaetan de Villele -Galen Sampson -Gang Qiao -Gareth Rushgrove -Garrett Barboza -Gary Schaetz -Gaurav -Gaurav Singh -Gaël PORTAY -Genki Takiuchi -GennadySpb -Geoff Levand -Geoffrey Bachelet -Geon Kim -George Kontridze -George MacRorie -George Xie -Georgi Hristozov -Georgy Yakovlev -Gereon Frey -German DZ -Gert van Valkenhoef -Gerwim Feiken -Ghislain Bourgeois -Giampaolo Mancini -Gianluca Borello -Gildas Cuisinier -Giovan Isa Musthofa -gissehel -Giuseppe Mazzotta -Giuseppe Scrivano -Gleb Fotengauer-Malinovskiy -Gleb M Borisov -Glyn Normington -GoBella -Goffert van Gool -Goldwyn Rodrigues -Gopikannan Venugopalsamy -Gosuke Miyashita -Gou Rao -Govinda Fichtner -Grant Millar -Grant Reaber -Graydon Hoare -Greg Fausak -Greg Pflaum -Greg Stephens -Greg Thornton -Grzegorz Jaśkiewicz -Guilhem Lettron -Guilherme Salgado -Guillaume Dufour -Guillaume J. Charmes -Gunadhya S. <6939749+gunadhya@users.noreply.github.com> -Guoqiang QI -guoxiuyan -Guri -Gurjeet Singh -Guruprasad -Gustav Sinder -gwx296173 -Günter Zöchbauer -Haichao Yang -haikuoliu -haining.cao -Hakan Özler -Hamish Hutchings -Hannes Ljungberg -Hans Kristian Flaatten -Hans Rødtang -Hao Shu Wei -Hao Zhang <21521210@zju.edu.cn> -Harald Albers -Harald Niesche -Harley Laue -Harold Cooper -Harrison Turton -Harry Zhang -Harshal Patil -Harshal Patil -He Simei -He Xiaoxi -He Xin -heartlock <21521209@zju.edu.cn> -Hector Castro -Helen Xie -Henning Sprang -Hiroshi Hatake -Hiroyuki Sasagawa -Hobofan -Hollie Teal -Hong Xu -Hongbin Lu -Hongxu Jia -Honza Pokorny -Hsing-Hui Hsu -Hsing-Yu (David) Chen -hsinko <21551195@zju.edu.cn> -Hu Keping -Hu Tao -HuanHuan Ye -Huanzhong Zhang -Huayi Zhang -Hugo Barrera -Hugo Duncan -Hugo Marisco <0x6875676f@gmail.com> -Hui Kang -Hunter Blanks -huqun -Huu Nguyen -Hyeongkyu Lee -Hyzhou Zhy -Iago López Galeiras -Ian Bishop -Ian Bull -Ian Calvert -Ian Campbell -Ian Chen -Ian Lee -Ian Main -Ian Philpot -Ian Truslove -Iavael -Icaro Seara -Ignacio Capurro -Igor Dolzhikov -Igor Karpovich -Iliana Weller -Ilkka Laukkanen -Illia Antypenko -Illo Abdulrahim -Ilya Dmitrichenko -Ilya Gusev -Ilya Khlopotov -imre Fitos -inglesp -Ingo Gottwald -Innovimax -Isaac Dupree -Isabel Jimenez -Isaiah Grace -Isao Jonas -Iskander Sharipov -Ivan Babrou -Ivan Fraixedes -Ivan Grcic -Ivan Markin -J Bruni -J. Nunn -Jack Danger Canty -Jack Laxson -Jacob Atzen -Jacob Edelman -Jacob Tomlinson -Jacob Vallejo -Jacob Wen -Jaime Cepeda -Jaivish Kothari -Jake Champlin -Jake Moshenko -Jake Sanders -Jakub Drahos -Jakub Guzik -James Allen -James Carey -James Carr -James DeFelice -James Harrison Fisher -James Kyburz -James Kyle -James Lal -James Mills -James Nesbitt -James Nugent -James Sanders -James Turnbull -James Watkins-Harvey -Jamie Hannaford -Jamshid Afshar -Jan Breig -Jan Chren -Jan Garcia -Jan Götte -Jan Keromnes -Jan Koprowski -Jan Pazdziora -Jan Toebes -Jan-Gerd Tenberge -Jan-Jaap Driessen -Jana Radhakrishnan -Jannick Fahlbusch -Januar Wayong -Jared Biel -Jared Hocutt -Jaroslaw Zabiello -Jasmine Hegman -Jason A. Donenfeld -Jason Divock -Jason Giedymin -Jason Green -Jason Hall -Jason Heiss -Jason Livesay -Jason McVetta -Jason Plum -Jason Shepherd -Jason Smith -Jason Sommer -Jason Stangroome -Javier Bassi -jaxgeller -Jay -Jay Kamat -Jay Lim -Jean Rouge -Jean-Baptiste Barth -Jean-Baptiste Dalido -Jean-Christophe Berthon -Jean-Paul Calderone -Jean-Pierre Huynh -Jean-Tiare Le Bigot -Jeeva S. Chelladhurai -Jeff Anderson -Jeff Hajewski -Jeff Johnston -Jeff Lindsay -Jeff Mickey -Jeff Minard -Jeff Nickoloff -Jeff Silberman -Jeff Welch -Jeff Zvier -Jeffrey Bolle -Jeffrey Morgan -Jeffrey van Gogh -Jenny Gebske -Jeremy Chambers -Jeremy Grosser -Jeremy Huntwork -Jeremy Price -Jeremy Qian -Jeremy Unruh -Jeremy Yallop -Jeroen Franse -Jeroen Jacobs -Jesse Dearing -Jesse Dubay -Jessica Frazelle -Jezeniel Zapanta -Jhon Honce -Ji.Zhilong -Jian Liao -Jian Zhang -Jiang Jinyang -Jianyong Wu -Jie Luo -Jie Ma -Jihyun Hwang -Jilles Oldenbeuving -Jim Alateras -Jim Carroll -Jim Ehrismann -Jim Galasyn -Jim Lin -Jim Minter -Jim Perrin -Jimmy Cuadra -Jimmy Puckett -Jimmy Song -Jinsoo Park -Jintao Zhang -Jiri Appl -Jiri Popelka -Jiuyue Ma -Jiří Župka -Joakim Roubert -Joao Fernandes -Joao Trindade -Joe Beda -Joe Doliner -Joe Ferguson -Joe Gordon -Joe Shaw -Joe Van Dyk -Joel Friedly -Joel Handwell -Joel Hansson -Joel Wurtz -Joey Geiger -Joey Geiger -Joey Gibson -Joffrey F -Johan Euphrosine -Johan Rydberg -Johanan Lieberman -Johannes 'fish' Ziemke -John Costa -John Feminella -John Gardiner Myers -John Gossman -John Harris -John Howard -John Laswell -John Maguire -John Mulhausen -John OBrien III -John Starks -John Stephens -John Tims -John V. Martinez -John Warwick -John Willis -Jon Johnson -Jon Surrell -Jon Wedaman -Jonas Dohse -Jonas Heinrich -Jonas Pfenniger -Jonathan A. Schweder -Jonathan A. Sternberg -Jonathan Boulle -Jonathan Camp -Jonathan Choy -Jonathan Dowland -Jonathan Lebon -Jonathan Lomas -Jonathan McCrohan -Jonathan Mueller -Jonathan Pares -Jonathan Rudenberg -Jonathan Stoppani -Jonh Wendell -Joni Sar -Joost Cassee -Jordan Arentsen -Jordan Jennings -Jordan Sissel -Jordi Massaguer Pla -Jorge Marin -Jorit Kleine-Möllhoff -Jose Diaz-Gonzalez -Joseph Anthony Pasquale Holsten -Joseph Hager -Joseph Kern -Joseph Rothrock -Josh -Josh Bodah -Josh Bonczkowski -Josh Chorlton -Josh Eveleth -Josh Hawn -Josh Horwitz -Josh Poimboeuf -Josh Soref -Josh Wilson -Josiah Kiehl -José Tomás Albornoz -Joyce Jang -JP -Julian Taylor -Julien Barbier -Julien Bisconti -Julien Bordellier -Julien Dubois -Julien Kassar -Julien Maitrehenry -Julien Pervillé -Julien Pivotto -Julio Guerra -Julio Montes -Jun Du -Jun-Ru Chang -junxu -Jussi Nummelin -Justas Brazauskas -Justen Martin -Justin Cormack -Justin Force -Justin Keller <85903732+jk-vb@users.noreply.github.com> -Justin Menga -Justin Plock -Justin Simonelis -Justin Terry -Justyn Temme -Jyrki Puttonen -Jérémy Leherpeur -Jérôme Petazzoni -Jörg Thalheim -K. Heller -Kai Blin -Kai Qiang Wu (Kennan) -Kaijie Chen -Kamil Domański -Kamjar Gerami -Kanstantsin Shautsou -Kara Alexandra -Karan Lyons -Kareem Khazem -kargakis -Karl Grzeszczak -Karol Duleba -Karthik Karanth -Karthik Nayak -Kasper Fabæch Brandt -Kate Heddleston -Katie McLaughlin -Kato Kazuyoshi -Katrina Owen -Kawsar Saiyeed -Kay Yan -kayrus -Kazuhiro Sera -Kazuyoshi Kato -Ke Li -Ke Xu -Kei Ohmura -Keith Hudgins -Keli Hu -Ken Cochrane -Ken Herner -Ken ICHIKAWA -Ken Reese -Kenfe-Mickaël Laventure -Kenjiro Nakayama -Kent Johnson -Kenta Tada -Kevin "qwazerty" Houdebert -Kevin Alvarez -Kevin Burke -Kevin Clark -Kevin Feyrer -Kevin J. Lynagh -Kevin Jing Qiu -Kevin Kern -Kevin Menard -Kevin Meredith -Kevin P. Kucharczyk -Kevin Parsons -Kevin Richardson -Kevin Shi -Kevin Wallace -Kevin Yap -Keyvan Fatehi -kies -Kim BKC Carlbacker -Kim Eik -Kimbro Staken -Kir Kolyshkin -Kiran Gangadharan -Kirill SIbirev -Kirk Easterson -knappe -Kohei Tsuruta -Koichi Shiraishi -Konrad Kleine -Konrad Ponichtera -Konstantin Gribov -Konstantin L -Konstantin Pelykh -Kostadin Plachkov -Krasi Georgiev -Krasimir Georgiev -Kris-Mikael Krister -Kristian Haugene -Kristina Zabunova -Krystian Wojcicki -Kunal Kushwaha -Kunal Tyagi -Kyle Conroy -Kyle Linden -Kyle Squizzato -Kyle Wuolle -kyu -Lachlan Coote -Lai Jiangshan -Lajos Papp -Lakshan Perera -Lalatendu Mohanty -Lance Chen -Lance Kinley -Lars Butler -Lars Kellogg-Stedman -Lars R. Damerow -Lars-Magnus Skog -Laszlo Meszaros -Laura Brehm -Laura Frank -Laurent Bernaille -Laurent Erignoux -Laurie Voss -Leandro Motta Barros -Leandro Siqueira -Lee Calcote -Lee Chao <932819864@qq.com> -Lee, Meng-Han -Lei Gong -Lei Jitang -Leiiwang -Len Weincier -Lennie -Leo Gallucci -Leonardo Nodari -Leonardo Taccari -Leszek Kowalski -Levi Blackstone -Levi Gross -Levi Harrison -Lewis Daly -Lewis Marshall -Lewis Peckover -Li Yi -Liam Macgillavry -Liana Lo -Liang Mingqiang -Liang-Chi Hsieh -liangwei -Liao Qingwei -Lifubang -Lihua Tang -Lily Guo -limeidan -Lin Lu -LingFaKe -Linus Heckemann -Liran Tal -Liron Levin -Liu Bo -Liu Hua -liwenqi -lixiaobing10051267 -Liz Zhang -LIZAO LI -Lizzie Dixon <_@lizzie.io> -Lloyd Dewolf -Lokesh Mandvekar -longliqiang88 <394564827@qq.com> -Lorenz Leutgeb -Lorenzo Fontana -Lotus Fenn -Louis Delossantos -Louis Opter -Luca Favatella -Luca Marturana -Luca Orlandi -Luca-Bogdan Grigorescu -Lucas Chan -Lucas Chi -Lucas Molas -Lucas Silvestre -Luciano Mores -Luis Henrique Mulinari -Luis Martínez de Bartolomé Izquierdo -Luiz Svoboda -Lukas Heeren -Lukas Waslowski -lukaspustina -Lukasz Zajaczkowski -Luke Marsden -Lyn -Lynda O'Leary -Lénaïc Huard -Ma Müller -Ma Shimiao -Mabin -Madhan Raj Mookkandy -Madhav Puri -Madhu Venugopal -Mageee -Mahesh Tiyyagura -malnick -Malte Janduda -Manfred Touron -Manfred Zabarauskas -Manjunath A Kumatagi -Mansi Nahar -Manuel Meurer -Manuel Rüger -Manuel Woelker -mapk0y -Marc Abramowitz -Marc Kuo -Marc Tamsky -Marcel Edmund Franke -Marcelo Horacio Fortino -Marcelo Salazar -Marco Hennings -Marcus Cobden -Marcus Farkas -Marcus Linke -Marcus Martins -Marcus Ramberg -Marek Goldmann -Marian Marinov -Marianna Tessel -Mario Loriedo -Marius Gundersen -Marius Sturm -Marius Voila -Mark Allen -Mark Feit -Mark Jeromin -Mark McGranaghan -Mark McKinstry -Mark Milstein -Mark Oates -Mark Parker -Mark Vainomaa -Mark West -Markan Patel -Marko Mikulicic -Marko Tibold -Markus Fix -Markus Kortlang -Martijn Dwars -Martijn van Oosterhout -Martin Braun -Martin Dojcak -Martin Honermeyer -Martin Kelly -Martin Mosegaard Amdisen -Martin Muzatko -Martin Redmond -Maru Newby -Mary Anthony -Masahito Zembutsu -Masato Ohba -Masayuki Morita -Mason Malone -Mateusz Sulima -Mathias Monnerville -Mathieu Champlon -Mathieu Le Marec - Pasquet -Mathieu Parent -Mathieu Paturel -Matt Apperson -Matt Bachmann -Matt Bajor -Matt Bentley -Matt Haggard -Matt Hoyle -Matt McCormick -Matt Moore -Matt Morrison <3maven@gmail.com> -Matt Richardson -Matt Rickard -Matt Robenolt -Matt Schurenko -Matt Williams -Matthew Heon -Matthew Lapworth -Matthew Mayer -Matthew Mosesohn -Matthew Mueller -Matthew Riley -Matthias Klumpp -Matthias Kühnle -Matthias Rampke -Matthieu Fronton -Matthieu Hauglustaine -Mattias Jernberg -Mauricio Garavaglia -mauriyouth -Max Harmathy -Max Shytikov -Max Timchenko -Maxim Fedchyshyn -Maxim Ivanov -Maxim Kulkin -Maxim Treskin -Maxime Petazzoni -Maximiliano Maccanti -Maxwell -Meaglith Ma -meejah -Megan Kostick -Mehul Kar -Mei ChunTao -Mengdi Gao -Menghui Chen -Mert Yazıcıoğlu -mgniu -Micah Zoltu -Michael A. Smith -Michael Beskin -Michael Bridgen -Michael Brown -Michael Chiang -Michael Crosby -Michael Currie -Michael Friis -Michael Gorsuch -Michael Grauer -Michael Holzheu -Michael Hudson-Doyle -Michael Huettermann -Michael Irwin -Michael Kuehn -Michael Käufl -Michael Neale -Michael Nussbaum -Michael Prokop -Michael Scharf -Michael Spetsiotis -Michael Stapelberg -Michael Steinert -Michael Thies -Michael Weidmann -Michael West -Michael Zhao -Michal Fojtik -Michal Gebauer -Michal Jemala -Michal Kostrzewa -Michal Minář -Michal Rostecki -Michal Wieczorek -Michaël Pailloncy -Michał Czeraszkiewicz -Michał Gryko -Michał Kosek -Michiel de Jong -Mickaël Fortunato -Mickaël Remars -Miguel Angel Fernández -Miguel Morales -Miguel Perez -Mihai Borobocea -Mihuleacc Sergiu -Mikael Davranche -Mike Brown -Mike Bush -Mike Casas -Mike Chelen -Mike Danese -Mike Dillon -Mike Dougherty -Mike Estes -Mike Gaffney -Mike Goelzer -Mike Leone -Mike Lundy -Mike MacCana -Mike Naberezny -Mike Snitzer -mikelinjie <294893458@qq.com> -Mikhail Sobolev -Miklos Szegedi -Milas Bowman -Milind Chawre -Miloslav Trmač -mingqing -Mingzhen Feng -Misty Stanley-Jones -Mitch Capper -Mizuki Urushida -mlarcher -Mohammad Banikazemi -Mohammad Nasirifar -Mohammed Aaqib Ansari -Mohit Soni -Moorthy RS -Morgan Bauer -Morgante Pell -Morgy93 -Morten Siebuhr -Morton Fox -Moysés Borges -mrfly -Mrunal Patel -Muayyad Alsadi -Muhammad Zohaib Aslam -Mustafa Akın -Muthukumar R -Máximo Cuadros -Médi-Rémi Hashim -Nace Oroz -Nahum Shalman -Nakul Pathak -Nalin Dahyabhai -Nan Monnand Deng -Naoki Orii -Natalie Parker -Natanael Copa -Natasha Jarus -Nate Brennand -Nate Eagleson -Nate Jones -Nathan Carlson -Nathan Herald -Nathan Hsieh -Nathan Kleyn -Nathan LeClaire -Nathan McCauley -Nathan Williams -Naveed Jamil -Neal McBurnett -Neil Horman -Neil Peterson -Nelson Chen -Neyazul Haque -Nghia Tran -Niall O'Higgins -Nicholas E. Rabenau -Nick Adcock -Nick DeCoursin -Nick Irvine -Nick Neisen -Nick Parker -Nick Payne -Nick Russo -Nick Santos -Nick Stenning -Nick Stinemates -Nick Wood -NickrenREN -Nicola Kabar -Nicolas Borboën -Nicolas De Loof -Nicolas Dudebout -Nicolas Goy -Nicolas Kaiser -Nicolas Sterchele -Nicolas V Castet -Nicolás Hock Isaza -Niel Drummond -Nigel Poulton -Nik Nyby -Nikhil Chawla -NikolaMandic -Nikolas Garofil -Nikolay Edigaryev -Nikolay Milovanov -ningmingxiao -Nirmal Mehta -Nishant Totla -NIWA Hideyuki -Noah Meyerhans -Noah Treuhaft -NobodyOnSE -noducks -Nolan Darilek -Noriki Nakamura -nponeccop -Nurahmadie -Nuutti Kotivuori -nzwsch -O.S. Tezer -objectified -Odin Ugedal -Oguz Bilgic -Oh Jinkyun -Ohad Schneider -ohmystack -Ole Reifschneider -Oliver Neal -Oliver Reason -Olivier Gambier -Olle Jonsson -Olli Janatuinen -Olly Pomeroy -Omri Shiv -Onur Filiz -Oriol Francès -Oscar Bonilla <6f6231@gmail.com> -oscar.chen <2972789494@qq.com> -Oskar Niburski -Otto Kekäläinen -Ouyang Liduo -Ovidio Mallo -Panagiotis Moustafellos -Paolo G. Giarrusso -Pascal -Pascal Bach -Pascal Borreli -Pascal Hartig -Patrick Böänziger -Patrick Devine -Patrick Haas -Patrick Hemmer -Patrick Stapleton -Patrik Cyvoct -pattichen -Paul "TBBle" Hampson -Paul -paul -Paul Annesley -Paul Bellamy -Paul Bowsher -Paul Furtado -Paul Hammond -Paul Jimenez -Paul Kehrer -Paul Lietar -Paul Liljenberg -Paul Morie -Paul Nasrat -Paul Weaver -Paulo Gomes -Paulo Ribeiro -Pavel Lobashov -Pavel Matěja -Pavel Pletenev -Pavel Pospisil -Pavel Sutyrin -Pavel Tikhomirov -Pavlos Ratis -Pavol Vargovcik -Pawel Konczalski -Paweł Gronowski -Peeyush Gupta -Peggy Li -Pei Su -Peng Tao -Penghan Wang -Per Weijnitz -perhapszzy@sina.com -Pete Woods -Peter Bourgon -Peter Braden -Peter Bücker -Peter Choi -Peter Dave Hello -Peter Edge -Peter Ericson -Peter Esbensen -Peter Jaffe -Peter Kang -Peter Malmgren -Peter Salvatore -Peter Volpe -Peter Waller -Petr Švihlík -Petros Angelatos -Phil -Phil Estes -Phil Sphicas -Phil Spitler -Philip Alexander Etling -Philip Monroe -Philipp Gillé -Philipp Wahala -Philipp Weissensteiner -Phillip Alexander -phineas -pidster -Piergiuliano Bossi -Pierre -Pierre Carrier -Pierre Dal-Pra -Pierre Wacrenier -Pierre-Alain RIVIERE -Piotr Bogdan -Piotr Karbowski -Porjo -Poul Kjeldager Sørensen -Pradeep Chhetri -Pradip Dhara -Pradipta Kr. Banerjee -Prasanna Gautam -Pratik Karki -Prayag Verma -Priya Wadhwa -Projjol Banerji -Przemek Hejman -Puneet Pruthi -Pure White -pysqz -Qiang Huang -Qin TianHuan -Qinglan Peng -Quan Tian -qudongfang -Quentin Brossard -Quentin Perez -Quentin Tayssier -r0n22 -Radostin Stoyanov -Rafal Jeczalik -Rafe Colton -Raghavendra K T -Raghuram Devarakonda -Raja Sami -Rajat Pandit -Rajdeep Dua -Ralf Sippl -Ralle -Ralph Bean -Ramkumar Ramachandra -Ramon Brooker -Ramon van Alteren -RaviTeja Pothana -Ray Tsang -ReadmeCritic -realityone -Recursive Madman -Reficul -Regan McCooey -Remi Rampin -Remy Suen -Renato Riccieri Santos Zannon -Renaud Gaubert -Rhys Hiltner -Ri Xu -Ricardo N Feliciano -Rich Horwood -Rich Moyse -Rich Seymour -Richard Burnison -Richard Harvey -Richard Mathie -Richard Metzler -Richard Scothern -Richo Healey -Rick Bradley -Rick van de Loo -Rick Wieman -Rik Nijessen -Riku Voipio -Riley Guerin -Ritesh H Shukla -Riyaz Faizullabhoy -Rob Cowsill <42620235+rcowsill@users.noreply.github.com> -Rob Gulewich -Rob Vesse -Robert Bachmann -Robert Bittle -Robert Obryk -Robert Schneider -Robert Shade -Robert Stern -Robert Terhaar -Robert Wallis -Robert Wang -Roberto G. Hashioka -Roberto Muñoz Fernández -Robin Naundorf -Robin Schneider -Robin Speekenbrink -Robin Thoni -robpc -Rodolfo Carvalho -Rodrigo Campos -Rodrigo Vaz -Roel Van Nyen -Roger Peppe -Rohit Jnagal -Rohit Kadam -Rohit Kapur -Rojin George -Roland Huß -Roland Kammerer -Roland Moriz -Roma Sokolov -Roman Dudin -Roman Mazur -Roman Strashkin -Roman Volosatovs -Roman Zabaluev -Ron Smits -Ron Williams -Rong Gao -Rong Zhang -Rongxiang Song -Rony Weng -root -root -root -root -Rory Hunter -Rory McCune -Ross Boucher -Rovanion Luckey -Roy Reznik -Royce Remer -Rozhnov Alexandr -Rudolph Gottesheim -Rui Cao -Rui Lopes -Ruilin Li -Runshen Zhu -Russ Magee -Ryan Abrams -Ryan Anderson -Ryan Aslett -Ryan Barry -Ryan Belgrave -Ryan Campbell -Ryan Detzel -Ryan Fowler -Ryan Liu -Ryan McLaughlin -Ryan O'Donnell -Ryan Seto -Ryan Shea -Ryan Simmen -Ryan Stelly -Ryan Thomas -Ryan Trauntvein -Ryan Wallner -Ryan Zhang -ryancooper7 -RyanDeng -Ryo Nakao -Ryoga Saito -Rémy Greinhofer -s. rannou -Sabin Basyal -Sachin Joshi -Sagar Hani -Sainath Grandhi -Sakeven Jiang -Salahuddin Khan -Sally O'Malley -Sam Abed -Sam Alba -Sam Bailey -Sam J Sharpe -Sam Neirinck -Sam Reis -Sam Rijs -Sam Whited -Sambuddha Basu -Sami Wagiaalla -Samuel Andaya -Samuel Dion-Girardeau -Samuel Karp -Samuel PHAN -sanchayanghosh -Sandeep Bansal -Sankar சங்கர் -Sanket Saurav -Santhosh Manohar -sapphiredev -Sargun Dhillon -Sascha Andres -Sascha Grunert -SataQiu -Satnam Singh -Satoshi Amemiya -Satoshi Tagomori -Scott Bessler -Scott Collier -Scott Johnston -Scott Percival -Scott Stamp -Scott Walls -sdreyesg -Sean Christopherson -Sean Cronin -Sean Lee -Sean McIntyre -Sean OMeara -Sean P. Kane -Sean Rodman -Sebastiaan van Steenis -Sebastiaan van Stijn -Sebastian Höffner -Sebastian Radloff -Sebastien Goasguen -Senthil Kumar Selvaraj -Senthil Kumaran -SeongJae Park -Seongyeol Lim -Serge Hallyn -Sergey Alekseev -Sergey Evstifeev -Sergii Kabashniuk -Sergio Lopez -Serhat Gülçiçek -SeungUkLee -Sevki Hasirci -Shane Canon -Shane da Silva -Shaun Kaasten -shaunol -Shawn Landden -Shawn Siefkas -shawnhe -Shayan Pooya -Shayne Wang -Shekhar Gulati -Sheng Yang -Shengbo Song -Shengjing Zhu -Shev Yan -Shih-Yuan Lee -Shihao Xia -Shijiang Wei -Shijun Qin -Shishir Mahajan -Shoubhik Bose -Shourya Sarcar -Shu-Wai Chow -shuai-z -Shukui Yang -Sian Lerk Lau -Siarhei Rasiukevich -Sidhartha Mani -sidharthamani -Silas Sewell -Silvan Jegen -Simão Reis -Simon Barendse -Simon Eskildsen -Simon Ferquel -Simon Leinen -Simon Menke -Simon Taranto -Simon Vikstrom -Sindhu S -Sjoerd Langkemper -skanehira -Smark Meng -Solganik Alexander -Solomon Hykes -Song Gao -Soshi Katsuta -Sotiris Salloumis -Soulou -Spencer Brown -Spencer Smith -Spike Curtis -Sridatta Thatipamala -Sridhar Ratnakumar -Srini Brahmaroutu -Srinivasan Srivatsan -Staf Wagemakers -Stanislav Bondarenko -Stanislav Levin -Steeve Morin -Stefan Berger -Stefan J. Wernli -Stefan Praszalowicz -Stefan S. -Stefan Scherer -Stefan Staudenmeyer -Stefan Weil -Steffen Butzer -Stephan Spindler -Stephen Benjamin -Stephen Crosby -Stephen Day -Stephen Drake -Stephen Rust -Steve Desmond -Steve Dougherty -Steve Durrheimer -Steve Francia -Steve Koch -Steven Burgess -Steven Erenst -Steven Hartland -Steven Iveson -Steven Merrill -Steven Richards -Steven Taylor -Stéphane Este-Gracias -Stig Larsson -Su Wang -Subhajit Ghosh -Sujith Haridasan -Sun Gengze <690388648@qq.com> -Sun Jianbo -Sune Keller -Sunny Gogoi -Suryakumar Sudar -Sven Dowideit -Swapnil Daingade -Sylvain Baubeau -Sylvain Bellemare -Sébastien -Sébastien HOUZÉ -Sébastien Luttringer -Sébastien Stormacq -Sören Tempel -Tabakhase -Tadej Janež -Takuto Sato -tang0th -Tangi Colin -Tatsuki Sugiura -Tatsushi Inagaki -Taylan Isikdemir -Taylor Jones -Ted M. Young -Tehmasp Chaudhri -Tejaswini Duggaraju -Tejesh Mehta -Terry Chu -terryding77 <550147740@qq.com> -Thatcher Peskens -theadactyl -Thell 'Bo' Fowler -Thermionix -Thiago Alves Silva -Thijs Terlouw -Thomas Bikeev -Thomas Frössman -Thomas Gazagnaire -Thomas Graf -Thomas Grainger -Thomas Hansen -Thomas Ledos -Thomas Leonard -Thomas Léveil -Thomas Orozco -Thomas Riccardi -Thomas Schroeter -Thomas Sjögren -Thomas Swift -Thomas Tanaka -Thomas Texier -Ti Zhou -Tiago Seabra -Tianon Gravi -Tianyi Wang -Tibor Vass -Tiffany Jernigan -Tiffany Low -Till Claassen -Till Wegmüller -Tim -Tim Bart -Tim Bosse -Tim Dettrick -Tim Düsterhus -Tim Hockin -Tim Potter -Tim Ruffles -Tim Smith -Tim Terhorst -Tim Wagner -Tim Wang -Tim Waugh -Tim Wraight -Tim Zju <21651152@zju.edu.cn> -timchenxiaoyu <837829664@qq.com> -timfeirg -Timo Rothenpieler -Timothy Hobbs -tjwebb123 -tobe -Tobias Bieniek -Tobias Bradtke -Tobias Gesellchen -Tobias Klauser -Tobias Munk -Tobias Pfandzelter -Tobias Schmidt -Tobias Schwab -Todd Crane -Todd Lunter -Todd Whiteman -Toli Kuznets -Tom Barlow -Tom Booth -Tom Denham -Tom Fotherby -Tom Howe -Tom Hulihan -Tom Maaswinkel -Tom Parker -Tom Sweeney -Tom Wilkie -Tom X. Tobin -Tom Zhao -Tomas Janousek -Tomas Kral -Tomas Tomecek -Tomasz Kopczynski -Tomasz Lipinski -Tomasz Nurkiewicz -Tomek Mańko -Tommaso Visconti -Tomoya Tabuchi -Tomáš Hrčka -tonic -Tonny Xu -Tony Abboud -Tony Daws -Tony Miller -toogley -Torstein Husebø -Toshiaki Makita -Tõnis Tiigi -Trace Andreason -tracylihui <793912329@qq.com> -Trapier Marshall -Travis Cline -Travis Thieman -Trent Ogren -Trevor -Trevor Pounds -Trevor Sullivan -Trishna Guha -Tristan Carel -Troy Denton -Tudor Brindus -Ty Alexander -Tycho Andersen -Tyler Brock -Tyler Brown -Tzu-Jung Lee -uhayate -Ulysse Carion -Umesh Yadav -Utz Bacher -vagrant -Vaidas Jablonskis -Valentin Kulesh -vanderliang -Velko Ivanov -Veres Lajos -Victor Algaze -Victor Coisne -Victor Costan -Victor I. Wood -Victor Lyuboslavsky -Victor Marmol -Victor Palma -Victor Vieux -Victoria Bialas -Vijaya Kumar K -Vikas Choudhary -Vikram bir Singh -Viktor Stanchev -Viktor Vojnovski -VinayRaghavanKS -Vincent Batts -Vincent Bernat -Vincent Boulineau -Vincent Demeester -Vincent Giersch -Vincent Mayers -Vincent Woo -Vinod Kulkarni -Vishal Doshi -Vishnu Kannan -Vitaly Ostrosablin -Vitor Monteiro -Vivek Agarwal -Vivek Dasgupta -Vivek Goyal -Vladimir Bulyga -Vladimir Kirillov -Vladimir Pouzanov -Vladimir Rutsky -Vladimir Varankin -VladimirAus -Vladislav Kolesnikov -Vlastimil Zeman -Vojtech Vitek (V-Teq) -Walter Leibbrandt -Walter Stanish -Wang Chao -Wang Guoliang -Wang Jie -Wang Long -Wang Ping -Wang Xing -Wang Yuexiao -Wang Yumu <37442693@qq.com> -wanghuaiqing -Ward Vandewege -WarheadsSE -Wassim Dhif -Wataru Ishida -Wayne Chang -Wayne Song -Weerasak Chongnguluam -Wei Fu -Wei Wu -Wei-Ting Kuo -weipeng -weiyan -Weiyang Zhu -Wen Cheng Ma -Wendel Fleming -Wenjun Tang -Wenkai Yin -wenlxie -Wenxuan Zhao -Wenyu You <21551128@zju.edu.cn> -Wenzhi Liang -Wes Morgan -Wewang Xiaorenfine -Wiktor Kwapisiewicz -Will Dietz -Will Rouesnel -Will Weaver -willhf -William Delanoue -William Henry -William Hubbs -William Martin -William Riancho -William Thurston -Wilson Júnior -Wing-Kam Wong -WiseTrem -Wolfgang Nagele -Wolfgang Powisch -Wonjun Kim -WuLonghui -xamyzhao -Xia Wu -Xian Chaobo -Xianglin Gao -Xianjie -Xianlu Bird -Xiao YongBiao -Xiao Zhang -XiaoBing Jiang -Xiaodong Liu -Xiaodong Zhang -Xiaohua Ding -Xiaoxi He -Xiaoxu Chen -Xiaoyu Zhang -xichengliudui <1693291525@qq.com> -xiekeyang -Ximo Guanter Gonzálbez -xin.li -Xinbo Weng -Xinfeng Liu -Xinzi Zhou -Xiuming Chen -Xuecong Liao -xuzhaokui -Yadnyawalkya Tale -Yahya -yalpul -YAMADA Tsuyoshi -Yamasaki Masahide -Yamazaki Masashi -Yan Feng -Yan Zhu -Yang Bai -Yang Li -Yang Pengfei -yangchenliang -Yann Autissier -Yanqiang Miao -Yao Zaiyong -Yash Murty -Yassine Tijani -Yasunori Mahata -Yazhong Liu -Yestin Sun -Yi EungJun -Yibai Zhang -Yihang Ho -Ying Li -Yohei Ueda -Yong Tang -Yongxin Li -Yongzhi Pan -Yosef Fertel -You-Sheng Yang (楊有勝) -youcai -Youcef YEKHLEF -Youfu Zhang -Yu Changchun -Yu Chengxia -Yu Peng -Yu-Ju Hong -Yuan Sun -Yuanhong Peng -Yue Zhang -Yufei Xiong -Yuhao Fang -Yuichiro Kaneko -YujiOshima -Yunxiang Huang -Yurii Rashkovskii -Yusuf Tarık Günaydın -Yves Blusseau <90z7oey02@sneakemail.com> -Yves Junqueira -Zac Dover -Zach Borboa -Zach Gershman -Zachary Jaffee -Zain Memon -Zaiste! -Zane DeGraffenried -Zefan Li -Zen Lin(Zhinan Lin) -Zhang Kun -Zhang Wei -Zhang Wentao -ZhangHang -zhangxianwei -Zhenan Ye <21551168@zju.edu.cn> -zhenghenghuo -Zhenhai Gao -Zhenkun Bi -ZhiPeng Lu -zhipengzuo -Zhou Hao -Zhoulin Xie -Zhu Guihua -Zhu Kunjia -Zhuoyun Wei -Ziheng Liu -Zilin Du -zimbatm -Ziming Dong -ZJUshuaizhou <21551191@zju.edu.cn> -zmarouf -Zoltan Tombol -Zou Yu -zqh -Zuhayr Elahi -Zunayed Ali -Álvaro Lázaro -Átila Camurça Alves -尹吉峰 -屈骏 -徐俊杰 -慕陶 -搏通 -黄艳红00139573 -정재영 diff --git a/vendor/github.com/docker/docker/LICENSE b/vendor/github.com/docker/docker/LICENSE deleted file mode 100644 index 6d8d58fb6..000000000 --- a/vendor/github.com/docker/docker/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2013-2018 Docker, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - https://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/docker/docker/NOTICE b/vendor/github.com/docker/docker/NOTICE deleted file mode 100644 index 58b19b6d1..000000000 --- a/vendor/github.com/docker/docker/NOTICE +++ /dev/null @@ -1,19 +0,0 @@ -Docker -Copyright 2012-2017 Docker, Inc. - -This product includes software developed at Docker, Inc. (https://www.docker.com). - -This product contains software (https://github.com/creack/pty) developed -by Keith Rarick, licensed under the MIT License. - -The following is courtesy of our legal counsel: - - -Use and transfer of Docker may be subject to certain restrictions by the -United States and other governments. -It is your responsibility to ensure that your use and/or transfer does not -violate applicable laws. - -For more information, please see https://www.bis.doc.gov - -See also https://www.apache.org/dev/crypto.html and/or seek legal counsel. diff --git a/vendor/github.com/docker/docker/api/README.md b/vendor/github.com/docker/docker/api/README.md deleted file mode 100644 index f136c3433..000000000 --- a/vendor/github.com/docker/docker/api/README.md +++ /dev/null @@ -1,42 +0,0 @@ -# Working on the Engine API - -The Engine API is an HTTP API used by the command-line client to communicate with the daemon. It can also be used by third-party software to control the daemon. - -It consists of various components in this repository: - -- `api/swagger.yaml` A Swagger definition of the API. -- `api/types/` Types shared by both the client and server, representing various objects, options, responses, etc. Most are written manually, but some are automatically generated from the Swagger definition. See [#27919](https://github.com/docker/docker/issues/27919) for progress on this. -- `cli/` The command-line client. -- `client/` The Go client used by the command-line client. It can also be used by third-party Go programs. -- `daemon/` The daemon, which serves the API. - -## Swagger definition - -The API is defined by the [Swagger](http://swagger.io/specification/) definition in `api/swagger.yaml`. This definition can be used to: - -1. Automatically generate documentation. -2. Automatically generate the Go server and client. (A work-in-progress.) -3. Provide a machine readable version of the API for introspecting what it can do, automatically generating clients for other languages, etc. - -## Updating the API documentation - -The API documentation is generated entirely from `api/swagger.yaml`. If you make updates to the API, edit this file to represent the change in the documentation. - -The file is split into two main sections: - -- `definitions`, which defines re-usable objects used in requests and responses -- `paths`, which defines the API endpoints (and some inline objects which don't need to be reusable) - -To make an edit, first look for the endpoint you want to edit under `paths`, then make the required edits. Endpoints may reference reusable objects with `$ref`, which can be found in the `definitions` section. - -There is hopefully enough example material in the file for you to copy a similar pattern from elsewhere in the file (e.g. adding new fields or endpoints), but for the full reference, see the [Swagger specification](https://github.com/docker/docker/issues/27919). - -`swagger.yaml` is validated by `hack/validate/swagger` to ensure it is a valid Swagger definition. This is useful when making edits to ensure you are doing the right thing. - -## Viewing the API documentation - -When you make edits to `swagger.yaml`, you may want to check the generated API documentation to ensure it renders correctly. - -Run `make swagger-docs` and a preview will be running at `http://localhost`. Some of the styling may be incorrect, but you'll be able to ensure that it is generating the correct documentation. - -The production documentation is generated by vendoring `swagger.yaml` into [docker/docker.github.io](https://github.com/docker/docker.github.io). diff --git a/vendor/github.com/docker/docker/api/common.go b/vendor/github.com/docker/docker/api/common.go deleted file mode 100644 index cba66bc46..000000000 --- a/vendor/github.com/docker/docker/api/common.go +++ /dev/null @@ -1,11 +0,0 @@ -package api // import "github.com/docker/docker/api" - -// Common constants for daemon and client. -const ( - // DefaultVersion of Current REST API - DefaultVersion = "1.43" - - // NoBaseImageSpecifier is the symbol used by the FROM - // command to specify that no base image is to be used. - NoBaseImageSpecifier = "scratch" -) diff --git a/vendor/github.com/docker/docker/api/common_unix.go b/vendor/github.com/docker/docker/api/common_unix.go deleted file mode 100644 index 19fc63d65..000000000 --- a/vendor/github.com/docker/docker/api/common_unix.go +++ /dev/null @@ -1,7 +0,0 @@ -//go:build !windows -// +build !windows - -package api // import "github.com/docker/docker/api" - -// MinVersion represents Minimum REST API version supported -const MinVersion = "1.12" diff --git a/vendor/github.com/docker/docker/api/common_windows.go b/vendor/github.com/docker/docker/api/common_windows.go deleted file mode 100644 index 590ba5479..000000000 --- a/vendor/github.com/docker/docker/api/common_windows.go +++ /dev/null @@ -1,8 +0,0 @@ -package api // import "github.com/docker/docker/api" - -// MinVersion represents Minimum REST API version supported -// Technically the first daemon API version released on Windows is v1.25 in -// engine version 1.13. However, some clients are explicitly using downlevel -// APIs (e.g. docker-compose v2.1 file format) and that is just too restrictive. -// Hence also allowing 1.24 on Windows. -const MinVersion string = "1.24" diff --git a/vendor/github.com/docker/docker/api/swagger-gen.yaml b/vendor/github.com/docker/docker/api/swagger-gen.yaml deleted file mode 100644 index f07a02737..000000000 --- a/vendor/github.com/docker/docker/api/swagger-gen.yaml +++ /dev/null @@ -1,12 +0,0 @@ - -layout: - models: - - name: definition - source: asset:model - target: "{{ joinFilePath .Target .ModelPackage }}" - file_name: "{{ (snakize (pascalize .Name)) }}.go" - operations: - - name: handler - source: asset:serverOperation - target: "{{ joinFilePath .Target .APIPackage .Package }}" - file_name: "{{ (snakize (pascalize .Name)) }}.go" diff --git a/vendor/github.com/docker/docker/api/swagger.yaml b/vendor/github.com/docker/docker/api/swagger.yaml deleted file mode 100644 index d98bc1bfd..000000000 --- a/vendor/github.com/docker/docker/api/swagger.yaml +++ /dev/null @@ -1,12143 +0,0 @@ -# A Swagger 2.0 (a.k.a. OpenAPI) definition of the Engine API. -# -# This is used for generating API documentation and the types used by the -# client/server. See api/README.md for more information. -# -# Some style notes: -# - This file is used by ReDoc, which allows GitHub Flavored Markdown in -# descriptions. -# - There is no maximum line length, for ease of editing and pretty diffs. -# - operationIds are in the format "NounVerb", with a singular noun. - -swagger: "2.0" -schemes: - - "http" - - "https" -produces: - - "application/json" - - "text/plain" -consumes: - - "application/json" - - "text/plain" -basePath: "/v1.43" -info: - title: "Docker Engine API" - version: "1.43" - x-logo: - url: "https://docs.docker.com/assets/images/logo-docker-main.png" - description: | - The Engine API is an HTTP API served by Docker Engine. It is the API the - Docker client uses to communicate with the Engine, so everything the Docker - client can do can be done with the API. - - Most of the client's commands map directly to API endpoints (e.g. `docker ps` - is `GET /containers/json`). The notable exception is running containers, - which consists of several API calls. - - # Errors - - The API uses standard HTTP status codes to indicate the success or failure - of the API call. The body of the response will be JSON in the following - format: - - ``` - { - "message": "page not found" - } - ``` - - # Versioning - - The API is usually changed in each release, so API calls are versioned to - ensure that clients don't break. To lock to a specific version of the API, - you prefix the URL with its version, for example, call `/v1.30/info` to use - the v1.30 version of the `/info` endpoint. If the API version specified in - the URL is not supported by the daemon, a HTTP `400 Bad Request` error message - is returned. - - If you omit the version-prefix, the current version of the API (v1.43) is used. - For example, calling `/info` is the same as calling `/v1.43/info`. Using the - API without a version-prefix is deprecated and will be removed in a future release. - - Engine releases in the near future should support this version of the API, - so your client will continue to work even if it is talking to a newer Engine. - - The API uses an open schema model, which means server may add extra properties - to responses. Likewise, the server will ignore any extra query parameters and - request body properties. When you write clients, you need to ignore additional - properties in responses to ensure they do not break when talking to newer - daemons. - - - # Authentication - - Authentication for registries is handled client side. The client has to send - authentication details to various endpoints that need to communicate with - registries, such as `POST /images/(name)/push`. These are sent as - `X-Registry-Auth` header as a [base64url encoded](https://tools.ietf.org/html/rfc4648#section-5) - (JSON) string with the following structure: - - ``` - { - "username": "string", - "password": "string", - "email": "string", - "serveraddress": "string" - } - ``` - - The `serveraddress` is a domain/IP without a protocol. Throughout this - structure, double quotes are required. - - If you have already got an identity token from the [`/auth` endpoint](#operation/SystemAuth), - you can just pass this instead of credentials: - - ``` - { - "identitytoken": "9cbaf023786cd7..." - } - ``` - -# The tags on paths define the menu sections in the ReDoc documentation, so -# the usage of tags must make sense for that: -# - They should be singular, not plural. -# - There should not be too many tags, or the menu becomes unwieldy. For -# example, it is preferable to add a path to the "System" tag instead of -# creating a tag with a single path in it. -# - The order of tags in this list defines the order in the menu. -tags: - # Primary objects - - name: "Container" - x-displayName: "Containers" - description: | - Create and manage containers. - - name: "Image" - x-displayName: "Images" - - name: "Network" - x-displayName: "Networks" - description: | - Networks are user-defined networks that containers can be attached to. - See the [networking documentation](https://docs.docker.com/network/) - for more information. - - name: "Volume" - x-displayName: "Volumes" - description: | - Create and manage persistent storage that can be attached to containers. - - name: "Exec" - x-displayName: "Exec" - description: | - Run new commands inside running containers. Refer to the - [command-line reference](https://docs.docker.com/engine/reference/commandline/exec/) - for more information. - - To exec a command in a container, you first need to create an exec instance, - then start it. These two API endpoints are wrapped up in a single command-line - command, `docker exec`. - - # Swarm things - - name: "Swarm" - x-displayName: "Swarm" - description: | - Engines can be clustered together in a swarm. Refer to the - [swarm mode documentation](https://docs.docker.com/engine/swarm/) - for more information. - - name: "Node" - x-displayName: "Nodes" - description: | - Nodes are instances of the Engine participating in a swarm. Swarm mode - must be enabled for these endpoints to work. - - name: "Service" - x-displayName: "Services" - description: | - Services are the definitions of tasks to run on a swarm. Swarm mode must - be enabled for these endpoints to work. - - name: "Task" - x-displayName: "Tasks" - description: | - A task is a container running on a swarm. It is the atomic scheduling unit - of swarm. Swarm mode must be enabled for these endpoints to work. - - name: "Secret" - x-displayName: "Secrets" - description: | - Secrets are sensitive data that can be used by services. Swarm mode must - be enabled for these endpoints to work. - - name: "Config" - x-displayName: "Configs" - description: | - Configs are application configurations that can be used by services. Swarm - mode must be enabled for these endpoints to work. - # System things - - name: "Plugin" - x-displayName: "Plugins" - - name: "System" - x-displayName: "System" - -definitions: - Port: - type: "object" - description: "An open port on a container" - required: [PrivatePort, Type] - properties: - IP: - type: "string" - format: "ip-address" - description: "Host IP address that the container's port is mapped to" - PrivatePort: - type: "integer" - format: "uint16" - x-nullable: false - description: "Port on the container" - PublicPort: - type: "integer" - format: "uint16" - description: "Port exposed on the host" - Type: - type: "string" - x-nullable: false - enum: ["tcp", "udp", "sctp"] - example: - PrivatePort: 8080 - PublicPort: 80 - Type: "tcp" - - MountPoint: - type: "object" - description: | - MountPoint represents a mount point configuration inside the container. - This is used for reporting the mountpoints in use by a container. - properties: - Type: - description: | - The mount type: - - - `bind` a mount of a file or directory from the host into the container. - - `volume` a docker volume with the given `Name`. - - `tmpfs` a `tmpfs`. - - `npipe` a named pipe from the host into the container. - - `cluster` a Swarm cluster volume - type: "string" - enum: - - "bind" - - "volume" - - "tmpfs" - - "npipe" - - "cluster" - example: "volume" - Name: - description: | - Name is the name reference to the underlying data defined by `Source` - e.g., the volume name. - type: "string" - example: "myvolume" - Source: - description: | - Source location of the mount. - - For volumes, this contains the storage location of the volume (within - `/var/lib/docker/volumes/`). For bind-mounts, and `npipe`, this contains - the source (host) part of the bind-mount. For `tmpfs` mount points, this - field is empty. - type: "string" - example: "/var/lib/docker/volumes/myvolume/_data" - Destination: - description: | - Destination is the path relative to the container root (`/`) where - the `Source` is mounted inside the container. - type: "string" - example: "/usr/share/nginx/html/" - Driver: - description: | - Driver is the volume driver used to create the volume (if it is a volume). - type: "string" - example: "local" - Mode: - description: | - Mode is a comma separated list of options supplied by the user when - creating the bind/volume mount. - - The default is platform-specific (`"z"` on Linux, empty on Windows). - type: "string" - example: "z" - RW: - description: | - Whether the mount is mounted writable (read-write). - type: "boolean" - example: true - Propagation: - description: | - Propagation describes how mounts are propagated from the host into the - mount point, and vice-versa. Refer to the [Linux kernel documentation](https://www.kernel.org/doc/Documentation/filesystems/sharedsubtree.txt) - for details. This field is not used on Windows. - type: "string" - example: "" - - DeviceMapping: - type: "object" - description: "A device mapping between the host and container" - properties: - PathOnHost: - type: "string" - PathInContainer: - type: "string" - CgroupPermissions: - type: "string" - example: - PathOnHost: "/dev/deviceName" - PathInContainer: "/dev/deviceName" - CgroupPermissions: "mrw" - - DeviceRequest: - type: "object" - description: "A request for devices to be sent to device drivers" - properties: - Driver: - type: "string" - example: "nvidia" - Count: - type: "integer" - example: -1 - DeviceIDs: - type: "array" - items: - type: "string" - example: - - "0" - - "1" - - "GPU-fef8089b-4820-abfc-e83e-94318197576e" - Capabilities: - description: | - A list of capabilities; an OR list of AND lists of capabilities. - type: "array" - items: - type: "array" - items: - type: "string" - example: - # gpu AND nvidia AND compute - - ["gpu", "nvidia", "compute"] - Options: - description: | - Driver-specific options, specified as a key/value pairs. These options - are passed directly to the driver. - type: "object" - additionalProperties: - type: "string" - - ThrottleDevice: - type: "object" - properties: - Path: - description: "Device path" - type: "string" - Rate: - description: "Rate" - type: "integer" - format: "int64" - minimum: 0 - - Mount: - type: "object" - properties: - Target: - description: "Container path." - type: "string" - Source: - description: "Mount source (e.g. a volume name, a host path)." - type: "string" - Type: - description: | - The mount type. Available types: - - - `bind` Mounts a file or directory from the host into the container. Must exist prior to creating the container. - - `volume` Creates a volume with the given name and options (or uses a pre-existing volume with the same name and options). These are **not** removed when the container is removed. - - `tmpfs` Create a tmpfs with the given options. The mount source cannot be specified for tmpfs. - - `npipe` Mounts a named pipe from the host into the container. Must exist prior to creating the container. - - `cluster` a Swarm cluster volume - type: "string" - enum: - - "bind" - - "volume" - - "tmpfs" - - "npipe" - - "cluster" - ReadOnly: - description: "Whether the mount should be read-only." - type: "boolean" - Consistency: - description: "The consistency requirement for the mount: `default`, `consistent`, `cached`, or `delegated`." - type: "string" - BindOptions: - description: "Optional configuration for the `bind` type." - type: "object" - properties: - Propagation: - description: "A propagation mode with the value `[r]private`, `[r]shared`, or `[r]slave`." - type: "string" - enum: - - "private" - - "rprivate" - - "shared" - - "rshared" - - "slave" - - "rslave" - NonRecursive: - description: "Disable recursive bind mount." - type: "boolean" - default: false - CreateMountpoint: - description: "Create mount point on host if missing" - type: "boolean" - default: false - VolumeOptions: - description: "Optional configuration for the `volume` type." - type: "object" - properties: - NoCopy: - description: "Populate volume with data from the target." - type: "boolean" - default: false - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - DriverConfig: - description: "Map of driver specific options" - type: "object" - properties: - Name: - description: "Name of the driver to use to create the volume." - type: "string" - Options: - description: "key/value map of driver specific options." - type: "object" - additionalProperties: - type: "string" - TmpfsOptions: - description: "Optional configuration for the `tmpfs` type." - type: "object" - properties: - SizeBytes: - description: "The size for the tmpfs mount in bytes." - type: "integer" - format: "int64" - Mode: - description: "The permission mode for the tmpfs mount in an integer." - type: "integer" - - RestartPolicy: - description: | - The behavior to apply when the container exits. The default is not to - restart. - - An ever increasing delay (double the previous delay, starting at 100ms) is - added before each restart to prevent flooding the server. - type: "object" - properties: - Name: - type: "string" - description: | - - Empty string means not to restart - - `no` Do not automatically restart - - `always` Always restart - - `unless-stopped` Restart always except when the user has manually stopped the container - - `on-failure` Restart only when the container exit code is non-zero - enum: - - "" - - "no" - - "always" - - "unless-stopped" - - "on-failure" - MaximumRetryCount: - type: "integer" - description: | - If `on-failure` is used, the number of times to retry before giving up. - - Resources: - description: "A container's resources (cgroups config, ulimits, etc)" - type: "object" - properties: - # Applicable to all platforms - CpuShares: - description: | - An integer value representing this container's relative CPU weight - versus other containers. - type: "integer" - Memory: - description: "Memory limit in bytes." - type: "integer" - format: "int64" - default: 0 - # Applicable to UNIX platforms - CgroupParent: - description: | - Path to `cgroups` under which the container's `cgroup` is created. If - the path is not absolute, the path is considered to be relative to the - `cgroups` path of the init process. Cgroups are created if they do not - already exist. - type: "string" - BlkioWeight: - description: "Block IO weight (relative weight)." - type: "integer" - minimum: 0 - maximum: 1000 - BlkioWeightDevice: - description: | - Block IO weight (relative device weight) in the form: - - ``` - [{"Path": "device_path", "Weight": weight}] - ``` - type: "array" - items: - type: "object" - properties: - Path: - type: "string" - Weight: - type: "integer" - minimum: 0 - BlkioDeviceReadBps: - description: | - Limit read rate (bytes per second) from a device, in the form: - - ``` - [{"Path": "device_path", "Rate": rate}] - ``` - type: "array" - items: - $ref: "#/definitions/ThrottleDevice" - BlkioDeviceWriteBps: - description: | - Limit write rate (bytes per second) to a device, in the form: - - ``` - [{"Path": "device_path", "Rate": rate}] - ``` - type: "array" - items: - $ref: "#/definitions/ThrottleDevice" - BlkioDeviceReadIOps: - description: | - Limit read rate (IO per second) from a device, in the form: - - ``` - [{"Path": "device_path", "Rate": rate}] - ``` - type: "array" - items: - $ref: "#/definitions/ThrottleDevice" - BlkioDeviceWriteIOps: - description: | - Limit write rate (IO per second) to a device, in the form: - - ``` - [{"Path": "device_path", "Rate": rate}] - ``` - type: "array" - items: - $ref: "#/definitions/ThrottleDevice" - CpuPeriod: - description: "The length of a CPU period in microseconds." - type: "integer" - format: "int64" - CpuQuota: - description: | - Microseconds of CPU time that the container can get in a CPU period. - type: "integer" - format: "int64" - CpuRealtimePeriod: - description: | - The length of a CPU real-time period in microseconds. Set to 0 to - allocate no time allocated to real-time tasks. - type: "integer" - format: "int64" - CpuRealtimeRuntime: - description: | - The length of a CPU real-time runtime in microseconds. Set to 0 to - allocate no time allocated to real-time tasks. - type: "integer" - format: "int64" - CpusetCpus: - description: | - CPUs in which to allow execution (e.g., `0-3`, `0,1`). - type: "string" - example: "0-3" - CpusetMems: - description: | - Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only - effective on NUMA systems. - type: "string" - Devices: - description: "A list of devices to add to the container." - type: "array" - items: - $ref: "#/definitions/DeviceMapping" - DeviceCgroupRules: - description: "a list of cgroup rules to apply to the container" - type: "array" - items: - type: "string" - example: "c 13:* rwm" - DeviceRequests: - description: | - A list of requests for devices to be sent to device drivers. - type: "array" - items: - $ref: "#/definitions/DeviceRequest" - KernelMemoryTCP: - description: | - Hard limit for kernel TCP buffer memory (in bytes). Depending on the - OCI runtime in use, this option may be ignored. It is no longer supported - by the default (runc) runtime. - - This field is omitted when empty. - type: "integer" - format: "int64" - MemoryReservation: - description: "Memory soft limit in bytes." - type: "integer" - format: "int64" - MemorySwap: - description: | - Total memory limit (memory + swap). Set as `-1` to enable unlimited - swap. - type: "integer" - format: "int64" - MemorySwappiness: - description: | - Tune a container's memory swappiness behavior. Accepts an integer - between 0 and 100. - type: "integer" - format: "int64" - minimum: 0 - maximum: 100 - NanoCpus: - description: "CPU quota in units of 10-9 CPUs." - type: "integer" - format: "int64" - OomKillDisable: - description: "Disable OOM Killer for the container." - type: "boolean" - Init: - description: | - Run an init inside the container that forwards signals and reaps - processes. This field is omitted if empty, and the default (as - configured on the daemon) is used. - type: "boolean" - x-nullable: true - PidsLimit: - description: | - Tune a container's PIDs limit. Set `0` or `-1` for unlimited, or `null` - to not change. - type: "integer" - format: "int64" - x-nullable: true - Ulimits: - description: | - A list of resource limits to set in the container. For example: - - ``` - {"Name": "nofile", "Soft": 1024, "Hard": 2048} - ``` - type: "array" - items: - type: "object" - properties: - Name: - description: "Name of ulimit" - type: "string" - Soft: - description: "Soft limit" - type: "integer" - Hard: - description: "Hard limit" - type: "integer" - # Applicable to Windows - CpuCount: - description: | - The number of usable CPUs (Windows only). - - On Windows Server containers, the processor resource controls are - mutually exclusive. The order of precedence is `CPUCount` first, then - `CPUShares`, and `CPUPercent` last. - type: "integer" - format: "int64" - CpuPercent: - description: | - The usable percentage of the available CPUs (Windows only). - - On Windows Server containers, the processor resource controls are - mutually exclusive. The order of precedence is `CPUCount` first, then - `CPUShares`, and `CPUPercent` last. - type: "integer" - format: "int64" - IOMaximumIOps: - description: "Maximum IOps for the container system drive (Windows only)" - type: "integer" - format: "int64" - IOMaximumBandwidth: - description: | - Maximum IO in bytes per second for the container system drive - (Windows only). - type: "integer" - format: "int64" - - Limit: - description: | - An object describing a limit on resources which can be requested by a task. - type: "object" - properties: - NanoCPUs: - type: "integer" - format: "int64" - example: 4000000000 - MemoryBytes: - type: "integer" - format: "int64" - example: 8272408576 - Pids: - description: | - Limits the maximum number of PIDs in the container. Set `0` for unlimited. - type: "integer" - format: "int64" - default: 0 - example: 100 - - ResourceObject: - description: | - An object describing the resources which can be advertised by a node and - requested by a task. - type: "object" - properties: - NanoCPUs: - type: "integer" - format: "int64" - example: 4000000000 - MemoryBytes: - type: "integer" - format: "int64" - example: 8272408576 - GenericResources: - $ref: "#/definitions/GenericResources" - - GenericResources: - description: | - User-defined resources can be either Integer resources (e.g, `SSD=3`) or - String resources (e.g, `GPU=UUID1`). - type: "array" - items: - type: "object" - properties: - NamedResourceSpec: - type: "object" - properties: - Kind: - type: "string" - Value: - type: "string" - DiscreteResourceSpec: - type: "object" - properties: - Kind: - type: "string" - Value: - type: "integer" - format: "int64" - example: - - DiscreteResourceSpec: - Kind: "SSD" - Value: 3 - - NamedResourceSpec: - Kind: "GPU" - Value: "UUID1" - - NamedResourceSpec: - Kind: "GPU" - Value: "UUID2" - - HealthConfig: - description: "A test to perform to check that the container is healthy." - type: "object" - properties: - Test: - description: | - The test to perform. Possible values are: - - - `[]` inherit healthcheck from image or parent image - - `["NONE"]` disable healthcheck - - `["CMD", args...]` exec arguments directly - - `["CMD-SHELL", command]` run command with system's default shell - type: "array" - items: - type: "string" - Interval: - description: | - The time to wait between checks in nanoseconds. It should be 0 or at - least 1000000 (1 ms). 0 means inherit. - type: "integer" - format: "int64" - Timeout: - description: | - The time to wait before considering the check to have hung. It should - be 0 or at least 1000000 (1 ms). 0 means inherit. - type: "integer" - format: "int64" - Retries: - description: | - The number of consecutive failures needed to consider a container as - unhealthy. 0 means inherit. - type: "integer" - StartPeriod: - description: | - Start period for the container to initialize before starting - health-retries countdown in nanoseconds. It should be 0 or at least - 1000000 (1 ms). 0 means inherit. - type: "integer" - format: "int64" - - Health: - description: | - Health stores information about the container's healthcheck results. - type: "object" - x-nullable: true - properties: - Status: - description: | - Status is one of `none`, `starting`, `healthy` or `unhealthy` - - - "none" Indicates there is no healthcheck - - "starting" Starting indicates that the container is not yet ready - - "healthy" Healthy indicates that the container is running correctly - - "unhealthy" Unhealthy indicates that the container has a problem - type: "string" - enum: - - "none" - - "starting" - - "healthy" - - "unhealthy" - example: "healthy" - FailingStreak: - description: "FailingStreak is the number of consecutive failures" - type: "integer" - example: 0 - Log: - type: "array" - description: | - Log contains the last few results (oldest first) - items: - $ref: "#/definitions/HealthcheckResult" - - HealthcheckResult: - description: | - HealthcheckResult stores information about a single run of a healthcheck probe - type: "object" - x-nullable: true - properties: - Start: - description: | - Date and time at which this check started in - [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format with nano-seconds. - type: "string" - format: "date-time" - example: "2020-01-04T10:44:24.496525531Z" - End: - description: | - Date and time at which this check ended in - [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format with nano-seconds. - type: "string" - format: "dateTime" - example: "2020-01-04T10:45:21.364524523Z" - ExitCode: - description: | - ExitCode meanings: - - - `0` healthy - - `1` unhealthy - - `2` reserved (considered unhealthy) - - other values: error running probe - type: "integer" - example: 0 - Output: - description: "Output from last check" - type: "string" - - HostConfig: - description: "Container configuration that depends on the host we are running on" - allOf: - - $ref: "#/definitions/Resources" - - type: "object" - properties: - # Applicable to all platforms - Binds: - type: "array" - description: | - A list of volume bindings for this container. Each volume binding - is a string in one of these forms: - - - `host-src:container-dest[:options]` to bind-mount a host path - into the container. Both `host-src`, and `container-dest` must - be an _absolute_ path. - - `volume-name:container-dest[:options]` to bind-mount a volume - managed by a volume driver into the container. `container-dest` - must be an _absolute_ path. - - `options` is an optional, comma-delimited list of: - - - `nocopy` disables automatic copying of data from the container - path to the volume. The `nocopy` flag only applies to named volumes. - - `[ro|rw]` mounts a volume read-only or read-write, respectively. - If omitted or set to `rw`, volumes are mounted read-write. - - `[z|Z]` applies SELinux labels to allow or deny multiple containers - to read and write to the same volume. - - `z`: a _shared_ content label is applied to the content. This - label indicates that multiple containers can share the volume - content, for both reading and writing. - - `Z`: a _private unshared_ label is applied to the content. - This label indicates that only the current container can use - a private volume. Labeling systems such as SELinux require - proper labels to be placed on volume content that is mounted - into a container. Without a label, the security system can - prevent a container's processes from using the content. By - default, the labels set by the host operating system are not - modified. - - `[[r]shared|[r]slave|[r]private]` specifies mount - [propagation behavior](https://www.kernel.org/doc/Documentation/filesystems/sharedsubtree.txt). - This only applies to bind-mounted volumes, not internal volumes - or named volumes. Mount propagation requires the source mount - point (the location where the source directory is mounted in the - host operating system) to have the correct propagation properties. - For shared volumes, the source mount point must be set to `shared`. - For slave volumes, the mount must be set to either `shared` or - `slave`. - items: - type: "string" - ContainerIDFile: - type: "string" - description: "Path to a file where the container ID is written" - LogConfig: - type: "object" - description: "The logging configuration for this container" - properties: - Type: - type: "string" - enum: - - "json-file" - - "syslog" - - "journald" - - "gelf" - - "fluentd" - - "awslogs" - - "splunk" - - "etwlogs" - - "none" - Config: - type: "object" - additionalProperties: - type: "string" - NetworkMode: - type: "string" - description: | - Network mode to use for this container. Supported standard values - are: `bridge`, `host`, `none`, and `container:`. Any - other value is taken as a custom network's name to which this - container should connect to. - PortBindings: - $ref: "#/definitions/PortMap" - RestartPolicy: - $ref: "#/definitions/RestartPolicy" - AutoRemove: - type: "boolean" - description: | - Automatically remove the container when the container's process - exits. This has no effect if `RestartPolicy` is set. - VolumeDriver: - type: "string" - description: "Driver that this container uses to mount volumes." - VolumesFrom: - type: "array" - description: | - A list of volumes to inherit from another container, specified in - the form `[:]`. - items: - type: "string" - Mounts: - description: | - Specification for mounts to be added to the container. - type: "array" - items: - $ref: "#/definitions/Mount" - ConsoleSize: - type: "array" - description: | - Initial console size, as an `[height, width]` array. - x-nullable: true - minItems: 2 - maxItems: 2 - items: - type: "integer" - minimum: 0 - Annotations: - type: "object" - description: | - Arbitrary non-identifying metadata attached to container and - provided to the runtime when the container is started. - additionalProperties: - type: "string" - - # Applicable to UNIX platforms - CapAdd: - type: "array" - description: | - A list of kernel capabilities to add to the container. Conflicts - with option 'Capabilities'. - items: - type: "string" - CapDrop: - type: "array" - description: | - A list of kernel capabilities to drop from the container. Conflicts - with option 'Capabilities'. - items: - type: "string" - CgroupnsMode: - type: "string" - enum: - - "private" - - "host" - description: | - cgroup namespace mode for the container. Possible values are: - - - `"private"`: the container runs in its own private cgroup namespace - - `"host"`: use the host system's cgroup namespace - - If not specified, the daemon default is used, which can either be `"private"` - or `"host"`, depending on daemon version, kernel support and configuration. - Dns: - type: "array" - description: "A list of DNS servers for the container to use." - items: - type: "string" - DnsOptions: - type: "array" - description: "A list of DNS options." - items: - type: "string" - DnsSearch: - type: "array" - description: "A list of DNS search domains." - items: - type: "string" - ExtraHosts: - type: "array" - description: | - A list of hostnames/IP mappings to add to the container's `/etc/hosts` - file. Specified in the form `["hostname:IP"]`. - items: - type: "string" - GroupAdd: - type: "array" - description: | - A list of additional groups that the container process will run as. - items: - type: "string" - IpcMode: - type: "string" - description: | - IPC sharing mode for the container. Possible values are: - - - `"none"`: own private IPC namespace, with /dev/shm not mounted - - `"private"`: own private IPC namespace - - `"shareable"`: own private IPC namespace, with a possibility to share it with other containers - - `"container:"`: join another (shareable) container's IPC namespace - - `"host"`: use the host system's IPC namespace - - If not specified, daemon default is used, which can either be `"private"` - or `"shareable"`, depending on daemon version and configuration. - Cgroup: - type: "string" - description: "Cgroup to use for the container." - Links: - type: "array" - description: | - A list of links for the container in the form `container_name:alias`. - items: - type: "string" - OomScoreAdj: - type: "integer" - description: | - An integer value containing the score given to the container in - order to tune OOM killer preferences. - example: 500 - PidMode: - type: "string" - description: | - Set the PID (Process) Namespace mode for the container. It can be - either: - - - `"container:"`: joins another container's PID namespace - - `"host"`: use the host's PID namespace inside the container - Privileged: - type: "boolean" - description: "Gives the container full access to the host." - PublishAllPorts: - type: "boolean" - description: | - Allocates an ephemeral host port for all of a container's - exposed ports. - - Ports are de-allocated when the container stops and allocated when - the container starts. The allocated port might be changed when - restarting the container. - - The port is selected from the ephemeral port range that depends on - the kernel. For example, on Linux the range is defined by - `/proc/sys/net/ipv4/ip_local_port_range`. - ReadonlyRootfs: - type: "boolean" - description: "Mount the container's root filesystem as read only." - SecurityOpt: - type: "array" - description: | - A list of string values to customize labels for MLS systems, such - as SELinux. - items: - type: "string" - StorageOpt: - type: "object" - description: | - Storage driver options for this container, in the form `{"size": "120G"}`. - additionalProperties: - type: "string" - Tmpfs: - type: "object" - description: | - A map of container directories which should be replaced by tmpfs - mounts, and their corresponding mount options. For example: - - ``` - { "/run": "rw,noexec,nosuid,size=65536k" } - ``` - additionalProperties: - type: "string" - UTSMode: - type: "string" - description: "UTS namespace to use for the container." - UsernsMode: - type: "string" - description: | - Sets the usernamespace mode for the container when usernamespace - remapping option is enabled. - ShmSize: - type: "integer" - format: "int64" - description: | - Size of `/dev/shm` in bytes. If omitted, the system uses 64MB. - minimum: 0 - Sysctls: - type: "object" - description: | - A list of kernel parameters (sysctls) to set in the container. - For example: - - ``` - {"net.ipv4.ip_forward": "1"} - ``` - additionalProperties: - type: "string" - Runtime: - type: "string" - description: "Runtime to use with this container." - # Applicable to Windows - Isolation: - type: "string" - description: | - Isolation technology of the container. (Windows only) - enum: - - "default" - - "process" - - "hyperv" - MaskedPaths: - type: "array" - description: | - The list of paths to be masked inside the container (this overrides - the default set of paths). - items: - type: "string" - ReadonlyPaths: - type: "array" - description: | - The list of paths to be set as read-only inside the container - (this overrides the default set of paths). - items: - type: "string" - - ContainerConfig: - description: | - Configuration for a container that is portable between hosts. - - When used as `ContainerConfig` field in an image, `ContainerConfig` is an - optional field containing the configuration of the container that was last - committed when creating the image. - - Previous versions of Docker builder used this field to store build cache, - and it is not in active use anymore. - type: "object" - properties: - Hostname: - description: | - The hostname to use for the container, as a valid RFC 1123 hostname. - type: "string" - example: "439f4e91bd1d" - Domainname: - description: | - The domain name to use for the container. - type: "string" - User: - description: "The user that commands are run as inside the container." - type: "string" - AttachStdin: - description: "Whether to attach to `stdin`." - type: "boolean" - default: false - AttachStdout: - description: "Whether to attach to `stdout`." - type: "boolean" - default: true - AttachStderr: - description: "Whether to attach to `stderr`." - type: "boolean" - default: true - ExposedPorts: - description: | - An object mapping ports to an empty object in the form: - - `{"/": {}}` - type: "object" - x-nullable: true - additionalProperties: - type: "object" - enum: - - {} - default: {} - example: { - "80/tcp": {}, - "443/tcp": {} - } - Tty: - description: | - Attach standard streams to a TTY, including `stdin` if it is not closed. - type: "boolean" - default: false - OpenStdin: - description: "Open `stdin`" - type: "boolean" - default: false - StdinOnce: - description: "Close `stdin` after one attached client disconnects" - type: "boolean" - default: false - Env: - description: | - A list of environment variables to set inside the container in the - form `["VAR=value", ...]`. A variable without `=` is removed from the - environment, rather than to have an empty value. - type: "array" - items: - type: "string" - example: - - "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" - Cmd: - description: | - Command to run specified as a string or an array of strings. - type: "array" - items: - type: "string" - example: ["/bin/sh"] - Healthcheck: - $ref: "#/definitions/HealthConfig" - ArgsEscaped: - description: "Command is already escaped (Windows only)" - type: "boolean" - default: false - example: false - x-nullable: true - Image: - description: | - The name (or reference) of the image to use when creating the container, - or which was used when the container was created. - type: "string" - example: "example-image:1.0" - Volumes: - description: | - An object mapping mount point paths inside the container to empty - objects. - type: "object" - additionalProperties: - type: "object" - enum: - - {} - default: {} - WorkingDir: - description: "The working directory for commands to run in." - type: "string" - example: "/public/" - Entrypoint: - description: | - The entry point for the container as a string or an array of strings. - - If the array consists of exactly one empty string (`[""]`) then the - entry point is reset to system default (i.e., the entry point used by - docker when there is no `ENTRYPOINT` instruction in the `Dockerfile`). - type: "array" - items: - type: "string" - example: [] - NetworkDisabled: - description: "Disable networking for the container." - type: "boolean" - x-nullable: true - MacAddress: - description: "MAC address of the container." - type: "string" - x-nullable: true - OnBuild: - description: | - `ONBUILD` metadata that were defined in the image's `Dockerfile`. - type: "array" - x-nullable: true - items: - type: "string" - example: [] - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - example: - com.example.some-label: "some-value" - com.example.some-other-label: "some-other-value" - StopSignal: - description: | - Signal to stop a container as a string or unsigned integer. - type: "string" - example: "SIGTERM" - x-nullable: true - StopTimeout: - description: "Timeout to stop a container in seconds." - type: "integer" - default: 10 - x-nullable: true - Shell: - description: | - Shell for when `RUN`, `CMD`, and `ENTRYPOINT` uses a shell. - type: "array" - x-nullable: true - items: - type: "string" - example: ["/bin/sh", "-c"] - - NetworkingConfig: - description: | - NetworkingConfig represents the container's networking configuration for - each of its interfaces. - It is used for the networking configs specified in the `docker create` - and `docker network connect` commands. - type: "object" - properties: - EndpointsConfig: - description: | - A mapping of network name to endpoint configuration for that network. - type: "object" - additionalProperties: - $ref: "#/definitions/EndpointSettings" - example: - # putting an example here, instead of using the example values from - # /definitions/EndpointSettings, because containers/create currently - # does not support attaching to multiple networks, so the example request - # would be confusing if it showed that multiple networks can be contained - # in the EndpointsConfig. - # TODO remove once we support multiple networks on container create (see https://github.com/moby/moby/blob/07e6b843594e061f82baa5fa23c2ff7d536c2a05/daemon/create.go#L323) - EndpointsConfig: - isolated_nw: - IPAMConfig: - IPv4Address: "172.20.30.33" - IPv6Address: "2001:db8:abcd::3033" - LinkLocalIPs: - - "169.254.34.68" - - "fe80::3468" - Links: - - "container_1" - - "container_2" - Aliases: - - "server_x" - - "server_y" - - NetworkSettings: - description: "NetworkSettings exposes the network settings in the API" - type: "object" - properties: - Bridge: - description: Name of the network's bridge (for example, `docker0`). - type: "string" - example: "docker0" - SandboxID: - description: SandboxID uniquely represents a container's network stack. - type: "string" - example: "9d12daf2c33f5959c8bf90aa513e4f65b561738661003029ec84830cd503a0c3" - HairpinMode: - description: | - Indicates if hairpin NAT should be enabled on the virtual interface. - type: "boolean" - example: false - LinkLocalIPv6Address: - description: IPv6 unicast address using the link-local prefix. - type: "string" - example: "fe80::42:acff:fe11:1" - LinkLocalIPv6PrefixLen: - description: Prefix length of the IPv6 unicast address. - type: "integer" - example: "64" - Ports: - $ref: "#/definitions/PortMap" - SandboxKey: - description: SandboxKey identifies the sandbox - type: "string" - example: "/var/run/docker/netns/8ab54b426c38" - - # TODO is SecondaryIPAddresses actually used? - SecondaryIPAddresses: - description: "" - type: "array" - items: - $ref: "#/definitions/Address" - x-nullable: true - - # TODO is SecondaryIPv6Addresses actually used? - SecondaryIPv6Addresses: - description: "" - type: "array" - items: - $ref: "#/definitions/Address" - x-nullable: true - - # TODO properties below are part of DefaultNetworkSettings, which is - # marked as deprecated since Docker 1.9 and to be removed in Docker v17.12 - EndpointID: - description: | - EndpointID uniquely represents a service endpoint in a Sandbox. - -


- - > **Deprecated**: This field is only propagated when attached to the - > default "bridge" network. Use the information from the "bridge" - > network inside the `Networks` map instead, which contains the same - > information. This field was deprecated in Docker 1.9 and is scheduled - > to be removed in Docker 17.12.0 - type: "string" - example: "b88f5b905aabf2893f3cbc4ee42d1ea7980bbc0a92e2c8922b1e1795298afb0b" - Gateway: - description: | - Gateway address for the default "bridge" network. - -


- - > **Deprecated**: This field is only propagated when attached to the - > default "bridge" network. Use the information from the "bridge" - > network inside the `Networks` map instead, which contains the same - > information. This field was deprecated in Docker 1.9 and is scheduled - > to be removed in Docker 17.12.0 - type: "string" - example: "172.17.0.1" - GlobalIPv6Address: - description: | - Global IPv6 address for the default "bridge" network. - -


- - > **Deprecated**: This field is only propagated when attached to the - > default "bridge" network. Use the information from the "bridge" - > network inside the `Networks` map instead, which contains the same - > information. This field was deprecated in Docker 1.9 and is scheduled - > to be removed in Docker 17.12.0 - type: "string" - example: "2001:db8::5689" - GlobalIPv6PrefixLen: - description: | - Mask length of the global IPv6 address. - -


- - > **Deprecated**: This field is only propagated when attached to the - > default "bridge" network. Use the information from the "bridge" - > network inside the `Networks` map instead, which contains the same - > information. This field was deprecated in Docker 1.9 and is scheduled - > to be removed in Docker 17.12.0 - type: "integer" - example: 64 - IPAddress: - description: | - IPv4 address for the default "bridge" network. - -


- - > **Deprecated**: This field is only propagated when attached to the - > default "bridge" network. Use the information from the "bridge" - > network inside the `Networks` map instead, which contains the same - > information. This field was deprecated in Docker 1.9 and is scheduled - > to be removed in Docker 17.12.0 - type: "string" - example: "172.17.0.4" - IPPrefixLen: - description: | - Mask length of the IPv4 address. - -


- - > **Deprecated**: This field is only propagated when attached to the - > default "bridge" network. Use the information from the "bridge" - > network inside the `Networks` map instead, which contains the same - > information. This field was deprecated in Docker 1.9 and is scheduled - > to be removed in Docker 17.12.0 - type: "integer" - example: 16 - IPv6Gateway: - description: | - IPv6 gateway address for this network. - -


- - > **Deprecated**: This field is only propagated when attached to the - > default "bridge" network. Use the information from the "bridge" - > network inside the `Networks` map instead, which contains the same - > information. This field was deprecated in Docker 1.9 and is scheduled - > to be removed in Docker 17.12.0 - type: "string" - example: "2001:db8:2::100" - MacAddress: - description: | - MAC address for the container on the default "bridge" network. - -


- - > **Deprecated**: This field is only propagated when attached to the - > default "bridge" network. Use the information from the "bridge" - > network inside the `Networks` map instead, which contains the same - > information. This field was deprecated in Docker 1.9 and is scheduled - > to be removed in Docker 17.12.0 - type: "string" - example: "02:42:ac:11:00:04" - Networks: - description: | - Information about all networks that the container is connected to. - type: "object" - additionalProperties: - $ref: "#/definitions/EndpointSettings" - - Address: - description: Address represents an IPv4 or IPv6 IP address. - type: "object" - properties: - Addr: - description: IP address. - type: "string" - PrefixLen: - description: Mask length of the IP address. - type: "integer" - - PortMap: - description: | - PortMap describes the mapping of container ports to host ports, using the - container's port-number and protocol as key in the format `/`, - for example, `80/udp`. - - If a container's port is mapped for multiple protocols, separate entries - are added to the mapping table. - type: "object" - additionalProperties: - type: "array" - x-nullable: true - items: - $ref: "#/definitions/PortBinding" - example: - "443/tcp": - - HostIp: "127.0.0.1" - HostPort: "4443" - "80/tcp": - - HostIp: "0.0.0.0" - HostPort: "80" - - HostIp: "0.0.0.0" - HostPort: "8080" - "80/udp": - - HostIp: "0.0.0.0" - HostPort: "80" - "53/udp": - - HostIp: "0.0.0.0" - HostPort: "53" - "2377/tcp": null - - PortBinding: - description: | - PortBinding represents a binding between a host IP address and a host - port. - type: "object" - properties: - HostIp: - description: "Host IP address that the container's port is mapped to." - type: "string" - example: "127.0.0.1" - HostPort: - description: "Host port number that the container's port is mapped to." - type: "string" - example: "4443" - - GraphDriverData: - description: | - Information about the storage driver used to store the container's and - image's filesystem. - type: "object" - required: [Name, Data] - properties: - Name: - description: "Name of the storage driver." - type: "string" - x-nullable: false - example: "overlay2" - Data: - description: | - Low-level storage metadata, provided as key/value pairs. - - This information is driver-specific, and depends on the storage-driver - in use, and should be used for informational purposes only. - type: "object" - x-nullable: false - additionalProperties: - type: "string" - example: { - "MergedDir": "/var/lib/docker/overlay2/ef749362d13333e65fc95c572eb525abbe0052e16e086cb64bc3b98ae9aa6d74/merged", - "UpperDir": "/var/lib/docker/overlay2/ef749362d13333e65fc95c572eb525abbe0052e16e086cb64bc3b98ae9aa6d74/diff", - "WorkDir": "/var/lib/docker/overlay2/ef749362d13333e65fc95c572eb525abbe0052e16e086cb64bc3b98ae9aa6d74/work" - } - - FilesystemChange: - description: | - Change in the container's filesystem. - type: "object" - required: [Path, Kind] - properties: - Path: - description: | - Path to file or directory that has changed. - type: "string" - x-nullable: false - Kind: - $ref: "#/definitions/ChangeType" - - ChangeType: - description: | - Kind of change - - Can be one of: - - - `0`: Modified ("C") - - `1`: Added ("A") - - `2`: Deleted ("D") - type: "integer" - format: "uint8" - enum: [0, 1, 2] - x-nullable: false - - ImageInspect: - description: | - Information about an image in the local image cache. - type: "object" - properties: - Id: - description: | - ID is the content-addressable ID of an image. - - This identifier is a content-addressable digest calculated from the - image's configuration (which includes the digests of layers used by - the image). - - Note that this digest differs from the `RepoDigests` below, which - holds digests of image manifests that reference the image. - type: "string" - x-nullable: false - example: "sha256:ec3f0931a6e6b6855d76b2d7b0be30e81860baccd891b2e243280bf1cd8ad710" - RepoTags: - description: | - List of image names/tags in the local image cache that reference this - image. - - Multiple image tags can refer to the same image, and this list may be - empty if no tags reference the image, in which case the image is - "untagged", in which case it can still be referenced by its ID. - type: "array" - items: - type: "string" - example: - - "example:1.0" - - "example:latest" - - "example:stable" - - "internal.registry.example.com:5000/example:1.0" - RepoDigests: - description: | - List of content-addressable digests of locally available image manifests - that the image is referenced from. Multiple manifests can refer to the - same image. - - These digests are usually only available if the image was either pulled - from a registry, or if the image was pushed to a registry, which is when - the manifest is generated and its digest calculated. - type: "array" - items: - type: "string" - example: - - "example@sha256:afcc7f1ac1b49db317a7196c902e61c6c3c4607d63599ee1a82d702d249a0ccb" - - "internal.registry.example.com:5000/example@sha256:b69959407d21e8a062e0416bf13405bb2b71ed7a84dde4158ebafacfa06f5578" - Parent: - description: | - ID of the parent image. - - Depending on how the image was created, this field may be empty and - is only set for images that were built/created locally. This field - is empty if the image was pulled from an image registry. - type: "string" - x-nullable: false - example: "" - Comment: - description: | - Optional message that was set when committing or importing the image. - type: "string" - x-nullable: false - example: "" - Created: - description: | - Date and time at which the image was created, formatted in - [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format with nano-seconds. - type: "string" - x-nullable: false - example: "2022-02-04T21:20:12.497794809Z" - Container: - description: | - The ID of the container that was used to create the image. - - Depending on how the image was created, this field may be empty. - type: "string" - x-nullable: false - example: "65974bc86f1770ae4bff79f651ebdbce166ae9aada632ee3fa9af3a264911735" - ContainerConfig: - $ref: "#/definitions/ContainerConfig" - DockerVersion: - description: | - The version of Docker that was used to build the image. - - Depending on how the image was created, this field may be empty. - type: "string" - x-nullable: false - example: "20.10.7" - Author: - description: | - Name of the author that was specified when committing the image, or as - specified through MAINTAINER (deprecated) in the Dockerfile. - type: "string" - x-nullable: false - example: "" - Config: - $ref: "#/definitions/ContainerConfig" - Architecture: - description: | - Hardware CPU architecture that the image runs on. - type: "string" - x-nullable: false - example: "arm" - Variant: - description: | - CPU architecture variant (presently ARM-only). - type: "string" - x-nullable: true - example: "v7" - Os: - description: | - Operating System the image is built to run on. - type: "string" - x-nullable: false - example: "linux" - OsVersion: - description: | - Operating System version the image is built to run on (especially - for Windows). - type: "string" - example: "" - x-nullable: true - Size: - description: | - Total size of the image including all layers it is composed of. - type: "integer" - format: "int64" - x-nullable: false - example: 1239828 - VirtualSize: - description: | - Total size of the image including all layers it is composed of. - - In versions of Docker before v1.10, this field was calculated from - the image itself and all of its parent images. Images are now stored - self-contained, and no longer use a parent-chain, making this field - an equivalent of the Size field. - - > **Deprecated**: this field is kept for backward compatibility, but - > will be removed in API v1.44. - type: "integer" - format: "int64" - example: 1239828 - GraphDriver: - $ref: "#/definitions/GraphDriverData" - RootFS: - description: | - Information about the image's RootFS, including the layer IDs. - type: "object" - required: [Type] - properties: - Type: - type: "string" - x-nullable: false - example: "layers" - Layers: - type: "array" - items: - type: "string" - example: - - "sha256:1834950e52ce4d5a88a1bbd131c537f4d0e56d10ff0dd69e66be3b7dfa9df7e6" - - "sha256:5f70bf18a086007016e948b04aed3b82103a36bea41755b6cddfaf10ace3c6ef" - Metadata: - description: | - Additional metadata of the image in the local cache. This information - is local to the daemon, and not part of the image itself. - type: "object" - properties: - LastTagTime: - description: | - Date and time at which the image was last tagged in - [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format with nano-seconds. - - This information is only available if the image was tagged locally, - and omitted otherwise. - type: "string" - format: "dateTime" - example: "2022-02-28T14:40:02.623929178Z" - x-nullable: true - ImageSummary: - type: "object" - required: - - Id - - ParentId - - RepoTags - - RepoDigests - - Created - - Size - - SharedSize - - Labels - - Containers - properties: - Id: - description: | - ID is the content-addressable ID of an image. - - This identifier is a content-addressable digest calculated from the - image's configuration (which includes the digests of layers used by - the image). - - Note that this digest differs from the `RepoDigests` below, which - holds digests of image manifests that reference the image. - type: "string" - x-nullable: false - example: "sha256:ec3f0931a6e6b6855d76b2d7b0be30e81860baccd891b2e243280bf1cd8ad710" - ParentId: - description: | - ID of the parent image. - - Depending on how the image was created, this field may be empty and - is only set for images that were built/created locally. This field - is empty if the image was pulled from an image registry. - type: "string" - x-nullable: false - example: "" - RepoTags: - description: | - List of image names/tags in the local image cache that reference this - image. - - Multiple image tags can refer to the same image, and this list may be - empty if no tags reference the image, in which case the image is - "untagged", in which case it can still be referenced by its ID. - type: "array" - x-nullable: false - items: - type: "string" - example: - - "example:1.0" - - "example:latest" - - "example:stable" - - "internal.registry.example.com:5000/example:1.0" - RepoDigests: - description: | - List of content-addressable digests of locally available image manifests - that the image is referenced from. Multiple manifests can refer to the - same image. - - These digests are usually only available if the image was either pulled - from a registry, or if the image was pushed to a registry, which is when - the manifest is generated and its digest calculated. - type: "array" - x-nullable: false - items: - type: "string" - example: - - "example@sha256:afcc7f1ac1b49db317a7196c902e61c6c3c4607d63599ee1a82d702d249a0ccb" - - "internal.registry.example.com:5000/example@sha256:b69959407d21e8a062e0416bf13405bb2b71ed7a84dde4158ebafacfa06f5578" - Created: - description: | - Date and time at which the image was created as a Unix timestamp - (number of seconds sinds EPOCH). - type: "integer" - x-nullable: false - example: "1644009612" - Size: - description: | - Total size of the image including all layers it is composed of. - type: "integer" - format: "int64" - x-nullable: false - example: 172064416 - SharedSize: - description: | - Total size of image layers that are shared between this image and other - images. - - This size is not calculated by default. `-1` indicates that the value - has not been set / calculated. - type: "integer" - format: "int64" - x-nullable: false - example: 1239828 - VirtualSize: - description: |- - Total size of the image including all layers it is composed of. - - In versions of Docker before v1.10, this field was calculated from - the image itself and all of its parent images. Images are now stored - self-contained, and no longer use a parent-chain, making this field - an equivalent of the Size field. - - Deprecated: this field is kept for backward compatibility, and will be removed in API v1.44. - type: "integer" - format: "int64" - example: 172064416 - Labels: - description: "User-defined key/value metadata." - type: "object" - x-nullable: false - additionalProperties: - type: "string" - example: - com.example.some-label: "some-value" - com.example.some-other-label: "some-other-value" - Containers: - description: | - Number of containers using this image. Includes both stopped and running - containers. - - This size is not calculated by default, and depends on which API endpoint - is used. `-1` indicates that the value has not been set / calculated. - x-nullable: false - type: "integer" - example: 2 - - AuthConfig: - type: "object" - properties: - username: - type: "string" - password: - type: "string" - email: - type: "string" - serveraddress: - type: "string" - example: - username: "hannibal" - password: "xxxx" - serveraddress: "https://index.docker.io/v1/" - - ProcessConfig: - type: "object" - properties: - privileged: - type: "boolean" - user: - type: "string" - tty: - type: "boolean" - entrypoint: - type: "string" - arguments: - type: "array" - items: - type: "string" - - Volume: - type: "object" - required: [Name, Driver, Mountpoint, Labels, Scope, Options] - properties: - Name: - type: "string" - description: "Name of the volume." - x-nullable: false - example: "tardis" - Driver: - type: "string" - description: "Name of the volume driver used by the volume." - x-nullable: false - example: "custom" - Mountpoint: - type: "string" - description: "Mount path of the volume on the host." - x-nullable: false - example: "/var/lib/docker/volumes/tardis" - CreatedAt: - type: "string" - format: "dateTime" - description: "Date/Time the volume was created." - example: "2016-06-07T20:31:11.853781916Z" - Status: - type: "object" - description: | - Low-level details about the volume, provided by the volume driver. - Details are returned as a map with key/value pairs: - `{"key":"value","key2":"value2"}`. - - The `Status` field is optional, and is omitted if the volume driver - does not support this feature. - additionalProperties: - type: "object" - example: - hello: "world" - Labels: - type: "object" - description: "User-defined key/value metadata." - x-nullable: false - additionalProperties: - type: "string" - example: - com.example.some-label: "some-value" - com.example.some-other-label: "some-other-value" - Scope: - type: "string" - description: | - The level at which the volume exists. Either `global` for cluster-wide, - or `local` for machine level. - default: "local" - x-nullable: false - enum: ["local", "global"] - example: "local" - ClusterVolume: - $ref: "#/definitions/ClusterVolume" - Options: - type: "object" - description: | - The driver specific options used when creating the volume. - additionalProperties: - type: "string" - example: - device: "tmpfs" - o: "size=100m,uid=1000" - type: "tmpfs" - UsageData: - type: "object" - x-nullable: true - x-go-name: "UsageData" - required: [Size, RefCount] - description: | - Usage details about the volume. This information is used by the - `GET /system/df` endpoint, and omitted in other endpoints. - properties: - Size: - type: "integer" - format: "int64" - default: -1 - description: | - Amount of disk space used by the volume (in bytes). This information - is only available for volumes created with the `"local"` volume - driver. For volumes created with other volume drivers, this field - is set to `-1` ("not available") - x-nullable: false - RefCount: - type: "integer" - format: "int64" - default: -1 - description: | - The number of containers referencing this volume. This field - is set to `-1` if the reference-count is not available. - x-nullable: false - - VolumeCreateOptions: - description: "Volume configuration" - type: "object" - title: "VolumeConfig" - x-go-name: "CreateOptions" - properties: - Name: - description: | - The new volume's name. If not specified, Docker generates a name. - type: "string" - x-nullable: false - example: "tardis" - Driver: - description: "Name of the volume driver to use." - type: "string" - default: "local" - x-nullable: false - example: "custom" - DriverOpts: - description: | - A mapping of driver options and values. These options are - passed directly to the driver and are driver specific. - type: "object" - additionalProperties: - type: "string" - example: - device: "tmpfs" - o: "size=100m,uid=1000" - type: "tmpfs" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - example: - com.example.some-label: "some-value" - com.example.some-other-label: "some-other-value" - ClusterVolumeSpec: - $ref: "#/definitions/ClusterVolumeSpec" - - VolumeListResponse: - type: "object" - title: "VolumeListResponse" - x-go-name: "ListResponse" - description: "Volume list response" - properties: - Volumes: - type: "array" - description: "List of volumes" - items: - $ref: "#/definitions/Volume" - Warnings: - type: "array" - description: | - Warnings that occurred when fetching the list of volumes. - items: - type: "string" - example: [] - - Network: - type: "object" - properties: - Name: - type: "string" - Id: - type: "string" - Created: - type: "string" - format: "dateTime" - Scope: - type: "string" - Driver: - type: "string" - EnableIPv6: - type: "boolean" - IPAM: - $ref: "#/definitions/IPAM" - Internal: - type: "boolean" - Attachable: - type: "boolean" - Ingress: - type: "boolean" - Containers: - type: "object" - additionalProperties: - $ref: "#/definitions/NetworkContainer" - Options: - type: "object" - additionalProperties: - type: "string" - Labels: - type: "object" - additionalProperties: - type: "string" - example: - Name: "net01" - Id: "7d86d31b1478e7cca9ebed7e73aa0fdeec46c5ca29497431d3007d2d9e15ed99" - Created: "2016-10-19T04:33:30.360899459Z" - Scope: "local" - Driver: "bridge" - EnableIPv6: false - IPAM: - Driver: "default" - Config: - - Subnet: "172.19.0.0/16" - Gateway: "172.19.0.1" - Options: - foo: "bar" - Internal: false - Attachable: false - Ingress: false - Containers: - 19a4d5d687db25203351ed79d478946f861258f018fe384f229f2efa4b23513c: - Name: "test" - EndpointID: "628cadb8bcb92de107b2a1e516cbffe463e321f548feb37697cce00ad694f21a" - MacAddress: "02:42:ac:13:00:02" - IPv4Address: "172.19.0.2/16" - IPv6Address: "" - Options: - com.docker.network.bridge.default_bridge: "true" - com.docker.network.bridge.enable_icc: "true" - com.docker.network.bridge.enable_ip_masquerade: "true" - com.docker.network.bridge.host_binding_ipv4: "0.0.0.0" - com.docker.network.bridge.name: "docker0" - com.docker.network.driver.mtu: "1500" - Labels: - com.example.some-label: "some-value" - com.example.some-other-label: "some-other-value" - IPAM: - type: "object" - properties: - Driver: - description: "Name of the IPAM driver to use." - type: "string" - default: "default" - Config: - description: | - List of IPAM configuration options, specified as a map: - - ``` - {"Subnet": , "IPRange": , "Gateway": , "AuxAddress": } - ``` - type: "array" - items: - $ref: "#/definitions/IPAMConfig" - Options: - description: "Driver-specific options, specified as a map." - type: "object" - additionalProperties: - type: "string" - - IPAMConfig: - type: "object" - properties: - Subnet: - type: "string" - IPRange: - type: "string" - Gateway: - type: "string" - AuxiliaryAddresses: - type: "object" - additionalProperties: - type: "string" - - NetworkContainer: - type: "object" - properties: - Name: - type: "string" - EndpointID: - type: "string" - MacAddress: - type: "string" - IPv4Address: - type: "string" - IPv6Address: - type: "string" - - BuildInfo: - type: "object" - properties: - id: - type: "string" - stream: - type: "string" - error: - type: "string" - errorDetail: - $ref: "#/definitions/ErrorDetail" - status: - type: "string" - progress: - type: "string" - progressDetail: - $ref: "#/definitions/ProgressDetail" - aux: - $ref: "#/definitions/ImageID" - - BuildCache: - type: "object" - description: | - BuildCache contains information about a build cache record. - properties: - ID: - type: "string" - description: | - Unique ID of the build cache record. - example: "ndlpt0hhvkqcdfkputsk4cq9c" - Parent: - description: | - ID of the parent build cache record. - - > **Deprecated**: This field is deprecated, and omitted if empty. - type: "string" - x-nullable: true - example: "" - Parents: - description: | - List of parent build cache record IDs. - type: "array" - items: - type: "string" - x-nullable: true - example: ["hw53o5aio51xtltp5xjp8v7fx"] - Type: - type: "string" - description: | - Cache record type. - example: "regular" - # see https://github.com/moby/buildkit/blob/fce4a32258dc9d9664f71a4831d5de10f0670677/client/diskusage.go#L75-L84 - enum: - - "internal" - - "frontend" - - "source.local" - - "source.git.checkout" - - "exec.cachemount" - - "regular" - Description: - type: "string" - description: | - Description of the build-step that produced the build cache. - example: "mount / from exec /bin/sh -c echo 'Binary::apt::APT::Keep-Downloaded-Packages \"true\";' > /etc/apt/apt.conf.d/keep-cache" - InUse: - type: "boolean" - description: | - Indicates if the build cache is in use. - example: false - Shared: - type: "boolean" - description: | - Indicates if the build cache is shared. - example: true - Size: - description: | - Amount of disk space used by the build cache (in bytes). - type: "integer" - example: 51 - CreatedAt: - description: | - Date and time at which the build cache was created in - [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format with nano-seconds. - type: "string" - format: "dateTime" - example: "2016-08-18T10:44:24.496525531Z" - LastUsedAt: - description: | - Date and time at which the build cache was last used in - [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format with nano-seconds. - type: "string" - format: "dateTime" - x-nullable: true - example: "2017-08-09T07:09:37.632105588Z" - UsageCount: - type: "integer" - example: 26 - - ImageID: - type: "object" - description: "Image ID or Digest" - properties: - ID: - type: "string" - example: - ID: "sha256:85f05633ddc1c50679be2b16a0479ab6f7637f8884e0cfe0f4d20e1ebb3d6e7c" - - CreateImageInfo: - type: "object" - properties: - id: - type: "string" - error: - type: "string" - errorDetail: - $ref: "#/definitions/ErrorDetail" - status: - type: "string" - progress: - type: "string" - progressDetail: - $ref: "#/definitions/ProgressDetail" - - PushImageInfo: - type: "object" - properties: - error: - type: "string" - status: - type: "string" - progress: - type: "string" - progressDetail: - $ref: "#/definitions/ProgressDetail" - - ErrorDetail: - type: "object" - properties: - code: - type: "integer" - message: - type: "string" - - ProgressDetail: - type: "object" - properties: - current: - type: "integer" - total: - type: "integer" - - ErrorResponse: - description: "Represents an error." - type: "object" - required: ["message"] - properties: - message: - description: "The error message." - type: "string" - x-nullable: false - example: - message: "Something went wrong." - - IdResponse: - description: "Response to an API call that returns just an Id" - type: "object" - required: ["Id"] - properties: - Id: - description: "The id of the newly created object." - type: "string" - x-nullable: false - - EndpointSettings: - description: "Configuration for a network endpoint." - type: "object" - properties: - # Configurations - IPAMConfig: - $ref: "#/definitions/EndpointIPAMConfig" - Links: - type: "array" - items: - type: "string" - example: - - "container_1" - - "container_2" - Aliases: - type: "array" - items: - type: "string" - example: - - "server_x" - - "server_y" - - # Operational data - NetworkID: - description: | - Unique ID of the network. - type: "string" - example: "08754567f1f40222263eab4102e1c733ae697e8e354aa9cd6e18d7402835292a" - EndpointID: - description: | - Unique ID for the service endpoint in a Sandbox. - type: "string" - example: "b88f5b905aabf2893f3cbc4ee42d1ea7980bbc0a92e2c8922b1e1795298afb0b" - Gateway: - description: | - Gateway address for this network. - type: "string" - example: "172.17.0.1" - IPAddress: - description: | - IPv4 address. - type: "string" - example: "172.17.0.4" - IPPrefixLen: - description: | - Mask length of the IPv4 address. - type: "integer" - example: 16 - IPv6Gateway: - description: | - IPv6 gateway address. - type: "string" - example: "2001:db8:2::100" - GlobalIPv6Address: - description: | - Global IPv6 address. - type: "string" - example: "2001:db8::5689" - GlobalIPv6PrefixLen: - description: | - Mask length of the global IPv6 address. - type: "integer" - format: "int64" - example: 64 - MacAddress: - description: | - MAC address for the endpoint on this network. - type: "string" - example: "02:42:ac:11:00:04" - DriverOpts: - description: | - DriverOpts is a mapping of driver options and values. These options - are passed directly to the driver and are driver specific. - type: "object" - x-nullable: true - additionalProperties: - type: "string" - example: - com.example.some-label: "some-value" - com.example.some-other-label: "some-other-value" - - EndpointIPAMConfig: - description: | - EndpointIPAMConfig represents an endpoint's IPAM configuration. - type: "object" - x-nullable: true - properties: - IPv4Address: - type: "string" - example: "172.20.30.33" - IPv6Address: - type: "string" - example: "2001:db8:abcd::3033" - LinkLocalIPs: - type: "array" - items: - type: "string" - example: - - "169.254.34.68" - - "fe80::3468" - - PluginMount: - type: "object" - x-nullable: false - required: [Name, Description, Settable, Source, Destination, Type, Options] - properties: - Name: - type: "string" - x-nullable: false - example: "some-mount" - Description: - type: "string" - x-nullable: false - example: "This is a mount that's used by the plugin." - Settable: - type: "array" - items: - type: "string" - Source: - type: "string" - example: "/var/lib/docker/plugins/" - Destination: - type: "string" - x-nullable: false - example: "/mnt/state" - Type: - type: "string" - x-nullable: false - example: "bind" - Options: - type: "array" - items: - type: "string" - example: - - "rbind" - - "rw" - - PluginDevice: - type: "object" - required: [Name, Description, Settable, Path] - x-nullable: false - properties: - Name: - type: "string" - x-nullable: false - Description: - type: "string" - x-nullable: false - Settable: - type: "array" - items: - type: "string" - Path: - type: "string" - example: "/dev/fuse" - - PluginEnv: - type: "object" - x-nullable: false - required: [Name, Description, Settable, Value] - properties: - Name: - x-nullable: false - type: "string" - Description: - x-nullable: false - type: "string" - Settable: - type: "array" - items: - type: "string" - Value: - type: "string" - - PluginInterfaceType: - type: "object" - x-nullable: false - required: [Prefix, Capability, Version] - properties: - Prefix: - type: "string" - x-nullable: false - Capability: - type: "string" - x-nullable: false - Version: - type: "string" - x-nullable: false - - PluginPrivilege: - description: | - Describes a permission the user has to accept upon installing - the plugin. - type: "object" - x-go-name: "PluginPrivilege" - properties: - Name: - type: "string" - example: "network" - Description: - type: "string" - Value: - type: "array" - items: - type: "string" - example: - - "host" - - Plugin: - description: "A plugin for the Engine API" - type: "object" - required: [Settings, Enabled, Config, Name] - properties: - Id: - type: "string" - example: "5724e2c8652da337ab2eedd19fc6fc0ec908e4bd907c7421bf6a8dfc70c4c078" - Name: - type: "string" - x-nullable: false - example: "tiborvass/sample-volume-plugin" - Enabled: - description: - True if the plugin is running. False if the plugin is not running, - only installed. - type: "boolean" - x-nullable: false - example: true - Settings: - description: "Settings that can be modified by users." - type: "object" - x-nullable: false - required: [Args, Devices, Env, Mounts] - properties: - Mounts: - type: "array" - items: - $ref: "#/definitions/PluginMount" - Env: - type: "array" - items: - type: "string" - example: - - "DEBUG=0" - Args: - type: "array" - items: - type: "string" - Devices: - type: "array" - items: - $ref: "#/definitions/PluginDevice" - PluginReference: - description: "plugin remote reference used to push/pull the plugin" - type: "string" - x-nullable: false - example: "localhost:5000/tiborvass/sample-volume-plugin:latest" - Config: - description: "The config of a plugin." - type: "object" - x-nullable: false - required: - - Description - - Documentation - - Interface - - Entrypoint - - WorkDir - - Network - - Linux - - PidHost - - PropagatedMount - - IpcHost - - Mounts - - Env - - Args - properties: - DockerVersion: - description: "Docker Version used to create the plugin" - type: "string" - x-nullable: false - example: "17.06.0-ce" - Description: - type: "string" - x-nullable: false - example: "A sample volume plugin for Docker" - Documentation: - type: "string" - x-nullable: false - example: "https://docs.docker.com/engine/extend/plugins/" - Interface: - description: "The interface between Docker and the plugin" - x-nullable: false - type: "object" - required: [Types, Socket] - properties: - Types: - type: "array" - items: - $ref: "#/definitions/PluginInterfaceType" - example: - - "docker.volumedriver/1.0" - Socket: - type: "string" - x-nullable: false - example: "plugins.sock" - ProtocolScheme: - type: "string" - example: "some.protocol/v1.0" - description: "Protocol to use for clients connecting to the plugin." - enum: - - "" - - "moby.plugins.http/v1" - Entrypoint: - type: "array" - items: - type: "string" - example: - - "/usr/bin/sample-volume-plugin" - - "/data" - WorkDir: - type: "string" - x-nullable: false - example: "/bin/" - User: - type: "object" - x-nullable: false - properties: - UID: - type: "integer" - format: "uint32" - example: 1000 - GID: - type: "integer" - format: "uint32" - example: 1000 - Network: - type: "object" - x-nullable: false - required: [Type] - properties: - Type: - x-nullable: false - type: "string" - example: "host" - Linux: - type: "object" - x-nullable: false - required: [Capabilities, AllowAllDevices, Devices] - properties: - Capabilities: - type: "array" - items: - type: "string" - example: - - "CAP_SYS_ADMIN" - - "CAP_SYSLOG" - AllowAllDevices: - type: "boolean" - x-nullable: false - example: false - Devices: - type: "array" - items: - $ref: "#/definitions/PluginDevice" - PropagatedMount: - type: "string" - x-nullable: false - example: "/mnt/volumes" - IpcHost: - type: "boolean" - x-nullable: false - example: false - PidHost: - type: "boolean" - x-nullable: false - example: false - Mounts: - type: "array" - items: - $ref: "#/definitions/PluginMount" - Env: - type: "array" - items: - $ref: "#/definitions/PluginEnv" - example: - - Name: "DEBUG" - Description: "If set, prints debug messages" - Settable: null - Value: "0" - Args: - type: "object" - x-nullable: false - required: [Name, Description, Settable, Value] - properties: - Name: - x-nullable: false - type: "string" - example: "args" - Description: - x-nullable: false - type: "string" - example: "command line arguments" - Settable: - type: "array" - items: - type: "string" - Value: - type: "array" - items: - type: "string" - rootfs: - type: "object" - properties: - type: - type: "string" - example: "layers" - diff_ids: - type: "array" - items: - type: "string" - example: - - "sha256:675532206fbf3030b8458f88d6e26d4eb1577688a25efec97154c94e8b6b4887" - - "sha256:e216a057b1cb1efc11f8a268f37ef62083e70b1b38323ba252e25ac88904a7e8" - - ObjectVersion: - description: | - The version number of the object such as node, service, etc. This is needed - to avoid conflicting writes. The client must send the version number along - with the modified specification when updating these objects. - - This approach ensures safe concurrency and determinism in that the change - on the object may not be applied if the version number has changed from the - last read. In other words, if two update requests specify the same base - version, only one of the requests can succeed. As a result, two separate - update requests that happen at the same time will not unintentionally - overwrite each other. - type: "object" - properties: - Index: - type: "integer" - format: "uint64" - example: 373531 - - NodeSpec: - type: "object" - properties: - Name: - description: "Name for the node." - type: "string" - example: "my-node" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - Role: - description: "Role of the node." - type: "string" - enum: - - "worker" - - "manager" - example: "manager" - Availability: - description: "Availability of the node." - type: "string" - enum: - - "active" - - "pause" - - "drain" - example: "active" - example: - Availability: "active" - Name: "node-name" - Role: "manager" - Labels: - foo: "bar" - - Node: - type: "object" - properties: - ID: - type: "string" - example: "24ifsmvkjbyhk" - Version: - $ref: "#/definitions/ObjectVersion" - CreatedAt: - description: | - Date and time at which the node was added to the swarm in - [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format with nano-seconds. - type: "string" - format: "dateTime" - example: "2016-08-18T10:44:24.496525531Z" - UpdatedAt: - description: | - Date and time at which the node was last updated in - [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format with nano-seconds. - type: "string" - format: "dateTime" - example: "2017-08-09T07:09:37.632105588Z" - Spec: - $ref: "#/definitions/NodeSpec" - Description: - $ref: "#/definitions/NodeDescription" - Status: - $ref: "#/definitions/NodeStatus" - ManagerStatus: - $ref: "#/definitions/ManagerStatus" - - NodeDescription: - description: | - NodeDescription encapsulates the properties of the Node as reported by the - agent. - type: "object" - properties: - Hostname: - type: "string" - example: "bf3067039e47" - Platform: - $ref: "#/definitions/Platform" - Resources: - $ref: "#/definitions/ResourceObject" - Engine: - $ref: "#/definitions/EngineDescription" - TLSInfo: - $ref: "#/definitions/TLSInfo" - - Platform: - description: | - Platform represents the platform (Arch/OS). - type: "object" - properties: - Architecture: - description: | - Architecture represents the hardware architecture (for example, - `x86_64`). - type: "string" - example: "x86_64" - OS: - description: | - OS represents the Operating System (for example, `linux` or `windows`). - type: "string" - example: "linux" - - EngineDescription: - description: "EngineDescription provides information about an engine." - type: "object" - properties: - EngineVersion: - type: "string" - example: "17.06.0" - Labels: - type: "object" - additionalProperties: - type: "string" - example: - foo: "bar" - Plugins: - type: "array" - items: - type: "object" - properties: - Type: - type: "string" - Name: - type: "string" - example: - - Type: "Log" - Name: "awslogs" - - Type: "Log" - Name: "fluentd" - - Type: "Log" - Name: "gcplogs" - - Type: "Log" - Name: "gelf" - - Type: "Log" - Name: "journald" - - Type: "Log" - Name: "json-file" - - Type: "Log" - Name: "splunk" - - Type: "Log" - Name: "syslog" - - Type: "Network" - Name: "bridge" - - Type: "Network" - Name: "host" - - Type: "Network" - Name: "ipvlan" - - Type: "Network" - Name: "macvlan" - - Type: "Network" - Name: "null" - - Type: "Network" - Name: "overlay" - - Type: "Volume" - Name: "local" - - Type: "Volume" - Name: "localhost:5000/vieux/sshfs:latest" - - Type: "Volume" - Name: "vieux/sshfs:latest" - - TLSInfo: - description: | - Information about the issuer of leaf TLS certificates and the trusted root - CA certificate. - type: "object" - properties: - TrustRoot: - description: | - The root CA certificate(s) that are used to validate leaf TLS - certificates. - type: "string" - CertIssuerSubject: - description: - The base64-url-safe-encoded raw subject bytes of the issuer. - type: "string" - CertIssuerPublicKey: - description: | - The base64-url-safe-encoded raw public key bytes of the issuer. - type: "string" - example: - TrustRoot: | - -----BEGIN CERTIFICATE----- - MIIBajCCARCgAwIBAgIUbYqrLSOSQHoxD8CwG6Bi2PJi9c8wCgYIKoZIzj0EAwIw - EzERMA8GA1UEAxMIc3dhcm0tY2EwHhcNMTcwNDI0MjE0MzAwWhcNMzcwNDE5MjE0 - MzAwWjATMREwDwYDVQQDEwhzd2FybS1jYTBZMBMGByqGSM49AgEGCCqGSM49AwEH - A0IABJk/VyMPYdaqDXJb/VXh5n/1Yuv7iNrxV3Qb3l06XD46seovcDWs3IZNV1lf - 3Skyr0ofcchipoiHkXBODojJydSjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMB - Af8EBTADAQH/MB0GA1UdDgQWBBRUXxuRcnFjDfR/RIAUQab8ZV/n4jAKBggqhkjO - PQQDAgNIADBFAiAy+JTe6Uc3KyLCMiqGl2GyWGQqQDEcO3/YG36x7om65AIhAJvz - pxv6zFeVEkAEEkqIYi0omA9+CjanB/6Bz4n1uw8H - -----END CERTIFICATE----- - CertIssuerSubject: "MBMxETAPBgNVBAMTCHN3YXJtLWNh" - CertIssuerPublicKey: "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEmT9XIw9h1qoNclv9VeHmf/Vi6/uI2vFXdBveXTpcPjqx6i9wNazchk1XWV/dKTKvSh9xyGKmiIeRcE4OiMnJ1A==" - - NodeStatus: - description: | - NodeStatus represents the status of a node. - - It provides the current status of the node, as seen by the manager. - type: "object" - properties: - State: - $ref: "#/definitions/NodeState" - Message: - type: "string" - example: "" - Addr: - description: "IP address of the node." - type: "string" - example: "172.17.0.2" - - NodeState: - description: "NodeState represents the state of a node." - type: "string" - enum: - - "unknown" - - "down" - - "ready" - - "disconnected" - example: "ready" - - ManagerStatus: - description: | - ManagerStatus represents the status of a manager. - - It provides the current status of a node's manager component, if the node - is a manager. - x-nullable: true - type: "object" - properties: - Leader: - type: "boolean" - default: false - example: true - Reachability: - $ref: "#/definitions/Reachability" - Addr: - description: | - The IP address and port at which the manager is reachable. - type: "string" - example: "10.0.0.46:2377" - - Reachability: - description: "Reachability represents the reachability of a node." - type: "string" - enum: - - "unknown" - - "unreachable" - - "reachable" - example: "reachable" - - SwarmSpec: - description: "User modifiable swarm configuration." - type: "object" - properties: - Name: - description: "Name of the swarm." - type: "string" - example: "default" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - example: - com.example.corp.type: "production" - com.example.corp.department: "engineering" - Orchestration: - description: "Orchestration configuration." - type: "object" - x-nullable: true - properties: - TaskHistoryRetentionLimit: - description: | - The number of historic tasks to keep per instance or node. If - negative, never remove completed or failed tasks. - type: "integer" - format: "int64" - example: 10 - Raft: - description: "Raft configuration." - type: "object" - properties: - SnapshotInterval: - description: "The number of log entries between snapshots." - type: "integer" - format: "uint64" - example: 10000 - KeepOldSnapshots: - description: | - The number of snapshots to keep beyond the current snapshot. - type: "integer" - format: "uint64" - LogEntriesForSlowFollowers: - description: | - The number of log entries to keep around to sync up slow followers - after a snapshot is created. - type: "integer" - format: "uint64" - example: 500 - ElectionTick: - description: | - The number of ticks that a follower will wait for a message from - the leader before becoming a candidate and starting an election. - `ElectionTick` must be greater than `HeartbeatTick`. - - A tick currently defaults to one second, so these translate - directly to seconds currently, but this is NOT guaranteed. - type: "integer" - example: 3 - HeartbeatTick: - description: | - The number of ticks between heartbeats. Every HeartbeatTick ticks, - the leader will send a heartbeat to the followers. - - A tick currently defaults to one second, so these translate - directly to seconds currently, but this is NOT guaranteed. - type: "integer" - example: 1 - Dispatcher: - description: "Dispatcher configuration." - type: "object" - x-nullable: true - properties: - HeartbeatPeriod: - description: | - The delay for an agent to send a heartbeat to the dispatcher. - type: "integer" - format: "int64" - example: 5000000000 - CAConfig: - description: "CA configuration." - type: "object" - x-nullable: true - properties: - NodeCertExpiry: - description: "The duration node certificates are issued for." - type: "integer" - format: "int64" - example: 7776000000000000 - ExternalCAs: - description: | - Configuration for forwarding signing requests to an external - certificate authority. - type: "array" - items: - type: "object" - properties: - Protocol: - description: | - Protocol for communication with the external CA (currently - only `cfssl` is supported). - type: "string" - enum: - - "cfssl" - default: "cfssl" - URL: - description: | - URL where certificate signing requests should be sent. - type: "string" - Options: - description: | - An object with key/value pairs that are interpreted as - protocol-specific options for the external CA driver. - type: "object" - additionalProperties: - type: "string" - CACert: - description: | - The root CA certificate (in PEM format) this external CA uses - to issue TLS certificates (assumed to be to the current swarm - root CA certificate if not provided). - type: "string" - SigningCACert: - description: | - The desired signing CA certificate for all swarm node TLS leaf - certificates, in PEM format. - type: "string" - SigningCAKey: - description: | - The desired signing CA key for all swarm node TLS leaf certificates, - in PEM format. - type: "string" - ForceRotate: - description: | - An integer whose purpose is to force swarm to generate a new - signing CA certificate and key, if none have been specified in - `SigningCACert` and `SigningCAKey` - format: "uint64" - type: "integer" - EncryptionConfig: - description: "Parameters related to encryption-at-rest." - type: "object" - properties: - AutoLockManagers: - description: | - If set, generate a key and use it to lock data stored on the - managers. - type: "boolean" - example: false - TaskDefaults: - description: "Defaults for creating tasks in this cluster." - type: "object" - properties: - LogDriver: - description: | - The log driver to use for tasks created in the orchestrator if - unspecified by a service. - - Updating this value only affects new tasks. Existing tasks continue - to use their previously configured log driver until recreated. - type: "object" - properties: - Name: - description: | - The log driver to use as a default for new tasks. - type: "string" - example: "json-file" - Options: - description: | - Driver-specific options for the selectd log driver, specified - as key/value pairs. - type: "object" - additionalProperties: - type: "string" - example: - "max-file": "10" - "max-size": "100m" - - # The Swarm information for `GET /info`. It is the same as `GET /swarm`, but - # without `JoinTokens`. - ClusterInfo: - description: | - ClusterInfo represents information about the swarm as is returned by the - "/info" endpoint. Join-tokens are not included. - x-nullable: true - type: "object" - properties: - ID: - description: "The ID of the swarm." - type: "string" - example: "abajmipo7b4xz5ip2nrla6b11" - Version: - $ref: "#/definitions/ObjectVersion" - CreatedAt: - description: | - Date and time at which the swarm was initialised in - [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format with nano-seconds. - type: "string" - format: "dateTime" - example: "2016-08-18T10:44:24.496525531Z" - UpdatedAt: - description: | - Date and time at which the swarm was last updated in - [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format with nano-seconds. - type: "string" - format: "dateTime" - example: "2017-08-09T07:09:37.632105588Z" - Spec: - $ref: "#/definitions/SwarmSpec" - TLSInfo: - $ref: "#/definitions/TLSInfo" - RootRotationInProgress: - description: | - Whether there is currently a root CA rotation in progress for the swarm - type: "boolean" - example: false - DataPathPort: - description: | - DataPathPort specifies the data path port number for data traffic. - Acceptable port range is 1024 to 49151. - If no port is set or is set to 0, the default port (4789) is used. - type: "integer" - format: "uint32" - default: 4789 - example: 4789 - DefaultAddrPool: - description: | - Default Address Pool specifies default subnet pools for global scope - networks. - type: "array" - items: - type: "string" - format: "CIDR" - example: ["10.10.0.0/16", "20.20.0.0/16"] - SubnetSize: - description: | - SubnetSize specifies the subnet size of the networks created from the - default subnet pool. - type: "integer" - format: "uint32" - maximum: 29 - default: 24 - example: 24 - - JoinTokens: - description: | - JoinTokens contains the tokens workers and managers need to join the swarm. - type: "object" - properties: - Worker: - description: | - The token workers can use to join the swarm. - type: "string" - example: "SWMTKN-1-3pu6hszjas19xyp7ghgosyx9k8atbfcr8p2is99znpy26u2lkl-1awxwuwd3z9j1z3puu7rcgdbx" - Manager: - description: | - The token managers can use to join the swarm. - type: "string" - example: "SWMTKN-1-3pu6hszjas19xyp7ghgosyx9k8atbfcr8p2is99znpy26u2lkl-7p73s1dx5in4tatdymyhg9hu2" - - Swarm: - type: "object" - allOf: - - $ref: "#/definitions/ClusterInfo" - - type: "object" - properties: - JoinTokens: - $ref: "#/definitions/JoinTokens" - - TaskSpec: - description: "User modifiable task configuration." - type: "object" - properties: - PluginSpec: - type: "object" - description: | - Plugin spec for the service. *(Experimental release only.)* - -


- - > **Note**: ContainerSpec, NetworkAttachmentSpec, and PluginSpec are - > mutually exclusive. PluginSpec is only used when the Runtime field - > is set to `plugin`. NetworkAttachmentSpec is used when the Runtime - > field is set to `attachment`. - properties: - Name: - description: "The name or 'alias' to use for the plugin." - type: "string" - Remote: - description: "The plugin image reference to use." - type: "string" - Disabled: - description: "Disable the plugin once scheduled." - type: "boolean" - PluginPrivilege: - type: "array" - items: - $ref: "#/definitions/PluginPrivilege" - ContainerSpec: - type: "object" - description: | - Container spec for the service. - -


- - > **Note**: ContainerSpec, NetworkAttachmentSpec, and PluginSpec are - > mutually exclusive. PluginSpec is only used when the Runtime field - > is set to `plugin`. NetworkAttachmentSpec is used when the Runtime - > field is set to `attachment`. - properties: - Image: - description: "The image name to use for the container" - type: "string" - Labels: - description: "User-defined key/value data." - type: "object" - additionalProperties: - type: "string" - Command: - description: "The command to be run in the image." - type: "array" - items: - type: "string" - Args: - description: "Arguments to the command." - type: "array" - items: - type: "string" - Hostname: - description: | - The hostname to use for the container, as a valid - [RFC 1123](https://tools.ietf.org/html/rfc1123) hostname. - type: "string" - Env: - description: | - A list of environment variables in the form `VAR=value`. - type: "array" - items: - type: "string" - Dir: - description: "The working directory for commands to run in." - type: "string" - User: - description: "The user inside the container." - type: "string" - Groups: - type: "array" - description: | - A list of additional groups that the container process will run as. - items: - type: "string" - Privileges: - type: "object" - description: "Security options for the container" - properties: - CredentialSpec: - type: "object" - description: "CredentialSpec for managed service account (Windows only)" - properties: - Config: - type: "string" - example: "0bt9dmxjvjiqermk6xrop3ekq" - description: | - Load credential spec from a Swarm Config with the given ID. - The specified config must also be present in the Configs - field with the Runtime property set. - -


- - - > **Note**: `CredentialSpec.File`, `CredentialSpec.Registry`, - > and `CredentialSpec.Config` are mutually exclusive. - File: - type: "string" - example: "spec.json" - description: | - Load credential spec from this file. The file is read by - the daemon, and must be present in the `CredentialSpecs` - subdirectory in the docker data directory, which defaults - to `C:\ProgramData\Docker\` on Windows. - - For example, specifying `spec.json` loads - `C:\ProgramData\Docker\CredentialSpecs\spec.json`. - -


- - > **Note**: `CredentialSpec.File`, `CredentialSpec.Registry`, - > and `CredentialSpec.Config` are mutually exclusive. - Registry: - type: "string" - description: | - Load credential spec from this value in the Windows - registry. The specified registry value must be located in: - - `HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization\Containers\CredentialSpecs` - -


- - - > **Note**: `CredentialSpec.File`, `CredentialSpec.Registry`, - > and `CredentialSpec.Config` are mutually exclusive. - SELinuxContext: - type: "object" - description: "SELinux labels of the container" - properties: - Disable: - type: "boolean" - description: "Disable SELinux" - User: - type: "string" - description: "SELinux user label" - Role: - type: "string" - description: "SELinux role label" - Type: - type: "string" - description: "SELinux type label" - Level: - type: "string" - description: "SELinux level label" - TTY: - description: "Whether a pseudo-TTY should be allocated." - type: "boolean" - OpenStdin: - description: "Open `stdin`" - type: "boolean" - ReadOnly: - description: "Mount the container's root filesystem as read only." - type: "boolean" - Mounts: - description: | - Specification for mounts to be added to containers created as part - of the service. - type: "array" - items: - $ref: "#/definitions/Mount" - StopSignal: - description: "Signal to stop the container." - type: "string" - StopGracePeriod: - description: | - Amount of time to wait for the container to terminate before - forcefully killing it. - type: "integer" - format: "int64" - HealthCheck: - $ref: "#/definitions/HealthConfig" - Hosts: - type: "array" - description: | - A list of hostname/IP mappings to add to the container's `hosts` - file. The format of extra hosts is specified in the - [hosts(5)](http://man7.org/linux/man-pages/man5/hosts.5.html) - man page: - - IP_address canonical_hostname [aliases...] - items: - type: "string" - DNSConfig: - description: | - Specification for DNS related configurations in resolver configuration - file (`resolv.conf`). - type: "object" - properties: - Nameservers: - description: "The IP addresses of the name servers." - type: "array" - items: - type: "string" - Search: - description: "A search list for host-name lookup." - type: "array" - items: - type: "string" - Options: - description: | - A list of internal resolver variables to be modified (e.g., - `debug`, `ndots:3`, etc.). - type: "array" - items: - type: "string" - Secrets: - description: | - Secrets contains references to zero or more secrets that will be - exposed to the service. - type: "array" - items: - type: "object" - properties: - File: - description: | - File represents a specific target that is backed by a file. - type: "object" - properties: - Name: - description: | - Name represents the final filename in the filesystem. - type: "string" - UID: - description: "UID represents the file UID." - type: "string" - GID: - description: "GID represents the file GID." - type: "string" - Mode: - description: "Mode represents the FileMode of the file." - type: "integer" - format: "uint32" - SecretID: - description: | - SecretID represents the ID of the specific secret that we're - referencing. - type: "string" - SecretName: - description: | - SecretName is the name of the secret that this references, - but this is just provided for lookup/display purposes. The - secret in the reference will be identified by its ID. - type: "string" - Configs: - description: | - Configs contains references to zero or more configs that will be - exposed to the service. - type: "array" - items: - type: "object" - properties: - File: - description: | - File represents a specific target that is backed by a file. - -


- - > **Note**: `Configs.File` and `Configs.Runtime` are mutually exclusive - type: "object" - properties: - Name: - description: | - Name represents the final filename in the filesystem. - type: "string" - UID: - description: "UID represents the file UID." - type: "string" - GID: - description: "GID represents the file GID." - type: "string" - Mode: - description: "Mode represents the FileMode of the file." - type: "integer" - format: "uint32" - Runtime: - description: | - Runtime represents a target that is not mounted into the - container but is used by the task - -


- - > **Note**: `Configs.File` and `Configs.Runtime` are mutually - > exclusive - type: "object" - ConfigID: - description: | - ConfigID represents the ID of the specific config that we're - referencing. - type: "string" - ConfigName: - description: | - ConfigName is the name of the config that this references, - but this is just provided for lookup/display purposes. The - config in the reference will be identified by its ID. - type: "string" - Isolation: - type: "string" - description: | - Isolation technology of the containers running the service. - (Windows only) - enum: - - "default" - - "process" - - "hyperv" - Init: - description: | - Run an init inside the container that forwards signals and reaps - processes. This field is omitted if empty, and the default (as - configured on the daemon) is used. - type: "boolean" - x-nullable: true - Sysctls: - description: | - Set kernel namedspaced parameters (sysctls) in the container. - The Sysctls option on services accepts the same sysctls as the - are supported on containers. Note that while the same sysctls are - supported, no guarantees or checks are made about their - suitability for a clustered environment, and it's up to the user - to determine whether a given sysctl will work properly in a - Service. - type: "object" - additionalProperties: - type: "string" - # This option is not used by Windows containers - CapabilityAdd: - type: "array" - description: | - A list of kernel capabilities to add to the default set - for the container. - items: - type: "string" - example: - - "CAP_NET_RAW" - - "CAP_SYS_ADMIN" - - "CAP_SYS_CHROOT" - - "CAP_SYSLOG" - CapabilityDrop: - type: "array" - description: | - A list of kernel capabilities to drop from the default set - for the container. - items: - type: "string" - example: - - "CAP_NET_RAW" - Ulimits: - description: | - A list of resource limits to set in the container. For example: `{"Name": "nofile", "Soft": 1024, "Hard": 2048}`" - type: "array" - items: - type: "object" - properties: - Name: - description: "Name of ulimit" - type: "string" - Soft: - description: "Soft limit" - type: "integer" - Hard: - description: "Hard limit" - type: "integer" - NetworkAttachmentSpec: - description: | - Read-only spec type for non-swarm containers attached to swarm overlay - networks. - -


- - > **Note**: ContainerSpec, NetworkAttachmentSpec, and PluginSpec are - > mutually exclusive. PluginSpec is only used when the Runtime field - > is set to `plugin`. NetworkAttachmentSpec is used when the Runtime - > field is set to `attachment`. - type: "object" - properties: - ContainerID: - description: "ID of the container represented by this task" - type: "string" - Resources: - description: | - Resource requirements which apply to each individual container created - as part of the service. - type: "object" - properties: - Limits: - description: "Define resources limits." - $ref: "#/definitions/Limit" - Reservations: - description: "Define resources reservation." - $ref: "#/definitions/ResourceObject" - RestartPolicy: - description: | - Specification for the restart policy which applies to containers - created as part of this service. - type: "object" - properties: - Condition: - description: "Condition for restart." - type: "string" - enum: - - "none" - - "on-failure" - - "any" - Delay: - description: "Delay between restart attempts." - type: "integer" - format: "int64" - MaxAttempts: - description: | - Maximum attempts to restart a given container before giving up - (default value is 0, which is ignored). - type: "integer" - format: "int64" - default: 0 - Window: - description: | - Windows is the time window used to evaluate the restart policy - (default value is 0, which is unbounded). - type: "integer" - format: "int64" - default: 0 - Placement: - type: "object" - properties: - Constraints: - description: | - An array of constraint expressions to limit the set of nodes where - a task can be scheduled. Constraint expressions can either use a - _match_ (`==`) or _exclude_ (`!=`) rule. Multiple constraints find - nodes that satisfy every expression (AND match). Constraints can - match node or Docker Engine labels as follows: - - node attribute | matches | example - ---------------------|--------------------------------|----------------------------------------------- - `node.id` | Node ID | `node.id==2ivku8v2gvtg4` - `node.hostname` | Node hostname | `node.hostname!=node-2` - `node.role` | Node role (`manager`/`worker`) | `node.role==manager` - `node.platform.os` | Node operating system | `node.platform.os==windows` - `node.platform.arch` | Node architecture | `node.platform.arch==x86_64` - `node.labels` | User-defined node labels | `node.labels.security==high` - `engine.labels` | Docker Engine's labels | `engine.labels.operatingsystem==ubuntu-14.04` - - `engine.labels` apply to Docker Engine labels like operating system, - drivers, etc. Swarm administrators add `node.labels` for operational - purposes by using the [`node update endpoint`](#operation/NodeUpdate). - - type: "array" - items: - type: "string" - example: - - "node.hostname!=node3.corp.example.com" - - "node.role!=manager" - - "node.labels.type==production" - - "node.platform.os==linux" - - "node.platform.arch==x86_64" - Preferences: - description: | - Preferences provide a way to make the scheduler aware of factors - such as topology. They are provided in order from highest to - lowest precedence. - type: "array" - items: - type: "object" - properties: - Spread: - type: "object" - properties: - SpreadDescriptor: - description: | - label descriptor, such as `engine.labels.az`. - type: "string" - example: - - Spread: - SpreadDescriptor: "node.labels.datacenter" - - Spread: - SpreadDescriptor: "node.labels.rack" - MaxReplicas: - description: | - Maximum number of replicas for per node (default value is 0, which - is unlimited) - type: "integer" - format: "int64" - default: 0 - Platforms: - description: | - Platforms stores all the platforms that the service's image can - run on. This field is used in the platform filter for scheduling. - If empty, then the platform filter is off, meaning there are no - scheduling restrictions. - type: "array" - items: - $ref: "#/definitions/Platform" - ForceUpdate: - description: | - A counter that triggers an update even if no relevant parameters have - been changed. - type: "integer" - Runtime: - description: | - Runtime is the type of runtime specified for the task executor. - type: "string" - Networks: - description: "Specifies which networks the service should attach to." - type: "array" - items: - $ref: "#/definitions/NetworkAttachmentConfig" - LogDriver: - description: | - Specifies the log driver to use for tasks created from this spec. If - not present, the default one for the swarm will be used, finally - falling back to the engine default if not specified. - type: "object" - properties: - Name: - type: "string" - Options: - type: "object" - additionalProperties: - type: "string" - - TaskState: - type: "string" - enum: - - "new" - - "allocated" - - "pending" - - "assigned" - - "accepted" - - "preparing" - - "ready" - - "starting" - - "running" - - "complete" - - "shutdown" - - "failed" - - "rejected" - - "remove" - - "orphaned" - - Task: - type: "object" - properties: - ID: - description: "The ID of the task." - type: "string" - Version: - $ref: "#/definitions/ObjectVersion" - CreatedAt: - type: "string" - format: "dateTime" - UpdatedAt: - type: "string" - format: "dateTime" - Name: - description: "Name of the task." - type: "string" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - Spec: - $ref: "#/definitions/TaskSpec" - ServiceID: - description: "The ID of the service this task is part of." - type: "string" - Slot: - type: "integer" - NodeID: - description: "The ID of the node that this task is on." - type: "string" - AssignedGenericResources: - $ref: "#/definitions/GenericResources" - Status: - type: "object" - properties: - Timestamp: - type: "string" - format: "dateTime" - State: - $ref: "#/definitions/TaskState" - Message: - type: "string" - Err: - type: "string" - ContainerStatus: - type: "object" - properties: - ContainerID: - type: "string" - PID: - type: "integer" - ExitCode: - type: "integer" - DesiredState: - $ref: "#/definitions/TaskState" - JobIteration: - description: | - If the Service this Task belongs to is a job-mode service, contains - the JobIteration of the Service this Task was created for. Absent if - the Task was created for a Replicated or Global Service. - $ref: "#/definitions/ObjectVersion" - example: - ID: "0kzzo1i0y4jz6027t0k7aezc7" - Version: - Index: 71 - CreatedAt: "2016-06-07T21:07:31.171892745Z" - UpdatedAt: "2016-06-07T21:07:31.376370513Z" - Spec: - ContainerSpec: - Image: "redis" - Resources: - Limits: {} - Reservations: {} - RestartPolicy: - Condition: "any" - MaxAttempts: 0 - Placement: {} - ServiceID: "9mnpnzenvg8p8tdbtq4wvbkcz" - Slot: 1 - NodeID: "60gvrl6tm78dmak4yl7srz94v" - Status: - Timestamp: "2016-06-07T21:07:31.290032978Z" - State: "running" - Message: "started" - ContainerStatus: - ContainerID: "e5d62702a1b48d01c3e02ca1e0212a250801fa8d67caca0b6f35919ebc12f035" - PID: 677 - DesiredState: "running" - NetworksAttachments: - - Network: - ID: "4qvuz4ko70xaltuqbt8956gd1" - Version: - Index: 18 - CreatedAt: "2016-06-07T20:31:11.912919752Z" - UpdatedAt: "2016-06-07T21:07:29.955277358Z" - Spec: - Name: "ingress" - Labels: - com.docker.swarm.internal: "true" - DriverConfiguration: {} - IPAMOptions: - Driver: {} - Configs: - - Subnet: "10.255.0.0/16" - Gateway: "10.255.0.1" - DriverState: - Name: "overlay" - Options: - com.docker.network.driver.overlay.vxlanid_list: "256" - IPAMOptions: - Driver: - Name: "default" - Configs: - - Subnet: "10.255.0.0/16" - Gateway: "10.255.0.1" - Addresses: - - "10.255.0.10/16" - AssignedGenericResources: - - DiscreteResourceSpec: - Kind: "SSD" - Value: 3 - - NamedResourceSpec: - Kind: "GPU" - Value: "UUID1" - - NamedResourceSpec: - Kind: "GPU" - Value: "UUID2" - - ServiceSpec: - description: "User modifiable configuration for a service." - type: object - properties: - Name: - description: "Name of the service." - type: "string" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - TaskTemplate: - $ref: "#/definitions/TaskSpec" - Mode: - description: "Scheduling mode for the service." - type: "object" - properties: - Replicated: - type: "object" - properties: - Replicas: - type: "integer" - format: "int64" - Global: - type: "object" - ReplicatedJob: - description: | - The mode used for services with a finite number of tasks that run - to a completed state. - type: "object" - properties: - MaxConcurrent: - description: | - The maximum number of replicas to run simultaneously. - type: "integer" - format: "int64" - default: 1 - TotalCompletions: - description: | - The total number of replicas desired to reach the Completed - state. If unset, will default to the value of `MaxConcurrent` - type: "integer" - format: "int64" - GlobalJob: - description: | - The mode used for services which run a task to the completed state - on each valid node. - type: "object" - UpdateConfig: - description: "Specification for the update strategy of the service." - type: "object" - properties: - Parallelism: - description: | - Maximum number of tasks to be updated in one iteration (0 means - unlimited parallelism). - type: "integer" - format: "int64" - Delay: - description: "Amount of time between updates, in nanoseconds." - type: "integer" - format: "int64" - FailureAction: - description: | - Action to take if an updated task fails to run, or stops running - during the update. - type: "string" - enum: - - "continue" - - "pause" - - "rollback" - Monitor: - description: | - Amount of time to monitor each updated task for failures, in - nanoseconds. - type: "integer" - format: "int64" - MaxFailureRatio: - description: | - The fraction of tasks that may fail during an update before the - failure action is invoked, specified as a floating point number - between 0 and 1. - type: "number" - default: 0 - Order: - description: | - The order of operations when rolling out an updated task. Either - the old task is shut down before the new task is started, or the - new task is started before the old task is shut down. - type: "string" - enum: - - "stop-first" - - "start-first" - RollbackConfig: - description: "Specification for the rollback strategy of the service." - type: "object" - properties: - Parallelism: - description: | - Maximum number of tasks to be rolled back in one iteration (0 means - unlimited parallelism). - type: "integer" - format: "int64" - Delay: - description: | - Amount of time between rollback iterations, in nanoseconds. - type: "integer" - format: "int64" - FailureAction: - description: | - Action to take if an rolled back task fails to run, or stops - running during the rollback. - type: "string" - enum: - - "continue" - - "pause" - Monitor: - description: | - Amount of time to monitor each rolled back task for failures, in - nanoseconds. - type: "integer" - format: "int64" - MaxFailureRatio: - description: | - The fraction of tasks that may fail during a rollback before the - failure action is invoked, specified as a floating point number - between 0 and 1. - type: "number" - default: 0 - Order: - description: | - The order of operations when rolling back a task. Either the old - task is shut down before the new task is started, or the new task - is started before the old task is shut down. - type: "string" - enum: - - "stop-first" - - "start-first" - Networks: - description: "Specifies which networks the service should attach to." - type: "array" - items: - $ref: "#/definitions/NetworkAttachmentConfig" - - EndpointSpec: - $ref: "#/definitions/EndpointSpec" - - EndpointPortConfig: - type: "object" - properties: - Name: - type: "string" - Protocol: - type: "string" - enum: - - "tcp" - - "udp" - - "sctp" - TargetPort: - description: "The port inside the container." - type: "integer" - PublishedPort: - description: "The port on the swarm hosts." - type: "integer" - PublishMode: - description: | - The mode in which port is published. - -


- - - "ingress" makes the target port accessible on every node, - regardless of whether there is a task for the service running on - that node or not. - - "host" bypasses the routing mesh and publish the port directly on - the swarm node where that service is running. - - type: "string" - enum: - - "ingress" - - "host" - default: "ingress" - example: "ingress" - - EndpointSpec: - description: "Properties that can be configured to access and load balance a service." - type: "object" - properties: - Mode: - description: | - The mode of resolution to use for internal load balancing between tasks. - type: "string" - enum: - - "vip" - - "dnsrr" - default: "vip" - Ports: - description: | - List of exposed ports that this service is accessible on from the - outside. Ports can only be provided if `vip` resolution mode is used. - type: "array" - items: - $ref: "#/definitions/EndpointPortConfig" - - Service: - type: "object" - properties: - ID: - type: "string" - Version: - $ref: "#/definitions/ObjectVersion" - CreatedAt: - type: "string" - format: "dateTime" - UpdatedAt: - type: "string" - format: "dateTime" - Spec: - $ref: "#/definitions/ServiceSpec" - Endpoint: - type: "object" - properties: - Spec: - $ref: "#/definitions/EndpointSpec" - Ports: - type: "array" - items: - $ref: "#/definitions/EndpointPortConfig" - VirtualIPs: - type: "array" - items: - type: "object" - properties: - NetworkID: - type: "string" - Addr: - type: "string" - UpdateStatus: - description: "The status of a service update." - type: "object" - properties: - State: - type: "string" - enum: - - "updating" - - "paused" - - "completed" - StartedAt: - type: "string" - format: "dateTime" - CompletedAt: - type: "string" - format: "dateTime" - Message: - type: "string" - ServiceStatus: - description: | - The status of the service's tasks. Provided only when requested as - part of a ServiceList operation. - type: "object" - properties: - RunningTasks: - description: | - The number of tasks for the service currently in the Running state. - type: "integer" - format: "uint64" - example: 7 - DesiredTasks: - description: | - The number of tasks for the service desired to be running. - For replicated services, this is the replica count from the - service spec. For global services, this is computed by taking - count of all tasks for the service with a Desired State other - than Shutdown. - type: "integer" - format: "uint64" - example: 10 - CompletedTasks: - description: | - The number of tasks for a job that are in the Completed state. - This field must be cross-referenced with the service type, as the - value of 0 may mean the service is not in a job mode, or it may - mean the job-mode service has no tasks yet Completed. - type: "integer" - format: "uint64" - JobStatus: - description: | - The status of the service when it is in one of ReplicatedJob or - GlobalJob modes. Absent on Replicated and Global mode services. The - JobIteration is an ObjectVersion, but unlike the Service's version, - does not need to be sent with an update request. - type: "object" - properties: - JobIteration: - description: | - JobIteration is a value increased each time a Job is executed, - successfully or otherwise. "Executed", in this case, means the - job as a whole has been started, not that an individual Task has - been launched. A job is "Executed" when its ServiceSpec is - updated. JobIteration can be used to disambiguate Tasks belonging - to different executions of a job. Though JobIteration will - increase with each subsequent execution, it may not necessarily - increase by 1, and so JobIteration should not be used to - $ref: "#/definitions/ObjectVersion" - LastExecution: - description: | - The last time, as observed by the server, that this job was - started. - type: "string" - format: "dateTime" - example: - ID: "9mnpnzenvg8p8tdbtq4wvbkcz" - Version: - Index: 19 - CreatedAt: "2016-06-07T21:05:51.880065305Z" - UpdatedAt: "2016-06-07T21:07:29.962229872Z" - Spec: - Name: "hopeful_cori" - TaskTemplate: - ContainerSpec: - Image: "redis" - Resources: - Limits: {} - Reservations: {} - RestartPolicy: - Condition: "any" - MaxAttempts: 0 - Placement: {} - ForceUpdate: 0 - Mode: - Replicated: - Replicas: 1 - UpdateConfig: - Parallelism: 1 - Delay: 1000000000 - FailureAction: "pause" - Monitor: 15000000000 - MaxFailureRatio: 0.15 - RollbackConfig: - Parallelism: 1 - Delay: 1000000000 - FailureAction: "pause" - Monitor: 15000000000 - MaxFailureRatio: 0.15 - EndpointSpec: - Mode: "vip" - Ports: - - - Protocol: "tcp" - TargetPort: 6379 - PublishedPort: 30001 - Endpoint: - Spec: - Mode: "vip" - Ports: - - - Protocol: "tcp" - TargetPort: 6379 - PublishedPort: 30001 - Ports: - - - Protocol: "tcp" - TargetPort: 6379 - PublishedPort: 30001 - VirtualIPs: - - - NetworkID: "4qvuz4ko70xaltuqbt8956gd1" - Addr: "10.255.0.2/16" - - - NetworkID: "4qvuz4ko70xaltuqbt8956gd1" - Addr: "10.255.0.3/16" - - ImageDeleteResponseItem: - type: "object" - properties: - Untagged: - description: "The image ID of an image that was untagged" - type: "string" - Deleted: - description: "The image ID of an image that was deleted" - type: "string" - - ServiceUpdateResponse: - type: "object" - properties: - Warnings: - description: "Optional warning messages" - type: "array" - items: - type: "string" - example: - Warning: "unable to pin image doesnotexist:latest to digest: image library/doesnotexist:latest not found" - - ContainerSummary: - type: "object" - properties: - Id: - description: "The ID of this container" - type: "string" - x-go-name: "ID" - Names: - description: "The names that this container has been given" - type: "array" - items: - type: "string" - Image: - description: "The name of the image used when creating this container" - type: "string" - ImageID: - description: "The ID of the image that this container was created from" - type: "string" - Command: - description: "Command to run when starting the container" - type: "string" - Created: - description: "When the container was created" - type: "integer" - format: "int64" - Ports: - description: "The ports exposed by this container" - type: "array" - items: - $ref: "#/definitions/Port" - SizeRw: - description: "The size of files that have been created or changed by this container" - type: "integer" - format: "int64" - SizeRootFs: - description: "The total size of all the files in this container" - type: "integer" - format: "int64" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - State: - description: "The state of this container (e.g. `Exited`)" - type: "string" - Status: - description: "Additional human-readable status of this container (e.g. `Exit 0`)" - type: "string" - HostConfig: - type: "object" - properties: - NetworkMode: - type: "string" - NetworkSettings: - description: "A summary of the container's network settings" - type: "object" - properties: - Networks: - type: "object" - additionalProperties: - $ref: "#/definitions/EndpointSettings" - Mounts: - type: "array" - items: - $ref: "#/definitions/MountPoint" - - Driver: - description: "Driver represents a driver (network, logging, secrets)." - type: "object" - required: [Name] - properties: - Name: - description: "Name of the driver." - type: "string" - x-nullable: false - example: "some-driver" - Options: - description: "Key/value map of driver-specific options." - type: "object" - x-nullable: false - additionalProperties: - type: "string" - example: - OptionA: "value for driver-specific option A" - OptionB: "value for driver-specific option B" - - SecretSpec: - type: "object" - properties: - Name: - description: "User-defined name of the secret." - type: "string" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - example: - com.example.some-label: "some-value" - com.example.some-other-label: "some-other-value" - Data: - description: | - Base64-url-safe-encoded ([RFC 4648](https://tools.ietf.org/html/rfc4648#section-5)) - data to store as secret. - - This field is only used to _create_ a secret, and is not returned by - other endpoints. - type: "string" - example: "" - Driver: - description: | - Name of the secrets driver used to fetch the secret's value from an - external secret store. - $ref: "#/definitions/Driver" - Templating: - description: | - Templating driver, if applicable - - Templating controls whether and how to evaluate the config payload as - a template. If no driver is set, no templating is used. - $ref: "#/definitions/Driver" - - Secret: - type: "object" - properties: - ID: - type: "string" - example: "blt1owaxmitz71s9v5zh81zun" - Version: - $ref: "#/definitions/ObjectVersion" - CreatedAt: - type: "string" - format: "dateTime" - example: "2017-07-20T13:55:28.678958722Z" - UpdatedAt: - type: "string" - format: "dateTime" - example: "2017-07-20T13:55:28.678958722Z" - Spec: - $ref: "#/definitions/SecretSpec" - - ConfigSpec: - type: "object" - properties: - Name: - description: "User-defined name of the config." - type: "string" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - Data: - description: | - Base64-url-safe-encoded ([RFC 4648](https://tools.ietf.org/html/rfc4648#section-5)) - config data. - type: "string" - Templating: - description: | - Templating driver, if applicable - - Templating controls whether and how to evaluate the config payload as - a template. If no driver is set, no templating is used. - $ref: "#/definitions/Driver" - - Config: - type: "object" - properties: - ID: - type: "string" - Version: - $ref: "#/definitions/ObjectVersion" - CreatedAt: - type: "string" - format: "dateTime" - UpdatedAt: - type: "string" - format: "dateTime" - Spec: - $ref: "#/definitions/ConfigSpec" - - ContainerState: - description: | - ContainerState stores container's running state. It's part of ContainerJSONBase - and will be returned by the "inspect" command. - type: "object" - x-nullable: true - properties: - Status: - description: | - String representation of the container state. Can be one of "created", - "running", "paused", "restarting", "removing", "exited", or "dead". - type: "string" - enum: ["created", "running", "paused", "restarting", "removing", "exited", "dead"] - example: "running" - Running: - description: | - Whether this container is running. - - Note that a running container can be _paused_. The `Running` and `Paused` - booleans are not mutually exclusive: - - When pausing a container (on Linux), the freezer cgroup is used to suspend - all processes in the container. Freezing the process requires the process to - be running. As a result, paused containers are both `Running` _and_ `Paused`. - - Use the `Status` field instead to determine if a container's state is "running". - type: "boolean" - example: true - Paused: - description: "Whether this container is paused." - type: "boolean" - example: false - Restarting: - description: "Whether this container is restarting." - type: "boolean" - example: false - OOMKilled: - description: | - Whether a process within this container has been killed because it ran - out of memory since the container was last started. - type: "boolean" - example: false - Dead: - type: "boolean" - example: false - Pid: - description: "The process ID of this container" - type: "integer" - example: 1234 - ExitCode: - description: "The last exit code of this container" - type: "integer" - example: 0 - Error: - type: "string" - StartedAt: - description: "The time when this container was last started." - type: "string" - example: "2020-01-06T09:06:59.461876391Z" - FinishedAt: - description: "The time when this container last exited." - type: "string" - example: "2020-01-06T09:07:59.461876391Z" - Health: - $ref: "#/definitions/Health" - - ContainerCreateResponse: - description: "OK response to ContainerCreate operation" - type: "object" - title: "ContainerCreateResponse" - x-go-name: "CreateResponse" - required: [Id, Warnings] - properties: - Id: - description: "The ID of the created container" - type: "string" - x-nullable: false - example: "ede54ee1afda366ab42f824e8a5ffd195155d853ceaec74a927f249ea270c743" - Warnings: - description: "Warnings encountered when creating the container" - type: "array" - x-nullable: false - items: - type: "string" - example: [] - - ContainerWaitResponse: - description: "OK response to ContainerWait operation" - type: "object" - x-go-name: "WaitResponse" - title: "ContainerWaitResponse" - required: [StatusCode] - properties: - StatusCode: - description: "Exit code of the container" - type: "integer" - format: "int64" - x-nullable: false - Error: - $ref: "#/definitions/ContainerWaitExitError" - - ContainerWaitExitError: - description: "container waiting error, if any" - type: "object" - x-go-name: "WaitExitError" - properties: - Message: - description: "Details of an error" - type: "string" - - SystemVersion: - type: "object" - description: | - Response of Engine API: GET "/version" - properties: - Platform: - type: "object" - required: [Name] - properties: - Name: - type: "string" - Components: - type: "array" - description: | - Information about system components - items: - type: "object" - x-go-name: ComponentVersion - required: [Name, Version] - properties: - Name: - description: | - Name of the component - type: "string" - example: "Engine" - Version: - description: | - Version of the component - type: "string" - x-nullable: false - example: "19.03.12" - Details: - description: | - Key/value pairs of strings with additional information about the - component. These values are intended for informational purposes - only, and their content is not defined, and not part of the API - specification. - - These messages can be printed by the client as information to the user. - type: "object" - x-nullable: true - Version: - description: "The version of the daemon" - type: "string" - example: "19.03.12" - ApiVersion: - description: | - The default (and highest) API version that is supported by the daemon - type: "string" - example: "1.40" - MinAPIVersion: - description: | - The minimum API version that is supported by the daemon - type: "string" - example: "1.12" - GitCommit: - description: | - The Git commit of the source code that was used to build the daemon - type: "string" - example: "48a66213fe" - GoVersion: - description: | - The version Go used to compile the daemon, and the version of the Go - runtime in use. - type: "string" - example: "go1.13.14" - Os: - description: | - The operating system that the daemon is running on ("linux" or "windows") - type: "string" - example: "linux" - Arch: - description: | - The architecture that the daemon is running on - type: "string" - example: "amd64" - KernelVersion: - description: | - The kernel version (`uname -r`) that the daemon is running on. - - This field is omitted when empty. - type: "string" - example: "4.19.76-linuxkit" - Experimental: - description: | - Indicates if the daemon is started with experimental features enabled. - - This field is omitted when empty / false. - type: "boolean" - example: true - BuildTime: - description: | - The date and time that the daemon was compiled. - type: "string" - example: "2020-06-22T15:49:27.000000000+00:00" - - SystemInfo: - type: "object" - properties: - ID: - description: | - Unique identifier of the daemon. - -


- - > **Note**: The format of the ID itself is not part of the API, and - > should not be considered stable. - type: "string" - example: "7TRN:IPZB:QYBB:VPBQ:UMPP:KARE:6ZNR:XE6T:7EWV:PKF4:ZOJD:TPYS" - Containers: - description: "Total number of containers on the host." - type: "integer" - example: 14 - ContainersRunning: - description: | - Number of containers with status `"running"`. - type: "integer" - example: 3 - ContainersPaused: - description: | - Number of containers with status `"paused"`. - type: "integer" - example: 1 - ContainersStopped: - description: | - Number of containers with status `"stopped"`. - type: "integer" - example: 10 - Images: - description: | - Total number of images on the host. - - Both _tagged_ and _untagged_ (dangling) images are counted. - type: "integer" - example: 508 - Driver: - description: "Name of the storage driver in use." - type: "string" - example: "overlay2" - DriverStatus: - description: | - Information specific to the storage driver, provided as - "label" / "value" pairs. - - This information is provided by the storage driver, and formatted - in a way consistent with the output of `docker info` on the command - line. - -


- - > **Note**: The information returned in this field, including the - > formatting of values and labels, should not be considered stable, - > and may change without notice. - type: "array" - items: - type: "array" - items: - type: "string" - example: - - ["Backing Filesystem", "extfs"] - - ["Supports d_type", "true"] - - ["Native Overlay Diff", "true"] - DockerRootDir: - description: | - Root directory of persistent Docker state. - - Defaults to `/var/lib/docker` on Linux, and `C:\ProgramData\docker` - on Windows. - type: "string" - example: "/var/lib/docker" - Plugins: - $ref: "#/definitions/PluginsInfo" - MemoryLimit: - description: "Indicates if the host has memory limit support enabled." - type: "boolean" - example: true - SwapLimit: - description: "Indicates if the host has memory swap limit support enabled." - type: "boolean" - example: true - KernelMemoryTCP: - description: | - Indicates if the host has kernel memory TCP limit support enabled. This - field is omitted if not supported. - - Kernel memory TCP limits are not supported when using cgroups v2, which - does not support the corresponding `memory.kmem.tcp.limit_in_bytes` cgroup. - type: "boolean" - example: true - CpuCfsPeriod: - description: | - Indicates if CPU CFS(Completely Fair Scheduler) period is supported by - the host. - type: "boolean" - example: true - CpuCfsQuota: - description: | - Indicates if CPU CFS(Completely Fair Scheduler) quota is supported by - the host. - type: "boolean" - example: true - CPUShares: - description: | - Indicates if CPU Shares limiting is supported by the host. - type: "boolean" - example: true - CPUSet: - description: | - Indicates if CPUsets (cpuset.cpus, cpuset.mems) are supported by the host. - - See [cpuset(7)](https://www.kernel.org/doc/Documentation/cgroup-v1/cpusets.txt) - type: "boolean" - example: true - PidsLimit: - description: "Indicates if the host kernel has PID limit support enabled." - type: "boolean" - example: true - OomKillDisable: - description: "Indicates if OOM killer disable is supported on the host." - type: "boolean" - IPv4Forwarding: - description: "Indicates IPv4 forwarding is enabled." - type: "boolean" - example: true - BridgeNfIptables: - description: "Indicates if `bridge-nf-call-iptables` is available on the host." - type: "boolean" - example: true - BridgeNfIp6tables: - description: "Indicates if `bridge-nf-call-ip6tables` is available on the host." - type: "boolean" - example: true - Debug: - description: | - Indicates if the daemon is running in debug-mode / with debug-level - logging enabled. - type: "boolean" - example: true - NFd: - description: | - The total number of file Descriptors in use by the daemon process. - - This information is only returned if debug-mode is enabled. - type: "integer" - example: 64 - NGoroutines: - description: | - The number of goroutines that currently exist. - - This information is only returned if debug-mode is enabled. - type: "integer" - example: 174 - SystemTime: - description: | - Current system-time in [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) - format with nano-seconds. - type: "string" - example: "2017-08-08T20:28:29.06202363Z" - LoggingDriver: - description: | - The logging driver to use as a default for new containers. - type: "string" - CgroupDriver: - description: | - The driver to use for managing cgroups. - type: "string" - enum: ["cgroupfs", "systemd", "none"] - default: "cgroupfs" - example: "cgroupfs" - CgroupVersion: - description: | - The version of the cgroup. - type: "string" - enum: ["1", "2"] - default: "1" - example: "1" - NEventsListener: - description: "Number of event listeners subscribed." - type: "integer" - example: 30 - KernelVersion: - description: | - Kernel version of the host. - - On Linux, this information obtained from `uname`. On Windows this - information is queried from the HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ - registry value, for example _"10.0 14393 (14393.1198.amd64fre.rs1_release_sec.170427-1353)"_. - type: "string" - example: "4.9.38-moby" - OperatingSystem: - description: | - Name of the host's operating system, for example: "Ubuntu 16.04.2 LTS" - or "Windows Server 2016 Datacenter" - type: "string" - example: "Alpine Linux v3.5" - OSVersion: - description: | - Version of the host's operating system - -


- - > **Note**: The information returned in this field, including its - > very existence, and the formatting of values, should not be considered - > stable, and may change without notice. - type: "string" - example: "16.04" - OSType: - description: | - Generic type of the operating system of the host, as returned by the - Go runtime (`GOOS`). - - Currently returned values are "linux" and "windows". A full list of - possible values can be found in the [Go documentation](https://go.dev/doc/install/source#environment). - type: "string" - example: "linux" - Architecture: - description: | - Hardware architecture of the host, as returned by the Go runtime - (`GOARCH`). - - A full list of possible values can be found in the [Go documentation](https://go.dev/doc/install/source#environment). - type: "string" - example: "x86_64" - NCPU: - description: | - The number of logical CPUs usable by the daemon. - - The number of available CPUs is checked by querying the operating - system when the daemon starts. Changes to operating system CPU - allocation after the daemon is started are not reflected. - type: "integer" - example: 4 - MemTotal: - description: | - Total amount of physical memory available on the host, in bytes. - type: "integer" - format: "int64" - example: 2095882240 - - IndexServerAddress: - description: | - Address / URL of the index server that is used for image search, - and as a default for user authentication for Docker Hub and Docker Cloud. - default: "https://index.docker.io/v1/" - type: "string" - example: "https://index.docker.io/v1/" - RegistryConfig: - $ref: "#/definitions/RegistryServiceConfig" - GenericResources: - $ref: "#/definitions/GenericResources" - HttpProxy: - description: | - HTTP-proxy configured for the daemon. This value is obtained from the - [`HTTP_PROXY`](https://www.gnu.org/software/wget/manual/html_node/Proxies.html) environment variable. - Credentials ([user info component](https://tools.ietf.org/html/rfc3986#section-3.2.1)) in the proxy URL - are masked in the API response. - - Containers do not automatically inherit this configuration. - type: "string" - example: "http://xxxxx:xxxxx@proxy.corp.example.com:8080" - HttpsProxy: - description: | - HTTPS-proxy configured for the daemon. This value is obtained from the - [`HTTPS_PROXY`](https://www.gnu.org/software/wget/manual/html_node/Proxies.html) environment variable. - Credentials ([user info component](https://tools.ietf.org/html/rfc3986#section-3.2.1)) in the proxy URL - are masked in the API response. - - Containers do not automatically inherit this configuration. - type: "string" - example: "https://xxxxx:xxxxx@proxy.corp.example.com:4443" - NoProxy: - description: | - Comma-separated list of domain extensions for which no proxy should be - used. This value is obtained from the [`NO_PROXY`](https://www.gnu.org/software/wget/manual/html_node/Proxies.html) - environment variable. - - Containers do not automatically inherit this configuration. - type: "string" - example: "*.local, 169.254/16" - Name: - description: "Hostname of the host." - type: "string" - example: "node5.corp.example.com" - Labels: - description: | - User-defined labels (key/value metadata) as set on the daemon. - -


- - > **Note**: When part of a Swarm, nodes can both have _daemon_ labels, - > set through the daemon configuration, and _node_ labels, set from a - > manager node in the Swarm. Node labels are not included in this - > field. Node labels can be retrieved using the `/nodes/(id)` endpoint - > on a manager node in the Swarm. - type: "array" - items: - type: "string" - example: ["storage=ssd", "production"] - ExperimentalBuild: - description: | - Indicates if experimental features are enabled on the daemon. - type: "boolean" - example: true - ServerVersion: - description: | - Version string of the daemon. - type: "string" - example: "24.0.2" - Runtimes: - description: | - List of [OCI compliant](https://github.com/opencontainers/runtime-spec) - runtimes configured on the daemon. Keys hold the "name" used to - reference the runtime. - - The Docker daemon relies on an OCI compliant runtime (invoked via the - `containerd` daemon) as its interface to the Linux kernel namespaces, - cgroups, and SELinux. - - The default runtime is `runc`, and automatically configured. Additional - runtimes can be configured by the user and will be listed here. - type: "object" - additionalProperties: - $ref: "#/definitions/Runtime" - default: - runc: - path: "runc" - example: - runc: - path: "runc" - runc-master: - path: "/go/bin/runc" - custom: - path: "/usr/local/bin/my-oci-runtime" - runtimeArgs: ["--debug", "--systemd-cgroup=false"] - DefaultRuntime: - description: | - Name of the default OCI runtime that is used when starting containers. - - The default can be overridden per-container at create time. - type: "string" - default: "runc" - example: "runc" - Swarm: - $ref: "#/definitions/SwarmInfo" - LiveRestoreEnabled: - description: | - Indicates if live restore is enabled. - - If enabled, containers are kept running when the daemon is shutdown - or upon daemon start if running containers are detected. - type: "boolean" - default: false - example: false - Isolation: - description: | - Represents the isolation technology to use as a default for containers. - The supported values are platform-specific. - - If no isolation value is specified on daemon start, on Windows client, - the default is `hyperv`, and on Windows server, the default is `process`. - - This option is currently not used on other platforms. - default: "default" - type: "string" - enum: - - "default" - - "hyperv" - - "process" - InitBinary: - description: | - Name and, optional, path of the `docker-init` binary. - - If the path is omitted, the daemon searches the host's `$PATH` for the - binary and uses the first result. - type: "string" - example: "docker-init" - ContainerdCommit: - $ref: "#/definitions/Commit" - RuncCommit: - $ref: "#/definitions/Commit" - InitCommit: - $ref: "#/definitions/Commit" - SecurityOptions: - description: | - List of security features that are enabled on the daemon, such as - apparmor, seccomp, SELinux, user-namespaces (userns), rootless and - no-new-privileges. - - Additional configuration options for each security feature may - be present, and are included as a comma-separated list of key/value - pairs. - type: "array" - items: - type: "string" - example: - - "name=apparmor" - - "name=seccomp,profile=default" - - "name=selinux" - - "name=userns" - - "name=rootless" - ProductLicense: - description: | - Reports a summary of the product license on the daemon. - - If a commercial license has been applied to the daemon, information - such as number of nodes, and expiration are included. - type: "string" - example: "Community Engine" - DefaultAddressPools: - description: | - List of custom default address pools for local networks, which can be - specified in the daemon.json file or dockerd option. - - Example: a Base "10.10.0.0/16" with Size 24 will define the set of 256 - 10.10.[0-255].0/24 address pools. - type: "array" - items: - type: "object" - properties: - Base: - description: "The network address in CIDR format" - type: "string" - example: "10.10.0.0/16" - Size: - description: "The network pool size" - type: "integer" - example: "24" - Warnings: - description: | - List of warnings / informational messages about missing features, or - issues related to the daemon configuration. - - These messages can be printed by the client as information to the user. - type: "array" - items: - type: "string" - example: - - "WARNING: No memory limit support" - - "WARNING: bridge-nf-call-iptables is disabled" - - "WARNING: bridge-nf-call-ip6tables is disabled" - - - # PluginsInfo is a temp struct holding Plugins name - # registered with docker daemon. It is used by Info struct - PluginsInfo: - description: | - Available plugins per type. - -


- - > **Note**: Only unmanaged (V1) plugins are included in this list. - > V1 plugins are "lazily" loaded, and are not returned in this list - > if there is no resource using the plugin. - type: "object" - properties: - Volume: - description: "Names of available volume-drivers, and network-driver plugins." - type: "array" - items: - type: "string" - example: ["local"] - Network: - description: "Names of available network-drivers, and network-driver plugins." - type: "array" - items: - type: "string" - example: ["bridge", "host", "ipvlan", "macvlan", "null", "overlay"] - Authorization: - description: "Names of available authorization plugins." - type: "array" - items: - type: "string" - example: ["img-authz-plugin", "hbm"] - Log: - description: "Names of available logging-drivers, and logging-driver plugins." - type: "array" - items: - type: "string" - example: ["awslogs", "fluentd", "gcplogs", "gelf", "journald", "json-file", "splunk", "syslog"] - - - RegistryServiceConfig: - description: | - RegistryServiceConfig stores daemon registry services configuration. - type: "object" - x-nullable: true - properties: - AllowNondistributableArtifactsCIDRs: - description: | - List of IP ranges to which nondistributable artifacts can be pushed, - using the CIDR syntax [RFC 4632](https://tools.ietf.org/html/4632). - - Some images (for example, Windows base images) contain artifacts - whose distribution is restricted by license. When these images are - pushed to a registry, restricted artifacts are not included. - - This configuration override this behavior, and enables the daemon to - push nondistributable artifacts to all registries whose resolved IP - address is within the subnet described by the CIDR syntax. - - This option is useful when pushing images containing - nondistributable artifacts to a registry on an air-gapped network so - hosts on that network can pull the images without connecting to - another server. - - > **Warning**: Nondistributable artifacts typically have restrictions - > on how and where they can be distributed and shared. Only use this - > feature to push artifacts to private registries and ensure that you - > are in compliance with any terms that cover redistributing - > nondistributable artifacts. - - type: "array" - items: - type: "string" - example: ["::1/128", "127.0.0.0/8"] - AllowNondistributableArtifactsHostnames: - description: | - List of registry hostnames to which nondistributable artifacts can be - pushed, using the format `[:]` or `[:]`. - - Some images (for example, Windows base images) contain artifacts - whose distribution is restricted by license. When these images are - pushed to a registry, restricted artifacts are not included. - - This configuration override this behavior for the specified - registries. - - This option is useful when pushing images containing - nondistributable artifacts to a registry on an air-gapped network so - hosts on that network can pull the images without connecting to - another server. - - > **Warning**: Nondistributable artifacts typically have restrictions - > on how and where they can be distributed and shared. Only use this - > feature to push artifacts to private registries and ensure that you - > are in compliance with any terms that cover redistributing - > nondistributable artifacts. - type: "array" - items: - type: "string" - example: ["registry.internal.corp.example.com:3000", "[2001:db8:a0b:12f0::1]:443"] - InsecureRegistryCIDRs: - description: | - List of IP ranges of insecure registries, using the CIDR syntax - ([RFC 4632](https://tools.ietf.org/html/4632)). Insecure registries - accept un-encrypted (HTTP) and/or untrusted (HTTPS with certificates - from unknown CAs) communication. - - By default, local registries (`127.0.0.0/8`) are configured as - insecure. All other registries are secure. Communicating with an - insecure registry is not possible if the daemon assumes that registry - is secure. - - This configuration override this behavior, insecure communication with - registries whose resolved IP address is within the subnet described by - the CIDR syntax. - - Registries can also be marked insecure by hostname. Those registries - are listed under `IndexConfigs` and have their `Secure` field set to - `false`. - - > **Warning**: Using this option can be useful when running a local - > registry, but introduces security vulnerabilities. This option - > should therefore ONLY be used for testing purposes. For increased - > security, users should add their CA to their system's list of trusted - > CAs instead of enabling this option. - type: "array" - items: - type: "string" - example: ["::1/128", "127.0.0.0/8"] - IndexConfigs: - type: "object" - additionalProperties: - $ref: "#/definitions/IndexInfo" - example: - "127.0.0.1:5000": - "Name": "127.0.0.1:5000" - "Mirrors": [] - "Secure": false - "Official": false - "[2001:db8:a0b:12f0::1]:80": - "Name": "[2001:db8:a0b:12f0::1]:80" - "Mirrors": [] - "Secure": false - "Official": false - "docker.io": - Name: "docker.io" - Mirrors: ["https://hub-mirror.corp.example.com:5000/"] - Secure: true - Official: true - "registry.internal.corp.example.com:3000": - Name: "registry.internal.corp.example.com:3000" - Mirrors: [] - Secure: false - Official: false - Mirrors: - description: | - List of registry URLs that act as a mirror for the official - (`docker.io`) registry. - - type: "array" - items: - type: "string" - example: - - "https://hub-mirror.corp.example.com:5000/" - - "https://[2001:db8:a0b:12f0::1]/" - - IndexInfo: - description: - IndexInfo contains information about a registry. - type: "object" - x-nullable: true - properties: - Name: - description: | - Name of the registry, such as "docker.io". - type: "string" - example: "docker.io" - Mirrors: - description: | - List of mirrors, expressed as URIs. - type: "array" - items: - type: "string" - example: - - "https://hub-mirror.corp.example.com:5000/" - - "https://registry-2.docker.io/" - - "https://registry-3.docker.io/" - Secure: - description: | - Indicates if the registry is part of the list of insecure - registries. - - If `false`, the registry is insecure. Insecure registries accept - un-encrypted (HTTP) and/or untrusted (HTTPS with certificates from - unknown CAs) communication. - - > **Warning**: Insecure registries can be useful when running a local - > registry. However, because its use creates security vulnerabilities - > it should ONLY be enabled for testing purposes. For increased - > security, users should add their CA to their system's list of - > trusted CAs instead of enabling this option. - type: "boolean" - example: true - Official: - description: | - Indicates whether this is an official registry (i.e., Docker Hub / docker.io) - type: "boolean" - example: true - - Runtime: - description: | - Runtime describes an [OCI compliant](https://github.com/opencontainers/runtime-spec) - runtime. - - The runtime is invoked by the daemon via the `containerd` daemon. OCI - runtimes act as an interface to the Linux kernel namespaces, cgroups, - and SELinux. - type: "object" - properties: - path: - description: | - Name and, optional, path, of the OCI executable binary. - - If the path is omitted, the daemon searches the host's `$PATH` for the - binary and uses the first result. - type: "string" - example: "/usr/local/bin/my-oci-runtime" - runtimeArgs: - description: | - List of command-line arguments to pass to the runtime when invoked. - type: "array" - x-nullable: true - items: - type: "string" - example: ["--debug", "--systemd-cgroup=false"] - - Commit: - description: | - Commit holds the Git-commit (SHA1) that a binary was built from, as - reported in the version-string of external tools, such as `containerd`, - or `runC`. - type: "object" - properties: - ID: - description: "Actual commit ID of external tool." - type: "string" - example: "cfb82a876ecc11b5ca0977d1733adbe58599088a" - Expected: - description: | - Commit ID of external tool expected by dockerd as set at build time. - type: "string" - example: "2d41c047c83e09a6d61d464906feb2a2f3c52aa4" - - SwarmInfo: - description: | - Represents generic information about swarm. - type: "object" - properties: - NodeID: - description: "Unique identifier of for this node in the swarm." - type: "string" - default: "" - example: "k67qz4598weg5unwwffg6z1m1" - NodeAddr: - description: | - IP address at which this node can be reached by other nodes in the - swarm. - type: "string" - default: "" - example: "10.0.0.46" - LocalNodeState: - $ref: "#/definitions/LocalNodeState" - ControlAvailable: - type: "boolean" - default: false - example: true - Error: - type: "string" - default: "" - RemoteManagers: - description: | - List of ID's and addresses of other managers in the swarm. - type: "array" - default: null - x-nullable: true - items: - $ref: "#/definitions/PeerNode" - example: - - NodeID: "71izy0goik036k48jg985xnds" - Addr: "10.0.0.158:2377" - - NodeID: "79y6h1o4gv8n120drcprv5nmc" - Addr: "10.0.0.159:2377" - - NodeID: "k67qz4598weg5unwwffg6z1m1" - Addr: "10.0.0.46:2377" - Nodes: - description: "Total number of nodes in the swarm." - type: "integer" - x-nullable: true - example: 4 - Managers: - description: "Total number of managers in the swarm." - type: "integer" - x-nullable: true - example: 3 - Cluster: - $ref: "#/definitions/ClusterInfo" - - LocalNodeState: - description: "Current local status of this node." - type: "string" - default: "" - enum: - - "" - - "inactive" - - "pending" - - "active" - - "error" - - "locked" - example: "active" - - PeerNode: - description: "Represents a peer-node in the swarm" - type: "object" - properties: - NodeID: - description: "Unique identifier of for this node in the swarm." - type: "string" - Addr: - description: | - IP address and ports at which this node can be reached. - type: "string" - - NetworkAttachmentConfig: - description: | - Specifies how a service should be attached to a particular network. - type: "object" - properties: - Target: - description: | - The target network for attachment. Must be a network name or ID. - type: "string" - Aliases: - description: | - Discoverable alternate names for the service on this network. - type: "array" - items: - type: "string" - DriverOpts: - description: | - Driver attachment options for the network target. - type: "object" - additionalProperties: - type: "string" - - EventActor: - description: | - Actor describes something that generates events, like a container, network, - or a volume. - type: "object" - properties: - ID: - description: "The ID of the object emitting the event" - type: "string" - example: "ede54ee1afda366ab42f824e8a5ffd195155d853ceaec74a927f249ea270c743" - Attributes: - description: | - Various key/value attributes of the object, depending on its type. - type: "object" - additionalProperties: - type: "string" - example: - com.example.some-label: "some-label-value" - image: "alpine:latest" - name: "my-container" - - EventMessage: - description: | - EventMessage represents the information an event contains. - type: "object" - title: "SystemEventsResponse" - properties: - Type: - description: "The type of object emitting the event" - type: "string" - enum: ["builder", "config", "container", "daemon", "image", "network", "node", "plugin", "secret", "service", "volume"] - example: "container" - Action: - description: "The type of event" - type: "string" - example: "create" - Actor: - $ref: "#/definitions/EventActor" - scope: - description: | - Scope of the event. Engine events are `local` scope. Cluster (Swarm) - events are `swarm` scope. - type: "string" - enum: ["local", "swarm"] - time: - description: "Timestamp of event" - type: "integer" - format: "int64" - example: 1629574695 - timeNano: - description: "Timestamp of event, with nanosecond accuracy" - type: "integer" - format: "int64" - example: 1629574695515050031 - - OCIDescriptor: - type: "object" - x-go-name: Descriptor - description: | - A descriptor struct containing digest, media type, and size, as defined in - the [OCI Content Descriptors Specification](https://github.com/opencontainers/image-spec/blob/v1.0.1/descriptor.md). - properties: - mediaType: - description: | - The media type of the object this schema refers to. - type: "string" - example: "application/vnd.docker.distribution.manifest.v2+json" - digest: - description: | - The digest of the targeted content. - type: "string" - example: "sha256:c0537ff6a5218ef531ece93d4984efc99bbf3f7497c0a7726c88e2bb7584dc96" - size: - description: | - The size in bytes of the blob. - type: "integer" - format: "int64" - example: 3987495 - # TODO Not yet including these fields for now, as they are nil / omitted in our response. - # urls: - # description: | - # List of URLs from which this object MAY be downloaded. - # type: "array" - # items: - # type: "string" - # format: "uri" - # annotations: - # description: | - # Arbitrary metadata relating to the targeted content. - # type: "object" - # additionalProperties: - # type: "string" - # platform: - # $ref: "#/definitions/OCIPlatform" - - OCIPlatform: - type: "object" - x-go-name: Platform - description: | - Describes the platform which the image in the manifest runs on, as defined - in the [OCI Image Index Specification](https://github.com/opencontainers/image-spec/blob/v1.0.1/image-index.md). - properties: - architecture: - description: | - The CPU architecture, for example `amd64` or `ppc64`. - type: "string" - example: "arm" - os: - description: | - The operating system, for example `linux` or `windows`. - type: "string" - example: "windows" - os.version: - description: | - Optional field specifying the operating system version, for example on - Windows `10.0.19041.1165`. - type: "string" - example: "10.0.19041.1165" - os.features: - description: | - Optional field specifying an array of strings, each listing a required - OS feature (for example on Windows `win32k`). - type: "array" - items: - type: "string" - example: - - "win32k" - variant: - description: | - Optional field specifying a variant of the CPU, for example `v7` to - specify ARMv7 when architecture is `arm`. - type: "string" - example: "v7" - - DistributionInspect: - type: "object" - x-go-name: DistributionInspect - title: "DistributionInspectResponse" - required: [Descriptor, Platforms] - description: | - Describes the result obtained from contacting the registry to retrieve - image metadata. - properties: - Descriptor: - $ref: "#/definitions/OCIDescriptor" - Platforms: - type: "array" - description: | - An array containing all platforms supported by the image. - items: - $ref: "#/definitions/OCIPlatform" - - ClusterVolume: - type: "object" - description: | - Options and information specific to, and only present on, Swarm CSI - cluster volumes. - properties: - ID: - type: "string" - description: | - The Swarm ID of this volume. Because cluster volumes are Swarm - objects, they have an ID, unlike non-cluster volumes. This ID can - be used to refer to the Volume instead of the name. - Version: - $ref: "#/definitions/ObjectVersion" - CreatedAt: - type: "string" - format: "dateTime" - UpdatedAt: - type: "string" - format: "dateTime" - Spec: - $ref: "#/definitions/ClusterVolumeSpec" - Info: - type: "object" - description: | - Information about the global status of the volume. - properties: - CapacityBytes: - type: "integer" - format: "int64" - description: | - The capacity of the volume in bytes. A value of 0 indicates that - the capacity is unknown. - VolumeContext: - type: "object" - description: | - A map of strings to strings returned from the storage plugin when - the volume is created. - additionalProperties: - type: "string" - VolumeID: - type: "string" - description: | - The ID of the volume as returned by the CSI storage plugin. This - is distinct from the volume's ID as provided by Docker. This ID - is never used by the user when communicating with Docker to refer - to this volume. If the ID is blank, then the Volume has not been - successfully created in the plugin yet. - AccessibleTopology: - type: "array" - description: | - The topology this volume is actually accessible from. - items: - $ref: "#/definitions/Topology" - PublishStatus: - type: "array" - description: | - The status of the volume as it pertains to its publishing and use on - specific nodes - items: - type: "object" - properties: - NodeID: - type: "string" - description: | - The ID of the Swarm node the volume is published on. - State: - type: "string" - description: | - The published state of the volume. - * `pending-publish` The volume should be published to this node, but the call to the controller plugin to do so has not yet been successfully completed. - * `published` The volume is published successfully to the node. - * `pending-node-unpublish` The volume should be unpublished from the node, and the manager is awaiting confirmation from the worker that it has done so. - * `pending-controller-unpublish` The volume is successfully unpublished from the node, but has not yet been successfully unpublished on the controller. - enum: - - "pending-publish" - - "published" - - "pending-node-unpublish" - - "pending-controller-unpublish" - PublishContext: - type: "object" - description: | - A map of strings to strings returned by the CSI controller - plugin when a volume is published. - additionalProperties: - type: "string" - - ClusterVolumeSpec: - type: "object" - description: | - Cluster-specific options used to create the volume. - properties: - Group: - type: "string" - description: | - Group defines the volume group of this volume. Volumes belonging to - the same group can be referred to by group name when creating - Services. Referring to a volume by group instructs Swarm to treat - volumes in that group interchangeably for the purpose of scheduling. - Volumes with an empty string for a group technically all belong to - the same, emptystring group. - AccessMode: - type: "object" - description: | - Defines how the volume is used by tasks. - properties: - Scope: - type: "string" - description: | - The set of nodes this volume can be used on at one time. - - `single` The volume may only be scheduled to one node at a time. - - `multi` the volume may be scheduled to any supported number of nodes at a time. - default: "single" - enum: ["single", "multi"] - x-nullable: false - Sharing: - type: "string" - description: | - The number and way that different tasks can use this volume - at one time. - - `none` The volume may only be used by one task at a time. - - `readonly` The volume may be used by any number of tasks, but they all must mount the volume as readonly - - `onewriter` The volume may be used by any number of tasks, but only one may mount it as read/write. - - `all` The volume may have any number of readers and writers. - default: "none" - enum: ["none", "readonly", "onewriter", "all"] - x-nullable: false - MountVolume: - type: "object" - description: | - Options for using this volume as a Mount-type volume. - - Either MountVolume or BlockVolume, but not both, must be - present. - properties: - FsType: - type: "string" - description: | - Specifies the filesystem type for the mount volume. - Optional. - MountFlags: - type: "array" - description: | - Flags to pass when mounting the volume. Optional. - items: - type: "string" - BlockVolume: - type: "object" - description: | - Options for using this volume as a Block-type volume. - Intentionally empty. - Secrets: - type: "array" - description: | - Swarm Secrets that are passed to the CSI storage plugin when - operating on this volume. - items: - type: "object" - description: | - One cluster volume secret entry. Defines a key-value pair that - is passed to the plugin. - properties: - Key: - type: "string" - description: | - Key is the name of the key of the key-value pair passed to - the plugin. - Secret: - type: "string" - description: | - Secret is the swarm Secret object from which to read data. - This can be a Secret name or ID. The Secret data is - retrieved by swarm and used as the value of the key-value - pair passed to the plugin. - AccessibilityRequirements: - type: "object" - description: | - Requirements for the accessible topology of the volume. These - fields are optional. For an in-depth description of what these - fields mean, see the CSI specification. - properties: - Requisite: - type: "array" - description: | - A list of required topologies, at least one of which the - volume must be accessible from. - items: - $ref: "#/definitions/Topology" - Preferred: - type: "array" - description: | - A list of topologies that the volume should attempt to be - provisioned in. - items: - $ref: "#/definitions/Topology" - CapacityRange: - type: "object" - description: | - The desired capacity that the volume should be created with. If - empty, the plugin will decide the capacity. - properties: - RequiredBytes: - type: "integer" - format: "int64" - description: | - The volume must be at least this big. The value of 0 - indicates an unspecified minimum - LimitBytes: - type: "integer" - format: "int64" - description: | - The volume must not be bigger than this. The value of 0 - indicates an unspecified maximum. - Availability: - type: "string" - description: | - The availability of the volume for use in tasks. - - `active` The volume is fully available for scheduling on the cluster - - `pause` No new workloads should use the volume, but existing workloads are not stopped. - - `drain` All workloads using this volume should be stopped and rescheduled, and no new ones should be started. - default: "active" - x-nullable: false - enum: - - "active" - - "pause" - - "drain" - - Topology: - description: | - A map of topological domains to topological segments. For in depth - details, see documentation for the Topology object in the CSI - specification. - type: "object" - additionalProperties: - type: "string" - -paths: - /containers/json: - get: - summary: "List containers" - description: | - Returns a list of containers. For details on the format, see the - [inspect endpoint](#operation/ContainerInspect). - - Note that it uses a different, smaller representation of a container - than inspecting a single container. For example, the list of linked - containers is not propagated . - operationId: "ContainerList" - produces: - - "application/json" - parameters: - - name: "all" - in: "query" - description: | - Return all containers. By default, only running containers are shown. - type: "boolean" - default: false - - name: "limit" - in: "query" - description: | - Return this number of most recently created containers, including - non-running ones. - type: "integer" - - name: "size" - in: "query" - description: | - Return the size of container as fields `SizeRw` and `SizeRootFs`. - type: "boolean" - default: false - - name: "filters" - in: "query" - description: | - Filters to process on the container list, encoded as JSON (a - `map[string][]string`). For example, `{"status": ["paused"]}` will - only return paused containers. - - Available filters: - - - `ancestor`=(`[:]`, ``, or ``) - - `before`=(`` or ``) - - `expose`=(`[/]`|`/[]`) - - `exited=` containers with exit code of `` - - `health`=(`starting`|`healthy`|`unhealthy`|`none`) - - `id=` a container's ID - - `isolation=`(`default`|`process`|`hyperv`) (Windows daemon only) - - `is-task=`(`true`|`false`) - - `label=key` or `label="key=value"` of a container label - - `name=` a container's name - - `network`=(`` or ``) - - `publish`=(`[/]`|`/[]`) - - `since`=(`` or ``) - - `status=`(`created`|`restarting`|`running`|`removing`|`paused`|`exited`|`dead`) - - `volume`=(`` or ``) - type: "string" - responses: - 200: - description: "no error" - schema: - type: "array" - items: - $ref: "#/definitions/ContainerSummary" - examples: - application/json: - - Id: "8dfafdbc3a40" - Names: - - "/boring_feynman" - Image: "ubuntu:latest" - ImageID: "d74508fb6632491cea586a1fd7d748dfc5274cd6fdfedee309ecdcbc2bf5cb82" - Command: "echo 1" - Created: 1367854155 - State: "Exited" - Status: "Exit 0" - Ports: - - PrivatePort: 2222 - PublicPort: 3333 - Type: "tcp" - Labels: - com.example.vendor: "Acme" - com.example.license: "GPL" - com.example.version: "1.0" - SizeRw: 12288 - SizeRootFs: 0 - HostConfig: - NetworkMode: "default" - NetworkSettings: - Networks: - bridge: - NetworkID: "7ea29fc1412292a2d7bba362f9253545fecdfa8ce9a6e37dd10ba8bee7129812" - EndpointID: "2cdc4edb1ded3631c81f57966563e5c8525b81121bb3706a9a9a3ae102711f3f" - Gateway: "172.17.0.1" - IPAddress: "172.17.0.2" - IPPrefixLen: 16 - IPv6Gateway: "" - GlobalIPv6Address: "" - GlobalIPv6PrefixLen: 0 - MacAddress: "02:42:ac:11:00:02" - Mounts: - - Name: "fac362...80535" - Source: "/data" - Destination: "/data" - Driver: "local" - Mode: "ro,Z" - RW: false - Propagation: "" - - Id: "9cd87474be90" - Names: - - "/coolName" - Image: "ubuntu:latest" - ImageID: "d74508fb6632491cea586a1fd7d748dfc5274cd6fdfedee309ecdcbc2bf5cb82" - Command: "echo 222222" - Created: 1367854155 - State: "Exited" - Status: "Exit 0" - Ports: [] - Labels: {} - SizeRw: 12288 - SizeRootFs: 0 - HostConfig: - NetworkMode: "default" - NetworkSettings: - Networks: - bridge: - NetworkID: "7ea29fc1412292a2d7bba362f9253545fecdfa8ce9a6e37dd10ba8bee7129812" - EndpointID: "88eaed7b37b38c2a3f0c4bc796494fdf51b270c2d22656412a2ca5d559a64d7a" - Gateway: "172.17.0.1" - IPAddress: "172.17.0.8" - IPPrefixLen: 16 - IPv6Gateway: "" - GlobalIPv6Address: "" - GlobalIPv6PrefixLen: 0 - MacAddress: "02:42:ac:11:00:08" - Mounts: [] - - Id: "3176a2479c92" - Names: - - "/sleepy_dog" - Image: "ubuntu:latest" - ImageID: "d74508fb6632491cea586a1fd7d748dfc5274cd6fdfedee309ecdcbc2bf5cb82" - Command: "echo 3333333333333333" - Created: 1367854154 - State: "Exited" - Status: "Exit 0" - Ports: [] - Labels: {} - SizeRw: 12288 - SizeRootFs: 0 - HostConfig: - NetworkMode: "default" - NetworkSettings: - Networks: - bridge: - NetworkID: "7ea29fc1412292a2d7bba362f9253545fecdfa8ce9a6e37dd10ba8bee7129812" - EndpointID: "8b27c041c30326d59cd6e6f510d4f8d1d570a228466f956edf7815508f78e30d" - Gateway: "172.17.0.1" - IPAddress: "172.17.0.6" - IPPrefixLen: 16 - IPv6Gateway: "" - GlobalIPv6Address: "" - GlobalIPv6PrefixLen: 0 - MacAddress: "02:42:ac:11:00:06" - Mounts: [] - - Id: "4cb07b47f9fb" - Names: - - "/running_cat" - Image: "ubuntu:latest" - ImageID: "d74508fb6632491cea586a1fd7d748dfc5274cd6fdfedee309ecdcbc2bf5cb82" - Command: "echo 444444444444444444444444444444444" - Created: 1367854152 - State: "Exited" - Status: "Exit 0" - Ports: [] - Labels: {} - SizeRw: 12288 - SizeRootFs: 0 - HostConfig: - NetworkMode: "default" - NetworkSettings: - Networks: - bridge: - NetworkID: "7ea29fc1412292a2d7bba362f9253545fecdfa8ce9a6e37dd10ba8bee7129812" - EndpointID: "d91c7b2f0644403d7ef3095985ea0e2370325cd2332ff3a3225c4247328e66e9" - Gateway: "172.17.0.1" - IPAddress: "172.17.0.5" - IPPrefixLen: 16 - IPv6Gateway: "" - GlobalIPv6Address: "" - GlobalIPv6PrefixLen: 0 - MacAddress: "02:42:ac:11:00:05" - Mounts: [] - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Container"] - /containers/create: - post: - summary: "Create a container" - operationId: "ContainerCreate" - consumes: - - "application/json" - - "application/octet-stream" - produces: - - "application/json" - parameters: - - name: "name" - in: "query" - description: | - Assign the specified name to the container. Must match - `/?[a-zA-Z0-9][a-zA-Z0-9_.-]+`. - type: "string" - pattern: "^/?[a-zA-Z0-9][a-zA-Z0-9_.-]+$" - - name: "platform" - in: "query" - description: | - Platform in the format `os[/arch[/variant]]` used for image lookup. - - When specified, the daemon checks if the requested image is present - in the local image cache with the given OS and Architecture, and - otherwise returns a `404` status. - - If the option is not set, the host's native OS and Architecture are - used to look up the image in the image cache. However, if no platform - is passed and the given image does exist in the local image cache, - but its OS or architecture does not match, the container is created - with the available image, and a warning is added to the `Warnings` - field in the response, for example; - - WARNING: The requested image's platform (linux/arm64/v8) does not - match the detected host platform (linux/amd64) and no - specific platform was requested - - type: "string" - default: "" - - name: "body" - in: "body" - description: "Container to create" - schema: - allOf: - - $ref: "#/definitions/ContainerConfig" - - type: "object" - properties: - HostConfig: - $ref: "#/definitions/HostConfig" - NetworkingConfig: - $ref: "#/definitions/NetworkingConfig" - example: - Hostname: "" - Domainname: "" - User: "" - AttachStdin: false - AttachStdout: true - AttachStderr: true - Tty: false - OpenStdin: false - StdinOnce: false - Env: - - "FOO=bar" - - "BAZ=quux" - Cmd: - - "date" - Entrypoint: "" - Image: "ubuntu" - Labels: - com.example.vendor: "Acme" - com.example.license: "GPL" - com.example.version: "1.0" - Volumes: - /volumes/data: {} - WorkingDir: "" - NetworkDisabled: false - MacAddress: "12:34:56:78:9a:bc" - ExposedPorts: - 22/tcp: {} - StopSignal: "SIGTERM" - StopTimeout: 10 - HostConfig: - Binds: - - "/tmp:/tmp" - Links: - - "redis3:redis" - Memory: 0 - MemorySwap: 0 - MemoryReservation: 0 - NanoCpus: 500000 - CpuPercent: 80 - CpuShares: 512 - CpuPeriod: 100000 - CpuRealtimePeriod: 1000000 - CpuRealtimeRuntime: 10000 - CpuQuota: 50000 - CpusetCpus: "0,1" - CpusetMems: "0,1" - MaximumIOps: 0 - MaximumIOBps: 0 - BlkioWeight: 300 - BlkioWeightDevice: - - {} - BlkioDeviceReadBps: - - {} - BlkioDeviceReadIOps: - - {} - BlkioDeviceWriteBps: - - {} - BlkioDeviceWriteIOps: - - {} - DeviceRequests: - - Driver: "nvidia" - Count: -1 - DeviceIDs": ["0", "1", "GPU-fef8089b-4820-abfc-e83e-94318197576e"] - Capabilities: [["gpu", "nvidia", "compute"]] - Options: - property1: "string" - property2: "string" - MemorySwappiness: 60 - OomKillDisable: false - OomScoreAdj: 500 - PidMode: "" - PidsLimit: 0 - PortBindings: - 22/tcp: - - HostPort: "11022" - PublishAllPorts: false - Privileged: false - ReadonlyRootfs: false - Dns: - - "8.8.8.8" - DnsOptions: - - "" - DnsSearch: - - "" - VolumesFrom: - - "parent" - - "other:ro" - CapAdd: - - "NET_ADMIN" - CapDrop: - - "MKNOD" - GroupAdd: - - "newgroup" - RestartPolicy: - Name: "" - MaximumRetryCount: 0 - AutoRemove: true - NetworkMode: "bridge" - Devices: [] - Ulimits: - - {} - LogConfig: - Type: "json-file" - Config: {} - SecurityOpt: [] - StorageOpt: {} - CgroupParent: "" - VolumeDriver: "" - ShmSize: 67108864 - NetworkingConfig: - EndpointsConfig: - isolated_nw: - IPAMConfig: - IPv4Address: "172.20.30.33" - IPv6Address: "2001:db8:abcd::3033" - LinkLocalIPs: - - "169.254.34.68" - - "fe80::3468" - Links: - - "container_1" - - "container_2" - Aliases: - - "server_x" - - "server_y" - - required: true - responses: - 201: - description: "Container created successfully" - schema: - $ref: "#/definitions/ContainerCreateResponse" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such image" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such image: c2ada9df5af8" - 409: - description: "conflict" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Container"] - /containers/{id}/json: - get: - summary: "Inspect a container" - description: "Return low-level information about a container." - operationId: "ContainerInspect" - produces: - - "application/json" - responses: - 200: - description: "no error" - schema: - type: "object" - title: "ContainerInspectResponse" - properties: - Id: - description: "The ID of the container" - type: "string" - Created: - description: "The time the container was created" - type: "string" - Path: - description: "The path to the command being run" - type: "string" - Args: - description: "The arguments to the command being run" - type: "array" - items: - type: "string" - State: - $ref: "#/definitions/ContainerState" - Image: - description: "The container's image ID" - type: "string" - ResolvConfPath: - type: "string" - HostnamePath: - type: "string" - HostsPath: - type: "string" - LogPath: - type: "string" - Name: - type: "string" - RestartCount: - type: "integer" - Driver: - type: "string" - Platform: - type: "string" - MountLabel: - type: "string" - ProcessLabel: - type: "string" - AppArmorProfile: - type: "string" - ExecIDs: - description: "IDs of exec instances that are running in the container." - type: "array" - items: - type: "string" - x-nullable: true - HostConfig: - $ref: "#/definitions/HostConfig" - GraphDriver: - $ref: "#/definitions/GraphDriverData" - SizeRw: - description: | - The size of files that have been created or changed by this - container. - type: "integer" - format: "int64" - SizeRootFs: - description: "The total size of all the files in this container." - type: "integer" - format: "int64" - Mounts: - type: "array" - items: - $ref: "#/definitions/MountPoint" - Config: - $ref: "#/definitions/ContainerConfig" - NetworkSettings: - $ref: "#/definitions/NetworkSettings" - examples: - application/json: - AppArmorProfile: "" - Args: - - "-c" - - "exit 9" - Config: - AttachStderr: true - AttachStdin: false - AttachStdout: true - Cmd: - - "/bin/sh" - - "-c" - - "exit 9" - Domainname: "" - Env: - - "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" - Healthcheck: - Test: ["CMD-SHELL", "exit 0"] - Hostname: "ba033ac44011" - Image: "ubuntu" - Labels: - com.example.vendor: "Acme" - com.example.license: "GPL" - com.example.version: "1.0" - MacAddress: "" - NetworkDisabled: false - OpenStdin: false - StdinOnce: false - Tty: false - User: "" - Volumes: - /volumes/data: {} - WorkingDir: "" - StopSignal: "SIGTERM" - StopTimeout: 10 - Created: "2015-01-06T15:47:31.485331387Z" - Driver: "devicemapper" - ExecIDs: - - "b35395de42bc8abd327f9dd65d913b9ba28c74d2f0734eeeae84fa1c616a0fca" - - "3fc1232e5cd20c8de182ed81178503dc6437f4e7ef12b52cc5e8de020652f1c4" - HostConfig: - MaximumIOps: 0 - MaximumIOBps: 0 - BlkioWeight: 0 - BlkioWeightDevice: - - {} - BlkioDeviceReadBps: - - {} - BlkioDeviceWriteBps: - - {} - BlkioDeviceReadIOps: - - {} - BlkioDeviceWriteIOps: - - {} - ContainerIDFile: "" - CpusetCpus: "" - CpusetMems: "" - CpuPercent: 80 - CpuShares: 0 - CpuPeriod: 100000 - CpuRealtimePeriod: 1000000 - CpuRealtimeRuntime: 10000 - Devices: [] - DeviceRequests: - - Driver: "nvidia" - Count: -1 - DeviceIDs": ["0", "1", "GPU-fef8089b-4820-abfc-e83e-94318197576e"] - Capabilities: [["gpu", "nvidia", "compute"]] - Options: - property1: "string" - property2: "string" - IpcMode: "" - Memory: 0 - MemorySwap: 0 - MemoryReservation: 0 - OomKillDisable: false - OomScoreAdj: 500 - NetworkMode: "bridge" - PidMode: "" - PortBindings: {} - Privileged: false - ReadonlyRootfs: false - PublishAllPorts: false - RestartPolicy: - MaximumRetryCount: 2 - Name: "on-failure" - LogConfig: - Type: "json-file" - Sysctls: - net.ipv4.ip_forward: "1" - Ulimits: - - {} - VolumeDriver: "" - ShmSize: 67108864 - HostnamePath: "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/hostname" - HostsPath: "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/hosts" - LogPath: "/var/lib/docker/containers/1eb5fabf5a03807136561b3c00adcd2992b535d624d5e18b6cdc6a6844d9767b/1eb5fabf5a03807136561b3c00adcd2992b535d624d5e18b6cdc6a6844d9767b-json.log" - Id: "ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39" - Image: "04c5d3b7b0656168630d3ba35d8889bd0e9caafcaeb3004d2bfbc47e7c5d35d2" - MountLabel: "" - Name: "/boring_euclid" - NetworkSettings: - Bridge: "" - SandboxID: "" - HairpinMode: false - LinkLocalIPv6Address: "" - LinkLocalIPv6PrefixLen: 0 - SandboxKey: "" - EndpointID: "" - Gateway: "" - GlobalIPv6Address: "" - GlobalIPv6PrefixLen: 0 - IPAddress: "" - IPPrefixLen: 0 - IPv6Gateway: "" - MacAddress: "" - Networks: - bridge: - NetworkID: "7ea29fc1412292a2d7bba362f9253545fecdfa8ce9a6e37dd10ba8bee7129812" - EndpointID: "7587b82f0dada3656fda26588aee72630c6fab1536d36e394b2bfbcf898c971d" - Gateway: "172.17.0.1" - IPAddress: "172.17.0.2" - IPPrefixLen: 16 - IPv6Gateway: "" - GlobalIPv6Address: "" - GlobalIPv6PrefixLen: 0 - MacAddress: "02:42:ac:12:00:02" - Path: "/bin/sh" - ProcessLabel: "" - ResolvConfPath: "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/resolv.conf" - RestartCount: 1 - State: - Error: "" - ExitCode: 9 - FinishedAt: "2015-01-06T15:47:32.080254511Z" - Health: - Status: "healthy" - FailingStreak: 0 - Log: - - Start: "2019-12-22T10:59:05.6385933Z" - End: "2019-12-22T10:59:05.8078452Z" - ExitCode: 0 - Output: "" - OOMKilled: false - Dead: false - Paused: false - Pid: 0 - Restarting: false - Running: true - StartedAt: "2015-01-06T15:47:32.072697474Z" - Status: "running" - Mounts: - - Name: "fac362...80535" - Source: "/data" - Destination: "/data" - Driver: "local" - Mode: "ro,Z" - RW: false - Propagation: "" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "size" - in: "query" - type: "boolean" - default: false - description: "Return the size of container as fields `SizeRw` and `SizeRootFs`" - tags: ["Container"] - /containers/{id}/top: - get: - summary: "List processes running inside a container" - description: | - On Unix systems, this is done by running the `ps` command. This endpoint - is not supported on Windows. - operationId: "ContainerTop" - responses: - 200: - description: "no error" - schema: - type: "object" - title: "ContainerTopResponse" - description: "OK response to ContainerTop operation" - properties: - Titles: - description: "The ps column titles" - type: "array" - items: - type: "string" - Processes: - description: | - Each process running in the container, where each is process - is an array of values corresponding to the titles. - type: "array" - items: - type: "array" - items: - type: "string" - examples: - application/json: - Titles: - - "UID" - - "PID" - - "PPID" - - "C" - - "STIME" - - "TTY" - - "TIME" - - "CMD" - Processes: - - - - "root" - - "13642" - - "882" - - "0" - - "17:03" - - "pts/0" - - "00:00:00" - - "/bin/bash" - - - - "root" - - "13735" - - "13642" - - "0" - - "17:06" - - "pts/0" - - "00:00:00" - - "sleep 10" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "ps_args" - in: "query" - description: "The arguments to pass to `ps`. For example, `aux`" - type: "string" - default: "-ef" - tags: ["Container"] - /containers/{id}/logs: - get: - summary: "Get container logs" - description: | - Get `stdout` and `stderr` logs from a container. - - Note: This endpoint works only for containers with the `json-file` or - `journald` logging driver. - produces: - - "application/vnd.docker.raw-stream" - - "application/vnd.docker.multiplexed-stream" - operationId: "ContainerLogs" - responses: - 200: - description: | - logs returned as a stream in response body. - For the stream format, [see the documentation for the attach endpoint](#operation/ContainerAttach). - Note that unlike the attach endpoint, the logs endpoint does not - upgrade the connection and does not set Content-Type. - schema: - type: "string" - format: "binary" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "follow" - in: "query" - description: "Keep connection after returning logs." - type: "boolean" - default: false - - name: "stdout" - in: "query" - description: "Return logs from `stdout`" - type: "boolean" - default: false - - name: "stderr" - in: "query" - description: "Return logs from `stderr`" - type: "boolean" - default: false - - name: "since" - in: "query" - description: "Only return logs since this time, as a UNIX timestamp" - type: "integer" - default: 0 - - name: "until" - in: "query" - description: "Only return logs before this time, as a UNIX timestamp" - type: "integer" - default: 0 - - name: "timestamps" - in: "query" - description: "Add timestamps to every log line" - type: "boolean" - default: false - - name: "tail" - in: "query" - description: | - Only return this number of log lines from the end of the logs. - Specify as an integer or `all` to output all log lines. - type: "string" - default: "all" - tags: ["Container"] - /containers/{id}/changes: - get: - summary: "Get changes on a container’s filesystem" - description: | - Returns which files in a container's filesystem have been added, deleted, - or modified. The `Kind` of modification can be one of: - - - `0`: Modified ("C") - - `1`: Added ("A") - - `2`: Deleted ("D") - operationId: "ContainerChanges" - produces: ["application/json"] - responses: - 200: - description: "The list of changes" - schema: - type: "array" - items: - $ref: "#/definitions/FilesystemChange" - examples: - application/json: - - Path: "/dev" - Kind: 0 - - Path: "/dev/kmsg" - Kind: 1 - - Path: "/test" - Kind: 1 - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - tags: ["Container"] - /containers/{id}/export: - get: - summary: "Export a container" - description: "Export the contents of a container as a tarball." - operationId: "ContainerExport" - produces: - - "application/octet-stream" - responses: - 200: - description: "no error" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - tags: ["Container"] - /containers/{id}/stats: - get: - summary: "Get container stats based on resource usage" - description: | - This endpoint returns a live stream of a container’s resource usage - statistics. - - The `precpu_stats` is the CPU statistic of the *previous* read, and is - used to calculate the CPU usage percentage. It is not an exact copy - of the `cpu_stats` field. - - If either `precpu_stats.online_cpus` or `cpu_stats.online_cpus` is - nil then for compatibility with older daemons the length of the - corresponding `cpu_usage.percpu_usage` array should be used. - - On a cgroup v2 host, the following fields are not set - * `blkio_stats`: all fields other than `io_service_bytes_recursive` - * `cpu_stats`: `cpu_usage.percpu_usage` - * `memory_stats`: `max_usage` and `failcnt` - Also, `memory_stats.stats` fields are incompatible with cgroup v1. - - To calculate the values shown by the `stats` command of the docker cli tool - the following formulas can be used: - * used_memory = `memory_stats.usage - memory_stats.stats.cache` - * available_memory = `memory_stats.limit` - * Memory usage % = `(used_memory / available_memory) * 100.0` - * cpu_delta = `cpu_stats.cpu_usage.total_usage - precpu_stats.cpu_usage.total_usage` - * system_cpu_delta = `cpu_stats.system_cpu_usage - precpu_stats.system_cpu_usage` - * number_cpus = `lenght(cpu_stats.cpu_usage.percpu_usage)` or `cpu_stats.online_cpus` - * CPU usage % = `(cpu_delta / system_cpu_delta) * number_cpus * 100.0` - operationId: "ContainerStats" - produces: ["application/json"] - responses: - 200: - description: "no error" - schema: - type: "object" - examples: - application/json: - read: "2015-01-08T22:57:31.547920715Z" - pids_stats: - current: 3 - networks: - eth0: - rx_bytes: 5338 - rx_dropped: 0 - rx_errors: 0 - rx_packets: 36 - tx_bytes: 648 - tx_dropped: 0 - tx_errors: 0 - tx_packets: 8 - eth5: - rx_bytes: 4641 - rx_dropped: 0 - rx_errors: 0 - rx_packets: 26 - tx_bytes: 690 - tx_dropped: 0 - tx_errors: 0 - tx_packets: 9 - memory_stats: - stats: - total_pgmajfault: 0 - cache: 0 - mapped_file: 0 - total_inactive_file: 0 - pgpgout: 414 - rss: 6537216 - total_mapped_file: 0 - writeback: 0 - unevictable: 0 - pgpgin: 477 - total_unevictable: 0 - pgmajfault: 0 - total_rss: 6537216 - total_rss_huge: 6291456 - total_writeback: 0 - total_inactive_anon: 0 - rss_huge: 6291456 - hierarchical_memory_limit: 67108864 - total_pgfault: 964 - total_active_file: 0 - active_anon: 6537216 - total_active_anon: 6537216 - total_pgpgout: 414 - total_cache: 0 - inactive_anon: 0 - active_file: 0 - pgfault: 964 - inactive_file: 0 - total_pgpgin: 477 - max_usage: 6651904 - usage: 6537216 - failcnt: 0 - limit: 67108864 - blkio_stats: {} - cpu_stats: - cpu_usage: - percpu_usage: - - 8646879 - - 24472255 - - 36438778 - - 30657443 - usage_in_usermode: 50000000 - total_usage: 100215355 - usage_in_kernelmode: 30000000 - system_cpu_usage: 739306590000000 - online_cpus: 4 - throttling_data: - periods: 0 - throttled_periods: 0 - throttled_time: 0 - precpu_stats: - cpu_usage: - percpu_usage: - - 8646879 - - 24350896 - - 36438778 - - 30657443 - usage_in_usermode: 50000000 - total_usage: 100093996 - usage_in_kernelmode: 30000000 - system_cpu_usage: 9492140000000 - online_cpus: 4 - throttling_data: - periods: 0 - throttled_periods: 0 - throttled_time: 0 - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "stream" - in: "query" - description: | - Stream the output. If false, the stats will be output once and then - it will disconnect. - type: "boolean" - default: true - - name: "one-shot" - in: "query" - description: | - Only get a single stat instead of waiting for 2 cycles. Must be used - with `stream=false`. - type: "boolean" - default: false - tags: ["Container"] - /containers/{id}/resize: - post: - summary: "Resize a container TTY" - description: "Resize the TTY for a container." - operationId: "ContainerResize" - consumes: - - "application/octet-stream" - produces: - - "text/plain" - responses: - 200: - description: "no error" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "cannot resize container" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "h" - in: "query" - description: "Height of the TTY session in characters" - type: "integer" - - name: "w" - in: "query" - description: "Width of the TTY session in characters" - type: "integer" - tags: ["Container"] - /containers/{id}/start: - post: - summary: "Start a container" - operationId: "ContainerStart" - responses: - 204: - description: "no error" - 304: - description: "container already started" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "detachKeys" - in: "query" - description: | - Override the key sequence for detaching a container. Format is a - single character `[a-Z]` or `ctrl-` where `` is one - of: `a-z`, `@`, `^`, `[`, `,` or `_`. - type: "string" - tags: ["Container"] - /containers/{id}/stop: - post: - summary: "Stop a container" - operationId: "ContainerStop" - responses: - 204: - description: "no error" - 304: - description: "container already stopped" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "signal" - in: "query" - description: | - Signal to send to the container as an integer or string (e.g. `SIGINT`). - type: "string" - - name: "t" - in: "query" - description: "Number of seconds to wait before killing the container" - type: "integer" - tags: ["Container"] - /containers/{id}/restart: - post: - summary: "Restart a container" - operationId: "ContainerRestart" - responses: - 204: - description: "no error" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "signal" - in: "query" - description: | - Signal to send to the container as an integer or string (e.g. `SIGINT`). - type: "string" - - name: "t" - in: "query" - description: "Number of seconds to wait before killing the container" - type: "integer" - tags: ["Container"] - /containers/{id}/kill: - post: - summary: "Kill a container" - description: | - Send a POSIX signal to a container, defaulting to killing to the - container. - operationId: "ContainerKill" - responses: - 204: - description: "no error" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 409: - description: "container is not running" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "Container d37cde0fe4ad63c3a7252023b2f9800282894247d145cb5933ddf6e52cc03a28 is not running" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "signal" - in: "query" - description: | - Signal to send to the container as an integer or string (e.g. `SIGINT`). - type: "string" - default: "SIGKILL" - tags: ["Container"] - /containers/{id}/update: - post: - summary: "Update a container" - description: | - Change various configuration options of a container without having to - recreate it. - operationId: "ContainerUpdate" - consumes: ["application/json"] - produces: ["application/json"] - responses: - 200: - description: "The container has been updated." - schema: - type: "object" - title: "ContainerUpdateResponse" - description: "OK response to ContainerUpdate operation" - properties: - Warnings: - type: "array" - items: - type: "string" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "update" - in: "body" - required: true - schema: - allOf: - - $ref: "#/definitions/Resources" - - type: "object" - properties: - RestartPolicy: - $ref: "#/definitions/RestartPolicy" - example: - BlkioWeight: 300 - CpuShares: 512 - CpuPeriod: 100000 - CpuQuota: 50000 - CpuRealtimePeriod: 1000000 - CpuRealtimeRuntime: 10000 - CpusetCpus: "0,1" - CpusetMems: "0" - Memory: 314572800 - MemorySwap: 514288000 - MemoryReservation: 209715200 - RestartPolicy: - MaximumRetryCount: 4 - Name: "on-failure" - tags: ["Container"] - /containers/{id}/rename: - post: - summary: "Rename a container" - operationId: "ContainerRename" - responses: - 204: - description: "no error" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 409: - description: "name already in use" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "name" - in: "query" - required: true - description: "New name for the container" - type: "string" - tags: ["Container"] - /containers/{id}/pause: - post: - summary: "Pause a container" - description: | - Use the freezer cgroup to suspend all processes in a container. - - Traditionally, when suspending a process the `SIGSTOP` signal is used, - which is observable by the process being suspended. With the freezer - cgroup the process is unaware, and unable to capture, that it is being - suspended, and subsequently resumed. - operationId: "ContainerPause" - responses: - 204: - description: "no error" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - tags: ["Container"] - /containers/{id}/unpause: - post: - summary: "Unpause a container" - description: "Resume a container which has been paused." - operationId: "ContainerUnpause" - responses: - 204: - description: "no error" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - tags: ["Container"] - /containers/{id}/attach: - post: - summary: "Attach to a container" - description: | - Attach to a container to read its output or send it input. You can attach - to the same container multiple times and you can reattach to containers - that have been detached. - - Either the `stream` or `logs` parameter must be `true` for this endpoint - to do anything. - - See the [documentation for the `docker attach` command](https://docs.docker.com/engine/reference/commandline/attach/) - for more details. - - ### Hijacking - - This endpoint hijacks the HTTP connection to transport `stdin`, `stdout`, - and `stderr` on the same socket. - - This is the response from the daemon for an attach request: - - ``` - HTTP/1.1 200 OK - Content-Type: application/vnd.docker.raw-stream - - [STREAM] - ``` - - After the headers and two new lines, the TCP connection can now be used - for raw, bidirectional communication between the client and server. - - To hint potential proxies about connection hijacking, the Docker client - can also optionally send connection upgrade headers. - - For example, the client sends this request to upgrade the connection: - - ``` - POST /containers/16253994b7c4/attach?stream=1&stdout=1 HTTP/1.1 - Upgrade: tcp - Connection: Upgrade - ``` - - The Docker daemon will respond with a `101 UPGRADED` response, and will - similarly follow with the raw stream: - - ``` - HTTP/1.1 101 UPGRADED - Content-Type: application/vnd.docker.raw-stream - Connection: Upgrade - Upgrade: tcp - - [STREAM] - ``` - - ### Stream format - - When the TTY setting is disabled in [`POST /containers/create`](#operation/ContainerCreate), - the HTTP Content-Type header is set to application/vnd.docker.multiplexed-stream - and the stream over the hijacked connected is multiplexed to separate out - `stdout` and `stderr`. The stream consists of a series of frames, each - containing a header and a payload. - - The header contains the information which the stream writes (`stdout` or - `stderr`). It also contains the size of the associated frame encoded in - the last four bytes (`uint32`). - - It is encoded on the first eight bytes like this: - - ```go - header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4} - ``` - - `STREAM_TYPE` can be: - - - 0: `stdin` (is written on `stdout`) - - 1: `stdout` - - 2: `stderr` - - `SIZE1, SIZE2, SIZE3, SIZE4` are the four bytes of the `uint32` size - encoded as big endian. - - Following the header is the payload, which is the specified number of - bytes of `STREAM_TYPE`. - - The simplest way to implement this protocol is the following: - - 1. Read 8 bytes. - 2. Choose `stdout` or `stderr` depending on the first byte. - 3. Extract the frame size from the last four bytes. - 4. Read the extracted size and output it on the correct output. - 5. Goto 1. - - ### Stream format when using a TTY - - When the TTY setting is enabled in [`POST /containers/create`](#operation/ContainerCreate), - the stream is not multiplexed. The data exchanged over the hijacked - connection is simply the raw data from the process PTY and client's - `stdin`. - - operationId: "ContainerAttach" - produces: - - "application/vnd.docker.raw-stream" - - "application/vnd.docker.multiplexed-stream" - responses: - 101: - description: "no error, hints proxy about hijacking" - 200: - description: "no error, no upgrade header found" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "detachKeys" - in: "query" - description: | - Override the key sequence for detaching a container.Format is a single - character `[a-Z]` or `ctrl-` where `` is one of: `a-z`, - `@`, `^`, `[`, `,` or `_`. - type: "string" - - name: "logs" - in: "query" - description: | - Replay previous logs from the container. - - This is useful for attaching to a container that has started and you - want to output everything since the container started. - - If `stream` is also enabled, once all the previous output has been - returned, it will seamlessly transition into streaming current - output. - type: "boolean" - default: false - - name: "stream" - in: "query" - description: | - Stream attached streams from the time the request was made onwards. - type: "boolean" - default: false - - name: "stdin" - in: "query" - description: "Attach to `stdin`" - type: "boolean" - default: false - - name: "stdout" - in: "query" - description: "Attach to `stdout`" - type: "boolean" - default: false - - name: "stderr" - in: "query" - description: "Attach to `stderr`" - type: "boolean" - default: false - tags: ["Container"] - /containers/{id}/attach/ws: - get: - summary: "Attach to a container via a websocket" - operationId: "ContainerAttachWebsocket" - responses: - 101: - description: "no error, hints proxy about hijacking" - 200: - description: "no error, no upgrade header found" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "detachKeys" - in: "query" - description: | - Override the key sequence for detaching a container.Format is a single - character `[a-Z]` or `ctrl-` where `` is one of: `a-z`, - `@`, `^`, `[`, `,`, or `_`. - type: "string" - - name: "logs" - in: "query" - description: "Return logs" - type: "boolean" - default: false - - name: "stream" - in: "query" - description: "Return stream" - type: "boolean" - default: false - - name: "stdin" - in: "query" - description: "Attach to `stdin`" - type: "boolean" - default: false - - name: "stdout" - in: "query" - description: "Attach to `stdout`" - type: "boolean" - default: false - - name: "stderr" - in: "query" - description: "Attach to `stderr`" - type: "boolean" - default: false - tags: ["Container"] - /containers/{id}/wait: - post: - summary: "Wait for a container" - description: "Block until a container stops, then returns the exit code." - operationId: "ContainerWait" - produces: ["application/json"] - responses: - 200: - description: "The container has exit." - schema: - $ref: "#/definitions/ContainerWaitResponse" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "condition" - in: "query" - description: | - Wait until a container state reaches the given condition. - - Defaults to `not-running` if omitted or empty. - type: "string" - enum: - - "not-running" - - "next-exit" - - "removed" - default: "not-running" - tags: ["Container"] - /containers/{id}: - delete: - summary: "Remove a container" - operationId: "ContainerDelete" - responses: - 204: - description: "no error" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 409: - description: "conflict" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: | - You cannot remove a running container: c2ada9df5af8. Stop the - container before attempting removal or force remove - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "v" - in: "query" - description: "Remove anonymous volumes associated with the container." - type: "boolean" - default: false - - name: "force" - in: "query" - description: "If the container is running, kill it before removing it." - type: "boolean" - default: false - - name: "link" - in: "query" - description: "Remove the specified link associated with the container." - type: "boolean" - default: false - tags: ["Container"] - /containers/{id}/archive: - head: - summary: "Get information about files in a container" - description: | - A response header `X-Docker-Container-Path-Stat` is returned, containing - a base64 - encoded JSON object with some filesystem header information - about the path. - operationId: "ContainerArchiveInfo" - responses: - 200: - description: "no error" - headers: - X-Docker-Container-Path-Stat: - type: "string" - description: | - A base64 - encoded JSON object with some filesystem header - information about the path - 400: - description: "Bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "Container or path does not exist" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "path" - in: "query" - required: true - description: "Resource in the container’s filesystem to archive." - type: "string" - tags: ["Container"] - get: - summary: "Get an archive of a filesystem resource in a container" - description: "Get a tar archive of a resource in the filesystem of container id." - operationId: "ContainerArchive" - produces: ["application/x-tar"] - responses: - 200: - description: "no error" - 400: - description: "Bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "Container or path does not exist" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "path" - in: "query" - required: true - description: "Resource in the container’s filesystem to archive." - type: "string" - tags: ["Container"] - put: - summary: "Extract an archive of files or folders to a directory in a container" - description: | - Upload a tar archive to be extracted to a path in the filesystem of container id. - `path` parameter is asserted to be a directory. If it exists as a file, 400 error - will be returned with message "not a directory". - operationId: "PutContainerArchive" - consumes: ["application/x-tar", "application/octet-stream"] - responses: - 200: - description: "The content was extracted successfully" - 400: - description: "Bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "not a directory" - 403: - description: "Permission denied, the volume or container rootfs is marked as read-only." - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "No such container or path does not exist inside the container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "path" - in: "query" - required: true - description: "Path to a directory in the container to extract the archive’s contents into. " - type: "string" - - name: "noOverwriteDirNonDir" - in: "query" - description: | - If `1`, `true`, or `True` then it will be an error if unpacking the - given content would cause an existing directory to be replaced with - a non-directory and vice versa. - type: "string" - - name: "copyUIDGID" - in: "query" - description: | - If `1`, `true`, then it will copy UID/GID maps to the dest file or - dir - type: "string" - - name: "inputStream" - in: "body" - required: true - description: | - The input stream must be a tar archive compressed with one of the - following algorithms: `identity` (no compression), `gzip`, `bzip2`, - or `xz`. - schema: - type: "string" - format: "binary" - tags: ["Container"] - /containers/prune: - post: - summary: "Delete stopped containers" - produces: - - "application/json" - operationId: "ContainerPrune" - parameters: - - name: "filters" - in: "query" - description: | - Filters to process on the prune list, encoded as JSON (a `map[string][]string`). - - Available filters: - - `until=` Prune containers created before this timestamp. The `` can be Unix timestamps, date formatted timestamps, or Go duration strings (e.g. `10m`, `1h30m`) computed relative to the daemon machine’s time. - - `label` (`label=`, `label==`, `label!=`, or `label!==`) Prune containers with (or without, in case `label!=...` is used) the specified labels. - type: "string" - responses: - 200: - description: "No error" - schema: - type: "object" - title: "ContainerPruneResponse" - properties: - ContainersDeleted: - description: "Container IDs that were deleted" - type: "array" - items: - type: "string" - SpaceReclaimed: - description: "Disk space reclaimed in bytes" - type: "integer" - format: "int64" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Container"] - /images/json: - get: - summary: "List Images" - description: "Returns a list of images on the server. Note that it uses a different, smaller representation of an image than inspecting a single image." - operationId: "ImageList" - produces: - - "application/json" - responses: - 200: - description: "Summary image data for the images matching the query" - schema: - type: "array" - items: - $ref: "#/definitions/ImageSummary" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "all" - in: "query" - description: "Show all images. Only images from a final layer (no children) are shown by default." - type: "boolean" - default: false - - name: "filters" - in: "query" - description: | - A JSON encoded value of the filters (a `map[string][]string`) to - process on the images list. - - Available filters: - - - `before`=(`[:]`, `` or ``) - - `dangling=true` - - `label=key` or `label="key=value"` of an image label - - `reference`=(`[:]`) - - `since`=(`[:]`, `` or ``) - type: "string" - - name: "shared-size" - in: "query" - description: "Compute and show shared size as a `SharedSize` field on each image." - type: "boolean" - default: false - - name: "digests" - in: "query" - description: "Show digest information as a `RepoDigests` field on each image." - type: "boolean" - default: false - tags: ["Image"] - /build: - post: - summary: "Build an image" - description: | - Build an image from a tar archive with a `Dockerfile` in it. - - The `Dockerfile` specifies how the image is built from the tar archive. It is typically in the archive's root, but can be at a different path or have a different name by specifying the `dockerfile` parameter. [See the `Dockerfile` reference for more information](https://docs.docker.com/engine/reference/builder/). - - The Docker daemon performs a preliminary validation of the `Dockerfile` before starting the build, and returns an error if the syntax is incorrect. After that, each instruction is run one-by-one until the ID of the new image is output. - - The build is canceled if the client drops the connection by quitting or being killed. - operationId: "ImageBuild" - consumes: - - "application/octet-stream" - produces: - - "application/json" - parameters: - - name: "inputStream" - in: "body" - description: "A tar archive compressed with one of the following algorithms: identity (no compression), gzip, bzip2, xz." - schema: - type: "string" - format: "binary" - - name: "dockerfile" - in: "query" - description: "Path within the build context to the `Dockerfile`. This is ignored if `remote` is specified and points to an external `Dockerfile`." - type: "string" - default: "Dockerfile" - - name: "t" - in: "query" - description: "A name and optional tag to apply to the image in the `name:tag` format. If you omit the tag the default `latest` value is assumed. You can provide several `t` parameters." - type: "string" - - name: "extrahosts" - in: "query" - description: "Extra hosts to add to /etc/hosts" - type: "string" - - name: "remote" - in: "query" - description: "A Git repository URI or HTTP/HTTPS context URI. If the URI points to a single text file, the file’s contents are placed into a file called `Dockerfile` and the image is built from that file. If the URI points to a tarball, the file is downloaded by the daemon and the contents therein used as the context for the build. If the URI points to a tarball and the `dockerfile` parameter is also specified, there must be a file with the corresponding path inside the tarball." - type: "string" - - name: "q" - in: "query" - description: "Suppress verbose build output." - type: "boolean" - default: false - - name: "nocache" - in: "query" - description: "Do not use the cache when building the image." - type: "boolean" - default: false - - name: "cachefrom" - in: "query" - description: "JSON array of images used for build cache resolution." - type: "string" - - name: "pull" - in: "query" - description: "Attempt to pull the image even if an older image exists locally." - type: "string" - - name: "rm" - in: "query" - description: "Remove intermediate containers after a successful build." - type: "boolean" - default: true - - name: "forcerm" - in: "query" - description: "Always remove intermediate containers, even upon failure." - type: "boolean" - default: false - - name: "memory" - in: "query" - description: "Set memory limit for build." - type: "integer" - - name: "memswap" - in: "query" - description: "Total memory (memory + swap). Set as `-1` to disable swap." - type: "integer" - - name: "cpushares" - in: "query" - description: "CPU shares (relative weight)." - type: "integer" - - name: "cpusetcpus" - in: "query" - description: "CPUs in which to allow execution (e.g., `0-3`, `0,1`)." - type: "string" - - name: "cpuperiod" - in: "query" - description: "The length of a CPU period in microseconds." - type: "integer" - - name: "cpuquota" - in: "query" - description: "Microseconds of CPU time that the container can get in a CPU period." - type: "integer" - - name: "buildargs" - in: "query" - description: > - JSON map of string pairs for build-time variables. Users pass these values at build-time. Docker - uses the buildargs as the environment context for commands run via the `Dockerfile` RUN - instruction, or for variable expansion in other `Dockerfile` instructions. This is not meant for - passing secret values. - - - For example, the build arg `FOO=bar` would become `{"FOO":"bar"}` in JSON. This would result in the - query parameter `buildargs={"FOO":"bar"}`. Note that `{"FOO":"bar"}` should be URI component encoded. - - - [Read more about the buildargs instruction.](https://docs.docker.com/engine/reference/builder/#arg) - type: "string" - - name: "shmsize" - in: "query" - description: "Size of `/dev/shm` in bytes. The size must be greater than 0. If omitted the system uses 64MB." - type: "integer" - - name: "squash" - in: "query" - description: "Squash the resulting images layers into a single layer. *(Experimental release only.)*" - type: "boolean" - - name: "labels" - in: "query" - description: "Arbitrary key/value labels to set on the image, as a JSON map of string pairs." - type: "string" - - name: "networkmode" - in: "query" - description: | - Sets the networking mode for the run commands during build. Supported - standard values are: `bridge`, `host`, `none`, and `container:`. - Any other value is taken as a custom network's name or ID to which this - container should connect to. - type: "string" - - name: "Content-type" - in: "header" - type: "string" - enum: - - "application/x-tar" - default: "application/x-tar" - - name: "X-Registry-Config" - in: "header" - description: | - This is a base64-encoded JSON object with auth configurations for multiple registries that a build may refer to. - - The key is a registry URL, and the value is an auth configuration object, [as described in the authentication section](#section/Authentication). For example: - - ``` - { - "docker.example.com": { - "username": "janedoe", - "password": "hunter2" - }, - "https://index.docker.io/v1/": { - "username": "mobydock", - "password": "conta1n3rize14" - } - } - ``` - - Only the registry domain name (and port if not the default 443) are required. However, for legacy reasons, the Docker Hub registry must be specified with both a `https://` prefix and a `/v1/` suffix even though Docker will prefer to use the v2 registry API. - type: "string" - - name: "platform" - in: "query" - description: "Platform in the format os[/arch[/variant]]" - type: "string" - default: "" - - name: "target" - in: "query" - description: "Target build stage" - type: "string" - default: "" - - name: "outputs" - in: "query" - description: "BuildKit output configuration" - type: "string" - default: "" - responses: - 200: - description: "no error" - 400: - description: "Bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Image"] - /build/prune: - post: - summary: "Delete builder cache" - produces: - - "application/json" - operationId: "BuildPrune" - parameters: - - name: "keep-storage" - in: "query" - description: "Amount of disk space in bytes to keep for cache" - type: "integer" - format: "int64" - - name: "all" - in: "query" - type: "boolean" - description: "Remove all types of build cache" - - name: "filters" - in: "query" - type: "string" - description: | - A JSON encoded value of the filters (a `map[string][]string`) to - process on the list of build cache objects. - - Available filters: - - - `until=` remove cache older than ``. The `` can be Unix timestamps, date formatted timestamps, or Go duration strings (e.g. `10m`, `1h30m`) computed relative to the daemon's local time. - - `id=` - - `parent=` - - `type=` - - `description=` - - `inuse` - - `shared` - - `private` - responses: - 200: - description: "No error" - schema: - type: "object" - title: "BuildPruneResponse" - properties: - CachesDeleted: - type: "array" - items: - description: "ID of build cache object" - type: "string" - SpaceReclaimed: - description: "Disk space reclaimed in bytes" - type: "integer" - format: "int64" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Image"] - /images/create: - post: - summary: "Create an image" - description: "Create an image by either pulling it from a registry or importing it." - operationId: "ImageCreate" - consumes: - - "text/plain" - - "application/octet-stream" - produces: - - "application/json" - responses: - 200: - description: "no error" - 404: - description: "repository does not exist or no read access" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "fromImage" - in: "query" - description: "Name of the image to pull. The name may include a tag or digest. This parameter may only be used when pulling an image. The pull is cancelled if the HTTP connection is closed." - type: "string" - - name: "fromSrc" - in: "query" - description: "Source to import. The value may be a URL from which the image can be retrieved or `-` to read the image from the request body. This parameter may only be used when importing an image." - type: "string" - - name: "repo" - in: "query" - description: "Repository name given to an image when it is imported. The repo may include a tag. This parameter may only be used when importing an image." - type: "string" - - name: "tag" - in: "query" - description: "Tag or digest. If empty when pulling an image, this causes all tags for the given image to be pulled." - type: "string" - - name: "message" - in: "query" - description: "Set commit message for imported image." - type: "string" - - name: "inputImage" - in: "body" - description: "Image content if the value `-` has been specified in fromSrc query parameter" - schema: - type: "string" - required: false - - name: "X-Registry-Auth" - in: "header" - description: | - A base64url-encoded auth configuration. - - Refer to the [authentication section](#section/Authentication) for - details. - type: "string" - - name: "changes" - in: "query" - description: | - Apply `Dockerfile` instructions to the image that is created, - for example: `changes=ENV DEBUG=true`. - Note that `ENV DEBUG=true` should be URI component encoded. - - Supported `Dockerfile` instructions: - `CMD`|`ENTRYPOINT`|`ENV`|`EXPOSE`|`ONBUILD`|`USER`|`VOLUME`|`WORKDIR` - type: "array" - items: - type: "string" - - name: "platform" - in: "query" - description: | - Platform in the format os[/arch[/variant]]. - - When used in combination with the `fromImage` option, the daemon checks - if the given image is present in the local image cache with the given - OS and Architecture, and otherwise attempts to pull the image. If the - option is not set, the host's native OS and Architecture are used. - If the given image does not exist in the local image cache, the daemon - attempts to pull the image with the host's native OS and Architecture. - If the given image does exists in the local image cache, but its OS or - architecture does not match, a warning is produced. - - When used with the `fromSrc` option to import an image from an archive, - this option sets the platform information for the imported image. If - the option is not set, the host's native OS and Architecture are used - for the imported image. - type: "string" - default: "" - tags: ["Image"] - /images/{name}/json: - get: - summary: "Inspect an image" - description: "Return low-level information about an image." - operationId: "ImageInspect" - produces: - - "application/json" - responses: - 200: - description: "No error" - schema: - $ref: "#/definitions/ImageInspect" - 404: - description: "No such image" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such image: someimage (tag: latest)" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: "Image name or id" - type: "string" - required: true - tags: ["Image"] - /images/{name}/history: - get: - summary: "Get the history of an image" - description: "Return parent layers of an image." - operationId: "ImageHistory" - produces: ["application/json"] - responses: - 200: - description: "List of image layers" - schema: - type: "array" - items: - type: "object" - x-go-name: HistoryResponseItem - title: "HistoryResponseItem" - description: "individual image layer information in response to ImageHistory operation" - required: [Id, Created, CreatedBy, Tags, Size, Comment] - properties: - Id: - type: "string" - x-nullable: false - Created: - type: "integer" - format: "int64" - x-nullable: false - CreatedBy: - type: "string" - x-nullable: false - Tags: - type: "array" - items: - type: "string" - Size: - type: "integer" - format: "int64" - x-nullable: false - Comment: - type: "string" - x-nullable: false - examples: - application/json: - - Id: "3db9c44f45209632d6050b35958829c3a2aa256d81b9a7be45b362ff85c54710" - Created: 1398108230 - CreatedBy: "/bin/sh -c #(nop) ADD file:eb15dbd63394e063b805a3c32ca7bf0266ef64676d5a6fab4801f2e81e2a5148 in /" - Tags: - - "ubuntu:lucid" - - "ubuntu:10.04" - Size: 182964289 - Comment: "" - - Id: "6cfa4d1f33fb861d4d114f43b25abd0ac737509268065cdfd69d544a59c85ab8" - Created: 1398108222 - CreatedBy: "/bin/sh -c #(nop) MAINTAINER Tianon Gravi - mkimage-debootstrap.sh -i iproute,iputils-ping,ubuntu-minimal -t lucid.tar.xz lucid http://archive.ubuntu.com/ubuntu/" - Tags: [] - Size: 0 - Comment: "" - - Id: "511136ea3c5a64f264b78b5433614aec563103b4d4702f3ba7d4d2698e22c158" - Created: 1371157430 - CreatedBy: "" - Tags: - - "scratch12:latest" - - "scratch:latest" - Size: 0 - Comment: "Imported from -" - 404: - description: "No such image" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: "Image name or ID" - type: "string" - required: true - tags: ["Image"] - /images/{name}/push: - post: - summary: "Push an image" - description: | - Push an image to a registry. - - If you wish to push an image on to a private registry, that image must - already have a tag which references the registry. For example, - `registry.example.com/myimage:latest`. - - The push is cancelled if the HTTP connection is closed. - operationId: "ImagePush" - consumes: - - "application/octet-stream" - responses: - 200: - description: "No error" - 404: - description: "No such image" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: "Image name or ID." - type: "string" - required: true - - name: "tag" - in: "query" - description: "The tag to associate with the image on the registry." - type: "string" - - name: "X-Registry-Auth" - in: "header" - description: | - A base64url-encoded auth configuration. - - Refer to the [authentication section](#section/Authentication) for - details. - type: "string" - required: true - tags: ["Image"] - /images/{name}/tag: - post: - summary: "Tag an image" - description: "Tag an image so that it becomes part of a repository." - operationId: "ImageTag" - responses: - 201: - description: "No error" - 400: - description: "Bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "No such image" - schema: - $ref: "#/definitions/ErrorResponse" - 409: - description: "Conflict" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: "Image name or ID to tag." - type: "string" - required: true - - name: "repo" - in: "query" - description: "The repository to tag in. For example, `someuser/someimage`." - type: "string" - - name: "tag" - in: "query" - description: "The name of the new tag." - type: "string" - tags: ["Image"] - /images/{name}: - delete: - summary: "Remove an image" - description: | - Remove an image, along with any untagged parent images that were - referenced by that image. - - Images can't be removed if they have descendant images, are being - used by a running container or are being used by a build. - operationId: "ImageDelete" - produces: ["application/json"] - responses: - 200: - description: "The image was deleted successfully" - schema: - type: "array" - items: - $ref: "#/definitions/ImageDeleteResponseItem" - examples: - application/json: - - Untagged: "3e2f21a89f" - - Deleted: "3e2f21a89f" - - Deleted: "53b4f83ac9" - 404: - description: "No such image" - schema: - $ref: "#/definitions/ErrorResponse" - 409: - description: "Conflict" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: "Image name or ID" - type: "string" - required: true - - name: "force" - in: "query" - description: "Remove the image even if it is being used by stopped containers or has other tags" - type: "boolean" - default: false - - name: "noprune" - in: "query" - description: "Do not delete untagged parent images" - type: "boolean" - default: false - tags: ["Image"] - /images/search: - get: - summary: "Search images" - description: "Search for an image on Docker Hub." - operationId: "ImageSearch" - produces: - - "application/json" - responses: - 200: - description: "No error" - schema: - type: "array" - items: - type: "object" - title: "ImageSearchResponseItem" - properties: - description: - type: "string" - is_official: - type: "boolean" - is_automated: - type: "boolean" - name: - type: "string" - star_count: - type: "integer" - examples: - application/json: - - description: "" - is_official: false - is_automated: false - name: "wma55/u1210sshd" - star_count: 0 - - description: "" - is_official: false - is_automated: false - name: "jdswinbank/sshd" - star_count: 0 - - description: "" - is_official: false - is_automated: false - name: "vgauthier/sshd" - star_count: 0 - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "term" - in: "query" - description: "Term to search" - type: "string" - required: true - - name: "limit" - in: "query" - description: "Maximum number of results to return" - type: "integer" - - name: "filters" - in: "query" - description: | - A JSON encoded value of the filters (a `map[string][]string`) to process on the images list. Available filters: - - - `is-automated=(true|false)` - - `is-official=(true|false)` - - `stars=` Matches images that has at least 'number' stars. - type: "string" - tags: ["Image"] - /images/prune: - post: - summary: "Delete unused images" - produces: - - "application/json" - operationId: "ImagePrune" - parameters: - - name: "filters" - in: "query" - description: | - Filters to process on the prune list, encoded as JSON (a `map[string][]string`). Available filters: - - - `dangling=` When set to `true` (or `1`), prune only - unused *and* untagged images. When set to `false` - (or `0`), all unused images are pruned. - - `until=` Prune images created before this timestamp. The `` can be Unix timestamps, date formatted timestamps, or Go duration strings (e.g. `10m`, `1h30m`) computed relative to the daemon machine’s time. - - `label` (`label=`, `label==`, `label!=`, or `label!==`) Prune images with (or without, in case `label!=...` is used) the specified labels. - type: "string" - responses: - 200: - description: "No error" - schema: - type: "object" - title: "ImagePruneResponse" - properties: - ImagesDeleted: - description: "Images that were deleted" - type: "array" - items: - $ref: "#/definitions/ImageDeleteResponseItem" - SpaceReclaimed: - description: "Disk space reclaimed in bytes" - type: "integer" - format: "int64" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Image"] - /auth: - post: - summary: "Check auth configuration" - description: | - Validate credentials for a registry and, if available, get an identity - token for accessing the registry without password. - operationId: "SystemAuth" - consumes: ["application/json"] - produces: ["application/json"] - responses: - 200: - description: "An identity token was generated successfully." - schema: - type: "object" - title: "SystemAuthResponse" - required: [Status] - properties: - Status: - description: "The status of the authentication" - type: "string" - x-nullable: false - IdentityToken: - description: "An opaque token used to authenticate a user after a successful login" - type: "string" - x-nullable: false - examples: - application/json: - Status: "Login Succeeded" - IdentityToken: "9cbaf023786cd7..." - 204: - description: "No error" - 401: - description: "Auth error" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "authConfig" - in: "body" - description: "Authentication to check" - schema: - $ref: "#/definitions/AuthConfig" - tags: ["System"] - /info: - get: - summary: "Get system information" - operationId: "SystemInfo" - produces: - - "application/json" - responses: - 200: - description: "No error" - schema: - $ref: "#/definitions/SystemInfo" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["System"] - /version: - get: - summary: "Get version" - description: "Returns the version of Docker that is running and various information about the system that Docker is running on." - operationId: "SystemVersion" - produces: ["application/json"] - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/SystemVersion" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["System"] - /_ping: - get: - summary: "Ping" - description: "This is a dummy endpoint you can use to test if the server is accessible." - operationId: "SystemPing" - produces: ["text/plain"] - responses: - 200: - description: "no error" - schema: - type: "string" - example: "OK" - headers: - API-Version: - type: "string" - description: "Max API Version the server supports" - Builder-Version: - type: "string" - description: | - Default version of docker image builder - - The default on Linux is version "2" (BuildKit), but the daemon - can be configured to recommend version "1" (classic Builder). - Windows does not yet support BuildKit for native Windows images, - and uses "1" (classic builder) as a default. - - This value is a recommendation as advertised by the daemon, and - it is up to the client to choose which builder to use. - default: "2" - Docker-Experimental: - type: "boolean" - description: "If the server is running with experimental mode enabled" - Swarm: - type: "string" - enum: ["inactive", "pending", "error", "locked", "active/worker", "active/manager"] - description: | - Contains information about Swarm status of the daemon, - and if the daemon is acting as a manager or worker node. - default: "inactive" - Cache-Control: - type: "string" - default: "no-cache, no-store, must-revalidate" - Pragma: - type: "string" - default: "no-cache" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - headers: - Cache-Control: - type: "string" - default: "no-cache, no-store, must-revalidate" - Pragma: - type: "string" - default: "no-cache" - tags: ["System"] - head: - summary: "Ping" - description: "This is a dummy endpoint you can use to test if the server is accessible." - operationId: "SystemPingHead" - produces: ["text/plain"] - responses: - 200: - description: "no error" - schema: - type: "string" - example: "(empty)" - headers: - API-Version: - type: "string" - description: "Max API Version the server supports" - Builder-Version: - type: "string" - description: "Default version of docker image builder" - Docker-Experimental: - type: "boolean" - description: "If the server is running with experimental mode enabled" - Swarm: - type: "string" - enum: ["inactive", "pending", "error", "locked", "active/worker", "active/manager"] - description: | - Contains information about Swarm status of the daemon, - and if the daemon is acting as a manager or worker node. - default: "inactive" - Cache-Control: - type: "string" - default: "no-cache, no-store, must-revalidate" - Pragma: - type: "string" - default: "no-cache" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["System"] - /commit: - post: - summary: "Create a new image from a container" - operationId: "ImageCommit" - consumes: - - "application/json" - produces: - - "application/json" - responses: - 201: - description: "no error" - schema: - $ref: "#/definitions/IdResponse" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "containerConfig" - in: "body" - description: "The container configuration" - schema: - $ref: "#/definitions/ContainerConfig" - - name: "container" - in: "query" - description: "The ID or name of the container to commit" - type: "string" - - name: "repo" - in: "query" - description: "Repository name for the created image" - type: "string" - - name: "tag" - in: "query" - description: "Tag name for the create image" - type: "string" - - name: "comment" - in: "query" - description: "Commit message" - type: "string" - - name: "author" - in: "query" - description: "Author of the image (e.g., `John Hannibal Smith `)" - type: "string" - - name: "pause" - in: "query" - description: "Whether to pause the container before committing" - type: "boolean" - default: true - - name: "changes" - in: "query" - description: "`Dockerfile` instructions to apply while committing" - type: "string" - tags: ["Image"] - /events: - get: - summary: "Monitor events" - description: | - Stream real-time events from the server. - - Various objects within Docker report events when something happens to them. - - Containers report these events: `attach`, `commit`, `copy`, `create`, `destroy`, `detach`, `die`, `exec_create`, `exec_detach`, `exec_start`, `exec_die`, `export`, `health_status`, `kill`, `oom`, `pause`, `rename`, `resize`, `restart`, `start`, `stop`, `top`, `unpause`, `update`, and `prune` - - Images report these events: `delete`, `import`, `load`, `pull`, `push`, `save`, `tag`, `untag`, and `prune` - - Volumes report these events: `create`, `mount`, `unmount`, `destroy`, and `prune` - - Networks report these events: `create`, `connect`, `disconnect`, `destroy`, `update`, `remove`, and `prune` - - The Docker daemon reports these events: `reload` - - Services report these events: `create`, `update`, and `remove` - - Nodes report these events: `create`, `update`, and `remove` - - Secrets report these events: `create`, `update`, and `remove` - - Configs report these events: `create`, `update`, and `remove` - - The Builder reports `prune` events - - operationId: "SystemEvents" - produces: - - "application/json" - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/EventMessage" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "since" - in: "query" - description: "Show events created since this timestamp then stream new events." - type: "string" - - name: "until" - in: "query" - description: "Show events created until this timestamp then stop streaming." - type: "string" - - name: "filters" - in: "query" - description: | - A JSON encoded value of filters (a `map[string][]string`) to process on the event list. Available filters: - - - `config=` config name or ID - - `container=` container name or ID - - `daemon=` daemon name or ID - - `event=` event type - - `image=` image name or ID - - `label=` image or container label - - `network=` network name or ID - - `node=` node ID - - `plugin`= plugin name or ID - - `scope`= local or swarm - - `secret=` secret name or ID - - `service=` service name or ID - - `type=` object to filter by, one of `container`, `image`, `volume`, `network`, `daemon`, `plugin`, `node`, `service`, `secret` or `config` - - `volume=` volume name - type: "string" - tags: ["System"] - /system/df: - get: - summary: "Get data usage information" - operationId: "SystemDataUsage" - responses: - 200: - description: "no error" - schema: - type: "object" - title: "SystemDataUsageResponse" - properties: - LayersSize: - type: "integer" - format: "int64" - Images: - type: "array" - items: - $ref: "#/definitions/ImageSummary" - Containers: - type: "array" - items: - $ref: "#/definitions/ContainerSummary" - Volumes: - type: "array" - items: - $ref: "#/definitions/Volume" - BuildCache: - type: "array" - items: - $ref: "#/definitions/BuildCache" - example: - LayersSize: 1092588 - Images: - - - Id: "sha256:2b8fd9751c4c0f5dd266fcae00707e67a2545ef34f9a29354585f93dac906749" - ParentId: "" - RepoTags: - - "busybox:latest" - RepoDigests: - - "busybox@sha256:a59906e33509d14c036c8678d687bd4eec81ed7c4b8ce907b888c607f6a1e0e6" - Created: 1466724217 - Size: 1092588 - SharedSize: 0 - VirtualSize: 1092588 - Labels: {} - Containers: 1 - Containers: - - - Id: "e575172ed11dc01bfce087fb27bee502db149e1a0fad7c296ad300bbff178148" - Names: - - "/top" - Image: "busybox" - ImageID: "sha256:2b8fd9751c4c0f5dd266fcae00707e67a2545ef34f9a29354585f93dac906749" - Command: "top" - Created: 1472592424 - Ports: [] - SizeRootFs: 1092588 - Labels: {} - State: "exited" - Status: "Exited (0) 56 minutes ago" - HostConfig: - NetworkMode: "default" - NetworkSettings: - Networks: - bridge: - IPAMConfig: null - Links: null - Aliases: null - NetworkID: "d687bc59335f0e5c9ee8193e5612e8aee000c8c62ea170cfb99c098f95899d92" - EndpointID: "8ed5115aeaad9abb174f68dcf135b49f11daf597678315231a32ca28441dec6a" - Gateway: "172.18.0.1" - IPAddress: "172.18.0.2" - IPPrefixLen: 16 - IPv6Gateway: "" - GlobalIPv6Address: "" - GlobalIPv6PrefixLen: 0 - MacAddress: "02:42:ac:12:00:02" - Mounts: [] - Volumes: - - - Name: "my-volume" - Driver: "local" - Mountpoint: "/var/lib/docker/volumes/my-volume/_data" - Labels: null - Scope: "local" - Options: null - UsageData: - Size: 10920104 - RefCount: 2 - BuildCache: - - - ID: "hw53o5aio51xtltp5xjp8v7fx" - Parents: [] - Type: "regular" - Description: "pulled from docker.io/library/debian@sha256:234cb88d3020898631af0ccbbcca9a66ae7306ecd30c9720690858c1b007d2a0" - InUse: false - Shared: true - Size: 0 - CreatedAt: "2021-06-28T13:31:01.474619385Z" - LastUsedAt: "2021-07-07T22:02:32.738075951Z" - UsageCount: 26 - - - ID: "ndlpt0hhvkqcdfkputsk4cq9c" - Parents: ["ndlpt0hhvkqcdfkputsk4cq9c"] - Type: "regular" - Description: "mount / from exec /bin/sh -c echo 'Binary::apt::APT::Keep-Downloaded-Packages \"true\";' > /etc/apt/apt.conf.d/keep-cache" - InUse: false - Shared: true - Size: 51 - CreatedAt: "2021-06-28T13:31:03.002625487Z" - LastUsedAt: "2021-07-07T22:02:32.773909517Z" - UsageCount: 26 - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "type" - in: "query" - description: | - Object types, for which to compute and return data. - type: "array" - collectionFormat: multi - items: - type: "string" - enum: ["container", "image", "volume", "build-cache"] - tags: ["System"] - /images/{name}/get: - get: - summary: "Export an image" - description: | - Get a tarball containing all images and metadata for a repository. - - If `name` is a specific name and tag (e.g. `ubuntu:latest`), then only that image (and its parents) are returned. If `name` is an image ID, similarly only that image (and its parents) are returned, but with the exclusion of the `repositories` file in the tarball, as there were no image names referenced. - - ### Image tarball format - - An image tarball contains one directory per image layer (named using its long ID), each containing these files: - - - `VERSION`: currently `1.0` - the file format version - - `json`: detailed layer information, similar to `docker inspect layer_id` - - `layer.tar`: A tarfile containing the filesystem changes in this layer - - The `layer.tar` file contains `aufs` style `.wh..wh.aufs` files and directories for storing attribute changes and deletions. - - If the tarball defines a repository, the tarball should also include a `repositories` file at the root that contains a list of repository and tag names mapped to layer IDs. - - ```json - { - "hello-world": { - "latest": "565a9d68a73f6706862bfe8409a7f659776d4d60a8d096eb4a3cbce6999cc2a1" - } - } - ``` - operationId: "ImageGet" - produces: - - "application/x-tar" - responses: - 200: - description: "no error" - schema: - type: "string" - format: "binary" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: "Image name or ID" - type: "string" - required: true - tags: ["Image"] - /images/get: - get: - summary: "Export several images" - description: | - Get a tarball containing all images and metadata for several image - repositories. - - For each value of the `names` parameter: if it is a specific name and - tag (e.g. `ubuntu:latest`), then only that image (and its parents) are - returned; if it is an image ID, similarly only that image (and its parents) - are returned and there would be no names referenced in the 'repositories' - file for this image ID. - - For details on the format, see the [export image endpoint](#operation/ImageGet). - operationId: "ImageGetAll" - produces: - - "application/x-tar" - responses: - 200: - description: "no error" - schema: - type: "string" - format: "binary" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "names" - in: "query" - description: "Image names to filter by" - type: "array" - items: - type: "string" - tags: ["Image"] - /images/load: - post: - summary: "Import images" - description: | - Load a set of images and tags into a repository. - - For details on the format, see the [export image endpoint](#operation/ImageGet). - operationId: "ImageLoad" - consumes: - - "application/x-tar" - produces: - - "application/json" - responses: - 200: - description: "no error" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "imagesTarball" - in: "body" - description: "Tar archive containing images" - schema: - type: "string" - format: "binary" - - name: "quiet" - in: "query" - description: "Suppress progress details during load." - type: "boolean" - default: false - tags: ["Image"] - /containers/{id}/exec: - post: - summary: "Create an exec instance" - description: "Run a command inside a running container." - operationId: "ContainerExec" - consumes: - - "application/json" - produces: - - "application/json" - responses: - 201: - description: "no error" - schema: - $ref: "#/definitions/IdResponse" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 409: - description: "container is paused" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "execConfig" - in: "body" - description: "Exec configuration" - schema: - type: "object" - title: "ExecConfig" - properties: - AttachStdin: - type: "boolean" - description: "Attach to `stdin` of the exec command." - AttachStdout: - type: "boolean" - description: "Attach to `stdout` of the exec command." - AttachStderr: - type: "boolean" - description: "Attach to `stderr` of the exec command." - ConsoleSize: - type: "array" - description: "Initial console size, as an `[height, width]` array." - x-nullable: true - minItems: 2 - maxItems: 2 - items: - type: "integer" - minimum: 0 - DetachKeys: - type: "string" - description: | - Override the key sequence for detaching a container. Format is - a single character `[a-Z]` or `ctrl-` where `` - is one of: `a-z`, `@`, `^`, `[`, `,` or `_`. - Tty: - type: "boolean" - description: "Allocate a pseudo-TTY." - Env: - description: | - A list of environment variables in the form `["VAR=value", ...]`. - type: "array" - items: - type: "string" - Cmd: - type: "array" - description: "Command to run, as a string or array of strings." - items: - type: "string" - Privileged: - type: "boolean" - description: "Runs the exec process with extended privileges." - default: false - User: - type: "string" - description: | - The user, and optionally, group to run the exec process inside - the container. Format is one of: `user`, `user:group`, `uid`, - or `uid:gid`. - WorkingDir: - type: "string" - description: | - The working directory for the exec process inside the container. - example: - AttachStdin: false - AttachStdout: true - AttachStderr: true - DetachKeys: "ctrl-p,ctrl-q" - Tty: false - Cmd: - - "date" - Env: - - "FOO=bar" - - "BAZ=quux" - required: true - - name: "id" - in: "path" - description: "ID or name of container" - type: "string" - required: true - tags: ["Exec"] - /exec/{id}/start: - post: - summary: "Start an exec instance" - description: | - Starts a previously set up exec instance. If detach is true, this endpoint - returns immediately after starting the command. Otherwise, it sets up an - interactive session with the command. - operationId: "ExecStart" - consumes: - - "application/json" - produces: - - "application/vnd.docker.raw-stream" - - "application/vnd.docker.multiplexed-stream" - responses: - 200: - description: "No error" - 404: - description: "No such exec instance" - schema: - $ref: "#/definitions/ErrorResponse" - 409: - description: "Container is stopped or paused" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "execStartConfig" - in: "body" - schema: - type: "object" - title: "ExecStartConfig" - properties: - Detach: - type: "boolean" - description: "Detach from the command." - Tty: - type: "boolean" - description: "Allocate a pseudo-TTY." - ConsoleSize: - type: "array" - description: "Initial console size, as an `[height, width]` array." - x-nullable: true - minItems: 2 - maxItems: 2 - items: - type: "integer" - minimum: 0 - example: - Detach: false - Tty: true - ConsoleSize: [80, 64] - - name: "id" - in: "path" - description: "Exec instance ID" - required: true - type: "string" - tags: ["Exec"] - /exec/{id}/resize: - post: - summary: "Resize an exec instance" - description: | - Resize the TTY session used by an exec instance. This endpoint only works - if `tty` was specified as part of creating and starting the exec instance. - operationId: "ExecResize" - responses: - 200: - description: "No error" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "No such exec instance" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "Exec instance ID" - required: true - type: "string" - - name: "h" - in: "query" - description: "Height of the TTY session in characters" - type: "integer" - - name: "w" - in: "query" - description: "Width of the TTY session in characters" - type: "integer" - tags: ["Exec"] - /exec/{id}/json: - get: - summary: "Inspect an exec instance" - description: "Return low-level information about an exec instance." - operationId: "ExecInspect" - produces: - - "application/json" - responses: - 200: - description: "No error" - schema: - type: "object" - title: "ExecInspectResponse" - properties: - CanRemove: - type: "boolean" - DetachKeys: - type: "string" - ID: - type: "string" - Running: - type: "boolean" - ExitCode: - type: "integer" - ProcessConfig: - $ref: "#/definitions/ProcessConfig" - OpenStdin: - type: "boolean" - OpenStderr: - type: "boolean" - OpenStdout: - type: "boolean" - ContainerID: - type: "string" - Pid: - type: "integer" - description: "The system process ID for the exec process." - examples: - application/json: - CanRemove: false - ContainerID: "b53ee82b53a40c7dca428523e34f741f3abc51d9f297a14ff874bf761b995126" - DetachKeys: "" - ExitCode: 2 - ID: "f33bbfb39f5b142420f4759b2348913bd4a8d1a6d7fd56499cb41a1bb91d7b3b" - OpenStderr: true - OpenStdin: true - OpenStdout: true - ProcessConfig: - arguments: - - "-c" - - "exit 2" - entrypoint: "sh" - privileged: false - tty: true - user: "1000" - Running: false - Pid: 42000 - 404: - description: "No such exec instance" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "Exec instance ID" - required: true - type: "string" - tags: ["Exec"] - - /volumes: - get: - summary: "List volumes" - operationId: "VolumeList" - produces: ["application/json"] - responses: - 200: - description: "Summary volume data that matches the query" - schema: - $ref: "#/definitions/VolumeListResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "filters" - in: "query" - description: | - JSON encoded value of the filters (a `map[string][]string`) to - process on the volumes list. Available filters: - - - `dangling=` When set to `true` (or `1`), returns all - volumes that are not in use by a container. When set to `false` - (or `0`), only volumes that are in use by one or more - containers are returned. - - `driver=` Matches volumes based on their driver. - - `label=` or `label=:` Matches volumes based on - the presence of a `label` alone or a `label` and a value. - - `name=` Matches all or part of a volume name. - type: "string" - format: "json" - tags: ["Volume"] - - /volumes/create: - post: - summary: "Create a volume" - operationId: "VolumeCreate" - consumes: ["application/json"] - produces: ["application/json"] - responses: - 201: - description: "The volume was created successfully" - schema: - $ref: "#/definitions/Volume" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "volumeConfig" - in: "body" - required: true - description: "Volume configuration" - schema: - $ref: "#/definitions/VolumeCreateOptions" - tags: ["Volume"] - - /volumes/{name}: - get: - summary: "Inspect a volume" - operationId: "VolumeInspect" - produces: ["application/json"] - responses: - 200: - description: "No error" - schema: - $ref: "#/definitions/Volume" - 404: - description: "No such volume" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - required: true - description: "Volume name or ID" - type: "string" - tags: ["Volume"] - - put: - summary: | - "Update a volume. Valid only for Swarm cluster volumes" - operationId: "VolumeUpdate" - consumes: ["application/json"] - produces: ["application/json"] - responses: - 200: - description: "no error" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such volume" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: "The name or ID of the volume" - type: "string" - required: true - - name: "body" - in: "body" - schema: - # though the schema for is an object that contains only a - # ClusterVolumeSpec, wrapping the ClusterVolumeSpec in this object - # means that if, later on, we support things like changing the - # labels, we can do so without duplicating that information to the - # ClusterVolumeSpec. - type: "object" - description: "Volume configuration" - properties: - Spec: - $ref: "#/definitions/ClusterVolumeSpec" - description: | - The spec of the volume to update. Currently, only Availability may - change. All other fields must remain unchanged. - - name: "version" - in: "query" - description: | - The version number of the volume being updated. This is required to - avoid conflicting writes. Found in the volume's `ClusterVolume` - field. - type: "integer" - format: "int64" - required: true - tags: ["Volume"] - - delete: - summary: "Remove a volume" - description: "Instruct the driver to remove the volume." - operationId: "VolumeDelete" - responses: - 204: - description: "The volume was removed" - 404: - description: "No such volume or volume driver" - schema: - $ref: "#/definitions/ErrorResponse" - 409: - description: "Volume is in use and cannot be removed" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - required: true - description: "Volume name or ID" - type: "string" - - name: "force" - in: "query" - description: "Force the removal of the volume" - type: "boolean" - default: false - tags: ["Volume"] - - /volumes/prune: - post: - summary: "Delete unused volumes" - produces: - - "application/json" - operationId: "VolumePrune" - parameters: - - name: "filters" - in: "query" - description: | - Filters to process on the prune list, encoded as JSON (a `map[string][]string`). - - Available filters: - - `label` (`label=`, `label==`, `label!=`, or `label!==`) Prune volumes with (or without, in case `label!=...` is used) the specified labels. - - `all` (`all=true`) - Consider all (local) volumes for pruning and not just anonymous volumes. - type: "string" - responses: - 200: - description: "No error" - schema: - type: "object" - title: "VolumePruneResponse" - properties: - VolumesDeleted: - description: "Volumes that were deleted" - type: "array" - items: - type: "string" - SpaceReclaimed: - description: "Disk space reclaimed in bytes" - type: "integer" - format: "int64" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Volume"] - /networks: - get: - summary: "List networks" - description: | - Returns a list of networks. For details on the format, see the - [network inspect endpoint](#operation/NetworkInspect). - - Note that it uses a different, smaller representation of a network than - inspecting a single network. For example, the list of containers attached - to the network is not propagated in API versions 1.28 and up. - operationId: "NetworkList" - produces: - - "application/json" - responses: - 200: - description: "No error" - schema: - type: "array" - items: - $ref: "#/definitions/Network" - examples: - application/json: - - Name: "bridge" - Id: "f2de39df4171b0dc801e8002d1d999b77256983dfc63041c0f34030aa3977566" - Created: "2016-10-19T06:21:00.416543526Z" - Scope: "local" - Driver: "bridge" - EnableIPv6: false - Internal: false - Attachable: false - Ingress: false - IPAM: - Driver: "default" - Config: - - - Subnet: "172.17.0.0/16" - Options: - com.docker.network.bridge.default_bridge: "true" - com.docker.network.bridge.enable_icc: "true" - com.docker.network.bridge.enable_ip_masquerade: "true" - com.docker.network.bridge.host_binding_ipv4: "0.0.0.0" - com.docker.network.bridge.name: "docker0" - com.docker.network.driver.mtu: "1500" - - Name: "none" - Id: "e086a3893b05ab69242d3c44e49483a3bbbd3a26b46baa8f61ab797c1088d794" - Created: "0001-01-01T00:00:00Z" - Scope: "local" - Driver: "null" - EnableIPv6: false - Internal: false - Attachable: false - Ingress: false - IPAM: - Driver: "default" - Config: [] - Containers: {} - Options: {} - - Name: "host" - Id: "13e871235c677f196c4e1ecebb9dc733b9b2d2ab589e30c539efeda84a24215e" - Created: "0001-01-01T00:00:00Z" - Scope: "local" - Driver: "host" - EnableIPv6: false - Internal: false - Attachable: false - Ingress: false - IPAM: - Driver: "default" - Config: [] - Containers: {} - Options: {} - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "filters" - in: "query" - description: | - JSON encoded value of the filters (a `map[string][]string`) to process - on the networks list. - - Available filters: - - - `dangling=` When set to `true` (or `1`), returns all - networks that are not in use by a container. When set to `false` - (or `0`), only networks that are in use by one or more - containers are returned. - - `driver=` Matches a network's driver. - - `id=` Matches all or part of a network ID. - - `label=` or `label==` of a network label. - - `name=` Matches all or part of a network name. - - `scope=["swarm"|"global"|"local"]` Filters networks by scope (`swarm`, `global`, or `local`). - - `type=["custom"|"builtin"]` Filters networks by type. The `custom` keyword returns all user-defined networks. - type: "string" - tags: ["Network"] - - /networks/{id}: - get: - summary: "Inspect a network" - operationId: "NetworkInspect" - produces: - - "application/json" - responses: - 200: - description: "No error" - schema: - $ref: "#/definitions/Network" - 404: - description: "Network not found" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "Network ID or name" - required: true - type: "string" - - name: "verbose" - in: "query" - description: "Detailed inspect output for troubleshooting" - type: "boolean" - default: false - - name: "scope" - in: "query" - description: "Filter the network by scope (swarm, global, or local)" - type: "string" - tags: ["Network"] - - delete: - summary: "Remove a network" - operationId: "NetworkDelete" - responses: - 204: - description: "No error" - 403: - description: "operation not supported for pre-defined networks" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such network" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "Network ID or name" - required: true - type: "string" - tags: ["Network"] - - /networks/create: - post: - summary: "Create a network" - operationId: "NetworkCreate" - consumes: - - "application/json" - produces: - - "application/json" - responses: - 201: - description: "No error" - schema: - type: "object" - title: "NetworkCreateResponse" - properties: - Id: - description: "The ID of the created network." - type: "string" - Warning: - type: "string" - example: - Id: "22be93d5babb089c5aab8dbc369042fad48ff791584ca2da2100db837a1c7c30" - Warning: "" - 403: - description: | - Forbidden operation. This happens when trying to create a network named after a pre-defined network, - or when trying to create an overlay network on a daemon which is not part of a Swarm cluster. - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "plugin not found" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "networkConfig" - in: "body" - description: "Network configuration" - required: true - schema: - type: "object" - title: "NetworkCreateRequest" - required: ["Name"] - properties: - Name: - description: "The network's name." - type: "string" - CheckDuplicate: - description: | - Check for networks with duplicate names. Since Network is - primarily keyed based on a random ID and not on the name, and - network name is strictly a user-friendly alias to the network - which is uniquely identified using ID, there is no guaranteed - way to check for duplicates. CheckDuplicate is there to provide - a best effort checking of any networks which has the same name - but it is not guaranteed to catch all name collisions. - type: "boolean" - Driver: - description: "Name of the network driver plugin to use." - type: "string" - default: "bridge" - Internal: - description: "Restrict external access to the network." - type: "boolean" - Attachable: - description: | - Globally scoped network is manually attachable by regular - containers from workers in swarm mode. - type: "boolean" - Ingress: - description: | - Ingress network is the network which provides the routing-mesh - in swarm mode. - type: "boolean" - IPAM: - description: "Optional custom IP scheme for the network." - $ref: "#/definitions/IPAM" - EnableIPv6: - description: "Enable IPv6 on the network." - type: "boolean" - Options: - description: "Network specific options to be used by the drivers." - type: "object" - additionalProperties: - type: "string" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - example: - Name: "isolated_nw" - CheckDuplicate: false - Driver: "bridge" - EnableIPv6: true - IPAM: - Driver: "default" - Config: - - Subnet: "172.20.0.0/16" - IPRange: "172.20.10.0/24" - Gateway: "172.20.10.11" - - Subnet: "2001:db8:abcd::/64" - Gateway: "2001:db8:abcd::1011" - Options: - foo: "bar" - Internal: true - Attachable: false - Ingress: false - Options: - com.docker.network.bridge.default_bridge: "true" - com.docker.network.bridge.enable_icc: "true" - com.docker.network.bridge.enable_ip_masquerade: "true" - com.docker.network.bridge.host_binding_ipv4: "0.0.0.0" - com.docker.network.bridge.name: "docker0" - com.docker.network.driver.mtu: "1500" - Labels: - com.example.some-label: "some-value" - com.example.some-other-label: "some-other-value" - tags: ["Network"] - - /networks/{id}/connect: - post: - summary: "Connect a container to a network" - operationId: "NetworkConnect" - consumes: - - "application/json" - responses: - 200: - description: "No error" - 403: - description: "Operation not supported for swarm scoped networks" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "Network or container not found" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "Network ID or name" - required: true - type: "string" - - name: "container" - in: "body" - required: true - schema: - type: "object" - title: "NetworkConnectRequest" - properties: - Container: - type: "string" - description: "The ID or name of the container to connect to the network." - EndpointConfig: - $ref: "#/definitions/EndpointSettings" - example: - Container: "3613f73ba0e4" - EndpointConfig: - IPAMConfig: - IPv4Address: "172.24.56.89" - IPv6Address: "2001:db8::5689" - tags: ["Network"] - - /networks/{id}/disconnect: - post: - summary: "Disconnect a container from a network" - operationId: "NetworkDisconnect" - consumes: - - "application/json" - responses: - 200: - description: "No error" - 403: - description: "Operation not supported for swarm scoped networks" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "Network or container not found" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "Network ID or name" - required: true - type: "string" - - name: "container" - in: "body" - required: true - schema: - type: "object" - title: "NetworkDisconnectRequest" - properties: - Container: - type: "string" - description: | - The ID or name of the container to disconnect from the network. - Force: - type: "boolean" - description: | - Force the container to disconnect from the network. - tags: ["Network"] - /networks/prune: - post: - summary: "Delete unused networks" - produces: - - "application/json" - operationId: "NetworkPrune" - parameters: - - name: "filters" - in: "query" - description: | - Filters to process on the prune list, encoded as JSON (a `map[string][]string`). - - Available filters: - - `until=` Prune networks created before this timestamp. The `` can be Unix timestamps, date formatted timestamps, or Go duration strings (e.g. `10m`, `1h30m`) computed relative to the daemon machine’s time. - - `label` (`label=`, `label==`, `label!=`, or `label!==`) Prune networks with (or without, in case `label!=...` is used) the specified labels. - type: "string" - responses: - 200: - description: "No error" - schema: - type: "object" - title: "NetworkPruneResponse" - properties: - NetworksDeleted: - description: "Networks that were deleted" - type: "array" - items: - type: "string" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Network"] - /plugins: - get: - summary: "List plugins" - operationId: "PluginList" - description: "Returns information about installed plugins." - produces: ["application/json"] - responses: - 200: - description: "No error" - schema: - type: "array" - items: - $ref: "#/definitions/Plugin" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "filters" - in: "query" - type: "string" - description: | - A JSON encoded value of the filters (a `map[string][]string`) to - process on the plugin list. - - Available filters: - - - `capability=` - - `enable=|` - tags: ["Plugin"] - - /plugins/privileges: - get: - summary: "Get plugin privileges" - operationId: "GetPluginPrivileges" - responses: - 200: - description: "no error" - schema: - type: "array" - items: - $ref: "#/definitions/PluginPrivilege" - example: - - Name: "network" - Description: "" - Value: - - "host" - - Name: "mount" - Description: "" - Value: - - "/data" - - Name: "device" - Description: "" - Value: - - "/dev/cpu_dma_latency" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "remote" - in: "query" - description: | - The name of the plugin. The `:latest` tag is optional, and is the - default if omitted. - required: true - type: "string" - tags: - - "Plugin" - - /plugins/pull: - post: - summary: "Install a plugin" - operationId: "PluginPull" - description: | - Pulls and installs a plugin. After the plugin is installed, it can be - enabled using the [`POST /plugins/{name}/enable` endpoint](#operation/PostPluginsEnable). - produces: - - "application/json" - responses: - 204: - description: "no error" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "remote" - in: "query" - description: | - Remote reference for plugin to install. - - The `:latest` tag is optional, and is used as the default if omitted. - required: true - type: "string" - - name: "name" - in: "query" - description: | - Local name for the pulled plugin. - - The `:latest` tag is optional, and is used as the default if omitted. - required: false - type: "string" - - name: "X-Registry-Auth" - in: "header" - description: | - A base64url-encoded auth configuration to use when pulling a plugin - from a registry. - - Refer to the [authentication section](#section/Authentication) for - details. - type: "string" - - name: "body" - in: "body" - schema: - type: "array" - items: - $ref: "#/definitions/PluginPrivilege" - example: - - Name: "network" - Description: "" - Value: - - "host" - - Name: "mount" - Description: "" - Value: - - "/data" - - Name: "device" - Description: "" - Value: - - "/dev/cpu_dma_latency" - tags: ["Plugin"] - /plugins/{name}/json: - get: - summary: "Inspect a plugin" - operationId: "PluginInspect" - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/Plugin" - 404: - description: "plugin is not installed" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: | - The name of the plugin. The `:latest` tag is optional, and is the - default if omitted. - required: true - type: "string" - tags: ["Plugin"] - /plugins/{name}: - delete: - summary: "Remove a plugin" - operationId: "PluginDelete" - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/Plugin" - 404: - description: "plugin is not installed" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: | - The name of the plugin. The `:latest` tag is optional, and is the - default if omitted. - required: true - type: "string" - - name: "force" - in: "query" - description: | - Disable the plugin before removing. This may result in issues if the - plugin is in use by a container. - type: "boolean" - default: false - tags: ["Plugin"] - /plugins/{name}/enable: - post: - summary: "Enable a plugin" - operationId: "PluginEnable" - responses: - 200: - description: "no error" - 404: - description: "plugin is not installed" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: | - The name of the plugin. The `:latest` tag is optional, and is the - default if omitted. - required: true - type: "string" - - name: "timeout" - in: "query" - description: "Set the HTTP client timeout (in seconds)" - type: "integer" - default: 0 - tags: ["Plugin"] - /plugins/{name}/disable: - post: - summary: "Disable a plugin" - operationId: "PluginDisable" - responses: - 200: - description: "no error" - 404: - description: "plugin is not installed" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: | - The name of the plugin. The `:latest` tag is optional, and is the - default if omitted. - required: true - type: "string" - - name: "force" - in: "query" - description: | - Force disable a plugin even if still in use. - required: false - type: "boolean" - tags: ["Plugin"] - /plugins/{name}/upgrade: - post: - summary: "Upgrade a plugin" - operationId: "PluginUpgrade" - responses: - 204: - description: "no error" - 404: - description: "plugin not installed" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: | - The name of the plugin. The `:latest` tag is optional, and is the - default if omitted. - required: true - type: "string" - - name: "remote" - in: "query" - description: | - Remote reference to upgrade to. - - The `:latest` tag is optional, and is used as the default if omitted. - required: true - type: "string" - - name: "X-Registry-Auth" - in: "header" - description: | - A base64url-encoded auth configuration to use when pulling a plugin - from a registry. - - Refer to the [authentication section](#section/Authentication) for - details. - type: "string" - - name: "body" - in: "body" - schema: - type: "array" - items: - $ref: "#/definitions/PluginPrivilege" - example: - - Name: "network" - Description: "" - Value: - - "host" - - Name: "mount" - Description: "" - Value: - - "/data" - - Name: "device" - Description: "" - Value: - - "/dev/cpu_dma_latency" - tags: ["Plugin"] - /plugins/create: - post: - summary: "Create a plugin" - operationId: "PluginCreate" - consumes: - - "application/x-tar" - responses: - 204: - description: "no error" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "query" - description: | - The name of the plugin. The `:latest` tag is optional, and is the - default if omitted. - required: true - type: "string" - - name: "tarContext" - in: "body" - description: "Path to tar containing plugin rootfs and manifest" - schema: - type: "string" - format: "binary" - tags: ["Plugin"] - /plugins/{name}/push: - post: - summary: "Push a plugin" - operationId: "PluginPush" - description: | - Push a plugin to the registry. - parameters: - - name: "name" - in: "path" - description: | - The name of the plugin. The `:latest` tag is optional, and is the - default if omitted. - required: true - type: "string" - responses: - 200: - description: "no error" - 404: - description: "plugin not installed" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Plugin"] - /plugins/{name}/set: - post: - summary: "Configure a plugin" - operationId: "PluginSet" - consumes: - - "application/json" - parameters: - - name: "name" - in: "path" - description: | - The name of the plugin. The `:latest` tag is optional, and is the - default if omitted. - required: true - type: "string" - - name: "body" - in: "body" - schema: - type: "array" - items: - type: "string" - example: ["DEBUG=1"] - responses: - 204: - description: "No error" - 404: - description: "Plugin not installed" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Plugin"] - /nodes: - get: - summary: "List nodes" - operationId: "NodeList" - responses: - 200: - description: "no error" - schema: - type: "array" - items: - $ref: "#/definitions/Node" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "filters" - in: "query" - description: | - Filters to process on the nodes list, encoded as JSON (a `map[string][]string`). - - Available filters: - - `id=` - - `label=` - - `membership=`(`accepted`|`pending`)` - - `name=` - - `node.label=` - - `role=`(`manager`|`worker`)` - type: "string" - tags: ["Node"] - /nodes/{id}: - get: - summary: "Inspect a node" - operationId: "NodeInspect" - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/Node" - 404: - description: "no such node" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "The ID or name of the node" - type: "string" - required: true - tags: ["Node"] - delete: - summary: "Delete a node" - operationId: "NodeDelete" - responses: - 200: - description: "no error" - 404: - description: "no such node" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "The ID or name of the node" - type: "string" - required: true - - name: "force" - in: "query" - description: "Force remove a node from the swarm" - default: false - type: "boolean" - tags: ["Node"] - /nodes/{id}/update: - post: - summary: "Update a node" - operationId: "NodeUpdate" - responses: - 200: - description: "no error" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such node" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "The ID of the node" - type: "string" - required: true - - name: "body" - in: "body" - schema: - $ref: "#/definitions/NodeSpec" - - name: "version" - in: "query" - description: | - The version number of the node object being updated. This is required - to avoid conflicting writes. - type: "integer" - format: "int64" - required: true - tags: ["Node"] - /swarm: - get: - summary: "Inspect swarm" - operationId: "SwarmInspect" - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/Swarm" - 404: - description: "no such swarm" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Swarm"] - /swarm/init: - post: - summary: "Initialize a new swarm" - operationId: "SwarmInit" - produces: - - "application/json" - - "text/plain" - responses: - 200: - description: "no error" - schema: - description: "The node ID" - type: "string" - example: "7v2t30z9blmxuhnyo6s4cpenp" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is already part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "body" - in: "body" - required: true - schema: - type: "object" - title: "SwarmInitRequest" - properties: - ListenAddr: - description: | - Listen address used for inter-manager communication, as well - as determining the networking interface used for the VXLAN - Tunnel Endpoint (VTEP). This can either be an address/port - combination in the form `192.168.1.1:4567`, or an interface - followed by a port number, like `eth0:4567`. If the port number - is omitted, the default swarm listening port is used. - type: "string" - AdvertiseAddr: - description: | - Externally reachable address advertised to other nodes. This - can either be an address/port combination in the form - `192.168.1.1:4567`, or an interface followed by a port number, - like `eth0:4567`. If the port number is omitted, the port - number from the listen address is used. If `AdvertiseAddr` is - not specified, it will be automatically detected when possible. - type: "string" - DataPathAddr: - description: | - Address or interface to use for data path traffic (format: - ``), for example, `192.168.1.1`, or an interface, - like `eth0`. If `DataPathAddr` is unspecified, the same address - as `AdvertiseAddr` is used. - - The `DataPathAddr` specifies the address that global scope - network drivers will publish towards other nodes in order to - reach the containers running on this node. Using this parameter - it is possible to separate the container data traffic from the - management traffic of the cluster. - type: "string" - DataPathPort: - description: | - DataPathPort specifies the data path port number for data traffic. - Acceptable port range is 1024 to 49151. - if no port is set or is set to 0, default port 4789 will be used. - type: "integer" - format: "uint32" - DefaultAddrPool: - description: | - Default Address Pool specifies default subnet pools for global - scope networks. - type: "array" - items: - type: "string" - example: ["10.10.0.0/16", "20.20.0.0/16"] - ForceNewCluster: - description: "Force creation of a new swarm." - type: "boolean" - SubnetSize: - description: | - SubnetSize specifies the subnet size of the networks created - from the default subnet pool. - type: "integer" - format: "uint32" - Spec: - $ref: "#/definitions/SwarmSpec" - example: - ListenAddr: "0.0.0.0:2377" - AdvertiseAddr: "192.168.1.1:2377" - DataPathPort: 4789 - DefaultAddrPool: ["10.10.0.0/8", "20.20.0.0/8"] - SubnetSize: 24 - ForceNewCluster: false - Spec: - Orchestration: {} - Raft: {} - Dispatcher: {} - CAConfig: {} - EncryptionConfig: - AutoLockManagers: false - tags: ["Swarm"] - /swarm/join: - post: - summary: "Join an existing swarm" - operationId: "SwarmJoin" - responses: - 200: - description: "no error" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is already part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "body" - in: "body" - required: true - schema: - type: "object" - title: "SwarmJoinRequest" - properties: - ListenAddr: - description: | - Listen address used for inter-manager communication if the node - gets promoted to manager, as well as determining the networking - interface used for the VXLAN Tunnel Endpoint (VTEP). - type: "string" - AdvertiseAddr: - description: | - Externally reachable address advertised to other nodes. This - can either be an address/port combination in the form - `192.168.1.1:4567`, or an interface followed by a port number, - like `eth0:4567`. If the port number is omitted, the port - number from the listen address is used. If `AdvertiseAddr` is - not specified, it will be automatically detected when possible. - type: "string" - DataPathAddr: - description: | - Address or interface to use for data path traffic (format: - ``), for example, `192.168.1.1`, or an interface, - like `eth0`. If `DataPathAddr` is unspecified, the same address - as `AdvertiseAddr` is used. - - The `DataPathAddr` specifies the address that global scope - network drivers will publish towards other nodes in order to - reach the containers running on this node. Using this parameter - it is possible to separate the container data traffic from the - management traffic of the cluster. - - type: "string" - RemoteAddrs: - description: | - Addresses of manager nodes already participating in the swarm. - type: "array" - items: - type: "string" - JoinToken: - description: "Secret token for joining this swarm." - type: "string" - example: - ListenAddr: "0.0.0.0:2377" - AdvertiseAddr: "192.168.1.1:2377" - RemoteAddrs: - - "node1:2377" - JoinToken: "SWMTKN-1-3pu6hszjas19xyp7ghgosyx9k8atbfcr8p2is99znpy26u2lkl-7p73s1dx5in4tatdymyhg9hu2" - tags: ["Swarm"] - /swarm/leave: - post: - summary: "Leave a swarm" - operationId: "SwarmLeave" - responses: - 200: - description: "no error" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "force" - description: | - Force leave swarm, even if this is the last manager or that it will - break the cluster. - in: "query" - type: "boolean" - default: false - tags: ["Swarm"] - /swarm/update: - post: - summary: "Update a swarm" - operationId: "SwarmUpdate" - responses: - 200: - description: "no error" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "body" - in: "body" - required: true - schema: - $ref: "#/definitions/SwarmSpec" - - name: "version" - in: "query" - description: | - The version number of the swarm object being updated. This is - required to avoid conflicting writes. - type: "integer" - format: "int64" - required: true - - name: "rotateWorkerToken" - in: "query" - description: "Rotate the worker join token." - type: "boolean" - default: false - - name: "rotateManagerToken" - in: "query" - description: "Rotate the manager join token." - type: "boolean" - default: false - - name: "rotateManagerUnlockKey" - in: "query" - description: "Rotate the manager unlock key." - type: "boolean" - default: false - tags: ["Swarm"] - /swarm/unlockkey: - get: - summary: "Get the unlock key" - operationId: "SwarmUnlockkey" - consumes: - - "application/json" - responses: - 200: - description: "no error" - schema: - type: "object" - title: "UnlockKeyResponse" - properties: - UnlockKey: - description: "The swarm's unlock key." - type: "string" - example: - UnlockKey: "SWMKEY-1-7c37Cc8654o6p38HnroywCi19pllOnGtbdZEgtKxZu8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Swarm"] - /swarm/unlock: - post: - summary: "Unlock a locked manager" - operationId: "SwarmUnlock" - consumes: - - "application/json" - produces: - - "application/json" - parameters: - - name: "body" - in: "body" - required: true - schema: - type: "object" - title: "SwarmUnlockRequest" - properties: - UnlockKey: - description: "The swarm's unlock key." - type: "string" - example: - UnlockKey: "SWMKEY-1-7c37Cc8654o6p38HnroywCi19pllOnGtbdZEgtKxZu8" - responses: - 200: - description: "no error" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Swarm"] - /services: - get: - summary: "List services" - operationId: "ServiceList" - responses: - 200: - description: "no error" - schema: - type: "array" - items: - $ref: "#/definitions/Service" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "filters" - in: "query" - type: "string" - description: | - A JSON encoded value of the filters (a `map[string][]string`) to - process on the services list. - - Available filters: - - - `id=` - - `label=` - - `mode=["replicated"|"global"]` - - `name=` - - name: "status" - in: "query" - type: "boolean" - description: | - Include service status, with count of running and desired tasks. - tags: ["Service"] - /services/create: - post: - summary: "Create a service" - operationId: "ServiceCreate" - consumes: - - "application/json" - produces: - - "application/json" - responses: - 201: - description: "no error" - schema: - type: "object" - title: "ServiceCreateResponse" - properties: - ID: - description: "The ID of the created service." - type: "string" - Warning: - description: "Optional warning message" - type: "string" - example: - ID: "ak7w3gjqoa3kuz8xcpnyy0pvl" - Warning: "unable to pin image doesnotexist:latest to digest: image library/doesnotexist:latest not found" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 403: - description: "network is not eligible for services" - schema: - $ref: "#/definitions/ErrorResponse" - 409: - description: "name conflicts with an existing service" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "body" - in: "body" - required: true - schema: - allOf: - - $ref: "#/definitions/ServiceSpec" - - type: "object" - example: - Name: "web" - TaskTemplate: - ContainerSpec: - Image: "nginx:alpine" - Mounts: - - - ReadOnly: true - Source: "web-data" - Target: "/usr/share/nginx/html" - Type: "volume" - VolumeOptions: - DriverConfig: {} - Labels: - com.example.something: "something-value" - Hosts: ["10.10.10.10 host1", "ABCD:EF01:2345:6789:ABCD:EF01:2345:6789 host2"] - User: "33" - DNSConfig: - Nameservers: ["8.8.8.8"] - Search: ["example.org"] - Options: ["timeout:3"] - Secrets: - - - File: - Name: "www.example.org.key" - UID: "33" - GID: "33" - Mode: 384 - SecretID: "fpjqlhnwb19zds35k8wn80lq9" - SecretName: "example_org_domain_key" - LogDriver: - Name: "json-file" - Options: - max-file: "3" - max-size: "10M" - Placement: {} - Resources: - Limits: - MemoryBytes: 104857600 - Reservations: {} - RestartPolicy: - Condition: "on-failure" - Delay: 10000000000 - MaxAttempts: 10 - Mode: - Replicated: - Replicas: 4 - UpdateConfig: - Parallelism: 2 - Delay: 1000000000 - FailureAction: "pause" - Monitor: 15000000000 - MaxFailureRatio: 0.15 - RollbackConfig: - Parallelism: 1 - Delay: 1000000000 - FailureAction: "pause" - Monitor: 15000000000 - MaxFailureRatio: 0.15 - EndpointSpec: - Ports: - - - Protocol: "tcp" - PublishedPort: 8080 - TargetPort: 80 - Labels: - foo: "bar" - - name: "X-Registry-Auth" - in: "header" - description: | - A base64url-encoded auth configuration for pulling from private - registries. - - Refer to the [authentication section](#section/Authentication) for - details. - type: "string" - tags: ["Service"] - /services/{id}: - get: - summary: "Inspect a service" - operationId: "ServiceInspect" - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/Service" - 404: - description: "no such service" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "ID or name of service." - required: true - type: "string" - - name: "insertDefaults" - in: "query" - description: "Fill empty fields with default values." - type: "boolean" - default: false - tags: ["Service"] - delete: - summary: "Delete a service" - operationId: "ServiceDelete" - responses: - 200: - description: "no error" - 404: - description: "no such service" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "ID or name of service." - required: true - type: "string" - tags: ["Service"] - /services/{id}/update: - post: - summary: "Update a service" - operationId: "ServiceUpdate" - consumes: ["application/json"] - produces: ["application/json"] - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/ServiceUpdateResponse" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such service" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "ID or name of service." - required: true - type: "string" - - name: "body" - in: "body" - required: true - schema: - allOf: - - $ref: "#/definitions/ServiceSpec" - - type: "object" - example: - Name: "top" - TaskTemplate: - ContainerSpec: - Image: "busybox" - Args: - - "top" - Resources: - Limits: {} - Reservations: {} - RestartPolicy: - Condition: "any" - MaxAttempts: 0 - Placement: {} - ForceUpdate: 0 - Mode: - Replicated: - Replicas: 1 - UpdateConfig: - Parallelism: 2 - Delay: 1000000000 - FailureAction: "pause" - Monitor: 15000000000 - MaxFailureRatio: 0.15 - RollbackConfig: - Parallelism: 1 - Delay: 1000000000 - FailureAction: "pause" - Monitor: 15000000000 - MaxFailureRatio: 0.15 - EndpointSpec: - Mode: "vip" - - - name: "version" - in: "query" - description: | - The version number of the service object being updated. This is - required to avoid conflicting writes. - This version number should be the value as currently set on the - service *before* the update. You can find the current version by - calling `GET /services/{id}` - required: true - type: "integer" - - name: "registryAuthFrom" - in: "query" - description: | - If the `X-Registry-Auth` header is not specified, this parameter - indicates where to find registry authorization credentials. - type: "string" - enum: ["spec", "previous-spec"] - default: "spec" - - name: "rollback" - in: "query" - description: | - Set to this parameter to `previous` to cause a server-side rollback - to the previous service spec. The supplied spec will be ignored in - this case. - type: "string" - - name: "X-Registry-Auth" - in: "header" - description: | - A base64url-encoded auth configuration for pulling from private - registries. - - Refer to the [authentication section](#section/Authentication) for - details. - type: "string" - - tags: ["Service"] - /services/{id}/logs: - get: - summary: "Get service logs" - description: | - Get `stdout` and `stderr` logs from a service. See also - [`/containers/{id}/logs`](#operation/ContainerLogs). - - **Note**: This endpoint works only for services with the `local`, - `json-file` or `journald` logging drivers. - produces: - - "application/vnd.docker.raw-stream" - - "application/vnd.docker.multiplexed-stream" - operationId: "ServiceLogs" - responses: - 200: - description: "logs returned as a stream in response body" - schema: - type: "string" - format: "binary" - 404: - description: "no such service" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such service: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the service" - type: "string" - - name: "details" - in: "query" - description: "Show service context and extra details provided to logs." - type: "boolean" - default: false - - name: "follow" - in: "query" - description: "Keep connection after returning logs." - type: "boolean" - default: false - - name: "stdout" - in: "query" - description: "Return logs from `stdout`" - type: "boolean" - default: false - - name: "stderr" - in: "query" - description: "Return logs from `stderr`" - type: "boolean" - default: false - - name: "since" - in: "query" - description: "Only return logs since this time, as a UNIX timestamp" - type: "integer" - default: 0 - - name: "timestamps" - in: "query" - description: "Add timestamps to every log line" - type: "boolean" - default: false - - name: "tail" - in: "query" - description: | - Only return this number of log lines from the end of the logs. - Specify as an integer or `all` to output all log lines. - type: "string" - default: "all" - tags: ["Service"] - /tasks: - get: - summary: "List tasks" - operationId: "TaskList" - produces: - - "application/json" - responses: - 200: - description: "no error" - schema: - type: "array" - items: - $ref: "#/definitions/Task" - example: - - ID: "0kzzo1i0y4jz6027t0k7aezc7" - Version: - Index: 71 - CreatedAt: "2016-06-07T21:07:31.171892745Z" - UpdatedAt: "2016-06-07T21:07:31.376370513Z" - Spec: - ContainerSpec: - Image: "redis" - Resources: - Limits: {} - Reservations: {} - RestartPolicy: - Condition: "any" - MaxAttempts: 0 - Placement: {} - ServiceID: "9mnpnzenvg8p8tdbtq4wvbkcz" - Slot: 1 - NodeID: "60gvrl6tm78dmak4yl7srz94v" - Status: - Timestamp: "2016-06-07T21:07:31.290032978Z" - State: "running" - Message: "started" - ContainerStatus: - ContainerID: "e5d62702a1b48d01c3e02ca1e0212a250801fa8d67caca0b6f35919ebc12f035" - PID: 677 - DesiredState: "running" - NetworksAttachments: - - Network: - ID: "4qvuz4ko70xaltuqbt8956gd1" - Version: - Index: 18 - CreatedAt: "2016-06-07T20:31:11.912919752Z" - UpdatedAt: "2016-06-07T21:07:29.955277358Z" - Spec: - Name: "ingress" - Labels: - com.docker.swarm.internal: "true" - DriverConfiguration: {} - IPAMOptions: - Driver: {} - Configs: - - Subnet: "10.255.0.0/16" - Gateway: "10.255.0.1" - DriverState: - Name: "overlay" - Options: - com.docker.network.driver.overlay.vxlanid_list: "256" - IPAMOptions: - Driver: - Name: "default" - Configs: - - Subnet: "10.255.0.0/16" - Gateway: "10.255.0.1" - Addresses: - - "10.255.0.10/16" - - ID: "1yljwbmlr8er2waf8orvqpwms" - Version: - Index: 30 - CreatedAt: "2016-06-07T21:07:30.019104782Z" - UpdatedAt: "2016-06-07T21:07:30.231958098Z" - Name: "hopeful_cori" - Spec: - ContainerSpec: - Image: "redis" - Resources: - Limits: {} - Reservations: {} - RestartPolicy: - Condition: "any" - MaxAttempts: 0 - Placement: {} - ServiceID: "9mnpnzenvg8p8tdbtq4wvbkcz" - Slot: 1 - NodeID: "60gvrl6tm78dmak4yl7srz94v" - Status: - Timestamp: "2016-06-07T21:07:30.202183143Z" - State: "shutdown" - Message: "shutdown" - ContainerStatus: - ContainerID: "1cf8d63d18e79668b0004a4be4c6ee58cddfad2dae29506d8781581d0688a213" - DesiredState: "shutdown" - NetworksAttachments: - - Network: - ID: "4qvuz4ko70xaltuqbt8956gd1" - Version: - Index: 18 - CreatedAt: "2016-06-07T20:31:11.912919752Z" - UpdatedAt: "2016-06-07T21:07:29.955277358Z" - Spec: - Name: "ingress" - Labels: - com.docker.swarm.internal: "true" - DriverConfiguration: {} - IPAMOptions: - Driver: {} - Configs: - - Subnet: "10.255.0.0/16" - Gateway: "10.255.0.1" - DriverState: - Name: "overlay" - Options: - com.docker.network.driver.overlay.vxlanid_list: "256" - IPAMOptions: - Driver: - Name: "default" - Configs: - - Subnet: "10.255.0.0/16" - Gateway: "10.255.0.1" - Addresses: - - "10.255.0.5/16" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "filters" - in: "query" - type: "string" - description: | - A JSON encoded value of the filters (a `map[string][]string`) to - process on the tasks list. - - Available filters: - - - `desired-state=(running | shutdown | accepted)` - - `id=` - - `label=key` or `label="key=value"` - - `name=` - - `node=` - - `service=` - tags: ["Task"] - /tasks/{id}: - get: - summary: "Inspect a task" - operationId: "TaskInspect" - produces: - - "application/json" - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/Task" - 404: - description: "no such task" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "ID of the task" - required: true - type: "string" - tags: ["Task"] - /tasks/{id}/logs: - get: - summary: "Get task logs" - description: | - Get `stdout` and `stderr` logs from a task. - See also [`/containers/{id}/logs`](#operation/ContainerLogs). - - **Note**: This endpoint works only for services with the `local`, - `json-file` or `journald` logging drivers. - operationId: "TaskLogs" - produces: - - "application/vnd.docker.raw-stream" - - "application/vnd.docker.multiplexed-stream" - responses: - 200: - description: "logs returned as a stream in response body" - schema: - type: "string" - format: "binary" - 404: - description: "no such task" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such task: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID of the task" - type: "string" - - name: "details" - in: "query" - description: "Show task context and extra details provided to logs." - type: "boolean" - default: false - - name: "follow" - in: "query" - description: "Keep connection after returning logs." - type: "boolean" - default: false - - name: "stdout" - in: "query" - description: "Return logs from `stdout`" - type: "boolean" - default: false - - name: "stderr" - in: "query" - description: "Return logs from `stderr`" - type: "boolean" - default: false - - name: "since" - in: "query" - description: "Only return logs since this time, as a UNIX timestamp" - type: "integer" - default: 0 - - name: "timestamps" - in: "query" - description: "Add timestamps to every log line" - type: "boolean" - default: false - - name: "tail" - in: "query" - description: | - Only return this number of log lines from the end of the logs. - Specify as an integer or `all` to output all log lines. - type: "string" - default: "all" - tags: ["Task"] - /secrets: - get: - summary: "List secrets" - operationId: "SecretList" - produces: - - "application/json" - responses: - 200: - description: "no error" - schema: - type: "array" - items: - $ref: "#/definitions/Secret" - example: - - ID: "blt1owaxmitz71s9v5zh81zun" - Version: - Index: 85 - CreatedAt: "2017-07-20T13:55:28.678958722Z" - UpdatedAt: "2017-07-20T13:55:28.678958722Z" - Spec: - Name: "mysql-passwd" - Labels: - some.label: "some.value" - Driver: - Name: "secret-bucket" - Options: - OptionA: "value for driver option A" - OptionB: "value for driver option B" - - ID: "ktnbjxoalbkvbvedmg1urrz8h" - Version: - Index: 11 - CreatedAt: "2016-11-05T01:20:17.327670065Z" - UpdatedAt: "2016-11-05T01:20:17.327670065Z" - Spec: - Name: "app-dev.crt" - Labels: - foo: "bar" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "filters" - in: "query" - type: "string" - description: | - A JSON encoded value of the filters (a `map[string][]string`) to - process on the secrets list. - - Available filters: - - - `id=` - - `label= or label==value` - - `name=` - - `names=` - tags: ["Secret"] - /secrets/create: - post: - summary: "Create a secret" - operationId: "SecretCreate" - consumes: - - "application/json" - produces: - - "application/json" - responses: - 201: - description: "no error" - schema: - $ref: "#/definitions/IdResponse" - 409: - description: "name conflicts with an existing object" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "body" - in: "body" - schema: - allOf: - - $ref: "#/definitions/SecretSpec" - - type: "object" - example: - Name: "app-key.crt" - Labels: - foo: "bar" - Data: "VEhJUyBJUyBOT1QgQSBSRUFMIENFUlRJRklDQVRFCg==" - Driver: - Name: "secret-bucket" - Options: - OptionA: "value for driver option A" - OptionB: "value for driver option B" - tags: ["Secret"] - /secrets/{id}: - get: - summary: "Inspect a secret" - operationId: "SecretInspect" - produces: - - "application/json" - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/Secret" - examples: - application/json: - ID: "ktnbjxoalbkvbvedmg1urrz8h" - Version: - Index: 11 - CreatedAt: "2016-11-05T01:20:17.327670065Z" - UpdatedAt: "2016-11-05T01:20:17.327670065Z" - Spec: - Name: "app-dev.crt" - Labels: - foo: "bar" - Driver: - Name: "secret-bucket" - Options: - OptionA: "value for driver option A" - OptionB: "value for driver option B" - - 404: - description: "secret not found" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - type: "string" - description: "ID of the secret" - tags: ["Secret"] - delete: - summary: "Delete a secret" - operationId: "SecretDelete" - produces: - - "application/json" - responses: - 204: - description: "no error" - 404: - description: "secret not found" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - type: "string" - description: "ID of the secret" - tags: ["Secret"] - /secrets/{id}/update: - post: - summary: "Update a Secret" - operationId: "SecretUpdate" - responses: - 200: - description: "no error" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such secret" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "The ID or name of the secret" - type: "string" - required: true - - name: "body" - in: "body" - schema: - $ref: "#/definitions/SecretSpec" - description: | - The spec of the secret to update. Currently, only the Labels field - can be updated. All other fields must remain unchanged from the - [SecretInspect endpoint](#operation/SecretInspect) response values. - - name: "version" - in: "query" - description: | - The version number of the secret object being updated. This is - required to avoid conflicting writes. - type: "integer" - format: "int64" - required: true - tags: ["Secret"] - /configs: - get: - summary: "List configs" - operationId: "ConfigList" - produces: - - "application/json" - responses: - 200: - description: "no error" - schema: - type: "array" - items: - $ref: "#/definitions/Config" - example: - - ID: "ktnbjxoalbkvbvedmg1urrz8h" - Version: - Index: 11 - CreatedAt: "2016-11-05T01:20:17.327670065Z" - UpdatedAt: "2016-11-05T01:20:17.327670065Z" - Spec: - Name: "server.conf" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "filters" - in: "query" - type: "string" - description: | - A JSON encoded value of the filters (a `map[string][]string`) to - process on the configs list. - - Available filters: - - - `id=` - - `label= or label==value` - - `name=` - - `names=` - tags: ["Config"] - /configs/create: - post: - summary: "Create a config" - operationId: "ConfigCreate" - consumes: - - "application/json" - produces: - - "application/json" - responses: - 201: - description: "no error" - schema: - $ref: "#/definitions/IdResponse" - 409: - description: "name conflicts with an existing object" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "body" - in: "body" - schema: - allOf: - - $ref: "#/definitions/ConfigSpec" - - type: "object" - example: - Name: "server.conf" - Labels: - foo: "bar" - Data: "VEhJUyBJUyBOT1QgQSBSRUFMIENFUlRJRklDQVRFCg==" - tags: ["Config"] - /configs/{id}: - get: - summary: "Inspect a config" - operationId: "ConfigInspect" - produces: - - "application/json" - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/Config" - examples: - application/json: - ID: "ktnbjxoalbkvbvedmg1urrz8h" - Version: - Index: 11 - CreatedAt: "2016-11-05T01:20:17.327670065Z" - UpdatedAt: "2016-11-05T01:20:17.327670065Z" - Spec: - Name: "app-dev.crt" - 404: - description: "config not found" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - type: "string" - description: "ID of the config" - tags: ["Config"] - delete: - summary: "Delete a config" - operationId: "ConfigDelete" - produces: - - "application/json" - responses: - 204: - description: "no error" - 404: - description: "config not found" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - type: "string" - description: "ID of the config" - tags: ["Config"] - /configs/{id}/update: - post: - summary: "Update a Config" - operationId: "ConfigUpdate" - responses: - 200: - description: "no error" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such config" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "The ID or name of the config" - type: "string" - required: true - - name: "body" - in: "body" - schema: - $ref: "#/definitions/ConfigSpec" - description: | - The spec of the config to update. Currently, only the Labels field - can be updated. All other fields must remain unchanged from the - [ConfigInspect endpoint](#operation/ConfigInspect) response values. - - name: "version" - in: "query" - description: | - The version number of the config object being updated. This is - required to avoid conflicting writes. - type: "integer" - format: "int64" - required: true - tags: ["Config"] - /distribution/{name}/json: - get: - summary: "Get image information from the registry" - description: | - Return image digest and platform information by contacting the registry. - operationId: "DistributionInspect" - produces: - - "application/json" - responses: - 200: - description: "descriptor and platform information" - schema: - $ref: "#/definitions/DistributionInspect" - 401: - description: "Failed authentication or no image found" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such image: someimage (tag: latest)" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: "Image name or id" - type: "string" - required: true - tags: ["Distribution"] - /session: - post: - summary: "Initialize interactive session" - description: | - Start a new interactive session with a server. Session allows server to - call back to the client for advanced capabilities. - - ### Hijacking - - This endpoint hijacks the HTTP connection to HTTP2 transport that allows - the client to expose gPRC services on that connection. - - For example, the client sends this request to upgrade the connection: - - ``` - POST /session HTTP/1.1 - Upgrade: h2c - Connection: Upgrade - ``` - - The Docker daemon responds with a `101 UPGRADED` response follow with - the raw stream: - - ``` - HTTP/1.1 101 UPGRADED - Connection: Upgrade - Upgrade: h2c - ``` - operationId: "Session" - produces: - - "application/vnd.docker.raw-stream" - responses: - 101: - description: "no error, hijacking successful" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Session"] diff --git a/vendor/github.com/docker/docker/api/types/auth.go b/vendor/github.com/docker/docker/api/types/auth.go deleted file mode 100644 index 9ee329a2f..000000000 --- a/vendor/github.com/docker/docker/api/types/auth.go +++ /dev/null @@ -1,7 +0,0 @@ -package types // import "github.com/docker/docker/api/types" -import "github.com/docker/docker/api/types/registry" - -// AuthConfig contains authorization information for connecting to a Registry. -// -// Deprecated: use github.com/docker/docker/api/types/registry.AuthConfig -type AuthConfig = registry.AuthConfig diff --git a/vendor/github.com/docker/docker/api/types/blkiodev/blkio.go b/vendor/github.com/docker/docker/api/types/blkiodev/blkio.go deleted file mode 100644 index bf3463b90..000000000 --- a/vendor/github.com/docker/docker/api/types/blkiodev/blkio.go +++ /dev/null @@ -1,23 +0,0 @@ -package blkiodev // import "github.com/docker/docker/api/types/blkiodev" - -import "fmt" - -// WeightDevice is a structure that holds device:weight pair -type WeightDevice struct { - Path string - Weight uint16 -} - -func (w *WeightDevice) String() string { - return fmt.Sprintf("%s:%d", w.Path, w.Weight) -} - -// ThrottleDevice is a structure that holds device:rate_per_second pair -type ThrottleDevice struct { - Path string - Rate uint64 -} - -func (t *ThrottleDevice) String() string { - return fmt.Sprintf("%s:%d", t.Path, t.Rate) -} diff --git a/vendor/github.com/docker/docker/api/types/client.go b/vendor/github.com/docker/docker/api/types/client.go deleted file mode 100644 index d8cd30613..000000000 --- a/vendor/github.com/docker/docker/api/types/client.go +++ /dev/null @@ -1,444 +0,0 @@ -package types // import "github.com/docker/docker/api/types" - -import ( - "bufio" - "io" - "net" - - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/registry" - units "github.com/docker/go-units" -) - -// CheckpointCreateOptions holds parameters to create a checkpoint from a container -type CheckpointCreateOptions struct { - CheckpointID string - CheckpointDir string - Exit bool -} - -// CheckpointListOptions holds parameters to list checkpoints for a container -type CheckpointListOptions struct { - CheckpointDir string -} - -// CheckpointDeleteOptions holds parameters to delete a checkpoint from a container -type CheckpointDeleteOptions struct { - CheckpointID string - CheckpointDir string -} - -// ContainerAttachOptions holds parameters to attach to a container. -type ContainerAttachOptions struct { - Stream bool - Stdin bool - Stdout bool - Stderr bool - DetachKeys string - Logs bool -} - -// ContainerCommitOptions holds parameters to commit changes into a container. -type ContainerCommitOptions struct { - Reference string - Comment string - Author string - Changes []string - Pause bool - Config *container.Config -} - -// ContainerExecInspect holds information returned by exec inspect. -type ContainerExecInspect struct { - ExecID string `json:"ID"` - ContainerID string - Running bool - ExitCode int - Pid int -} - -// ContainerListOptions holds parameters to list containers with. -type ContainerListOptions struct { - Size bool - All bool - Latest bool - Since string - Before string - Limit int - Filters filters.Args -} - -// ContainerLogsOptions holds parameters to filter logs with. -type ContainerLogsOptions struct { - ShowStdout bool - ShowStderr bool - Since string - Until string - Timestamps bool - Follow bool - Tail string - Details bool -} - -// ContainerRemoveOptions holds parameters to remove containers. -type ContainerRemoveOptions struct { - RemoveVolumes bool - RemoveLinks bool - Force bool -} - -// ContainerStartOptions holds parameters to start containers. -type ContainerStartOptions struct { - CheckpointID string - CheckpointDir string -} - -// CopyToContainerOptions holds information -// about files to copy into a container -type CopyToContainerOptions struct { - AllowOverwriteDirWithFile bool - CopyUIDGID bool -} - -// EventsOptions holds parameters to filter events with. -type EventsOptions struct { - Since string - Until string - Filters filters.Args -} - -// NetworkListOptions holds parameters to filter the list of networks with. -type NetworkListOptions struct { - Filters filters.Args -} - -// NewHijackedResponse intializes a HijackedResponse type -func NewHijackedResponse(conn net.Conn, mediaType string) HijackedResponse { - return HijackedResponse{Conn: conn, Reader: bufio.NewReader(conn), mediaType: mediaType} -} - -// HijackedResponse holds connection information for a hijacked request. -type HijackedResponse struct { - mediaType string - Conn net.Conn - Reader *bufio.Reader -} - -// Close closes the hijacked connection and reader. -func (h *HijackedResponse) Close() { - h.Conn.Close() -} - -// MediaType let client know if HijackedResponse hold a raw or multiplexed stream. -// returns false if HTTP Content-Type is not relevant, and container must be inspected -func (h *HijackedResponse) MediaType() (string, bool) { - if h.mediaType == "" { - return "", false - } - return h.mediaType, true -} - -// CloseWriter is an interface that implements structs -// that close input streams to prevent from writing. -type CloseWriter interface { - CloseWrite() error -} - -// CloseWrite closes a readWriter for writing. -func (h *HijackedResponse) CloseWrite() error { - if conn, ok := h.Conn.(CloseWriter); ok { - return conn.CloseWrite() - } - return nil -} - -// ImageBuildOptions holds the information -// necessary to build images. -type ImageBuildOptions struct { - Tags []string - SuppressOutput bool - RemoteContext string - NoCache bool - Remove bool - ForceRemove bool - PullParent bool - Isolation container.Isolation - CPUSetCPUs string - CPUSetMems string - CPUShares int64 - CPUQuota int64 - CPUPeriod int64 - Memory int64 - MemorySwap int64 - CgroupParent string - NetworkMode string - ShmSize int64 - Dockerfile string - Ulimits []*units.Ulimit - // BuildArgs needs to be a *string instead of just a string so that - // we can tell the difference between "" (empty string) and no value - // at all (nil). See the parsing of buildArgs in - // api/server/router/build/build_routes.go for even more info. - BuildArgs map[string]*string - AuthConfigs map[string]registry.AuthConfig - Context io.Reader - Labels map[string]string - // squash the resulting image's layers to the parent - // preserves the original image and creates a new one from the parent with all - // the changes applied to a single layer - Squash bool - // CacheFrom specifies images that are used for matching cache. Images - // specified here do not need to have a valid parent chain to match cache. - CacheFrom []string - SecurityOpt []string - ExtraHosts []string // List of extra hosts - Target string - SessionID string - Platform string - // Version specifies the version of the unerlying builder to use - Version BuilderVersion - // BuildID is an optional identifier that can be passed together with the - // build request. The same identifier can be used to gracefully cancel the - // build with the cancel request. - BuildID string - // Outputs defines configurations for exporting build results. Only supported - // in BuildKit mode - Outputs []ImageBuildOutput -} - -// ImageBuildOutput defines configuration for exporting a build result -type ImageBuildOutput struct { - Type string - Attrs map[string]string -} - -// BuilderVersion sets the version of underlying builder to use -type BuilderVersion string - -const ( - // BuilderV1 is the first generation builder in docker daemon - BuilderV1 BuilderVersion = "1" - // BuilderBuildKit is builder based on moby/buildkit project - BuilderBuildKit BuilderVersion = "2" -) - -// ImageBuildResponse holds information -// returned by a server after building -// an image. -type ImageBuildResponse struct { - Body io.ReadCloser - OSType string -} - -// ImageCreateOptions holds information to create images. -type ImageCreateOptions struct { - RegistryAuth string // RegistryAuth is the base64 encoded credentials for the registry. - Platform string // Platform is the target platform of the image if it needs to be pulled from the registry. -} - -// ImageImportSource holds source information for ImageImport -type ImageImportSource struct { - Source io.Reader // Source is the data to send to the server to create this image from. You must set SourceName to "-" to leverage this. - SourceName string // SourceName is the name of the image to pull. Set to "-" to leverage the Source attribute. -} - -// ImageImportOptions holds information to import images from the client host. -type ImageImportOptions struct { - Tag string // Tag is the name to tag this image with. This attribute is deprecated. - Message string // Message is the message to tag the image with - Changes []string // Changes are the raw changes to apply to this image - Platform string // Platform is the target platform of the image -} - -// ImageListOptions holds parameters to list images with. -type ImageListOptions struct { - // All controls whether all images in the graph are filtered, or just - // the heads. - All bool - - // Filters is a JSON-encoded set of filter arguments. - Filters filters.Args - - // SharedSize indicates whether the shared size of images should be computed. - SharedSize bool - - // ContainerCount indicates whether container count should be computed. - ContainerCount bool -} - -// ImageLoadResponse returns information to the client about a load process. -type ImageLoadResponse struct { - // Body must be closed to avoid a resource leak - Body io.ReadCloser - JSON bool -} - -// ImagePullOptions holds information to pull images. -type ImagePullOptions struct { - All bool - RegistryAuth string // RegistryAuth is the base64 encoded credentials for the registry - PrivilegeFunc RequestPrivilegeFunc - Platform string -} - -// RequestPrivilegeFunc is a function interface that -// clients can supply to retry operations after -// getting an authorization error. -// This function returns the registry authentication -// header value in base 64 format, or an error -// if the privilege request fails. -type RequestPrivilegeFunc func() (string, error) - -// ImagePushOptions holds information to push images. -type ImagePushOptions ImagePullOptions - -// ImageRemoveOptions holds parameters to remove images. -type ImageRemoveOptions struct { - Force bool - PruneChildren bool -} - -// ImageSearchOptions holds parameters to search images with. -type ImageSearchOptions struct { - RegistryAuth string - PrivilegeFunc RequestPrivilegeFunc - Filters filters.Args - Limit int -} - -// ResizeOptions holds parameters to resize a tty. -// It can be used to resize container ttys and -// exec process ttys too. -type ResizeOptions struct { - Height uint - Width uint -} - -// NodeListOptions holds parameters to list nodes with. -type NodeListOptions struct { - Filters filters.Args -} - -// NodeRemoveOptions holds parameters to remove nodes with. -type NodeRemoveOptions struct { - Force bool -} - -// ServiceCreateOptions contains the options to use when creating a service. -type ServiceCreateOptions struct { - // EncodedRegistryAuth is the encoded registry authorization credentials to - // use when updating the service. - // - // This field follows the format of the X-Registry-Auth header. - EncodedRegistryAuth string - - // QueryRegistry indicates whether the service update requires - // contacting a registry. A registry may be contacted to retrieve - // the image digest and manifest, which in turn can be used to update - // platform or other information about the service. - QueryRegistry bool -} - -// ServiceCreateResponse contains the information returned to a client -// on the creation of a new service. -type ServiceCreateResponse struct { - // ID is the ID of the created service. - ID string - // Warnings is a set of non-fatal warning messages to pass on to the user. - Warnings []string `json:",omitempty"` -} - -// Values for RegistryAuthFrom in ServiceUpdateOptions -const ( - RegistryAuthFromSpec = "spec" - RegistryAuthFromPreviousSpec = "previous-spec" -) - -// ServiceUpdateOptions contains the options to be used for updating services. -type ServiceUpdateOptions struct { - // EncodedRegistryAuth is the encoded registry authorization credentials to - // use when updating the service. - // - // This field follows the format of the X-Registry-Auth header. - EncodedRegistryAuth string - - // TODO(stevvooe): Consider moving the version parameter of ServiceUpdate - // into this field. While it does open API users up to racy writes, most - // users may not need that level of consistency in practice. - - // RegistryAuthFrom specifies where to find the registry authorization - // credentials if they are not given in EncodedRegistryAuth. Valid - // values are "spec" and "previous-spec". - RegistryAuthFrom string - - // Rollback indicates whether a server-side rollback should be - // performed. When this is set, the provided spec will be ignored. - // The valid values are "previous" and "none". An empty value is the - // same as "none". - Rollback string - - // QueryRegistry indicates whether the service update requires - // contacting a registry. A registry may be contacted to retrieve - // the image digest and manifest, which in turn can be used to update - // platform or other information about the service. - QueryRegistry bool -} - -// ServiceListOptions holds parameters to list services with. -type ServiceListOptions struct { - Filters filters.Args - - // Status indicates whether the server should include the service task - // count of running and desired tasks. - Status bool -} - -// ServiceInspectOptions holds parameters related to the "service inspect" -// operation. -type ServiceInspectOptions struct { - InsertDefaults bool -} - -// TaskListOptions holds parameters to list tasks with. -type TaskListOptions struct { - Filters filters.Args -} - -// PluginRemoveOptions holds parameters to remove plugins. -type PluginRemoveOptions struct { - Force bool -} - -// PluginEnableOptions holds parameters to enable plugins. -type PluginEnableOptions struct { - Timeout int -} - -// PluginDisableOptions holds parameters to disable plugins. -type PluginDisableOptions struct { - Force bool -} - -// PluginInstallOptions holds parameters to install a plugin. -type PluginInstallOptions struct { - Disabled bool - AcceptAllPermissions bool - RegistryAuth string // RegistryAuth is the base64 encoded credentials for the registry - RemoteRef string // RemoteRef is the plugin name on the registry - PrivilegeFunc RequestPrivilegeFunc - AcceptPermissionsFunc func(PluginPrivileges) (bool, error) - Args []string -} - -// SwarmUnlockKeyResponse contains the response for Engine API: -// GET /swarm/unlockkey -type SwarmUnlockKeyResponse struct { - // UnlockKey is the unlock key in ASCII-armored format. - UnlockKey string -} - -// PluginCreateOptions hold all options to plugin create. -type PluginCreateOptions struct { - RepoName string -} diff --git a/vendor/github.com/docker/docker/api/types/configs.go b/vendor/github.com/docker/docker/api/types/configs.go deleted file mode 100644 index 7d5930bbe..000000000 --- a/vendor/github.com/docker/docker/api/types/configs.go +++ /dev/null @@ -1,67 +0,0 @@ -package types // import "github.com/docker/docker/api/types" - -import ( - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/network" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" -) - -// configs holds structs used for internal communication between the -// frontend (such as an http server) and the backend (such as the -// docker daemon). - -// ContainerCreateConfig is the parameter set to ContainerCreate() -type ContainerCreateConfig struct { - Name string - Config *container.Config - HostConfig *container.HostConfig - NetworkingConfig *network.NetworkingConfig - Platform *ocispec.Platform - AdjustCPUShares bool -} - -// ContainerRmConfig holds arguments for the container remove -// operation. This struct is used to tell the backend what operations -// to perform. -type ContainerRmConfig struct { - ForceRemove, RemoveVolume, RemoveLink bool -} - -// ExecConfig is a small subset of the Config struct that holds the configuration -// for the exec feature of docker. -type ExecConfig struct { - User string // User that will run the command - Privileged bool // Is the container in privileged mode - Tty bool // Attach standard streams to a tty. - ConsoleSize *[2]uint `json:",omitempty"` // Initial console size [height, width] - AttachStdin bool // Attach the standard input, makes possible user interaction - AttachStderr bool // Attach the standard error - AttachStdout bool // Attach the standard output - Detach bool // Execute in detach mode - DetachKeys string // Escape keys for detach - Env []string // Environment variables - WorkingDir string // Working directory - Cmd []string // Execution commands and args -} - -// PluginRmConfig holds arguments for plugin remove. -type PluginRmConfig struct { - ForceRemove bool -} - -// PluginEnableConfig holds arguments for plugin enable -type PluginEnableConfig struct { - Timeout int -} - -// PluginDisableConfig holds arguments for plugin disable. -type PluginDisableConfig struct { - ForceDisable bool -} - -// NetworkListConfig stores the options available for listing networks -type NetworkListConfig struct { - // TODO(@cpuguy83): naming is hard, this is pulled from what was being used in the router before moving here - Detailed bool - Verbose bool -} diff --git a/vendor/github.com/docker/docker/api/types/container/change_response_deprecated.go b/vendor/github.com/docker/docker/api/types/container/change_response_deprecated.go deleted file mode 100644 index 6b4b47390..000000000 --- a/vendor/github.com/docker/docker/api/types/container/change_response_deprecated.go +++ /dev/null @@ -1,6 +0,0 @@ -package container - -// ContainerChangeResponseItem change item in response to ContainerChanges operation -// -// Deprecated: use [FilesystemChange]. -type ContainerChangeResponseItem = FilesystemChange diff --git a/vendor/github.com/docker/docker/api/types/container/change_type.go b/vendor/github.com/docker/docker/api/types/container/change_type.go deleted file mode 100644 index fe8d6d369..000000000 --- a/vendor/github.com/docker/docker/api/types/container/change_type.go +++ /dev/null @@ -1,15 +0,0 @@ -package container - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// ChangeType Kind of change -// -// Can be one of: -// -// - `0`: Modified ("C") -// - `1`: Added ("A") -// - `2`: Deleted ("D") -// -// swagger:model ChangeType -type ChangeType uint8 diff --git a/vendor/github.com/docker/docker/api/types/container/change_types.go b/vendor/github.com/docker/docker/api/types/container/change_types.go deleted file mode 100644 index 3a3a83866..000000000 --- a/vendor/github.com/docker/docker/api/types/container/change_types.go +++ /dev/null @@ -1,23 +0,0 @@ -package container - -const ( - // ChangeModify represents the modify operation. - ChangeModify ChangeType = 0 - // ChangeAdd represents the add operation. - ChangeAdd ChangeType = 1 - // ChangeDelete represents the delete operation. - ChangeDelete ChangeType = 2 -) - -func (ct ChangeType) String() string { - switch ct { - case ChangeModify: - return "C" - case ChangeAdd: - return "A" - case ChangeDelete: - return "D" - default: - return "" - } -} diff --git a/vendor/github.com/docker/docker/api/types/container/config.go b/vendor/github.com/docker/docker/api/types/container/config.go deleted file mode 100644 index 077583e66..000000000 --- a/vendor/github.com/docker/docker/api/types/container/config.go +++ /dev/null @@ -1,96 +0,0 @@ -package container // import "github.com/docker/docker/api/types/container" - -import ( - "io" - "time" - - "github.com/docker/docker/api/types/strslice" - "github.com/docker/go-connections/nat" -) - -// MinimumDuration puts a minimum on user configured duration. -// This is to prevent API error on time unit. For example, API may -// set 3 as healthcheck interval with intention of 3 seconds, but -// Docker interprets it as 3 nanoseconds. -const MinimumDuration = 1 * time.Millisecond - -// StopOptions holds the options to stop or restart a container. -type StopOptions struct { - // Signal (optional) is the signal to send to the container to (gracefully) - // stop it before forcibly terminating the container with SIGKILL after the - // timeout expires. If not value is set, the default (SIGTERM) is used. - Signal string `json:",omitempty"` - - // Timeout (optional) is the timeout (in seconds) to wait for the container - // to stop gracefully before forcibly terminating it with SIGKILL. - // - // - Use nil to use the default timeout (10 seconds). - // - Use '-1' to wait indefinitely. - // - Use '0' to not wait for the container to exit gracefully, and - // immediately proceeds to forcibly terminating the container. - // - Other positive values are used as timeout (in seconds). - Timeout *int `json:",omitempty"` -} - -// HealthConfig holds configuration settings for the HEALTHCHECK feature. -type HealthConfig struct { - // Test is the test to perform to check that the container is healthy. - // An empty slice means to inherit the default. - // The options are: - // {} : inherit healthcheck - // {"NONE"} : disable healthcheck - // {"CMD", args...} : exec arguments directly - // {"CMD-SHELL", command} : run command with system's default shell - Test []string `json:",omitempty"` - - // Zero means to inherit. Durations are expressed as integer nanoseconds. - Interval time.Duration `json:",omitempty"` // Interval is the time to wait between checks. - Timeout time.Duration `json:",omitempty"` // Timeout is the time to wait before considering the check to have hung. - StartPeriod time.Duration `json:",omitempty"` // The start period for the container to initialize before the retries starts to count down. - - // Retries is the number of consecutive failures needed to consider a container as unhealthy. - // Zero means inherit. - Retries int `json:",omitempty"` -} - -// ExecStartOptions holds the options to start container's exec. -type ExecStartOptions struct { - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer - ConsoleSize *[2]uint `json:",omitempty"` -} - -// Config contains the configuration data about a container. -// It should hold only portable information about the container. -// Here, "portable" means "independent from the host we are running on". -// Non-portable information *should* appear in HostConfig. -// All fields added to this struct must be marked `omitempty` to keep getting -// predictable hashes from the old `v1Compatibility` configuration. -type Config struct { - Hostname string // Hostname - Domainname string // Domainname - User string // User that will run the command(s) inside the container, also support user:group - AttachStdin bool // Attach the standard input, makes possible user interaction - AttachStdout bool // Attach the standard output - AttachStderr bool // Attach the standard error - ExposedPorts nat.PortSet `json:",omitempty"` // List of exposed ports - Tty bool // Attach standard streams to a tty, including stdin if it is not closed. - OpenStdin bool // Open stdin - StdinOnce bool // If true, close stdin after the 1 attached client disconnects. - Env []string // List of environment variable to set in the container - Cmd strslice.StrSlice // Command to run when starting the container - Healthcheck *HealthConfig `json:",omitempty"` // Healthcheck describes how to check the container is healthy - ArgsEscaped bool `json:",omitempty"` // True if command is already escaped (meaning treat as a command line) (Windows specific). - Image string // Name of the image as it was passed by the operator (e.g. could be symbolic) - Volumes map[string]struct{} // List of volumes (mounts) used for the container - WorkingDir string // Current directory (PWD) in the command will be launched - Entrypoint strslice.StrSlice // Entrypoint to run when starting the container - NetworkDisabled bool `json:",omitempty"` // Is network disabled - MacAddress string `json:",omitempty"` // Mac Address of the container - OnBuild []string // ONBUILD metadata that were defined on the image Dockerfile - Labels map[string]string // List of labels set to this container - StopSignal string `json:",omitempty"` // Signal to stop a container - StopTimeout *int `json:",omitempty"` // Timeout (in seconds) to stop a container - Shell strslice.StrSlice `json:",omitempty"` // Shell for shell-form of RUN, CMD, ENTRYPOINT -} diff --git a/vendor/github.com/docker/docker/api/types/container/container_top.go b/vendor/github.com/docker/docker/api/types/container/container_top.go deleted file mode 100644 index 63381da36..000000000 --- a/vendor/github.com/docker/docker/api/types/container/container_top.go +++ /dev/null @@ -1,22 +0,0 @@ -package container // import "github.com/docker/docker/api/types/container" - -// ---------------------------------------------------------------------------- -// Code generated by `swagger generate operation`. DO NOT EDIT. -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -// ContainerTopOKBody OK response to ContainerTop operation -// swagger:model ContainerTopOKBody -type ContainerTopOKBody struct { - - // Each process running in the container, where each is process - // is an array of values corresponding to the titles. - // - // Required: true - Processes [][]string `json:"Processes"` - - // The ps column titles - // Required: true - Titles []string `json:"Titles"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/container_update.go b/vendor/github.com/docker/docker/api/types/container/container_update.go deleted file mode 100644 index c10f175ea..000000000 --- a/vendor/github.com/docker/docker/api/types/container/container_update.go +++ /dev/null @@ -1,16 +0,0 @@ -package container // import "github.com/docker/docker/api/types/container" - -// ---------------------------------------------------------------------------- -// Code generated by `swagger generate operation`. DO NOT EDIT. -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -// ContainerUpdateOKBody OK response to ContainerUpdate operation -// swagger:model ContainerUpdateOKBody -type ContainerUpdateOKBody struct { - - // warnings - // Required: true - Warnings []string `json:"Warnings"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/create_response.go b/vendor/github.com/docker/docker/api/types/container/create_response.go deleted file mode 100644 index aa0e7f7d0..000000000 --- a/vendor/github.com/docker/docker/api/types/container/create_response.go +++ /dev/null @@ -1,19 +0,0 @@ -package container - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// CreateResponse ContainerCreateResponse -// -// OK response to ContainerCreate operation -// swagger:model CreateResponse -type CreateResponse struct { - - // The ID of the created container - // Required: true - ID string `json:"Id"` - - // Warnings encountered when creating the container - // Required: true - Warnings []string `json:"Warnings"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/filesystem_change.go b/vendor/github.com/docker/docker/api/types/container/filesystem_change.go deleted file mode 100644 index 9e9c2ad1d..000000000 --- a/vendor/github.com/docker/docker/api/types/container/filesystem_change.go +++ /dev/null @@ -1,19 +0,0 @@ -package container - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// FilesystemChange Change in the container's filesystem. -// -// swagger:model FilesystemChange -type FilesystemChange struct { - - // kind - // Required: true - Kind ChangeType `json:"Kind"` - - // Path to file or directory that has changed. - // - // Required: true - Path string `json:"Path"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/hostconfig.go b/vendor/github.com/docker/docker/api/types/container/hostconfig.go deleted file mode 100644 index d4e6f5537..000000000 --- a/vendor/github.com/docker/docker/api/types/container/hostconfig.go +++ /dev/null @@ -1,456 +0,0 @@ -package container // import "github.com/docker/docker/api/types/container" - -import ( - "strings" - - "github.com/docker/docker/api/types/blkiodev" - "github.com/docker/docker/api/types/mount" - "github.com/docker/docker/api/types/strslice" - "github.com/docker/go-connections/nat" - units "github.com/docker/go-units" -) - -// CgroupnsMode represents the cgroup namespace mode of the container -type CgroupnsMode string - -// cgroup namespace modes for containers -const ( - CgroupnsModeEmpty CgroupnsMode = "" - CgroupnsModePrivate CgroupnsMode = "private" - CgroupnsModeHost CgroupnsMode = "host" -) - -// IsPrivate indicates whether the container uses its own private cgroup namespace -func (c CgroupnsMode) IsPrivate() bool { - return c == CgroupnsModePrivate -} - -// IsHost indicates whether the container shares the host's cgroup namespace -func (c CgroupnsMode) IsHost() bool { - return c == CgroupnsModeHost -} - -// IsEmpty indicates whether the container cgroup namespace mode is unset -func (c CgroupnsMode) IsEmpty() bool { - return c == CgroupnsModeEmpty -} - -// Valid indicates whether the cgroup namespace mode is valid -func (c CgroupnsMode) Valid() bool { - return c.IsEmpty() || c.IsPrivate() || c.IsHost() -} - -// Isolation represents the isolation technology of a container. The supported -// values are platform specific -type Isolation string - -// Isolation modes for containers -const ( - IsolationEmpty Isolation = "" // IsolationEmpty is unspecified (same behavior as default) - IsolationDefault Isolation = "default" // IsolationDefault is the default isolation mode on current daemon - IsolationProcess Isolation = "process" // IsolationProcess is process isolation mode - IsolationHyperV Isolation = "hyperv" // IsolationHyperV is HyperV isolation mode -) - -// IsDefault indicates the default isolation technology of a container. On Linux this -// is the native driver. On Windows, this is a Windows Server Container. -func (i Isolation) IsDefault() bool { - // TODO consider making isolation-mode strict (case-sensitive) - v := Isolation(strings.ToLower(string(i))) - return v == IsolationDefault || v == IsolationEmpty -} - -// IsHyperV indicates the use of a Hyper-V partition for isolation -func (i Isolation) IsHyperV() bool { - // TODO consider making isolation-mode strict (case-sensitive) - return Isolation(strings.ToLower(string(i))) == IsolationHyperV -} - -// IsProcess indicates the use of process isolation -func (i Isolation) IsProcess() bool { - // TODO consider making isolation-mode strict (case-sensitive) - return Isolation(strings.ToLower(string(i))) == IsolationProcess -} - -// IpcMode represents the container ipc stack. -type IpcMode string - -// IpcMode constants -const ( - IPCModeNone IpcMode = "none" - IPCModeHost IpcMode = "host" - IPCModeContainer IpcMode = "container" - IPCModePrivate IpcMode = "private" - IPCModeShareable IpcMode = "shareable" -) - -// IsPrivate indicates whether the container uses its own private ipc namespace which can not be shared. -func (n IpcMode) IsPrivate() bool { - return n == IPCModePrivate -} - -// IsHost indicates whether the container shares the host's ipc namespace. -func (n IpcMode) IsHost() bool { - return n == IPCModeHost -} - -// IsShareable indicates whether the container's ipc namespace can be shared with another container. -func (n IpcMode) IsShareable() bool { - return n == IPCModeShareable -} - -// IsContainer indicates whether the container uses another container's ipc namespace. -func (n IpcMode) IsContainer() bool { - _, ok := containerID(string(n)) - return ok -} - -// IsNone indicates whether container IpcMode is set to "none". -func (n IpcMode) IsNone() bool { - return n == IPCModeNone -} - -// IsEmpty indicates whether container IpcMode is empty -func (n IpcMode) IsEmpty() bool { - return n == "" -} - -// Valid indicates whether the ipc mode is valid. -func (n IpcMode) Valid() bool { - // TODO(thaJeztah): align with PidMode, and consider container-mode without a container name/ID to be invalid. - return n.IsEmpty() || n.IsNone() || n.IsPrivate() || n.IsHost() || n.IsShareable() || n.IsContainer() -} - -// Container returns the name of the container ipc stack is going to be used. -func (n IpcMode) Container() (idOrName string) { - idOrName, _ = containerID(string(n)) - return idOrName -} - -// NetworkMode represents the container network stack. -type NetworkMode string - -// IsNone indicates whether container isn't using a network stack. -func (n NetworkMode) IsNone() bool { - return n == "none" -} - -// IsDefault indicates whether container uses the default network stack. -func (n NetworkMode) IsDefault() bool { - return n == "default" -} - -// IsPrivate indicates whether container uses its private network stack. -func (n NetworkMode) IsPrivate() bool { - return !(n.IsHost() || n.IsContainer()) -} - -// IsContainer indicates whether container uses a container network stack. -func (n NetworkMode) IsContainer() bool { - _, ok := containerID(string(n)) - return ok -} - -// ConnectedContainer is the id of the container which network this container is connected to. -func (n NetworkMode) ConnectedContainer() (idOrName string) { - idOrName, _ = containerID(string(n)) - return idOrName -} - -// UserDefined indicates user-created network -func (n NetworkMode) UserDefined() string { - if n.IsUserDefined() { - return string(n) - } - return "" -} - -// UsernsMode represents userns mode in the container. -type UsernsMode string - -// IsHost indicates whether the container uses the host's userns. -func (n UsernsMode) IsHost() bool { - return n == "host" -} - -// IsPrivate indicates whether the container uses the a private userns. -func (n UsernsMode) IsPrivate() bool { - return !n.IsHost() -} - -// Valid indicates whether the userns is valid. -func (n UsernsMode) Valid() bool { - return n == "" || n.IsHost() -} - -// CgroupSpec represents the cgroup to use for the container. -type CgroupSpec string - -// IsContainer indicates whether the container is using another container cgroup -func (c CgroupSpec) IsContainer() bool { - _, ok := containerID(string(c)) - return ok -} - -// Valid indicates whether the cgroup spec is valid. -func (c CgroupSpec) Valid() bool { - // TODO(thaJeztah): align with PidMode, and consider container-mode without a container name/ID to be invalid. - return c == "" || c.IsContainer() -} - -// Container returns the ID or name of the container whose cgroup will be used. -func (c CgroupSpec) Container() (idOrName string) { - idOrName, _ = containerID(string(c)) - return idOrName -} - -// UTSMode represents the UTS namespace of the container. -type UTSMode string - -// IsPrivate indicates whether the container uses its private UTS namespace. -func (n UTSMode) IsPrivate() bool { - return !n.IsHost() -} - -// IsHost indicates whether the container uses the host's UTS namespace. -func (n UTSMode) IsHost() bool { - return n == "host" -} - -// Valid indicates whether the UTS namespace is valid. -func (n UTSMode) Valid() bool { - return n == "" || n.IsHost() -} - -// PidMode represents the pid namespace of the container. -type PidMode string - -// IsPrivate indicates whether the container uses its own new pid namespace. -func (n PidMode) IsPrivate() bool { - return !(n.IsHost() || n.IsContainer()) -} - -// IsHost indicates whether the container uses the host's pid namespace. -func (n PidMode) IsHost() bool { - return n == "host" -} - -// IsContainer indicates whether the container uses a container's pid namespace. -func (n PidMode) IsContainer() bool { - _, ok := containerID(string(n)) - return ok -} - -// Valid indicates whether the pid namespace is valid. -func (n PidMode) Valid() bool { - return n == "" || n.IsHost() || validContainer(string(n)) -} - -// Container returns the name of the container whose pid namespace is going to be used. -func (n PidMode) Container() (idOrName string) { - idOrName, _ = containerID(string(n)) - return idOrName -} - -// DeviceRequest represents a request for devices from a device driver. -// Used by GPU device drivers. -type DeviceRequest struct { - Driver string // Name of device driver - Count int // Number of devices to request (-1 = All) - DeviceIDs []string // List of device IDs as recognizable by the device driver - Capabilities [][]string // An OR list of AND lists of device capabilities (e.g. "gpu") - Options map[string]string // Options to pass onto the device driver -} - -// DeviceMapping represents the device mapping between the host and the container. -type DeviceMapping struct { - PathOnHost string - PathInContainer string - CgroupPermissions string -} - -// RestartPolicy represents the restart policies of the container. -type RestartPolicy struct { - Name string - MaximumRetryCount int -} - -// IsNone indicates whether the container has the "no" restart policy. -// This means the container will not automatically restart when exiting. -func (rp *RestartPolicy) IsNone() bool { - return rp.Name == "no" || rp.Name == "" -} - -// IsAlways indicates whether the container has the "always" restart policy. -// This means the container will automatically restart regardless of the exit status. -func (rp *RestartPolicy) IsAlways() bool { - return rp.Name == "always" -} - -// IsOnFailure indicates whether the container has the "on-failure" restart policy. -// This means the container will automatically restart of exiting with a non-zero exit status. -func (rp *RestartPolicy) IsOnFailure() bool { - return rp.Name == "on-failure" -} - -// IsUnlessStopped indicates whether the container has the -// "unless-stopped" restart policy. This means the container will -// automatically restart unless user has put it to stopped state. -func (rp *RestartPolicy) IsUnlessStopped() bool { - return rp.Name == "unless-stopped" -} - -// IsSame compares two RestartPolicy to see if they are the same -func (rp *RestartPolicy) IsSame(tp *RestartPolicy) bool { - return rp.Name == tp.Name && rp.MaximumRetryCount == tp.MaximumRetryCount -} - -// LogMode is a type to define the available modes for logging -// These modes affect how logs are handled when log messages start piling up. -type LogMode string - -// Available logging modes -const ( - LogModeUnset LogMode = "" - LogModeBlocking LogMode = "blocking" - LogModeNonBlock LogMode = "non-blocking" -) - -// LogConfig represents the logging configuration of the container. -type LogConfig struct { - Type string - Config map[string]string -} - -// Resources contains container's resources (cgroups config, ulimits...) -type Resources struct { - // Applicable to all platforms - CPUShares int64 `json:"CpuShares"` // CPU shares (relative weight vs. other containers) - Memory int64 // Memory limit (in bytes) - NanoCPUs int64 `json:"NanoCpus"` // CPU quota in units of 10-9 CPUs. - - // Applicable to UNIX platforms - CgroupParent string // Parent cgroup. - BlkioWeight uint16 // Block IO weight (relative weight vs. other containers) - BlkioWeightDevice []*blkiodev.WeightDevice - BlkioDeviceReadBps []*blkiodev.ThrottleDevice - BlkioDeviceWriteBps []*blkiodev.ThrottleDevice - BlkioDeviceReadIOps []*blkiodev.ThrottleDevice - BlkioDeviceWriteIOps []*blkiodev.ThrottleDevice - CPUPeriod int64 `json:"CpuPeriod"` // CPU CFS (Completely Fair Scheduler) period - CPUQuota int64 `json:"CpuQuota"` // CPU CFS (Completely Fair Scheduler) quota - CPURealtimePeriod int64 `json:"CpuRealtimePeriod"` // CPU real-time period - CPURealtimeRuntime int64 `json:"CpuRealtimeRuntime"` // CPU real-time runtime - CpusetCpus string // CpusetCpus 0-2, 0,1 - CpusetMems string // CpusetMems 0-2, 0,1 - Devices []DeviceMapping // List of devices to map inside the container - DeviceCgroupRules []string // List of rule to be added to the device cgroup - DeviceRequests []DeviceRequest // List of device requests for device drivers - - // KernelMemory specifies the kernel memory limit (in bytes) for the container. - // Deprecated: kernel 5.4 deprecated kmem.limit_in_bytes. - KernelMemory int64 `json:",omitempty"` - KernelMemoryTCP int64 `json:",omitempty"` // Hard limit for kernel TCP buffer memory (in bytes) - MemoryReservation int64 // Memory soft limit (in bytes) - MemorySwap int64 // Total memory usage (memory + swap); set `-1` to enable unlimited swap - MemorySwappiness *int64 // Tuning container memory swappiness behaviour - OomKillDisable *bool // Whether to disable OOM Killer or not - PidsLimit *int64 // Setting PIDs limit for a container; Set `0` or `-1` for unlimited, or `null` to not change. - Ulimits []*units.Ulimit // List of ulimits to be set in the container - - // Applicable to Windows - CPUCount int64 `json:"CpuCount"` // CPU count - CPUPercent int64 `json:"CpuPercent"` // CPU percent - IOMaximumIOps uint64 // Maximum IOps for the container system drive - IOMaximumBandwidth uint64 // Maximum IO in bytes per second for the container system drive -} - -// UpdateConfig holds the mutable attributes of a Container. -// Those attributes can be updated at runtime. -type UpdateConfig struct { - // Contains container's resources (cgroups, ulimits) - Resources - RestartPolicy RestartPolicy -} - -// HostConfig the non-portable Config structure of a container. -// Here, "non-portable" means "dependent of the host we are running on". -// Portable information *should* appear in Config. -type HostConfig struct { - // Applicable to all platforms - Binds []string // List of volume bindings for this container - ContainerIDFile string // File (path) where the containerId is written - LogConfig LogConfig // Configuration of the logs for this container - NetworkMode NetworkMode // Network mode to use for the container - PortBindings nat.PortMap // Port mapping between the exposed port (container) and the host - RestartPolicy RestartPolicy // Restart policy to be used for the container - AutoRemove bool // Automatically remove container when it exits - VolumeDriver string // Name of the volume driver used to mount volumes - VolumesFrom []string // List of volumes to take from other container - ConsoleSize [2]uint // Initial console size (height,width) - Annotations map[string]string `json:",omitempty"` // Arbitrary non-identifying metadata attached to container and provided to the runtime - - // Applicable to UNIX platforms - CapAdd strslice.StrSlice // List of kernel capabilities to add to the container - CapDrop strslice.StrSlice // List of kernel capabilities to remove from the container - CgroupnsMode CgroupnsMode // Cgroup namespace mode to use for the container - DNS []string `json:"Dns"` // List of DNS server to lookup - DNSOptions []string `json:"DnsOptions"` // List of DNSOption to look for - DNSSearch []string `json:"DnsSearch"` // List of DNSSearch to look for - ExtraHosts []string // List of extra hosts - GroupAdd []string // List of additional groups that the container process will run as - IpcMode IpcMode // IPC namespace to use for the container - Cgroup CgroupSpec // Cgroup to use for the container - Links []string // List of links (in the name:alias form) - OomScoreAdj int // Container preference for OOM-killing - PidMode PidMode // PID namespace to use for the container - Privileged bool // Is the container in privileged mode - PublishAllPorts bool // Should docker publish all exposed port for the container - ReadonlyRootfs bool // Is the container root filesystem in read-only - SecurityOpt []string // List of string values to customize labels for MLS systems, such as SELinux. - StorageOpt map[string]string `json:",omitempty"` // Storage driver options per container. - Tmpfs map[string]string `json:",omitempty"` // List of tmpfs (mounts) used for the container - UTSMode UTSMode // UTS namespace to use for the container - UsernsMode UsernsMode // The user namespace to use for the container - ShmSize int64 // Total shm memory usage - Sysctls map[string]string `json:",omitempty"` // List of Namespaced sysctls used for the container - Runtime string `json:",omitempty"` // Runtime to use with this container - - // Applicable to Windows - Isolation Isolation // Isolation technology of the container (e.g. default, hyperv) - - // Contains container's resources (cgroups, ulimits) - Resources - - // Mounts specs used by the container - Mounts []mount.Mount `json:",omitempty"` - - // MaskedPaths is the list of paths to be masked inside the container (this overrides the default set of paths) - MaskedPaths []string - - // ReadonlyPaths is the list of paths to be set as read-only inside the container (this overrides the default set of paths) - ReadonlyPaths []string - - // Run a custom init inside the container, if null, use the daemon's configured settings - Init *bool `json:",omitempty"` -} - -// containerID splits "container:" values. It returns the container -// ID or name, and whether an ID/name was found. It returns an empty string and -// a "false" if the value does not have a "container:" prefix. Further validation -// of the returned, including checking if the value is empty, should be handled -// by the caller. -func containerID(val string) (idOrName string, ok bool) { - k, v, hasSep := strings.Cut(val, ":") - if !hasSep || k != "container" { - return "", false - } - return v, true -} - -// validContainer checks if the given value is a "container:" mode with -// a non-empty name/ID. -func validContainer(val string) bool { - id, ok := containerID(val) - return ok && id != "" -} diff --git a/vendor/github.com/docker/docker/api/types/container/hostconfig_unix.go b/vendor/github.com/docker/docker/api/types/container/hostconfig_unix.go deleted file mode 100644 index 24c4fa8d9..000000000 --- a/vendor/github.com/docker/docker/api/types/container/hostconfig_unix.go +++ /dev/null @@ -1,42 +0,0 @@ -//go:build !windows -// +build !windows - -package container // import "github.com/docker/docker/api/types/container" - -// IsValid indicates if an isolation technology is valid -func (i Isolation) IsValid() bool { - return i.IsDefault() -} - -// NetworkName returns the name of the network stack. -func (n NetworkMode) NetworkName() string { - if n.IsBridge() { - return "bridge" - } else if n.IsHost() { - return "host" - } else if n.IsContainer() { - return "container" - } else if n.IsNone() { - return "none" - } else if n.IsDefault() { - return "default" - } else if n.IsUserDefined() { - return n.UserDefined() - } - return "" -} - -// IsBridge indicates whether container uses the bridge network stack -func (n NetworkMode) IsBridge() bool { - return n == "bridge" -} - -// IsHost indicates whether container uses the host network stack. -func (n NetworkMode) IsHost() bool { - return n == "host" -} - -// IsUserDefined indicates user-created network -func (n NetworkMode) IsUserDefined() bool { - return !n.IsDefault() && !n.IsBridge() && !n.IsHost() && !n.IsNone() && !n.IsContainer() -} diff --git a/vendor/github.com/docker/docker/api/types/container/hostconfig_windows.go b/vendor/github.com/docker/docker/api/types/container/hostconfig_windows.go deleted file mode 100644 index 99f803a5b..000000000 --- a/vendor/github.com/docker/docker/api/types/container/hostconfig_windows.go +++ /dev/null @@ -1,40 +0,0 @@ -package container // import "github.com/docker/docker/api/types/container" - -// IsBridge indicates whether container uses the bridge network stack -// in windows it is given the name NAT -func (n NetworkMode) IsBridge() bool { - return n == "nat" -} - -// IsHost indicates whether container uses the host network stack. -// returns false as this is not supported by windows -func (n NetworkMode) IsHost() bool { - return false -} - -// IsUserDefined indicates user-created network -func (n NetworkMode) IsUserDefined() bool { - return !n.IsDefault() && !n.IsNone() && !n.IsBridge() && !n.IsContainer() -} - -// IsValid indicates if an isolation technology is valid -func (i Isolation) IsValid() bool { - return i.IsDefault() || i.IsHyperV() || i.IsProcess() -} - -// NetworkName returns the name of the network stack. -func (n NetworkMode) NetworkName() string { - if n.IsDefault() { - return "default" - } else if n.IsBridge() { - return "nat" - } else if n.IsNone() { - return "none" - } else if n.IsContainer() { - return "container" - } else if n.IsUserDefined() { - return n.UserDefined() - } - - return "" -} diff --git a/vendor/github.com/docker/docker/api/types/container/wait_exit_error.go b/vendor/github.com/docker/docker/api/types/container/wait_exit_error.go deleted file mode 100644 index ab56d4eed..000000000 --- a/vendor/github.com/docker/docker/api/types/container/wait_exit_error.go +++ /dev/null @@ -1,12 +0,0 @@ -package container - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// WaitExitError container waiting error, if any -// swagger:model WaitExitError -type WaitExitError struct { - - // Details of an error - Message string `json:"Message,omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/wait_response.go b/vendor/github.com/docker/docker/api/types/container/wait_response.go deleted file mode 100644 index 84fc6afdd..000000000 --- a/vendor/github.com/docker/docker/api/types/container/wait_response.go +++ /dev/null @@ -1,18 +0,0 @@ -package container - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// WaitResponse ContainerWaitResponse -// -// OK response to ContainerWait operation -// swagger:model WaitResponse -type WaitResponse struct { - - // error - Error *WaitExitError `json:"Error,omitempty"` - - // Exit code of the container - // Required: true - StatusCode int64 `json:"StatusCode"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/waitcondition.go b/vendor/github.com/docker/docker/api/types/container/waitcondition.go deleted file mode 100644 index cd8311f99..000000000 --- a/vendor/github.com/docker/docker/api/types/container/waitcondition.go +++ /dev/null @@ -1,22 +0,0 @@ -package container // import "github.com/docker/docker/api/types/container" - -// WaitCondition is a type used to specify a container state for which -// to wait. -type WaitCondition string - -// Possible WaitCondition Values. -// -// WaitConditionNotRunning (default) is used to wait for any of the non-running -// states: "created", "exited", "dead", "removing", or "removed". -// -// WaitConditionNextExit is used to wait for the next time the state changes -// to a non-running state. If the state is currently "created" or "exited", -// this would cause Wait() to block until either the container runs and exits -// or is removed. -// -// WaitConditionRemoved is used to wait for the container to be removed. -const ( - WaitConditionNotRunning WaitCondition = "not-running" - WaitConditionNextExit WaitCondition = "next-exit" - WaitConditionRemoved WaitCondition = "removed" -) diff --git a/vendor/github.com/docker/docker/api/types/error_response.go b/vendor/github.com/docker/docker/api/types/error_response.go deleted file mode 100644 index dc942d9d9..000000000 --- a/vendor/github.com/docker/docker/api/types/error_response.go +++ /dev/null @@ -1,13 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// ErrorResponse Represents an error. -// swagger:model ErrorResponse -type ErrorResponse struct { - - // The error message. - // Required: true - Message string `json:"message"` -} diff --git a/vendor/github.com/docker/docker/api/types/error_response_ext.go b/vendor/github.com/docker/docker/api/types/error_response_ext.go deleted file mode 100644 index f84f034cd..000000000 --- a/vendor/github.com/docker/docker/api/types/error_response_ext.go +++ /dev/null @@ -1,6 +0,0 @@ -package types - -// Error returns the error message -func (e ErrorResponse) Error() string { - return e.Message -} diff --git a/vendor/github.com/docker/docker/api/types/events/events.go b/vendor/github.com/docker/docker/api/types/events/events.go deleted file mode 100644 index 9fe07e26f..000000000 --- a/vendor/github.com/docker/docker/api/types/events/events.go +++ /dev/null @@ -1,47 +0,0 @@ -package events // import "github.com/docker/docker/api/types/events" - -// Type is used for event-types. -type Type = string - -// List of known event types. -const ( - BuilderEventType Type = "builder" // BuilderEventType is the event type that the builder generates. - ConfigEventType Type = "config" // ConfigEventType is the event type that configs generate. - ContainerEventType Type = "container" // ContainerEventType is the event type that containers generate. - DaemonEventType Type = "daemon" // DaemonEventType is the event type that daemon generate. - ImageEventType Type = "image" // ImageEventType is the event type that images generate. - NetworkEventType Type = "network" // NetworkEventType is the event type that networks generate. - NodeEventType Type = "node" // NodeEventType is the event type that nodes generate. - PluginEventType Type = "plugin" // PluginEventType is the event type that plugins generate. - SecretEventType Type = "secret" // SecretEventType is the event type that secrets generate. - ServiceEventType Type = "service" // ServiceEventType is the event type that services generate. - VolumeEventType Type = "volume" // VolumeEventType is the event type that volumes generate. -) - -// Actor describes something that generates events, -// like a container, or a network, or a volume. -// It has a defined name and a set of attributes. -// The container attributes are its labels, other actors -// can generate these attributes from other properties. -type Actor struct { - ID string - Attributes map[string]string -} - -// Message represents the information an event contains -type Message struct { - // Deprecated information from JSONMessage. - // With data only in container events. - Status string `json:"status,omitempty"` // Deprecated: use Action instead. - ID string `json:"id,omitempty"` // Deprecated: use Actor.ID instead. - From string `json:"from,omitempty"` // Deprecated: use Actor.Attributes["image"] instead. - - Type Type - Action string - Actor Actor - // Engine events are local scope. Cluster events are swarm scope. - Scope string `json:"scope,omitempty"` - - Time int64 `json:"time,omitempty"` - TimeNano int64 `json:"timeNano,omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/filters/errors.go b/vendor/github.com/docker/docker/api/types/filters/errors.go deleted file mode 100644 index f52f69440..000000000 --- a/vendor/github.com/docker/docker/api/types/filters/errors.go +++ /dev/null @@ -1,37 +0,0 @@ -package filters - -import "fmt" - -// invalidFilter indicates that the provided filter or its value is invalid -type invalidFilter struct { - Filter string - Value []string -} - -func (e invalidFilter) Error() string { - msg := "invalid filter" - if e.Filter != "" { - msg += " '" + e.Filter - if e.Value != nil { - msg = fmt.Sprintf("%s=%s", msg, e.Value) - } - msg += "'" - } - return msg -} - -// InvalidParameter marks this error as ErrInvalidParameter -func (e invalidFilter) InvalidParameter() {} - -// unreachableCode is an error indicating that the code path was not expected to be reached. -type unreachableCode struct { - Filter string - Value []string -} - -// System marks this error as ErrSystem -func (e unreachableCode) System() {} - -func (e unreachableCode) Error() string { - return fmt.Sprintf("unreachable code reached for filter: %q with values: %s", e.Filter, e.Value) -} diff --git a/vendor/github.com/docker/docker/api/types/filters/parse.go b/vendor/github.com/docker/docker/api/types/filters/parse.go deleted file mode 100644 index 0c39ab5f1..000000000 --- a/vendor/github.com/docker/docker/api/types/filters/parse.go +++ /dev/null @@ -1,346 +0,0 @@ -/* -Package filters provides tools for encoding a mapping of keys to a set of -multiple values. -*/ -package filters // import "github.com/docker/docker/api/types/filters" - -import ( - "encoding/json" - "regexp" - "strings" - - "github.com/docker/docker/api/types/versions" -) - -// Args stores a mapping of keys to a set of multiple values. -type Args struct { - fields map[string]map[string]bool -} - -// KeyValuePair are used to initialize a new Args -type KeyValuePair struct { - Key string - Value string -} - -// Arg creates a new KeyValuePair for initializing Args -func Arg(key, value string) KeyValuePair { - return KeyValuePair{Key: key, Value: value} -} - -// NewArgs returns a new Args populated with the initial args -func NewArgs(initialArgs ...KeyValuePair) Args { - args := Args{fields: map[string]map[string]bool{}} - for _, arg := range initialArgs { - args.Add(arg.Key, arg.Value) - } - return args -} - -// Keys returns all the keys in list of Args -func (args Args) Keys() []string { - keys := make([]string, 0, len(args.fields)) - for k := range args.fields { - keys = append(keys, k) - } - return keys -} - -// MarshalJSON returns a JSON byte representation of the Args -func (args Args) MarshalJSON() ([]byte, error) { - if len(args.fields) == 0 { - return []byte("{}"), nil - } - return json.Marshal(args.fields) -} - -// ToJSON returns the Args as a JSON encoded string -func ToJSON(a Args) (string, error) { - if a.Len() == 0 { - return "", nil - } - buf, err := json.Marshal(a) - return string(buf), err -} - -// ToParamWithVersion encodes Args as a JSON string. If version is less than 1.22 -// then the encoded format will use an older legacy format where the values are a -// list of strings, instead of a set. -// -// Deprecated: do not use in any new code; use ToJSON instead -func ToParamWithVersion(version string, a Args) (string, error) { - if a.Len() == 0 { - return "", nil - } - - if version != "" && versions.LessThan(version, "1.22") { - buf, err := json.Marshal(convertArgsToSlice(a.fields)) - return string(buf), err - } - - return ToJSON(a) -} - -// FromJSON decodes a JSON encoded string into Args -func FromJSON(p string) (Args, error) { - args := NewArgs() - - if p == "" { - return args, nil - } - - raw := []byte(p) - err := json.Unmarshal(raw, &args) - if err == nil { - return args, nil - } - - // Fallback to parsing arguments in the legacy slice format - deprecated := map[string][]string{} - if legacyErr := json.Unmarshal(raw, &deprecated); legacyErr != nil { - return args, &invalidFilter{} - } - - args.fields = deprecatedArgs(deprecated) - return args, nil -} - -// UnmarshalJSON populates the Args from JSON encode bytes -func (args Args) UnmarshalJSON(raw []byte) error { - return json.Unmarshal(raw, &args.fields) -} - -// Get returns the list of values associated with the key -func (args Args) Get(key string) []string { - values := args.fields[key] - if values == nil { - return make([]string, 0) - } - slice := make([]string, 0, len(values)) - for key := range values { - slice = append(slice, key) - } - return slice -} - -// Add a new value to the set of values -func (args Args) Add(key, value string) { - if _, ok := args.fields[key]; ok { - args.fields[key][value] = true - } else { - args.fields[key] = map[string]bool{value: true} - } -} - -// Del removes a value from the set -func (args Args) Del(key, value string) { - if _, ok := args.fields[key]; ok { - delete(args.fields[key], value) - if len(args.fields[key]) == 0 { - delete(args.fields, key) - } - } -} - -// Len returns the number of keys in the mapping -func (args Args) Len() int { - return len(args.fields) -} - -// MatchKVList returns true if all the pairs in sources exist as key=value -// pairs in the mapping at key, or if there are no values at key. -func (args Args) MatchKVList(key string, sources map[string]string) bool { - fieldValues := args.fields[key] - - // do not filter if there is no filter set or cannot determine filter - if len(fieldValues) == 0 { - return true - } - - if len(sources) == 0 { - return false - } - - for value := range fieldValues { - testK, testV, hasValue := strings.Cut(value, "=") - - v, ok := sources[testK] - if !ok { - return false - } - if hasValue && testV != v { - return false - } - } - - return true -} - -// Match returns true if any of the values at key match the source string -func (args Args) Match(field, source string) bool { - if args.ExactMatch(field, source) { - return true - } - - fieldValues := args.fields[field] - for name2match := range fieldValues { - match, err := regexp.MatchString(name2match, source) - if err != nil { - continue - } - if match { - return true - } - } - return false -} - -// GetBoolOrDefault returns a boolean value of the key if the key is present -// and is intepretable as a boolean value. Otherwise the default value is returned. -// Error is not nil only if the filter values are not valid boolean or are conflicting. -func (args Args) GetBoolOrDefault(key string, defaultValue bool) (bool, error) { - fieldValues, ok := args.fields[key] - - if !ok { - return defaultValue, nil - } - - if len(fieldValues) == 0 { - return defaultValue, &invalidFilter{key, nil} - } - - isFalse := fieldValues["0"] || fieldValues["false"] - isTrue := fieldValues["1"] || fieldValues["true"] - - conflicting := isFalse && isTrue - invalid := !isFalse && !isTrue - - if conflicting || invalid { - return defaultValue, &invalidFilter{key, args.Get(key)} - } else if isFalse { - return false, nil - } else if isTrue { - return true, nil - } - - // This code shouldn't be reached. - return defaultValue, &unreachableCode{Filter: key, Value: args.Get(key)} -} - -// ExactMatch returns true if the source matches exactly one of the values. -func (args Args) ExactMatch(key, source string) bool { - fieldValues, ok := args.fields[key] - // do not filter if there is no filter set or cannot determine filter - if !ok || len(fieldValues) == 0 { - return true - } - - // try to match full name value to avoid O(N) regular expression matching - return fieldValues[source] -} - -// UniqueExactMatch returns true if there is only one value and the source -// matches exactly the value. -func (args Args) UniqueExactMatch(key, source string) bool { - fieldValues := args.fields[key] - // do not filter if there is no filter set or cannot determine filter - if len(fieldValues) == 0 { - return true - } - if len(args.fields[key]) != 1 { - return false - } - - // try to match full name value to avoid O(N) regular expression matching - return fieldValues[source] -} - -// FuzzyMatch returns true if the source matches exactly one value, or the -// source has one of the values as a prefix. -func (args Args) FuzzyMatch(key, source string) bool { - if args.ExactMatch(key, source) { - return true - } - - fieldValues := args.fields[key] - for prefix := range fieldValues { - if strings.HasPrefix(source, prefix) { - return true - } - } - return false -} - -// Contains returns true if the key exists in the mapping -func (args Args) Contains(field string) bool { - _, ok := args.fields[field] - return ok -} - -// Validate compared the set of accepted keys against the keys in the mapping. -// An error is returned if any mapping keys are not in the accepted set. -func (args Args) Validate(accepted map[string]bool) error { - for name := range args.fields { - if !accepted[name] { - return &invalidFilter{name, nil} - } - } - return nil -} - -// WalkValues iterates over the list of values for a key in the mapping and calls -// op() for each value. If op returns an error the iteration stops and the -// error is returned. -func (args Args) WalkValues(field string, op func(value string) error) error { - if _, ok := args.fields[field]; !ok { - return nil - } - for v := range args.fields[field] { - if err := op(v); err != nil { - return err - } - } - return nil -} - -// Clone returns a copy of args. -func (args Args) Clone() (newArgs Args) { - newArgs.fields = make(map[string]map[string]bool, len(args.fields)) - for k, m := range args.fields { - var mm map[string]bool - if m != nil { - mm = make(map[string]bool, len(m)) - for kk, v := range m { - mm[kk] = v - } - } - newArgs.fields[k] = mm - } - return newArgs -} - -func deprecatedArgs(d map[string][]string) map[string]map[string]bool { - m := map[string]map[string]bool{} - for k, v := range d { - values := map[string]bool{} - for _, vv := range v { - values[vv] = true - } - m[k] = values - } - return m -} - -func convertArgsToSlice(f map[string]map[string]bool) map[string][]string { - m := map[string][]string{} - for k, v := range f { - values := []string{} - for kk := range v { - if v[kk] { - values = append(values, kk) - } - } - m[k] = values - } - return m -} diff --git a/vendor/github.com/docker/docker/api/types/graph_driver_data.go b/vendor/github.com/docker/docker/api/types/graph_driver_data.go deleted file mode 100644 index ce3deb331..000000000 --- a/vendor/github.com/docker/docker/api/types/graph_driver_data.go +++ /dev/null @@ -1,23 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// GraphDriverData Information about the storage driver used to store the container's and -// image's filesystem. -// -// swagger:model GraphDriverData -type GraphDriverData struct { - - // Low-level storage metadata, provided as key/value pairs. - // - // This information is driver-specific, and depends on the storage-driver - // in use, and should be used for informational purposes only. - // - // Required: true - Data map[string]string `json:"Data"` - - // Name of the storage driver. - // Required: true - Name string `json:"Name"` -} diff --git a/vendor/github.com/docker/docker/api/types/id_response.go b/vendor/github.com/docker/docker/api/types/id_response.go deleted file mode 100644 index 7592d2f8b..000000000 --- a/vendor/github.com/docker/docker/api/types/id_response.go +++ /dev/null @@ -1,13 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// IDResponse Response to an API call that returns just an Id -// swagger:model IdResponse -type IDResponse struct { - - // The id of the newly created object. - // Required: true - ID string `json:"Id"` -} diff --git a/vendor/github.com/docker/docker/api/types/image/image_history.go b/vendor/github.com/docker/docker/api/types/image/image_history.go deleted file mode 100644 index e302bb0ae..000000000 --- a/vendor/github.com/docker/docker/api/types/image/image_history.go +++ /dev/null @@ -1,36 +0,0 @@ -package image // import "github.com/docker/docker/api/types/image" - -// ---------------------------------------------------------------------------- -// Code generated by `swagger generate operation`. DO NOT EDIT. -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -// HistoryResponseItem individual image layer information in response to ImageHistory operation -// swagger:model HistoryResponseItem -type HistoryResponseItem struct { - - // comment - // Required: true - Comment string `json:"Comment"` - - // created - // Required: true - Created int64 `json:"Created"` - - // created by - // Required: true - CreatedBy string `json:"CreatedBy"` - - // Id - // Required: true - ID string `json:"Id"` - - // size - // Required: true - Size int64 `json:"Size"` - - // tags - // Required: true - Tags []string `json:"Tags"` -} diff --git a/vendor/github.com/docker/docker/api/types/image/opts.go b/vendor/github.com/docker/docker/api/types/image/opts.go deleted file mode 100644 index 3cefecb0d..000000000 --- a/vendor/github.com/docker/docker/api/types/image/opts.go +++ /dev/null @@ -1,9 +0,0 @@ -package image - -import ocispec "github.com/opencontainers/image-spec/specs-go/v1" - -// GetImageOpts holds parameters to inspect an image. -type GetImageOpts struct { - Platform *ocispec.Platform - Details bool -} diff --git a/vendor/github.com/docker/docker/api/types/image_delete_response_item.go b/vendor/github.com/docker/docker/api/types/image_delete_response_item.go deleted file mode 100644 index b9a65a0d8..000000000 --- a/vendor/github.com/docker/docker/api/types/image_delete_response_item.go +++ /dev/null @@ -1,15 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// ImageDeleteResponseItem image delete response item -// swagger:model ImageDeleteResponseItem -type ImageDeleteResponseItem struct { - - // The image ID of an image that was deleted - Deleted string `json:"Deleted,omitempty"` - - // The image ID of an image that was untagged - Untagged string `json:"Untagged,omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/image_summary.go b/vendor/github.com/docker/docker/api/types/image_summary.go deleted file mode 100644 index 0f6f14484..000000000 --- a/vendor/github.com/docker/docker/api/types/image_summary.go +++ /dev/null @@ -1,94 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// ImageSummary image summary -// swagger:model ImageSummary -type ImageSummary struct { - - // Number of containers using this image. Includes both stopped and running - // containers. - // - // This size is not calculated by default, and depends on which API endpoint - // is used. `-1` indicates that the value has not been set / calculated. - // - // Required: true - Containers int64 `json:"Containers"` - - // Date and time at which the image was created as a Unix timestamp - // (number of seconds sinds EPOCH). - // - // Required: true - Created int64 `json:"Created"` - - // ID is the content-addressable ID of an image. - // - // This identifier is a content-addressable digest calculated from the - // image's configuration (which includes the digests of layers used by - // the image). - // - // Note that this digest differs from the `RepoDigests` below, which - // holds digests of image manifests that reference the image. - // - // Required: true - ID string `json:"Id"` - - // User-defined key/value metadata. - // Required: true - Labels map[string]string `json:"Labels"` - - // ID of the parent image. - // - // Depending on how the image was created, this field may be empty and - // is only set for images that were built/created locally. This field - // is empty if the image was pulled from an image registry. - // - // Required: true - ParentID string `json:"ParentId"` - - // List of content-addressable digests of locally available image manifests - // that the image is referenced from. Multiple manifests can refer to the - // same image. - // - // These digests are usually only available if the image was either pulled - // from a registry, or if the image was pushed to a registry, which is when - // the manifest is generated and its digest calculated. - // - // Required: true - RepoDigests []string `json:"RepoDigests"` - - // List of image names/tags in the local image cache that reference this - // image. - // - // Multiple image tags can refer to the same image, and this list may be - // empty if no tags reference the image, in which case the image is - // "untagged", in which case it can still be referenced by its ID. - // - // Required: true - RepoTags []string `json:"RepoTags"` - - // Total size of image layers that are shared between this image and other - // images. - // - // This size is not calculated by default. `-1` indicates that the value - // has not been set / calculated. - // - // Required: true - SharedSize int64 `json:"SharedSize"` - - // Total size of the image including all layers it is composed of. - // - // Required: true - Size int64 `json:"Size"` - - // Total size of the image including all layers it is composed of. - // - // In versions of Docker before v1.10, this field was calculated from - // the image itself and all of its parent images. Images are now stored - // self-contained, and no longer use a parent-chain, making this field - // an equivalent of the Size field. - // - // Deprecated: this field is kept for backward compatibility, and will be removed in API v1.44. - VirtualSize int64 `json:"VirtualSize,omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/mount/mount.go b/vendor/github.com/docker/docker/api/types/mount/mount.go deleted file mode 100644 index ac4ce6223..000000000 --- a/vendor/github.com/docker/docker/api/types/mount/mount.go +++ /dev/null @@ -1,140 +0,0 @@ -package mount // import "github.com/docker/docker/api/types/mount" - -import ( - "os" -) - -// Type represents the type of a mount. -type Type string - -// Type constants -const ( - // TypeBind is the type for mounting host dir - TypeBind Type = "bind" - // TypeVolume is the type for remote storage volumes - TypeVolume Type = "volume" - // TypeTmpfs is the type for mounting tmpfs - TypeTmpfs Type = "tmpfs" - // TypeNamedPipe is the type for mounting Windows named pipes - TypeNamedPipe Type = "npipe" - // TypeCluster is the type for Swarm Cluster Volumes. - TypeCluster Type = "cluster" -) - -// Mount represents a mount (volume). -type Mount struct { - Type Type `json:",omitempty"` - // Source specifies the name of the mount. Depending on mount type, this - // may be a volume name or a host path, or even ignored. - // Source is not supported for tmpfs (must be an empty value) - Source string `json:",omitempty"` - Target string `json:",omitempty"` - ReadOnly bool `json:",omitempty"` - Consistency Consistency `json:",omitempty"` - - BindOptions *BindOptions `json:",omitempty"` - VolumeOptions *VolumeOptions `json:",omitempty"` - TmpfsOptions *TmpfsOptions `json:",omitempty"` - ClusterOptions *ClusterOptions `json:",omitempty"` -} - -// Propagation represents the propagation of a mount. -type Propagation string - -const ( - // PropagationRPrivate RPRIVATE - PropagationRPrivate Propagation = "rprivate" - // PropagationPrivate PRIVATE - PropagationPrivate Propagation = "private" - // PropagationRShared RSHARED - PropagationRShared Propagation = "rshared" - // PropagationShared SHARED - PropagationShared Propagation = "shared" - // PropagationRSlave RSLAVE - PropagationRSlave Propagation = "rslave" - // PropagationSlave SLAVE - PropagationSlave Propagation = "slave" -) - -// Propagations is the list of all valid mount propagations -var Propagations = []Propagation{ - PropagationRPrivate, - PropagationPrivate, - PropagationRShared, - PropagationShared, - PropagationRSlave, - PropagationSlave, -} - -// Consistency represents the consistency requirements of a mount. -type Consistency string - -const ( - // ConsistencyFull guarantees bind mount-like consistency - ConsistencyFull Consistency = "consistent" - // ConsistencyCached mounts can cache read data and FS structure - ConsistencyCached Consistency = "cached" - // ConsistencyDelegated mounts can cache read and written data and structure - ConsistencyDelegated Consistency = "delegated" - // ConsistencyDefault provides "consistent" behavior unless overridden - ConsistencyDefault Consistency = "default" -) - -// BindOptions defines options specific to mounts of type "bind". -type BindOptions struct { - Propagation Propagation `json:",omitempty"` - NonRecursive bool `json:",omitempty"` - CreateMountpoint bool `json:",omitempty"` -} - -// VolumeOptions represents the options for a mount of type volume. -type VolumeOptions struct { - NoCopy bool `json:",omitempty"` - Labels map[string]string `json:",omitempty"` - DriverConfig *Driver `json:",omitempty"` -} - -// Driver represents a volume driver. -type Driver struct { - Name string `json:",omitempty"` - Options map[string]string `json:",omitempty"` -} - -// TmpfsOptions defines options specific to mounts of type "tmpfs". -type TmpfsOptions struct { - // Size sets the size of the tmpfs, in bytes. - // - // This will be converted to an operating system specific value - // depending on the host. For example, on linux, it will be converted to - // use a 'k', 'm' or 'g' syntax. BSD, though not widely supported with - // docker, uses a straight byte value. - // - // Percentages are not supported. - SizeBytes int64 `json:",omitempty"` - // Mode of the tmpfs upon creation - Mode os.FileMode `json:",omitempty"` - - // TODO(stevvooe): There are several more tmpfs flags, specified in the - // daemon, that are accepted. Only the most basic are added for now. - // - // From https://github.com/moby/sys/blob/mount/v0.1.1/mount/flags.go#L47-L56 - // - // var validFlags = map[string]bool{ - // "": true, - // "size": true, X - // "mode": true, X - // "uid": true, - // "gid": true, - // "nr_inodes": true, - // "nr_blocks": true, - // "mpol": true, - // } - // - // Some of these may be straightforward to add, but others, such as - // uid/gid have implications in a clustered system. -} - -// ClusterOptions specifies options for a Cluster volume. -type ClusterOptions struct { - // intentionally empty -} diff --git a/vendor/github.com/docker/docker/api/types/network/network.go b/vendor/github.com/docker/docker/api/types/network/network.go deleted file mode 100644 index 437b184c6..000000000 --- a/vendor/github.com/docker/docker/api/types/network/network.go +++ /dev/null @@ -1,126 +0,0 @@ -package network // import "github.com/docker/docker/api/types/network" -import ( - "github.com/docker/docker/api/types/filters" -) - -// Address represents an IP address -type Address struct { - Addr string - PrefixLen int -} - -// IPAM represents IP Address Management -type IPAM struct { - Driver string - Options map[string]string // Per network IPAM driver options - Config []IPAMConfig -} - -// IPAMConfig represents IPAM configurations -type IPAMConfig struct { - Subnet string `json:",omitempty"` - IPRange string `json:",omitempty"` - Gateway string `json:",omitempty"` - AuxAddress map[string]string `json:"AuxiliaryAddresses,omitempty"` -} - -// EndpointIPAMConfig represents IPAM configurations for the endpoint -type EndpointIPAMConfig struct { - IPv4Address string `json:",omitempty"` - IPv6Address string `json:",omitempty"` - LinkLocalIPs []string `json:",omitempty"` -} - -// Copy makes a copy of the endpoint ipam config -func (cfg *EndpointIPAMConfig) Copy() *EndpointIPAMConfig { - cfgCopy := *cfg - cfgCopy.LinkLocalIPs = make([]string, 0, len(cfg.LinkLocalIPs)) - cfgCopy.LinkLocalIPs = append(cfgCopy.LinkLocalIPs, cfg.LinkLocalIPs...) - return &cfgCopy -} - -// PeerInfo represents one peer of an overlay network -type PeerInfo struct { - Name string - IP string -} - -// EndpointSettings stores the network endpoint details -type EndpointSettings struct { - // Configurations - IPAMConfig *EndpointIPAMConfig - Links []string - Aliases []string - // Operational data - NetworkID string - EndpointID string - Gateway string - IPAddress string - IPPrefixLen int - IPv6Gateway string - GlobalIPv6Address string - GlobalIPv6PrefixLen int - MacAddress string - DriverOpts map[string]string -} - -// Task carries the information about one backend task -type Task struct { - Name string - EndpointID string - EndpointIP string - Info map[string]string -} - -// ServiceInfo represents service parameters with the list of service's tasks -type ServiceInfo struct { - VIP string - Ports []string - LocalLBIndex int - Tasks []Task -} - -// Copy makes a deep copy of `EndpointSettings` -func (es *EndpointSettings) Copy() *EndpointSettings { - epCopy := *es - if es.IPAMConfig != nil { - epCopy.IPAMConfig = es.IPAMConfig.Copy() - } - - if es.Links != nil { - links := make([]string, 0, len(es.Links)) - epCopy.Links = append(links, es.Links...) - } - - if es.Aliases != nil { - aliases := make([]string, 0, len(es.Aliases)) - epCopy.Aliases = append(aliases, es.Aliases...) - } - return &epCopy -} - -// NetworkingConfig represents the container's networking configuration for each of its interfaces -// Carries the networking configs specified in the `docker run` and `docker network connect` commands -type NetworkingConfig struct { - EndpointsConfig map[string]*EndpointSettings // Endpoint configs for each connecting network -} - -// ConfigReference specifies the source which provides a network's configuration -type ConfigReference struct { - Network string -} - -var acceptedFilters = map[string]bool{ - "dangling": true, - "driver": true, - "id": true, - "label": true, - "name": true, - "scope": true, - "type": true, -} - -// ValidateFilters validates the list of filter args with the available filters. -func ValidateFilters(filter filters.Args) error { - return filter.Validate(acceptedFilters) -} diff --git a/vendor/github.com/docker/docker/api/types/plugin.go b/vendor/github.com/docker/docker/api/types/plugin.go deleted file mode 100644 index abae48b9a..000000000 --- a/vendor/github.com/docker/docker/api/types/plugin.go +++ /dev/null @@ -1,203 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// Plugin A plugin for the Engine API -// swagger:model Plugin -type Plugin struct { - - // config - // Required: true - Config PluginConfig `json:"Config"` - - // True if the plugin is running. False if the plugin is not running, only installed. - // Required: true - Enabled bool `json:"Enabled"` - - // Id - ID string `json:"Id,omitempty"` - - // name - // Required: true - Name string `json:"Name"` - - // plugin remote reference used to push/pull the plugin - PluginReference string `json:"PluginReference,omitempty"` - - // settings - // Required: true - Settings PluginSettings `json:"Settings"` -} - -// PluginConfig The config of a plugin. -// swagger:model PluginConfig -type PluginConfig struct { - - // args - // Required: true - Args PluginConfigArgs `json:"Args"` - - // description - // Required: true - Description string `json:"Description"` - - // Docker Version used to create the plugin - DockerVersion string `json:"DockerVersion,omitempty"` - - // documentation - // Required: true - Documentation string `json:"Documentation"` - - // entrypoint - // Required: true - Entrypoint []string `json:"Entrypoint"` - - // env - // Required: true - Env []PluginEnv `json:"Env"` - - // interface - // Required: true - Interface PluginConfigInterface `json:"Interface"` - - // ipc host - // Required: true - IpcHost bool `json:"IpcHost"` - - // linux - // Required: true - Linux PluginConfigLinux `json:"Linux"` - - // mounts - // Required: true - Mounts []PluginMount `json:"Mounts"` - - // network - // Required: true - Network PluginConfigNetwork `json:"Network"` - - // pid host - // Required: true - PidHost bool `json:"PidHost"` - - // propagated mount - // Required: true - PropagatedMount string `json:"PropagatedMount"` - - // user - User PluginConfigUser `json:"User,omitempty"` - - // work dir - // Required: true - WorkDir string `json:"WorkDir"` - - // rootfs - Rootfs *PluginConfigRootfs `json:"rootfs,omitempty"` -} - -// PluginConfigArgs plugin config args -// swagger:model PluginConfigArgs -type PluginConfigArgs struct { - - // description - // Required: true - Description string `json:"Description"` - - // name - // Required: true - Name string `json:"Name"` - - // settable - // Required: true - Settable []string `json:"Settable"` - - // value - // Required: true - Value []string `json:"Value"` -} - -// PluginConfigInterface The interface between Docker and the plugin -// swagger:model PluginConfigInterface -type PluginConfigInterface struct { - - // Protocol to use for clients connecting to the plugin. - ProtocolScheme string `json:"ProtocolScheme,omitempty"` - - // socket - // Required: true - Socket string `json:"Socket"` - - // types - // Required: true - Types []PluginInterfaceType `json:"Types"` -} - -// PluginConfigLinux plugin config linux -// swagger:model PluginConfigLinux -type PluginConfigLinux struct { - - // allow all devices - // Required: true - AllowAllDevices bool `json:"AllowAllDevices"` - - // capabilities - // Required: true - Capabilities []string `json:"Capabilities"` - - // devices - // Required: true - Devices []PluginDevice `json:"Devices"` -} - -// PluginConfigNetwork plugin config network -// swagger:model PluginConfigNetwork -type PluginConfigNetwork struct { - - // type - // Required: true - Type string `json:"Type"` -} - -// PluginConfigRootfs plugin config rootfs -// swagger:model PluginConfigRootfs -type PluginConfigRootfs struct { - - // diff ids - DiffIds []string `json:"diff_ids"` - - // type - Type string `json:"type,omitempty"` -} - -// PluginConfigUser plugin config user -// swagger:model PluginConfigUser -type PluginConfigUser struct { - - // g ID - GID uint32 `json:"GID,omitempty"` - - // UID - UID uint32 `json:"UID,omitempty"` -} - -// PluginSettings Settings that can be modified by users. -// swagger:model PluginSettings -type PluginSettings struct { - - // args - // Required: true - Args []string `json:"Args"` - - // devices - // Required: true - Devices []PluginDevice `json:"Devices"` - - // env - // Required: true - Env []string `json:"Env"` - - // mounts - // Required: true - Mounts []PluginMount `json:"Mounts"` -} diff --git a/vendor/github.com/docker/docker/api/types/plugin_device.go b/vendor/github.com/docker/docker/api/types/plugin_device.go deleted file mode 100644 index 569901067..000000000 --- a/vendor/github.com/docker/docker/api/types/plugin_device.go +++ /dev/null @@ -1,25 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// PluginDevice plugin device -// swagger:model PluginDevice -type PluginDevice struct { - - // description - // Required: true - Description string `json:"Description"` - - // name - // Required: true - Name string `json:"Name"` - - // path - // Required: true - Path *string `json:"Path"` - - // settable - // Required: true - Settable []string `json:"Settable"` -} diff --git a/vendor/github.com/docker/docker/api/types/plugin_env.go b/vendor/github.com/docker/docker/api/types/plugin_env.go deleted file mode 100644 index 32962dc2e..000000000 --- a/vendor/github.com/docker/docker/api/types/plugin_env.go +++ /dev/null @@ -1,25 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// PluginEnv plugin env -// swagger:model PluginEnv -type PluginEnv struct { - - // description - // Required: true - Description string `json:"Description"` - - // name - // Required: true - Name string `json:"Name"` - - // settable - // Required: true - Settable []string `json:"Settable"` - - // value - // Required: true - Value *string `json:"Value"` -} diff --git a/vendor/github.com/docker/docker/api/types/plugin_interface_type.go b/vendor/github.com/docker/docker/api/types/plugin_interface_type.go deleted file mode 100644 index c82f204e8..000000000 --- a/vendor/github.com/docker/docker/api/types/plugin_interface_type.go +++ /dev/null @@ -1,21 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// PluginInterfaceType plugin interface type -// swagger:model PluginInterfaceType -type PluginInterfaceType struct { - - // capability - // Required: true - Capability string `json:"Capability"` - - // prefix - // Required: true - Prefix string `json:"Prefix"` - - // version - // Required: true - Version string `json:"Version"` -} diff --git a/vendor/github.com/docker/docker/api/types/plugin_mount.go b/vendor/github.com/docker/docker/api/types/plugin_mount.go deleted file mode 100644 index 5c031cf8b..000000000 --- a/vendor/github.com/docker/docker/api/types/plugin_mount.go +++ /dev/null @@ -1,37 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// PluginMount plugin mount -// swagger:model PluginMount -type PluginMount struct { - - // description - // Required: true - Description string `json:"Description"` - - // destination - // Required: true - Destination string `json:"Destination"` - - // name - // Required: true - Name string `json:"Name"` - - // options - // Required: true - Options []string `json:"Options"` - - // settable - // Required: true - Settable []string `json:"Settable"` - - // source - // Required: true - Source *string `json:"Source"` - - // type - // Required: true - Type string `json:"Type"` -} diff --git a/vendor/github.com/docker/docker/api/types/plugin_responses.go b/vendor/github.com/docker/docker/api/types/plugin_responses.go deleted file mode 100644 index 60d1fb5ad..000000000 --- a/vendor/github.com/docker/docker/api/types/plugin_responses.go +++ /dev/null @@ -1,71 +0,0 @@ -package types // import "github.com/docker/docker/api/types" - -import ( - "encoding/json" - "fmt" - "sort" -) - -// PluginsListResponse contains the response for the Engine API -type PluginsListResponse []*Plugin - -// UnmarshalJSON implements json.Unmarshaler for PluginInterfaceType -func (t *PluginInterfaceType) UnmarshalJSON(p []byte) error { - versionIndex := len(p) - prefixIndex := 0 - if len(p) < 2 || p[0] != '"' || p[len(p)-1] != '"' { - return fmt.Errorf("%q is not a plugin interface type", p) - } - p = p[1 : len(p)-1] -loop: - for i, b := range p { - switch b { - case '.': - prefixIndex = i - case '/': - versionIndex = i - break loop - } - } - t.Prefix = string(p[:prefixIndex]) - t.Capability = string(p[prefixIndex+1 : versionIndex]) - if versionIndex < len(p) { - t.Version = string(p[versionIndex+1:]) - } - return nil -} - -// MarshalJSON implements json.Marshaler for PluginInterfaceType -func (t *PluginInterfaceType) MarshalJSON() ([]byte, error) { - return json.Marshal(t.String()) -} - -// String implements fmt.Stringer for PluginInterfaceType -func (t PluginInterfaceType) String() string { - return fmt.Sprintf("%s.%s/%s", t.Prefix, t.Capability, t.Version) -} - -// PluginPrivilege describes a permission the user has to accept -// upon installing a plugin. -type PluginPrivilege struct { - Name string - Description string - Value []string -} - -// PluginPrivileges is a list of PluginPrivilege -type PluginPrivileges []PluginPrivilege - -func (s PluginPrivileges) Len() int { - return len(s) -} - -func (s PluginPrivileges) Less(i, j int) bool { - return s[i].Name < s[j].Name -} - -func (s PluginPrivileges) Swap(i, j int) { - sort.Strings(s[i].Value) - sort.Strings(s[j].Value) - s[i], s[j] = s[j], s[i] -} diff --git a/vendor/github.com/docker/docker/api/types/port.go b/vendor/github.com/docker/docker/api/types/port.go deleted file mode 100644 index d91234744..000000000 --- a/vendor/github.com/docker/docker/api/types/port.go +++ /dev/null @@ -1,23 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// Port An open port on a container -// swagger:model Port -type Port struct { - - // Host IP address that the container's port is mapped to - IP string `json:"IP,omitempty"` - - // Port on the container - // Required: true - PrivatePort uint16 `json:"PrivatePort"` - - // Port exposed on the host - PublicPort uint16 `json:"PublicPort,omitempty"` - - // type - // Required: true - Type string `json:"Type"` -} diff --git a/vendor/github.com/docker/docker/api/types/registry/authconfig.go b/vendor/github.com/docker/docker/api/types/registry/authconfig.go deleted file mode 100644 index 97a924e37..000000000 --- a/vendor/github.com/docker/docker/api/types/registry/authconfig.go +++ /dev/null @@ -1,99 +0,0 @@ -package registry // import "github.com/docker/docker/api/types/registry" -import ( - "encoding/base64" - "encoding/json" - "io" - "strings" - - "github.com/pkg/errors" -) - -// AuthHeader is the name of the header used to send encoded registry -// authorization credentials for registry operations (push/pull). -const AuthHeader = "X-Registry-Auth" - -// AuthConfig contains authorization information for connecting to a Registry. -type AuthConfig struct { - Username string `json:"username,omitempty"` - Password string `json:"password,omitempty"` - Auth string `json:"auth,omitempty"` - - // Email is an optional value associated with the username. - // This field is deprecated and will be removed in a later - // version of docker. - Email string `json:"email,omitempty"` - - ServerAddress string `json:"serveraddress,omitempty"` - - // IdentityToken is used to authenticate the user and get - // an access token for the registry. - IdentityToken string `json:"identitytoken,omitempty"` - - // RegistryToken is a bearer token to be sent to a registry - RegistryToken string `json:"registrytoken,omitempty"` -} - -// EncodeAuthConfig serializes the auth configuration as a base64url encoded -// RFC4648, section 5) JSON string for sending through the X-Registry-Auth header. -// -// For details on base64url encoding, see: -// - RFC4648, section 5: https://tools.ietf.org/html/rfc4648#section-5 -func EncodeAuthConfig(authConfig AuthConfig) (string, error) { - buf, err := json.Marshal(authConfig) - if err != nil { - return "", errInvalidParameter{err} - } - return base64.URLEncoding.EncodeToString(buf), nil -} - -// DecodeAuthConfig decodes base64url encoded (RFC4648, section 5) JSON -// authentication information as sent through the X-Registry-Auth header. -// -// This function always returns an AuthConfig, even if an error occurs. It is up -// to the caller to decide if authentication is required, and if the error can -// be ignored. -// -// For details on base64url encoding, see: -// - RFC4648, section 5: https://tools.ietf.org/html/rfc4648#section-5 -func DecodeAuthConfig(authEncoded string) (*AuthConfig, error) { - if authEncoded == "" { - return &AuthConfig{}, nil - } - - authJSON := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded)) - return decodeAuthConfigFromReader(authJSON) -} - -// DecodeAuthConfigBody decodes authentication information as sent as JSON in the -// body of a request. This function is to provide backward compatibility with old -// clients and API versions. Current clients and API versions expect authentication -// to be provided through the X-Registry-Auth header. -// -// Like DecodeAuthConfig, this function always returns an AuthConfig, even if an -// error occurs. It is up to the caller to decide if authentication is required, -// and if the error can be ignored. -func DecodeAuthConfigBody(rdr io.ReadCloser) (*AuthConfig, error) { - return decodeAuthConfigFromReader(rdr) -} - -func decodeAuthConfigFromReader(rdr io.Reader) (*AuthConfig, error) { - authConfig := &AuthConfig{} - if err := json.NewDecoder(rdr).Decode(authConfig); err != nil { - // always return an (empty) AuthConfig to increase compatibility with - // the existing API. - return &AuthConfig{}, invalid(err) - } - return authConfig, nil -} - -func invalid(err error) error { - return errInvalidParameter{errors.Wrap(err, "invalid X-Registry-Auth header")} -} - -type errInvalidParameter struct{ error } - -func (errInvalidParameter) InvalidParameter() {} - -func (e errInvalidParameter) Cause() error { return e.error } - -func (e errInvalidParameter) Unwrap() error { return e.error } diff --git a/vendor/github.com/docker/docker/api/types/registry/authenticate.go b/vendor/github.com/docker/docker/api/types/registry/authenticate.go deleted file mode 100644 index f0a2113e4..000000000 --- a/vendor/github.com/docker/docker/api/types/registry/authenticate.go +++ /dev/null @@ -1,21 +0,0 @@ -package registry // import "github.com/docker/docker/api/types/registry" - -// ---------------------------------------------------------------------------- -// DO NOT EDIT THIS FILE -// This file was generated by `swagger generate operation` -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -// AuthenticateOKBody authenticate o k body -// swagger:model AuthenticateOKBody -type AuthenticateOKBody struct { - - // An opaque token used to authenticate a user after a successful login - // Required: true - IdentityToken string `json:"IdentityToken"` - - // The status of the authentication - // Required: true - Status string `json:"Status"` -} diff --git a/vendor/github.com/docker/docker/api/types/registry/registry.go b/vendor/github.com/docker/docker/api/types/registry/registry.go deleted file mode 100644 index b83f5d7b2..000000000 --- a/vendor/github.com/docker/docker/api/types/registry/registry.go +++ /dev/null @@ -1,120 +0,0 @@ -package registry // import "github.com/docker/docker/api/types/registry" - -import ( - "encoding/json" - "net" - - ocispec "github.com/opencontainers/image-spec/specs-go/v1" -) - -// ServiceConfig stores daemon registry services configuration. -type ServiceConfig struct { - AllowNondistributableArtifactsCIDRs []*NetIPNet - AllowNondistributableArtifactsHostnames []string - InsecureRegistryCIDRs []*NetIPNet `json:"InsecureRegistryCIDRs"` - IndexConfigs map[string]*IndexInfo `json:"IndexConfigs"` - Mirrors []string -} - -// NetIPNet is the net.IPNet type, which can be marshalled and -// unmarshalled to JSON -type NetIPNet net.IPNet - -// String returns the CIDR notation of ipnet -func (ipnet *NetIPNet) String() string { - return (*net.IPNet)(ipnet).String() -} - -// MarshalJSON returns the JSON representation of the IPNet -func (ipnet *NetIPNet) MarshalJSON() ([]byte, error) { - return json.Marshal((*net.IPNet)(ipnet).String()) -} - -// UnmarshalJSON sets the IPNet from a byte array of JSON -func (ipnet *NetIPNet) UnmarshalJSON(b []byte) (err error) { - var ipnetStr string - if err = json.Unmarshal(b, &ipnetStr); err == nil { - var cidr *net.IPNet - if _, cidr, err = net.ParseCIDR(ipnetStr); err == nil { - *ipnet = NetIPNet(*cidr) - } - } - return -} - -// IndexInfo contains information about a registry -// -// RepositoryInfo Examples: -// -// { -// "Index" : { -// "Name" : "docker.io", -// "Mirrors" : ["https://registry-2.docker.io/v1/", "https://registry-3.docker.io/v1/"], -// "Secure" : true, -// "Official" : true, -// }, -// "RemoteName" : "library/debian", -// "LocalName" : "debian", -// "CanonicalName" : "docker.io/debian" -// "Official" : true, -// } -// -// { -// "Index" : { -// "Name" : "127.0.0.1:5000", -// "Mirrors" : [], -// "Secure" : false, -// "Official" : false, -// }, -// "RemoteName" : "user/repo", -// "LocalName" : "127.0.0.1:5000/user/repo", -// "CanonicalName" : "127.0.0.1:5000/user/repo", -// "Official" : false, -// } -type IndexInfo struct { - // Name is the name of the registry, such as "docker.io" - Name string - // Mirrors is a list of mirrors, expressed as URIs - Mirrors []string - // Secure is set to false if the registry is part of the list of - // insecure registries. Insecure registries accept HTTP and/or accept - // HTTPS with certificates from unknown CAs. - Secure bool - // Official indicates whether this is an official registry - Official bool -} - -// SearchResult describes a search result returned from a registry -type SearchResult struct { - // StarCount indicates the number of stars this repository has - StarCount int `json:"star_count"` - // IsOfficial is true if the result is from an official repository. - IsOfficial bool `json:"is_official"` - // Name is the name of the repository - Name string `json:"name"` - // IsAutomated indicates whether the result is automated - IsAutomated bool `json:"is_automated"` - // Description is a textual description of the repository - Description string `json:"description"` -} - -// SearchResults lists a collection search results returned from a registry -type SearchResults struct { - // Query contains the query string that generated the search results - Query string `json:"query"` - // NumResults indicates the number of results the query returned - NumResults int `json:"num_results"` - // Results is a slice containing the actual results for the search - Results []SearchResult `json:"results"` -} - -// DistributionInspect describes the result obtained from contacting the -// registry to retrieve image metadata -type DistributionInspect struct { - // Descriptor contains information about the manifest, including - // the content addressable digest - Descriptor ocispec.Descriptor - // Platforms contains the list of platforms supported by the image, - // obtained by parsing the manifest - Platforms []ocispec.Platform -} diff --git a/vendor/github.com/docker/docker/api/types/service_update_response.go b/vendor/github.com/docker/docker/api/types/service_update_response.go deleted file mode 100644 index 74ea64b1b..000000000 --- a/vendor/github.com/docker/docker/api/types/service_update_response.go +++ /dev/null @@ -1,12 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// ServiceUpdateResponse service update response -// swagger:model ServiceUpdateResponse -type ServiceUpdateResponse struct { - - // Optional warning messages - Warnings []string `json:"Warnings"` -} diff --git a/vendor/github.com/docker/docker/api/types/stats.go b/vendor/github.com/docker/docker/api/types/stats.go deleted file mode 100644 index 20daebed1..000000000 --- a/vendor/github.com/docker/docker/api/types/stats.go +++ /dev/null @@ -1,181 +0,0 @@ -// Package types is used for API stability in the types and response to the -// consumers of the API stats endpoint. -package types // import "github.com/docker/docker/api/types" - -import "time" - -// ThrottlingData stores CPU throttling stats of one running container. -// Not used on Windows. -type ThrottlingData struct { - // Number of periods with throttling active - Periods uint64 `json:"periods"` - // Number of periods when the container hits its throttling limit. - ThrottledPeriods uint64 `json:"throttled_periods"` - // Aggregate time the container was throttled for in nanoseconds. - ThrottledTime uint64 `json:"throttled_time"` -} - -// CPUUsage stores All CPU stats aggregated since container inception. -type CPUUsage struct { - // Total CPU time consumed. - // Units: nanoseconds (Linux) - // Units: 100's of nanoseconds (Windows) - TotalUsage uint64 `json:"total_usage"` - - // Total CPU time consumed per core (Linux). Not used on Windows. - // Units: nanoseconds. - PercpuUsage []uint64 `json:"percpu_usage,omitempty"` - - // Time spent by tasks of the cgroup in kernel mode (Linux). - // Time spent by all container processes in kernel mode (Windows). - // Units: nanoseconds (Linux). - // Units: 100's of nanoseconds (Windows). Not populated for Hyper-V Containers. - UsageInKernelmode uint64 `json:"usage_in_kernelmode"` - - // Time spent by tasks of the cgroup in user mode (Linux). - // Time spent by all container processes in user mode (Windows). - // Units: nanoseconds (Linux). - // Units: 100's of nanoseconds (Windows). Not populated for Hyper-V Containers - UsageInUsermode uint64 `json:"usage_in_usermode"` -} - -// CPUStats aggregates and wraps all CPU related info of container -type CPUStats struct { - // CPU Usage. Linux and Windows. - CPUUsage CPUUsage `json:"cpu_usage"` - - // System Usage. Linux only. - SystemUsage uint64 `json:"system_cpu_usage,omitempty"` - - // Online CPUs. Linux only. - OnlineCPUs uint32 `json:"online_cpus,omitempty"` - - // Throttling Data. Linux only. - ThrottlingData ThrottlingData `json:"throttling_data,omitempty"` -} - -// MemoryStats aggregates all memory stats since container inception on Linux. -// Windows returns stats for commit and private working set only. -type MemoryStats struct { - // Linux Memory Stats - - // current res_counter usage for memory - Usage uint64 `json:"usage,omitempty"` - // maximum usage ever recorded. - MaxUsage uint64 `json:"max_usage,omitempty"` - // TODO(vishh): Export these as stronger types. - // all the stats exported via memory.stat. - Stats map[string]uint64 `json:"stats,omitempty"` - // number of times memory usage hits limits. - Failcnt uint64 `json:"failcnt,omitempty"` - Limit uint64 `json:"limit,omitempty"` - - // Windows Memory Stats - // See https://technet.microsoft.com/en-us/magazine/ff382715.aspx - - // committed bytes - Commit uint64 `json:"commitbytes,omitempty"` - // peak committed bytes - CommitPeak uint64 `json:"commitpeakbytes,omitempty"` - // private working set - PrivateWorkingSet uint64 `json:"privateworkingset,omitempty"` -} - -// BlkioStatEntry is one small entity to store a piece of Blkio stats -// Not used on Windows. -type BlkioStatEntry struct { - Major uint64 `json:"major"` - Minor uint64 `json:"minor"` - Op string `json:"op"` - Value uint64 `json:"value"` -} - -// BlkioStats stores All IO service stats for data read and write. -// This is a Linux specific structure as the differences between expressing -// block I/O on Windows and Linux are sufficiently significant to make -// little sense attempting to morph into a combined structure. -type BlkioStats struct { - // number of bytes transferred to and from the block device - IoServiceBytesRecursive []BlkioStatEntry `json:"io_service_bytes_recursive"` - IoServicedRecursive []BlkioStatEntry `json:"io_serviced_recursive"` - IoQueuedRecursive []BlkioStatEntry `json:"io_queue_recursive"` - IoServiceTimeRecursive []BlkioStatEntry `json:"io_service_time_recursive"` - IoWaitTimeRecursive []BlkioStatEntry `json:"io_wait_time_recursive"` - IoMergedRecursive []BlkioStatEntry `json:"io_merged_recursive"` - IoTimeRecursive []BlkioStatEntry `json:"io_time_recursive"` - SectorsRecursive []BlkioStatEntry `json:"sectors_recursive"` -} - -// StorageStats is the disk I/O stats for read/write on Windows. -type StorageStats struct { - ReadCountNormalized uint64 `json:"read_count_normalized,omitempty"` - ReadSizeBytes uint64 `json:"read_size_bytes,omitempty"` - WriteCountNormalized uint64 `json:"write_count_normalized,omitempty"` - WriteSizeBytes uint64 `json:"write_size_bytes,omitempty"` -} - -// NetworkStats aggregates the network stats of one container -type NetworkStats struct { - // Bytes received. Windows and Linux. - RxBytes uint64 `json:"rx_bytes"` - // Packets received. Windows and Linux. - RxPackets uint64 `json:"rx_packets"` - // Received errors. Not used on Windows. Note that we don't `omitempty` this - // field as it is expected in the >=v1.21 API stats structure. - RxErrors uint64 `json:"rx_errors"` - // Incoming packets dropped. Windows and Linux. - RxDropped uint64 `json:"rx_dropped"` - // Bytes sent. Windows and Linux. - TxBytes uint64 `json:"tx_bytes"` - // Packets sent. Windows and Linux. - TxPackets uint64 `json:"tx_packets"` - // Sent errors. Not used on Windows. Note that we don't `omitempty` this - // field as it is expected in the >=v1.21 API stats structure. - TxErrors uint64 `json:"tx_errors"` - // Outgoing packets dropped. Windows and Linux. - TxDropped uint64 `json:"tx_dropped"` - // Endpoint ID. Not used on Linux. - EndpointID string `json:"endpoint_id,omitempty"` - // Instance ID. Not used on Linux. - InstanceID string `json:"instance_id,omitempty"` -} - -// PidsStats contains the stats of a container's pids -type PidsStats struct { - // Current is the number of pids in the cgroup - Current uint64 `json:"current,omitempty"` - // Limit is the hard limit on the number of pids in the cgroup. - // A "Limit" of 0 means that there is no limit. - Limit uint64 `json:"limit,omitempty"` -} - -// Stats is Ultimate struct aggregating all types of stats of one container -type Stats struct { - // Common stats - Read time.Time `json:"read"` - PreRead time.Time `json:"preread"` - - // Linux specific stats, not populated on Windows. - PidsStats PidsStats `json:"pids_stats,omitempty"` - BlkioStats BlkioStats `json:"blkio_stats,omitempty"` - - // Windows specific stats, not populated on Linux. - NumProcs uint32 `json:"num_procs"` - StorageStats StorageStats `json:"storage_stats,omitempty"` - - // Shared stats - CPUStats CPUStats `json:"cpu_stats,omitempty"` - PreCPUStats CPUStats `json:"precpu_stats,omitempty"` // "Pre"="Previous" - MemoryStats MemoryStats `json:"memory_stats,omitempty"` -} - -// StatsJSON is newly used Networks -type StatsJSON struct { - Stats - - Name string `json:"name,omitempty"` - ID string `json:"id,omitempty"` - - // Networks request version >=1.21 - Networks map[string]NetworkStats `json:"networks,omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/strslice/strslice.go b/vendor/github.com/docker/docker/api/types/strslice/strslice.go deleted file mode 100644 index 82921cebc..000000000 --- a/vendor/github.com/docker/docker/api/types/strslice/strslice.go +++ /dev/null @@ -1,30 +0,0 @@ -package strslice // import "github.com/docker/docker/api/types/strslice" - -import "encoding/json" - -// StrSlice represents a string or an array of strings. -// We need to override the json decoder to accept both options. -type StrSlice []string - -// UnmarshalJSON decodes the byte slice whether it's a string or an array of -// strings. This method is needed to implement json.Unmarshaler. -func (e *StrSlice) UnmarshalJSON(b []byte) error { - if len(b) == 0 { - // With no input, we preserve the existing value by returning nil and - // leaving the target alone. This allows defining default values for - // the type. - return nil - } - - p := make([]string, 0, 1) - if err := json.Unmarshal(b, &p); err != nil { - var s string - if err := json.Unmarshal(b, &s); err != nil { - return err - } - p = append(p, s) - } - - *e = p - return nil -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/common.go b/vendor/github.com/docker/docker/api/types/swarm/common.go deleted file mode 100644 index 5ded7dba8..000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/common.go +++ /dev/null @@ -1,48 +0,0 @@ -package swarm // import "github.com/docker/docker/api/types/swarm" - -import ( - "strconv" - "time" -) - -// Version represents the internal object version. -type Version struct { - Index uint64 `json:",omitempty"` -} - -// String implements fmt.Stringer interface. -func (v Version) String() string { - return strconv.FormatUint(v.Index, 10) -} - -// Meta is a base object inherited by most of the other once. -type Meta struct { - Version Version `json:",omitempty"` - CreatedAt time.Time `json:",omitempty"` - UpdatedAt time.Time `json:",omitempty"` -} - -// Annotations represents how to describe an object. -type Annotations struct { - Name string `json:",omitempty"` - Labels map[string]string `json:"Labels"` -} - -// Driver represents a driver (network, logging, secrets backend). -type Driver struct { - Name string `json:",omitempty"` - Options map[string]string `json:",omitempty"` -} - -// TLSInfo represents the TLS information about what CA certificate is trusted, -// and who the issuer for a TLS certificate is -type TLSInfo struct { - // TrustRoot is the trusted CA root certificate in PEM format - TrustRoot string `json:",omitempty"` - - // CertIssuer is the raw subject bytes of the issuer - CertIssuerSubject []byte `json:",omitempty"` - - // CertIssuerPublicKey is the raw public key bytes of the issuer - CertIssuerPublicKey []byte `json:",omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/config.go b/vendor/github.com/docker/docker/api/types/swarm/config.go deleted file mode 100644 index 16202ccce..000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/config.go +++ /dev/null @@ -1,40 +0,0 @@ -package swarm // import "github.com/docker/docker/api/types/swarm" - -import "os" - -// Config represents a config. -type Config struct { - ID string - Meta - Spec ConfigSpec -} - -// ConfigSpec represents a config specification from a config in swarm -type ConfigSpec struct { - Annotations - Data []byte `json:",omitempty"` - - // Templating controls whether and how to evaluate the config payload as - // a template. If it is not set, no templating is used. - Templating *Driver `json:",omitempty"` -} - -// ConfigReferenceFileTarget is a file target in a config reference -type ConfigReferenceFileTarget struct { - Name string - UID string - GID string - Mode os.FileMode -} - -// ConfigReferenceRuntimeTarget is a target for a config specifying that it -// isn't mounted into the container but instead has some other purpose. -type ConfigReferenceRuntimeTarget struct{} - -// ConfigReference is a reference to a config in swarm -type ConfigReference struct { - File *ConfigReferenceFileTarget `json:",omitempty"` - Runtime *ConfigReferenceRuntimeTarget `json:",omitempty"` - ConfigID string - ConfigName string -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/container.go b/vendor/github.com/docker/docker/api/types/swarm/container.go deleted file mode 100644 index af5e1c0bc..000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/container.go +++ /dev/null @@ -1,80 +0,0 @@ -package swarm // import "github.com/docker/docker/api/types/swarm" - -import ( - "time" - - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/mount" - "github.com/docker/go-units" -) - -// DNSConfig specifies DNS related configurations in resolver configuration file (resolv.conf) -// Detailed documentation is available in: -// http://man7.org/linux/man-pages/man5/resolv.conf.5.html -// `nameserver`, `search`, `options` have been supported. -// TODO: `domain` is not supported yet. -type DNSConfig struct { - // Nameservers specifies the IP addresses of the name servers - Nameservers []string `json:",omitempty"` - // Search specifies the search list for host-name lookup - Search []string `json:",omitempty"` - // Options allows certain internal resolver variables to be modified - Options []string `json:",omitempty"` -} - -// SELinuxContext contains the SELinux labels of the container. -type SELinuxContext struct { - Disable bool - - User string - Role string - Type string - Level string -} - -// CredentialSpec for managed service account (Windows only) -type CredentialSpec struct { - Config string - File string - Registry string -} - -// Privileges defines the security options for the container. -type Privileges struct { - CredentialSpec *CredentialSpec - SELinuxContext *SELinuxContext -} - -// ContainerSpec represents the spec of a container. -type ContainerSpec struct { - Image string `json:",omitempty"` - Labels map[string]string `json:",omitempty"` - Command []string `json:",omitempty"` - Args []string `json:",omitempty"` - Hostname string `json:",omitempty"` - Env []string `json:",omitempty"` - Dir string `json:",omitempty"` - User string `json:",omitempty"` - Groups []string `json:",omitempty"` - Privileges *Privileges `json:",omitempty"` - Init *bool `json:",omitempty"` - StopSignal string `json:",omitempty"` - TTY bool `json:",omitempty"` - OpenStdin bool `json:",omitempty"` - ReadOnly bool `json:",omitempty"` - Mounts []mount.Mount `json:",omitempty"` - StopGracePeriod *time.Duration `json:",omitempty"` - Healthcheck *container.HealthConfig `json:",omitempty"` - // The format of extra hosts on swarmkit is specified in: - // http://man7.org/linux/man-pages/man5/hosts.5.html - // IP_address canonical_hostname [aliases...] - Hosts []string `json:",omitempty"` - DNSConfig *DNSConfig `json:",omitempty"` - Secrets []*SecretReference `json:",omitempty"` - Configs []*ConfigReference `json:",omitempty"` - Isolation container.Isolation `json:",omitempty"` - Sysctls map[string]string `json:",omitempty"` - CapabilityAdd []string `json:",omitempty"` - CapabilityDrop []string `json:",omitempty"` - Ulimits []*units.Ulimit `json:",omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/network.go b/vendor/github.com/docker/docker/api/types/swarm/network.go deleted file mode 100644 index 98ef3284d..000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/network.go +++ /dev/null @@ -1,121 +0,0 @@ -package swarm // import "github.com/docker/docker/api/types/swarm" - -import ( - "github.com/docker/docker/api/types/network" -) - -// Endpoint represents an endpoint. -type Endpoint struct { - Spec EndpointSpec `json:",omitempty"` - Ports []PortConfig `json:",omitempty"` - VirtualIPs []EndpointVirtualIP `json:",omitempty"` -} - -// EndpointSpec represents the spec of an endpoint. -type EndpointSpec struct { - Mode ResolutionMode `json:",omitempty"` - Ports []PortConfig `json:",omitempty"` -} - -// ResolutionMode represents a resolution mode. -type ResolutionMode string - -const ( - // ResolutionModeVIP VIP - ResolutionModeVIP ResolutionMode = "vip" - // ResolutionModeDNSRR DNSRR - ResolutionModeDNSRR ResolutionMode = "dnsrr" -) - -// PortConfig represents the config of a port. -type PortConfig struct { - Name string `json:",omitempty"` - Protocol PortConfigProtocol `json:",omitempty"` - // TargetPort is the port inside the container - TargetPort uint32 `json:",omitempty"` - // PublishedPort is the port on the swarm hosts - PublishedPort uint32 `json:",omitempty"` - // PublishMode is the mode in which port is published - PublishMode PortConfigPublishMode `json:",omitempty"` -} - -// PortConfigPublishMode represents the mode in which the port is to -// be published. -type PortConfigPublishMode string - -const ( - // PortConfigPublishModeIngress is used for ports published - // for ingress load balancing using routing mesh. - PortConfigPublishModeIngress PortConfigPublishMode = "ingress" - // PortConfigPublishModeHost is used for ports published - // for direct host level access on the host where the task is running. - PortConfigPublishModeHost PortConfigPublishMode = "host" -) - -// PortConfigProtocol represents the protocol of a port. -type PortConfigProtocol string - -const ( - // TODO(stevvooe): These should be used generally, not just for PortConfig. - - // PortConfigProtocolTCP TCP - PortConfigProtocolTCP PortConfigProtocol = "tcp" - // PortConfigProtocolUDP UDP - PortConfigProtocolUDP PortConfigProtocol = "udp" - // PortConfigProtocolSCTP SCTP - PortConfigProtocolSCTP PortConfigProtocol = "sctp" -) - -// EndpointVirtualIP represents the virtual ip of a port. -type EndpointVirtualIP struct { - NetworkID string `json:",omitempty"` - Addr string `json:",omitempty"` -} - -// Network represents a network. -type Network struct { - ID string - Meta - Spec NetworkSpec `json:",omitempty"` - DriverState Driver `json:",omitempty"` - IPAMOptions *IPAMOptions `json:",omitempty"` -} - -// NetworkSpec represents the spec of a network. -type NetworkSpec struct { - Annotations - DriverConfiguration *Driver `json:",omitempty"` - IPv6Enabled bool `json:",omitempty"` - Internal bool `json:",omitempty"` - Attachable bool `json:",omitempty"` - Ingress bool `json:",omitempty"` - IPAMOptions *IPAMOptions `json:",omitempty"` - ConfigFrom *network.ConfigReference `json:",omitempty"` - Scope string `json:",omitempty"` -} - -// NetworkAttachmentConfig represents the configuration of a network attachment. -type NetworkAttachmentConfig struct { - Target string `json:",omitempty"` - Aliases []string `json:",omitempty"` - DriverOpts map[string]string `json:",omitempty"` -} - -// NetworkAttachment represents a network attachment. -type NetworkAttachment struct { - Network Network `json:",omitempty"` - Addresses []string `json:",omitempty"` -} - -// IPAMOptions represents ipam options. -type IPAMOptions struct { - Driver Driver `json:",omitempty"` - Configs []IPAMConfig `json:",omitempty"` -} - -// IPAMConfig represents ipam configuration. -type IPAMConfig struct { - Subnet string `json:",omitempty"` - Range string `json:",omitempty"` - Gateway string `json:",omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/node.go b/vendor/github.com/docker/docker/api/types/swarm/node.go deleted file mode 100644 index bb98d5eed..000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/node.go +++ /dev/null @@ -1,139 +0,0 @@ -package swarm // import "github.com/docker/docker/api/types/swarm" - -// Node represents a node. -type Node struct { - ID string - Meta - // Spec defines the desired state of the node as specified by the user. - // The system will honor this and will *never* modify it. - Spec NodeSpec `json:",omitempty"` - // Description encapsulates the properties of the Node as reported by the - // agent. - Description NodeDescription `json:",omitempty"` - // Status provides the current status of the node, as seen by the manager. - Status NodeStatus `json:",omitempty"` - // ManagerStatus provides the current status of the node's manager - // component, if the node is a manager. - ManagerStatus *ManagerStatus `json:",omitempty"` -} - -// NodeSpec represents the spec of a node. -type NodeSpec struct { - Annotations - Role NodeRole `json:",omitempty"` - Availability NodeAvailability `json:",omitempty"` -} - -// NodeRole represents the role of a node. -type NodeRole string - -const ( - // NodeRoleWorker WORKER - NodeRoleWorker NodeRole = "worker" - // NodeRoleManager MANAGER - NodeRoleManager NodeRole = "manager" -) - -// NodeAvailability represents the availability of a node. -type NodeAvailability string - -const ( - // NodeAvailabilityActive ACTIVE - NodeAvailabilityActive NodeAvailability = "active" - // NodeAvailabilityPause PAUSE - NodeAvailabilityPause NodeAvailability = "pause" - // NodeAvailabilityDrain DRAIN - NodeAvailabilityDrain NodeAvailability = "drain" -) - -// NodeDescription represents the description of a node. -type NodeDescription struct { - Hostname string `json:",omitempty"` - Platform Platform `json:",omitempty"` - Resources Resources `json:",omitempty"` - Engine EngineDescription `json:",omitempty"` - TLSInfo TLSInfo `json:",omitempty"` - CSIInfo []NodeCSIInfo `json:",omitempty"` -} - -// Platform represents the platform (Arch/OS). -type Platform struct { - Architecture string `json:",omitempty"` - OS string `json:",omitempty"` -} - -// EngineDescription represents the description of an engine. -type EngineDescription struct { - EngineVersion string `json:",omitempty"` - Labels map[string]string `json:",omitempty"` - Plugins []PluginDescription `json:",omitempty"` -} - -// NodeCSIInfo represents information about a CSI plugin available on the node -type NodeCSIInfo struct { - // PluginName is the name of the CSI plugin. - PluginName string `json:",omitempty"` - // NodeID is the ID of the node as reported by the CSI plugin. This is - // different from the swarm node ID. - NodeID string `json:",omitempty"` - // MaxVolumesPerNode is the maximum number of volumes that may be published - // to this node - MaxVolumesPerNode int64 `json:",omitempty"` - // AccessibleTopology indicates the location of this node in the CSI - // plugin's topology - AccessibleTopology *Topology `json:",omitempty"` -} - -// PluginDescription represents the description of an engine plugin. -type PluginDescription struct { - Type string `json:",omitempty"` - Name string `json:",omitempty"` -} - -// NodeStatus represents the status of a node. -type NodeStatus struct { - State NodeState `json:",omitempty"` - Message string `json:",omitempty"` - Addr string `json:",omitempty"` -} - -// Reachability represents the reachability of a node. -type Reachability string - -const ( - // ReachabilityUnknown UNKNOWN - ReachabilityUnknown Reachability = "unknown" - // ReachabilityUnreachable UNREACHABLE - ReachabilityUnreachable Reachability = "unreachable" - // ReachabilityReachable REACHABLE - ReachabilityReachable Reachability = "reachable" -) - -// ManagerStatus represents the status of a manager. -type ManagerStatus struct { - Leader bool `json:",omitempty"` - Reachability Reachability `json:",omitempty"` - Addr string `json:",omitempty"` -} - -// NodeState represents the state of a node. -type NodeState string - -const ( - // NodeStateUnknown UNKNOWN - NodeStateUnknown NodeState = "unknown" - // NodeStateDown DOWN - NodeStateDown NodeState = "down" - // NodeStateReady READY - NodeStateReady NodeState = "ready" - // NodeStateDisconnected DISCONNECTED - NodeStateDisconnected NodeState = "disconnected" -) - -// Topology defines the CSI topology of this node. This type is a duplicate of -// github.com/docker/docker/api/types.Topology. Because the type definition -// is so simple and to avoid complicated structure or circular imports, we just -// duplicate it here. See that type for full documentation -type Topology struct { - Segments map[string]string `json:",omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/runtime.go b/vendor/github.com/docker/docker/api/types/swarm/runtime.go deleted file mode 100644 index 0c77403cc..000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/runtime.go +++ /dev/null @@ -1,27 +0,0 @@ -package swarm // import "github.com/docker/docker/api/types/swarm" - -// RuntimeType is the type of runtime used for the TaskSpec -type RuntimeType string - -// RuntimeURL is the proto type url -type RuntimeURL string - -const ( - // RuntimeContainer is the container based runtime - RuntimeContainer RuntimeType = "container" - // RuntimePlugin is the plugin based runtime - RuntimePlugin RuntimeType = "plugin" - // RuntimeNetworkAttachment is the network attachment runtime - RuntimeNetworkAttachment RuntimeType = "attachment" - - // RuntimeURLContainer is the proto url for the container type - RuntimeURLContainer RuntimeURL = "types.docker.com/RuntimeContainer" - // RuntimeURLPlugin is the proto url for the plugin type - RuntimeURLPlugin RuntimeURL = "types.docker.com/RuntimePlugin" -) - -// NetworkAttachmentSpec represents the runtime spec type for network -// attachment tasks -type NetworkAttachmentSpec struct { - ContainerID string -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/runtime/gen.go b/vendor/github.com/docker/docker/api/types/swarm/runtime/gen.go deleted file mode 100644 index 98c2806c3..000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/runtime/gen.go +++ /dev/null @@ -1,3 +0,0 @@ -//go:generate protoc -I . --gogofast_out=import_path=github.com/docker/docker/api/types/swarm/runtime:. plugin.proto - -package runtime // import "github.com/docker/docker/api/types/swarm/runtime" diff --git a/vendor/github.com/docker/docker/api/types/swarm/runtime/plugin.pb.go b/vendor/github.com/docker/docker/api/types/swarm/runtime/plugin.pb.go deleted file mode 100644 index e45045866..000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/runtime/plugin.pb.go +++ /dev/null @@ -1,754 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: plugin.proto - -/* - Package runtime is a generated protocol buffer package. - - It is generated from these files: - plugin.proto - - It has these top-level messages: - PluginSpec - PluginPrivilege -*/ -package runtime - -import proto "github.com/gogo/protobuf/proto" -import fmt "fmt" -import math "math" - -import io "io" - -// 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.GoGoProtoPackageIsVersion2 // please upgrade the proto package - -// PluginSpec defines the base payload which clients can specify for creating -// a service with the plugin runtime. -type PluginSpec struct { - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - Remote string `protobuf:"bytes,2,opt,name=remote,proto3" json:"remote,omitempty"` - Privileges []*PluginPrivilege `protobuf:"bytes,3,rep,name=privileges" json:"privileges,omitempty"` - Disabled bool `protobuf:"varint,4,opt,name=disabled,proto3" json:"disabled,omitempty"` - Env []string `protobuf:"bytes,5,rep,name=env" json:"env,omitempty"` -} - -func (m *PluginSpec) Reset() { *m = PluginSpec{} } -func (m *PluginSpec) String() string { return proto.CompactTextString(m) } -func (*PluginSpec) ProtoMessage() {} -func (*PluginSpec) Descriptor() ([]byte, []int) { return fileDescriptorPlugin, []int{0} } - -func (m *PluginSpec) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *PluginSpec) GetRemote() string { - if m != nil { - return m.Remote - } - return "" -} - -func (m *PluginSpec) GetPrivileges() []*PluginPrivilege { - if m != nil { - return m.Privileges - } - return nil -} - -func (m *PluginSpec) GetDisabled() bool { - if m != nil { - return m.Disabled - } - return false -} - -func (m *PluginSpec) GetEnv() []string { - if m != nil { - return m.Env - } - return nil -} - -// PluginPrivilege describes a permission the user has to accept -// upon installing a plugin. -type PluginPrivilege struct { - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - Value []string `protobuf:"bytes,3,rep,name=value" json:"value,omitempty"` -} - -func (m *PluginPrivilege) Reset() { *m = PluginPrivilege{} } -func (m *PluginPrivilege) String() string { return proto.CompactTextString(m) } -func (*PluginPrivilege) ProtoMessage() {} -func (*PluginPrivilege) Descriptor() ([]byte, []int) { return fileDescriptorPlugin, []int{1} } - -func (m *PluginPrivilege) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *PluginPrivilege) GetDescription() string { - if m != nil { - return m.Description - } - return "" -} - -func (m *PluginPrivilege) GetValue() []string { - if m != nil { - return m.Value - } - return nil -} - -func init() { - proto.RegisterType((*PluginSpec)(nil), "PluginSpec") - proto.RegisterType((*PluginPrivilege)(nil), "PluginPrivilege") -} -func (m *PluginSpec) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *PluginSpec) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.Name) > 0 { - dAtA[i] = 0xa - i++ - i = encodeVarintPlugin(dAtA, i, uint64(len(m.Name))) - i += copy(dAtA[i:], m.Name) - } - if len(m.Remote) > 0 { - dAtA[i] = 0x12 - i++ - i = encodeVarintPlugin(dAtA, i, uint64(len(m.Remote))) - i += copy(dAtA[i:], m.Remote) - } - if len(m.Privileges) > 0 { - for _, msg := range m.Privileges { - dAtA[i] = 0x1a - i++ - i = encodeVarintPlugin(dAtA, i, uint64(msg.Size())) - n, err := msg.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n - } - } - if m.Disabled { - dAtA[i] = 0x20 - i++ - if m.Disabled { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i++ - } - if len(m.Env) > 0 { - for _, s := range m.Env { - dAtA[i] = 0x2a - i++ - l = len(s) - for l >= 1<<7 { - dAtA[i] = uint8(uint64(l)&0x7f | 0x80) - l >>= 7 - i++ - } - dAtA[i] = uint8(l) - i++ - i += copy(dAtA[i:], s) - } - } - return i, nil -} - -func (m *PluginPrivilege) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *PluginPrivilege) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.Name) > 0 { - dAtA[i] = 0xa - i++ - i = encodeVarintPlugin(dAtA, i, uint64(len(m.Name))) - i += copy(dAtA[i:], m.Name) - } - if len(m.Description) > 0 { - dAtA[i] = 0x12 - i++ - i = encodeVarintPlugin(dAtA, i, uint64(len(m.Description))) - i += copy(dAtA[i:], m.Description) - } - if len(m.Value) > 0 { - for _, s := range m.Value { - dAtA[i] = 0x1a - i++ - l = len(s) - for l >= 1<<7 { - dAtA[i] = uint8(uint64(l)&0x7f | 0x80) - l >>= 7 - i++ - } - dAtA[i] = uint8(l) - i++ - i += copy(dAtA[i:], s) - } - } - return i, nil -} - -func encodeVarintPlugin(dAtA []byte, offset int, v uint64) int { - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return offset + 1 -} -func (m *PluginSpec) Size() (n int) { - var l int - _ = l - l = len(m.Name) - if l > 0 { - n += 1 + l + sovPlugin(uint64(l)) - } - l = len(m.Remote) - if l > 0 { - n += 1 + l + sovPlugin(uint64(l)) - } - if len(m.Privileges) > 0 { - for _, e := range m.Privileges { - l = e.Size() - n += 1 + l + sovPlugin(uint64(l)) - } - } - if m.Disabled { - n += 2 - } - if len(m.Env) > 0 { - for _, s := range m.Env { - l = len(s) - n += 1 + l + sovPlugin(uint64(l)) - } - } - return n -} - -func (m *PluginPrivilege) Size() (n int) { - var l int - _ = l - l = len(m.Name) - if l > 0 { - n += 1 + l + sovPlugin(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovPlugin(uint64(l)) - } - if len(m.Value) > 0 { - for _, s := range m.Value { - l = len(s) - n += 1 + l + sovPlugin(uint64(l)) - } - } - return n -} - -func sovPlugin(x uint64) (n int) { - for { - n++ - x >>= 7 - if x == 0 { - break - } - } - return n -} -func sozPlugin(x uint64) (n int) { - return sovPlugin(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *PluginSpec) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPlugin - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: PluginSpec: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PluginSpec: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPlugin - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthPlugin - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Name = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Remote", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPlugin - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthPlugin - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Remote = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Privileges", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPlugin - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthPlugin - } - postIndex := iNdEx + msglen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Privileges = append(m.Privileges, &PluginPrivilege{}) - if err := m.Privileges[len(m.Privileges)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Disabled", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPlugin - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - m.Disabled = bool(v != 0) - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Env", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPlugin - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthPlugin - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Env = append(m.Env, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipPlugin(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthPlugin - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *PluginPrivilege) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPlugin - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: PluginPrivilege: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PluginPrivilege: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPlugin - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthPlugin - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Name = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPlugin - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthPlugin - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPlugin - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthPlugin - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Value = append(m.Value, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipPlugin(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthPlugin - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipPlugin(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowPlugin - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowPlugin - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - return iNdEx, nil - case 1: - iNdEx += 8 - return iNdEx, nil - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowPlugin - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - iNdEx += length - if length < 0 { - return 0, ErrInvalidLengthPlugin - } - return iNdEx, nil - case 3: - for { - var innerWire uint64 - var start int = iNdEx - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowPlugin - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - innerWire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - innerWireType := int(innerWire & 0x7) - if innerWireType == 4 { - break - } - next, err := skipPlugin(dAtA[start:]) - if err != nil { - return 0, err - } - iNdEx = start + next - } - return iNdEx, nil - case 4: - return iNdEx, nil - case 5: - iNdEx += 4 - return iNdEx, nil - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - } - panic("unreachable") -} - -var ( - ErrInvalidLengthPlugin = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowPlugin = fmt.Errorf("proto: integer overflow") -) - -func init() { proto.RegisterFile("plugin.proto", fileDescriptorPlugin) } - -var fileDescriptorPlugin = []byte{ - // 256 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x90, 0x4d, 0x4b, 0xc3, 0x30, - 0x18, 0xc7, 0x89, 0xdd, 0xc6, 0xfa, 0x4c, 0x70, 0x04, 0x91, 0xe2, 0xa1, 0x94, 0x9d, 0x7a, 0x6a, - 0x45, 0x2f, 0x82, 0x37, 0x0f, 0x9e, 0x47, 0xbc, 0x09, 0x1e, 0xd2, 0xf6, 0xa1, 0x06, 0x9b, 0x17, - 0x92, 0xb4, 0xe2, 0x37, 0xf1, 0x23, 0x79, 0xf4, 0x23, 0x48, 0x3f, 0x89, 0x98, 0x75, 0x32, 0x64, - 0xa7, 0xff, 0x4b, 0xc2, 0x9f, 0x1f, 0x0f, 0x9c, 0x9a, 0xae, 0x6f, 0x85, 0x2a, 0x8c, 0xd5, 0x5e, - 0x6f, 0x3e, 0x08, 0xc0, 0x36, 0x14, 0x8f, 0x06, 0x6b, 0x4a, 0x61, 0xa6, 0xb8, 0xc4, 0x84, 0x64, - 0x24, 0x8f, 0x59, 0xf0, 0xf4, 0x02, 0x16, 0x16, 0xa5, 0xf6, 0x98, 0x9c, 0x84, 0x76, 0x4a, 0xf4, - 0x0a, 0xc0, 0x58, 0x31, 0x88, 0x0e, 0x5b, 0x74, 0x49, 0x94, 0x45, 0xf9, 0xea, 0x7a, 0x5d, 0xec, - 0xc6, 0xb6, 0xfb, 0x07, 0x76, 0xf0, 0x87, 0x5e, 0xc2, 0xb2, 0x11, 0x8e, 0x57, 0x1d, 0x36, 0xc9, - 0x2c, 0x23, 0xf9, 0x92, 0xfd, 0x65, 0xba, 0x86, 0x08, 0xd5, 0x90, 0xcc, 0xb3, 0x28, 0x8f, 0xd9, - 0xaf, 0xdd, 0x3c, 0xc3, 0xd9, 0xbf, 0xb1, 0xa3, 0x78, 0x19, 0xac, 0x1a, 0x74, 0xb5, 0x15, 0xc6, - 0x0b, 0xad, 0x26, 0xc6, 0xc3, 0x8a, 0x9e, 0xc3, 0x7c, 0xe0, 0x5d, 0x8f, 0x81, 0x31, 0x66, 0xbb, - 0x70, 0xff, 0xf0, 0x39, 0xa6, 0xe4, 0x6b, 0x4c, 0xc9, 0xf7, 0x98, 0x92, 0xa7, 0xdb, 0x56, 0xf8, - 0x97, 0xbe, 0x2a, 0x6a, 0x2d, 0xcb, 0x46, 0xd7, 0xaf, 0x68, 0xf7, 0xc2, 0x8d, 0x28, 0xfd, 0xbb, - 0x41, 0x57, 0xba, 0x37, 0x6e, 0x65, 0x69, 0x7b, 0xe5, 0x85, 0xc4, 0xbb, 0x49, 0xab, 0x45, 0x38, - 0xe4, 0xcd, 0x4f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x99, 0xa8, 0xd9, 0x9b, 0x58, 0x01, 0x00, 0x00, -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/runtime/plugin.proto b/vendor/github.com/docker/docker/api/types/swarm/runtime/plugin.proto deleted file mode 100644 index 9ef169046..000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/runtime/plugin.proto +++ /dev/null @@ -1,21 +0,0 @@ -syntax = "proto3"; - -option go_package = "github.com/docker/docker/api/types/swarm/runtime;runtime"; - -// PluginSpec defines the base payload which clients can specify for creating -// a service with the plugin runtime. -message PluginSpec { - string name = 1; - string remote = 2; - repeated PluginPrivilege privileges = 3; - bool disabled = 4; - repeated string env = 5; -} - -// PluginPrivilege describes a permission the user has to accept -// upon installing a plugin. -message PluginPrivilege { - string name = 1; - string description = 2; - repeated string value = 3; -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/secret.go b/vendor/github.com/docker/docker/api/types/swarm/secret.go deleted file mode 100644 index d5213ec98..000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/secret.go +++ /dev/null @@ -1,36 +0,0 @@ -package swarm // import "github.com/docker/docker/api/types/swarm" - -import "os" - -// Secret represents a secret. -type Secret struct { - ID string - Meta - Spec SecretSpec -} - -// SecretSpec represents a secret specification from a secret in swarm -type SecretSpec struct { - Annotations - Data []byte `json:",omitempty"` - Driver *Driver `json:",omitempty"` // name of the secrets driver used to fetch the secret's value from an external secret store - - // Templating controls whether and how to evaluate the secret payload as - // a template. If it is not set, no templating is used. - Templating *Driver `json:",omitempty"` -} - -// SecretReferenceFileTarget is a file target in a secret reference -type SecretReferenceFileTarget struct { - Name string - UID string - GID string - Mode os.FileMode -} - -// SecretReference is a reference to a secret in swarm -type SecretReference struct { - File *SecretReferenceFileTarget - SecretID string - SecretName string -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/service.go b/vendor/github.com/docker/docker/api/types/swarm/service.go deleted file mode 100644 index 6eb452d24..000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/service.go +++ /dev/null @@ -1,202 +0,0 @@ -package swarm // import "github.com/docker/docker/api/types/swarm" - -import "time" - -// Service represents a service. -type Service struct { - ID string - Meta - Spec ServiceSpec `json:",omitempty"` - PreviousSpec *ServiceSpec `json:",omitempty"` - Endpoint Endpoint `json:",omitempty"` - UpdateStatus *UpdateStatus `json:",omitempty"` - - // ServiceStatus is an optional, extra field indicating the number of - // desired and running tasks. It is provided primarily as a shortcut to - // calculating these values client-side, which otherwise would require - // listing all tasks for a service, an operation that could be - // computation and network expensive. - ServiceStatus *ServiceStatus `json:",omitempty"` - - // JobStatus is the status of a Service which is in one of ReplicatedJob or - // GlobalJob modes. It is absent on Replicated and Global services. - JobStatus *JobStatus `json:",omitempty"` -} - -// ServiceSpec represents the spec of a service. -type ServiceSpec struct { - Annotations - - // TaskTemplate defines how the service should construct new tasks when - // orchestrating this service. - TaskTemplate TaskSpec `json:",omitempty"` - Mode ServiceMode `json:",omitempty"` - UpdateConfig *UpdateConfig `json:",omitempty"` - RollbackConfig *UpdateConfig `json:",omitempty"` - - // Networks field in ServiceSpec is deprecated. The - // same field in TaskSpec should be used instead. - // This field will be removed in a future release. - Networks []NetworkAttachmentConfig `json:",omitempty"` - EndpointSpec *EndpointSpec `json:",omitempty"` -} - -// ServiceMode represents the mode of a service. -type ServiceMode struct { - Replicated *ReplicatedService `json:",omitempty"` - Global *GlobalService `json:",omitempty"` - ReplicatedJob *ReplicatedJob `json:",omitempty"` - GlobalJob *GlobalJob `json:",omitempty"` -} - -// UpdateState is the state of a service update. -type UpdateState string - -const ( - // UpdateStateUpdating is the updating state. - UpdateStateUpdating UpdateState = "updating" - // UpdateStatePaused is the paused state. - UpdateStatePaused UpdateState = "paused" - // UpdateStateCompleted is the completed state. - UpdateStateCompleted UpdateState = "completed" - // UpdateStateRollbackStarted is the state with a rollback in progress. - UpdateStateRollbackStarted UpdateState = "rollback_started" - // UpdateStateRollbackPaused is the state with a rollback in progress. - UpdateStateRollbackPaused UpdateState = "rollback_paused" - // UpdateStateRollbackCompleted is the state with a rollback in progress. - UpdateStateRollbackCompleted UpdateState = "rollback_completed" -) - -// UpdateStatus reports the status of a service update. -type UpdateStatus struct { - State UpdateState `json:",omitempty"` - StartedAt *time.Time `json:",omitempty"` - CompletedAt *time.Time `json:",omitempty"` - Message string `json:",omitempty"` -} - -// ReplicatedService is a kind of ServiceMode. -type ReplicatedService struct { - Replicas *uint64 `json:",omitempty"` -} - -// GlobalService is a kind of ServiceMode. -type GlobalService struct{} - -// ReplicatedJob is the a type of Service which executes a defined Tasks -// in parallel until the specified number of Tasks have succeeded. -type ReplicatedJob struct { - // MaxConcurrent indicates the maximum number of Tasks that should be - // executing simultaneously for this job at any given time. There may be - // fewer Tasks that MaxConcurrent executing simultaneously; for example, if - // there are fewer than MaxConcurrent tasks needed to reach - // TotalCompletions. - // - // If this field is empty, it will default to a max concurrency of 1. - MaxConcurrent *uint64 `json:",omitempty"` - - // TotalCompletions is the total number of Tasks desired to run to - // completion. - // - // If this field is empty, the value of MaxConcurrent will be used. - TotalCompletions *uint64 `json:",omitempty"` -} - -// GlobalJob is the type of a Service which executes a Task on every Node -// matching the Service's placement constraints. These tasks run to completion -// and then exit. -// -// This type is deliberately empty. -type GlobalJob struct{} - -const ( - // UpdateFailureActionPause PAUSE - UpdateFailureActionPause = "pause" - // UpdateFailureActionContinue CONTINUE - UpdateFailureActionContinue = "continue" - // UpdateFailureActionRollback ROLLBACK - UpdateFailureActionRollback = "rollback" - - // UpdateOrderStopFirst STOP_FIRST - UpdateOrderStopFirst = "stop-first" - // UpdateOrderStartFirst START_FIRST - UpdateOrderStartFirst = "start-first" -) - -// UpdateConfig represents the update configuration. -type UpdateConfig struct { - // Maximum number of tasks to be updated in one iteration. - // 0 means unlimited parallelism. - Parallelism uint64 - - // Amount of time between updates. - Delay time.Duration `json:",omitempty"` - - // FailureAction is the action to take when an update failures. - FailureAction string `json:",omitempty"` - - // Monitor indicates how long to monitor a task for failure after it is - // created. If the task fails by ending up in one of the states - // REJECTED, COMPLETED, or FAILED, within Monitor from its creation, - // this counts as a failure. If it fails after Monitor, it does not - // count as a failure. If Monitor is unspecified, a default value will - // be used. - Monitor time.Duration `json:",omitempty"` - - // MaxFailureRatio is the fraction of tasks that may fail during - // an update before the failure action is invoked. Any task created by - // the current update which ends up in one of the states REJECTED, - // COMPLETED or FAILED within Monitor from its creation counts as a - // failure. The number of failures is divided by the number of tasks - // being updated, and if this fraction is greater than - // MaxFailureRatio, the failure action is invoked. - // - // If the failure action is CONTINUE, there is no effect. - // If the failure action is PAUSE, no more tasks will be updated until - // another update is started. - MaxFailureRatio float32 - - // Order indicates the order of operations when rolling out an updated - // task. Either the old task is shut down before the new task is - // started, or the new task is started before the old task is shut down. - Order string -} - -// ServiceStatus represents the number of running tasks in a service and the -// number of tasks desired to be running. -type ServiceStatus struct { - // RunningTasks is the number of tasks for the service actually in the - // Running state - RunningTasks uint64 - - // DesiredTasks is the number of tasks desired to be running by the - // service. For replicated services, this is the replica count. For global - // services, this is computed by taking the number of tasks with desired - // state of not-Shutdown. - DesiredTasks uint64 - - // CompletedTasks is the number of tasks in the state Completed, if this - // service is in ReplicatedJob or GlobalJob mode. This field must be - // cross-referenced with the service type, because the default value of 0 - // may mean that a service is not in a job mode, or it may mean that the - // job has yet to complete any tasks. - CompletedTasks uint64 -} - -// JobStatus is the status of a job-type service. -type JobStatus struct { - // JobIteration is a value increased each time a Job is executed, - // successfully or otherwise. "Executed", in this case, means the job as a - // whole has been started, not that an individual Task has been launched. A - // job is "Executed" when its ServiceSpec is updated. JobIteration can be - // used to disambiguate Tasks belonging to different executions of a job. - // - // Though JobIteration will increase with each subsequent execution, it may - // not necessarily increase by 1, and so JobIteration should not be used to - // keep track of the number of times a job has been executed. - JobIteration Version - - // LastExecution is the time that the job was last executed, as observed by - // Swarm manager. - LastExecution time.Time `json:",omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/swarm.go b/vendor/github.com/docker/docker/api/types/swarm/swarm.go deleted file mode 100644 index 3eae4b9b2..000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/swarm.go +++ /dev/null @@ -1,237 +0,0 @@ -package swarm // import "github.com/docker/docker/api/types/swarm" - -import ( - "time" -) - -// ClusterInfo represents info about the cluster for outputting in "info" -// it contains the same information as "Swarm", but without the JoinTokens -type ClusterInfo struct { - ID string - Meta - Spec Spec - TLSInfo TLSInfo - RootRotationInProgress bool - DefaultAddrPool []string - SubnetSize uint32 - DataPathPort uint32 -} - -// Swarm represents a swarm. -type Swarm struct { - ClusterInfo - JoinTokens JoinTokens -} - -// JoinTokens contains the tokens workers and managers need to join the swarm. -type JoinTokens struct { - // Worker is the join token workers may use to join the swarm. - Worker string - // Manager is the join token managers may use to join the swarm. - Manager string -} - -// Spec represents the spec of a swarm. -type Spec struct { - Annotations - - Orchestration OrchestrationConfig `json:",omitempty"` - Raft RaftConfig `json:",omitempty"` - Dispatcher DispatcherConfig `json:",omitempty"` - CAConfig CAConfig `json:",omitempty"` - TaskDefaults TaskDefaults `json:",omitempty"` - EncryptionConfig EncryptionConfig `json:",omitempty"` -} - -// OrchestrationConfig represents orchestration configuration. -type OrchestrationConfig struct { - // TaskHistoryRetentionLimit is the number of historic tasks to keep per instance or - // node. If negative, never remove completed or failed tasks. - TaskHistoryRetentionLimit *int64 `json:",omitempty"` -} - -// TaskDefaults parameterizes cluster-level task creation with default values. -type TaskDefaults struct { - // LogDriver selects the log driver to use for tasks created in the - // orchestrator if unspecified by a service. - // - // Updating this value will only have an affect on new tasks. Old tasks - // will continue use their previously configured log driver until - // recreated. - LogDriver *Driver `json:",omitempty"` -} - -// EncryptionConfig controls at-rest encryption of data and keys. -type EncryptionConfig struct { - // AutoLockManagers specifies whether or not managers TLS keys and raft data - // should be encrypted at rest in such a way that they must be unlocked - // before the manager node starts up again. - AutoLockManagers bool -} - -// RaftConfig represents raft configuration. -type RaftConfig struct { - // SnapshotInterval is the number of log entries between snapshots. - SnapshotInterval uint64 `json:",omitempty"` - - // KeepOldSnapshots is the number of snapshots to keep beyond the - // current snapshot. - KeepOldSnapshots *uint64 `json:",omitempty"` - - // LogEntriesForSlowFollowers is the number of log entries to keep - // around to sync up slow followers after a snapshot is created. - LogEntriesForSlowFollowers uint64 `json:",omitempty"` - - // ElectionTick is the number of ticks that a follower will wait for a message - // from the leader before becoming a candidate and starting an election. - // ElectionTick must be greater than HeartbeatTick. - // - // A tick currently defaults to one second, so these translate directly to - // seconds currently, but this is NOT guaranteed. - ElectionTick int - - // HeartbeatTick is the number of ticks between heartbeats. Every - // HeartbeatTick ticks, the leader will send a heartbeat to the - // followers. - // - // A tick currently defaults to one second, so these translate directly to - // seconds currently, but this is NOT guaranteed. - HeartbeatTick int -} - -// DispatcherConfig represents dispatcher configuration. -type DispatcherConfig struct { - // HeartbeatPeriod defines how often agent should send heartbeats to - // dispatcher. - HeartbeatPeriod time.Duration `json:",omitempty"` -} - -// CAConfig represents CA configuration. -type CAConfig struct { - // NodeCertExpiry is the duration certificates should be issued for - NodeCertExpiry time.Duration `json:",omitempty"` - - // ExternalCAs is a list of CAs to which a manager node will make - // certificate signing requests for node certificates. - ExternalCAs []*ExternalCA `json:",omitempty"` - - // SigningCACert and SigningCAKey specify the desired signing root CA and - // root CA key for the swarm. When inspecting the cluster, the key will - // be redacted. - SigningCACert string `json:",omitempty"` - SigningCAKey string `json:",omitempty"` - - // If this value changes, and there is no specified signing cert and key, - // then the swarm is forced to generate a new root certificate ane key. - ForceRotate uint64 `json:",omitempty"` -} - -// ExternalCAProtocol represents type of external CA. -type ExternalCAProtocol string - -// ExternalCAProtocolCFSSL CFSSL -const ExternalCAProtocolCFSSL ExternalCAProtocol = "cfssl" - -// ExternalCA defines external CA to be used by the cluster. -type ExternalCA struct { - // Protocol is the protocol used by this external CA. - Protocol ExternalCAProtocol - - // URL is the URL where the external CA can be reached. - URL string - - // Options is a set of additional key/value pairs whose interpretation - // depends on the specified CA type. - Options map[string]string `json:",omitempty"` - - // CACert specifies which root CA is used by this external CA. This certificate must - // be in PEM format. - CACert string -} - -// InitRequest is the request used to init a swarm. -type InitRequest struct { - ListenAddr string - AdvertiseAddr string - DataPathAddr string - DataPathPort uint32 - ForceNewCluster bool - Spec Spec - AutoLockManagers bool - Availability NodeAvailability - DefaultAddrPool []string - SubnetSize uint32 -} - -// JoinRequest is the request used to join a swarm. -type JoinRequest struct { - ListenAddr string - AdvertiseAddr string - DataPathAddr string - RemoteAddrs []string - JoinToken string // accept by secret - Availability NodeAvailability -} - -// UnlockRequest is the request used to unlock a swarm. -type UnlockRequest struct { - // UnlockKey is the unlock key in ASCII-armored format. - UnlockKey string -} - -// LocalNodeState represents the state of the local node. -type LocalNodeState string - -const ( - // LocalNodeStateInactive INACTIVE - LocalNodeStateInactive LocalNodeState = "inactive" - // LocalNodeStatePending PENDING - LocalNodeStatePending LocalNodeState = "pending" - // LocalNodeStateActive ACTIVE - LocalNodeStateActive LocalNodeState = "active" - // LocalNodeStateError ERROR - LocalNodeStateError LocalNodeState = "error" - // LocalNodeStateLocked LOCKED - LocalNodeStateLocked LocalNodeState = "locked" -) - -// Info represents generic information about swarm. -type Info struct { - NodeID string - NodeAddr string - - LocalNodeState LocalNodeState - ControlAvailable bool - Error string - - RemoteManagers []Peer - Nodes int `json:",omitempty"` - Managers int `json:",omitempty"` - - Cluster *ClusterInfo `json:",omitempty"` - - Warnings []string `json:",omitempty"` -} - -// Status provides information about the current swarm status and role, -// obtained from the "Swarm" header in the API response. -type Status struct { - // NodeState represents the state of the node. - NodeState LocalNodeState - - // ControlAvailable indicates if the node is a swarm manager. - ControlAvailable bool -} - -// Peer represents a peer. -type Peer struct { - NodeID string - Addr string -} - -// UpdateFlags contains flags for SwarmUpdate. -type UpdateFlags struct { - RotateWorkerToken bool - RotateManagerToken bool - RotateManagerUnlockKey bool -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/task.go b/vendor/github.com/docker/docker/api/types/swarm/task.go deleted file mode 100644 index ad3eeca0b..000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/task.go +++ /dev/null @@ -1,225 +0,0 @@ -package swarm // import "github.com/docker/docker/api/types/swarm" - -import ( - "time" - - "github.com/docker/docker/api/types/swarm/runtime" -) - -// TaskState represents the state of a task. -type TaskState string - -const ( - // TaskStateNew NEW - TaskStateNew TaskState = "new" - // TaskStateAllocated ALLOCATED - TaskStateAllocated TaskState = "allocated" - // TaskStatePending PENDING - TaskStatePending TaskState = "pending" - // TaskStateAssigned ASSIGNED - TaskStateAssigned TaskState = "assigned" - // TaskStateAccepted ACCEPTED - TaskStateAccepted TaskState = "accepted" - // TaskStatePreparing PREPARING - TaskStatePreparing TaskState = "preparing" - // TaskStateReady READY - TaskStateReady TaskState = "ready" - // TaskStateStarting STARTING - TaskStateStarting TaskState = "starting" - // TaskStateRunning RUNNING - TaskStateRunning TaskState = "running" - // TaskStateComplete COMPLETE - TaskStateComplete TaskState = "complete" - // TaskStateShutdown SHUTDOWN - TaskStateShutdown TaskState = "shutdown" - // TaskStateFailed FAILED - TaskStateFailed TaskState = "failed" - // TaskStateRejected REJECTED - TaskStateRejected TaskState = "rejected" - // TaskStateRemove REMOVE - TaskStateRemove TaskState = "remove" - // TaskStateOrphaned ORPHANED - TaskStateOrphaned TaskState = "orphaned" -) - -// Task represents a task. -type Task struct { - ID string - Meta - Annotations - - Spec TaskSpec `json:",omitempty"` - ServiceID string `json:",omitempty"` - Slot int `json:",omitempty"` - NodeID string `json:",omitempty"` - Status TaskStatus `json:",omitempty"` - DesiredState TaskState `json:",omitempty"` - NetworksAttachments []NetworkAttachment `json:",omitempty"` - GenericResources []GenericResource `json:",omitempty"` - - // JobIteration is the JobIteration of the Service that this Task was - // spawned from, if the Service is a ReplicatedJob or GlobalJob. This is - // used to determine which Tasks belong to which run of the job. This field - // is absent if the Service mode is Replicated or Global. - JobIteration *Version `json:",omitempty"` - - // Volumes is the list of VolumeAttachments for this task. It specifies - // which particular volumes are to be used by this particular task, and - // fulfilling what mounts in the spec. - Volumes []VolumeAttachment -} - -// TaskSpec represents the spec of a task. -type TaskSpec struct { - // ContainerSpec, NetworkAttachmentSpec, and PluginSpec are mutually exclusive. - // PluginSpec is only used when the `Runtime` field is set to `plugin` - // NetworkAttachmentSpec is used if the `Runtime` field is set to - // `attachment`. - ContainerSpec *ContainerSpec `json:",omitempty"` - PluginSpec *runtime.PluginSpec `json:",omitempty"` - NetworkAttachmentSpec *NetworkAttachmentSpec `json:",omitempty"` - - Resources *ResourceRequirements `json:",omitempty"` - RestartPolicy *RestartPolicy `json:",omitempty"` - Placement *Placement `json:",omitempty"` - Networks []NetworkAttachmentConfig `json:",omitempty"` - - // LogDriver specifies the LogDriver to use for tasks created from this - // spec. If not present, the one on cluster default on swarm.Spec will be - // used, finally falling back to the engine default if not specified. - LogDriver *Driver `json:",omitempty"` - - // ForceUpdate is a counter that triggers an update even if no relevant - // parameters have been changed. - ForceUpdate uint64 - - Runtime RuntimeType `json:",omitempty"` -} - -// Resources represents resources (CPU/Memory) which can be advertised by a -// node and requested to be reserved for a task. -type Resources struct { - NanoCPUs int64 `json:",omitempty"` - MemoryBytes int64 `json:",omitempty"` - GenericResources []GenericResource `json:",omitempty"` -} - -// Limit describes limits on resources which can be requested by a task. -type Limit struct { - NanoCPUs int64 `json:",omitempty"` - MemoryBytes int64 `json:",omitempty"` - Pids int64 `json:",omitempty"` -} - -// GenericResource represents a "user defined" resource which can -// be either an integer (e.g: SSD=3) or a string (e.g: SSD=sda1) -type GenericResource struct { - NamedResourceSpec *NamedGenericResource `json:",omitempty"` - DiscreteResourceSpec *DiscreteGenericResource `json:",omitempty"` -} - -// NamedGenericResource represents a "user defined" resource which is defined -// as a string. -// "Kind" is used to describe the Kind of a resource (e.g: "GPU", "FPGA", "SSD", ...) -// Value is used to identify the resource (GPU="UUID-1", FPGA="/dev/sdb5", ...) -type NamedGenericResource struct { - Kind string `json:",omitempty"` - Value string `json:",omitempty"` -} - -// DiscreteGenericResource represents a "user defined" resource which is defined -// as an integer -// "Kind" is used to describe the Kind of a resource (e.g: "GPU", "FPGA", "SSD", ...) -// Value is used to count the resource (SSD=5, HDD=3, ...) -type DiscreteGenericResource struct { - Kind string `json:",omitempty"` - Value int64 `json:",omitempty"` -} - -// ResourceRequirements represents resources requirements. -type ResourceRequirements struct { - Limits *Limit `json:",omitempty"` - Reservations *Resources `json:",omitempty"` -} - -// Placement represents orchestration parameters. -type Placement struct { - Constraints []string `json:",omitempty"` - Preferences []PlacementPreference `json:",omitempty"` - MaxReplicas uint64 `json:",omitempty"` - - // Platforms stores all the platforms that the image can run on. - // This field is used in the platform filter for scheduling. If empty, - // then the platform filter is off, meaning there are no scheduling restrictions. - Platforms []Platform `json:",omitempty"` -} - -// PlacementPreference provides a way to make the scheduler aware of factors -// such as topology. -type PlacementPreference struct { - Spread *SpreadOver -} - -// SpreadOver is a scheduling preference that instructs the scheduler to spread -// tasks evenly over groups of nodes identified by labels. -type SpreadOver struct { - // label descriptor, such as engine.labels.az - SpreadDescriptor string -} - -// RestartPolicy represents the restart policy. -type RestartPolicy struct { - Condition RestartPolicyCondition `json:",omitempty"` - Delay *time.Duration `json:",omitempty"` - MaxAttempts *uint64 `json:",omitempty"` - Window *time.Duration `json:",omitempty"` -} - -// RestartPolicyCondition represents when to restart. -type RestartPolicyCondition string - -const ( - // RestartPolicyConditionNone NONE - RestartPolicyConditionNone RestartPolicyCondition = "none" - // RestartPolicyConditionOnFailure ON_FAILURE - RestartPolicyConditionOnFailure RestartPolicyCondition = "on-failure" - // RestartPolicyConditionAny ANY - RestartPolicyConditionAny RestartPolicyCondition = "any" -) - -// TaskStatus represents the status of a task. -type TaskStatus struct { - Timestamp time.Time `json:",omitempty"` - State TaskState `json:",omitempty"` - Message string `json:",omitempty"` - Err string `json:",omitempty"` - ContainerStatus *ContainerStatus `json:",omitempty"` - PortStatus PortStatus `json:",omitempty"` -} - -// ContainerStatus represents the status of a container. -type ContainerStatus struct { - ContainerID string - PID int - ExitCode int -} - -// PortStatus represents the port status of a task's host ports whose -// service has published host ports -type PortStatus struct { - Ports []PortConfig `json:",omitempty"` -} - -// VolumeAttachment contains the associating a Volume to a Task. -type VolumeAttachment struct { - // ID is the Swarmkit ID of the Volume. This is not the CSI VolumeId. - ID string `json:",omitempty"` - - // Source, together with Target, indicates the Mount, as specified in the - // ContainerSpec, that this volume fulfills. - Source string `json:",omitempty"` - - // Target, together with Source, indicates the Mount, as specified - // in the ContainerSpec, that this volume fulfills. - Target string `json:",omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/time/timestamp.go b/vendor/github.com/docker/docker/api/types/time/timestamp.go deleted file mode 100644 index cab5c32e3..000000000 --- a/vendor/github.com/docker/docker/api/types/time/timestamp.go +++ /dev/null @@ -1,131 +0,0 @@ -package time // import "github.com/docker/docker/api/types/time" - -import ( - "fmt" - "math" - "strconv" - "strings" - "time" -) - -// These are additional predefined layouts for use in Time.Format and Time.Parse -// with --since and --until parameters for `docker logs` and `docker events` -const ( - rFC3339Local = "2006-01-02T15:04:05" // RFC3339 with local timezone - rFC3339NanoLocal = "2006-01-02T15:04:05.999999999" // RFC3339Nano with local timezone - dateWithZone = "2006-01-02Z07:00" // RFC3339 with time at 00:00:00 - dateLocal = "2006-01-02" // RFC3339 with local timezone and time at 00:00:00 -) - -// GetTimestamp tries to parse given string as golang duration, -// then RFC3339 time and finally as a Unix timestamp. If -// any of these were successful, it returns a Unix timestamp -// as string otherwise returns the given value back. -// In case of duration input, the returned timestamp is computed -// as the given reference time minus the amount of the duration. -func GetTimestamp(value string, reference time.Time) (string, error) { - if d, err := time.ParseDuration(value); value != "0" && err == nil { - return strconv.FormatInt(reference.Add(-d).Unix(), 10), nil - } - - var format string - // if the string has a Z or a + or three dashes use parse otherwise use parseinlocation - parseInLocation := !(strings.ContainsAny(value, "zZ+") || strings.Count(value, "-") == 3) - - if strings.Contains(value, ".") { - if parseInLocation { - format = rFC3339NanoLocal - } else { - format = time.RFC3339Nano - } - } else if strings.Contains(value, "T") { - // we want the number of colons in the T portion of the timestamp - tcolons := strings.Count(value, ":") - // if parseInLocation is off and we have a +/- zone offset (not Z) then - // there will be an extra colon in the input for the tz offset subtract that - // colon from the tcolons count - if !parseInLocation && !strings.ContainsAny(value, "zZ") && tcolons > 0 { - tcolons-- - } - if parseInLocation { - switch tcolons { - case 0: - format = "2006-01-02T15" - case 1: - format = "2006-01-02T15:04" - default: - format = rFC3339Local - } - } else { - switch tcolons { - case 0: - format = "2006-01-02T15Z07:00" - case 1: - format = "2006-01-02T15:04Z07:00" - default: - format = time.RFC3339 - } - } - } else if parseInLocation { - format = dateLocal - } else { - format = dateWithZone - } - - var t time.Time - var err error - - if parseInLocation { - t, err = time.ParseInLocation(format, value, time.FixedZone(reference.Zone())) - } else { - t, err = time.Parse(format, value) - } - - if err != nil { - // if there is a `-` then it's an RFC3339 like timestamp - if strings.Contains(value, "-") { - return "", err // was probably an RFC3339 like timestamp but the parser failed with an error - } - if _, _, err := parseTimestamp(value); err != nil { - return "", fmt.Errorf("failed to parse value as time or duration: %q", value) - } - return value, nil // unix timestamp in and out case (meaning: the value passed at the command line is already in the right format for passing to the server) - } - - return fmt.Sprintf("%d.%09d", t.Unix(), int64(t.Nanosecond())), nil -} - -// ParseTimestamps returns seconds and nanoseconds from a timestamp that has -// the format ("%d.%09d", time.Unix(), int64(time.Nanosecond())). -// If the incoming nanosecond portion is longer than 9 digits it is truncated. -// The expectation is that the seconds and nanoseconds will be used to create a -// time variable. For example: -// -// seconds, nanoseconds, _ := ParseTimestamp("1136073600.000000001",0) -// since := time.Unix(seconds, nanoseconds) -// -// returns seconds as defaultSeconds if value == "" -func ParseTimestamps(value string, defaultSeconds int64) (seconds int64, nanoseconds int64, err error) { - if value == "" { - return defaultSeconds, 0, nil - } - return parseTimestamp(value) -} - -func parseTimestamp(value string) (sec int64, nsec int64, err error) { - s, n, ok := strings.Cut(value, ".") - sec, err = strconv.ParseInt(s, 10, 64) - if err != nil { - return sec, 0, err - } - if !ok { - return sec, 0, nil - } - nsec, err = strconv.ParseInt(n, 10, 64) - if err != nil { - return sec, nsec, err - } - // should already be in nanoseconds but just in case convert n to nanoseconds - nsec = int64(float64(nsec) * math.Pow(float64(10), float64(9-len(n)))) - return sec, nsec, nil -} diff --git a/vendor/github.com/docker/docker/api/types/types.go b/vendor/github.com/docker/docker/api/types/types.go deleted file mode 100644 index b413e0200..000000000 --- a/vendor/github.com/docker/docker/api/types/types.go +++ /dev/null @@ -1,811 +0,0 @@ -package types // import "github.com/docker/docker/api/types" - -import ( - "errors" - "fmt" - "io" - "os" - "strings" - "time" - - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/mount" - "github.com/docker/docker/api/types/network" - "github.com/docker/docker/api/types/registry" - "github.com/docker/docker/api/types/swarm" - "github.com/docker/docker/api/types/volume" - "github.com/docker/go-connections/nat" -) - -const ( - // MediaTypeRawStream is vendor specific MIME-Type set for raw TTY streams - MediaTypeRawStream = "application/vnd.docker.raw-stream" - - // MediaTypeMultiplexedStream is vendor specific MIME-Type set for stdin/stdout/stderr multiplexed streams - MediaTypeMultiplexedStream = "application/vnd.docker.multiplexed-stream" -) - -// RootFS returns Image's RootFS description including the layer IDs. -type RootFS struct { - Type string `json:",omitempty"` - Layers []string `json:",omitempty"` -} - -// ImageInspect contains response of Engine API: -// GET "/images/{name:.*}/json" -type ImageInspect struct { - // ID is the content-addressable ID of an image. - // - // This identifier is a content-addressable digest calculated from the - // image's configuration (which includes the digests of layers used by - // the image). - // - // Note that this digest differs from the `RepoDigests` below, which - // holds digests of image manifests that reference the image. - ID string `json:"Id"` - - // RepoTags is a list of image names/tags in the local image cache that - // reference this image. - // - // Multiple image tags can refer to the same image, and this list may be - // empty if no tags reference the image, in which case the image is - // "untagged", in which case it can still be referenced by its ID. - RepoTags []string - - // RepoDigests is a list of content-addressable digests of locally available - // image manifests that the image is referenced from. Multiple manifests can - // refer to the same image. - // - // These digests are usually only available if the image was either pulled - // from a registry, or if the image was pushed to a registry, which is when - // the manifest is generated and its digest calculated. - RepoDigests []string - - // Parent is the ID of the parent image. - // - // Depending on how the image was created, this field may be empty and - // is only set for images that were built/created locally. This field - // is empty if the image was pulled from an image registry. - Parent string - - // Comment is an optional message that can be set when committing or - // importing the image. - Comment string - - // Created is the date and time at which the image was created, formatted in - // RFC 3339 nano-seconds (time.RFC3339Nano). - Created string - - // Container is the ID of the container that was used to create the image. - // - // Depending on how the image was created, this field may be empty. - Container string - - // ContainerConfig is an optional field containing the configuration of the - // container that was last committed when creating the image. - // - // Previous versions of Docker builder used this field to store build cache, - // and it is not in active use anymore. - ContainerConfig *container.Config - - // DockerVersion is the version of Docker that was used to build the image. - // - // Depending on how the image was created, this field may be empty. - DockerVersion string - - // Author is the name of the author that was specified when committing the - // image, or as specified through MAINTAINER (deprecated) in the Dockerfile. - Author string - Config *container.Config - - // Architecture is the hardware CPU architecture that the image runs on. - Architecture string - - // Variant is the CPU architecture variant (presently ARM-only). - Variant string `json:",omitempty"` - - // OS is the Operating System the image is built to run on. - Os string - - // OsVersion is the version of the Operating System the image is built to - // run on (especially for Windows). - OsVersion string `json:",omitempty"` - - // Size is the total size of the image including all layers it is composed of. - Size int64 - - // VirtualSize is the total size of the image including all layers it is - // composed of. - // - // In versions of Docker before v1.10, this field was calculated from - // the image itself and all of its parent images. Docker v1.10 and up - // store images self-contained, and no longer use a parent-chain, making - // this field an equivalent of the Size field. - // - // Deprecated: Unused in API 1.43 and up, but kept for backward compatibility with older API versions. - VirtualSize int64 `json:"VirtualSize,omitempty"` - - // GraphDriver holds information about the storage driver used to store the - // container's and image's filesystem. - GraphDriver GraphDriverData - - // RootFS contains information about the image's RootFS, including the - // layer IDs. - RootFS RootFS - - // Metadata of the image in the local cache. - // - // This information is local to the daemon, and not part of the image itself. - Metadata ImageMetadata -} - -// ImageMetadata contains engine-local data about the image -type ImageMetadata struct { - // LastTagTime is the date and time at which the image was last tagged. - LastTagTime time.Time `json:",omitempty"` -} - -// Container contains response of Engine API: -// GET "/containers/json" -type Container struct { - ID string `json:"Id"` - Names []string - Image string - ImageID string - Command string - Created int64 - Ports []Port - SizeRw int64 `json:",omitempty"` - SizeRootFs int64 `json:",omitempty"` - Labels map[string]string - State string - Status string - HostConfig struct { - NetworkMode string `json:",omitempty"` - } - NetworkSettings *SummaryNetworkSettings - Mounts []MountPoint -} - -// CopyConfig contains request body of Engine API: -// POST "/containers/"+containerID+"/copy" -type CopyConfig struct { - Resource string -} - -// ContainerPathStat is used to encode the header from -// GET "/containers/{name:.*}/archive" -// "Name" is the file or directory name. -type ContainerPathStat struct { - Name string `json:"name"` - Size int64 `json:"size"` - Mode os.FileMode `json:"mode"` - Mtime time.Time `json:"mtime"` - LinkTarget string `json:"linkTarget"` -} - -// ContainerStats contains response of Engine API: -// GET "/stats" -type ContainerStats struct { - Body io.ReadCloser `json:"body"` - OSType string `json:"ostype"` -} - -// Ping contains response of Engine API: -// GET "/_ping" -type Ping struct { - APIVersion string - OSType string - Experimental bool - BuilderVersion BuilderVersion - - // SwarmStatus provides information about the current swarm status of the - // engine, obtained from the "Swarm" header in the API response. - // - // It can be a nil struct if the API version does not provide this header - // in the ping response, or if an error occurred, in which case the client - // should use other ways to get the current swarm status, such as the /swarm - // endpoint. - SwarmStatus *swarm.Status -} - -// ComponentVersion describes the version information for a specific component. -type ComponentVersion struct { - Name string - Version string - Details map[string]string `json:",omitempty"` -} - -// Version contains response of Engine API: -// GET "/version" -type Version struct { - Platform struct{ Name string } `json:",omitempty"` - Components []ComponentVersion `json:",omitempty"` - - // The following fields are deprecated, they relate to the Engine component and are kept for backwards compatibility - - Version string - APIVersion string `json:"ApiVersion"` - MinAPIVersion string `json:"MinAPIVersion,omitempty"` - GitCommit string - GoVersion string - Os string - Arch string - KernelVersion string `json:",omitempty"` - Experimental bool `json:",omitempty"` - BuildTime string `json:",omitempty"` -} - -// Commit holds the Git-commit (SHA1) that a binary was built from, as reported -// in the version-string of external tools, such as containerd, or runC. -type Commit struct { - ID string // ID is the actual commit ID of external tool. - Expected string // Expected is the commit ID of external tool expected by dockerd as set at build time. -} - -// Info contains response of Engine API: -// GET "/info" -type Info struct { - ID string - Containers int - ContainersRunning int - ContainersPaused int - ContainersStopped int - Images int - Driver string - DriverStatus [][2]string - SystemStatus [][2]string `json:",omitempty"` // SystemStatus is only propagated by the Swarm standalone API - Plugins PluginsInfo - MemoryLimit bool - SwapLimit bool - KernelMemory bool `json:",omitempty"` // Deprecated: kernel 5.4 deprecated kmem.limit_in_bytes - KernelMemoryTCP bool `json:",omitempty"` // KernelMemoryTCP is not supported on cgroups v2. - CPUCfsPeriod bool `json:"CpuCfsPeriod"` - CPUCfsQuota bool `json:"CpuCfsQuota"` - CPUShares bool - CPUSet bool - PidsLimit bool - IPv4Forwarding bool - BridgeNfIptables bool - BridgeNfIP6tables bool `json:"BridgeNfIp6tables"` - Debug bool - NFd int - OomKillDisable bool - NGoroutines int - SystemTime string - LoggingDriver string - CgroupDriver string - CgroupVersion string `json:",omitempty"` - NEventsListener int - KernelVersion string - OperatingSystem string - OSVersion string - OSType string - Architecture string - IndexServerAddress string - RegistryConfig *registry.ServiceConfig - NCPU int - MemTotal int64 - GenericResources []swarm.GenericResource - DockerRootDir string - HTTPProxy string `json:"HttpProxy"` - HTTPSProxy string `json:"HttpsProxy"` - NoProxy string - Name string - Labels []string - ExperimentalBuild bool - ServerVersion string - Runtimes map[string]Runtime - DefaultRuntime string - Swarm swarm.Info - // LiveRestoreEnabled determines whether containers should be kept - // running when the daemon is shutdown or upon daemon start if - // running containers are detected - LiveRestoreEnabled bool - Isolation container.Isolation - InitBinary string - ContainerdCommit Commit - RuncCommit Commit - InitCommit Commit - SecurityOptions []string - ProductLicense string `json:",omitempty"` - DefaultAddressPools []NetworkAddressPool `json:",omitempty"` - - // Warnings contains a slice of warnings that occurred while collecting - // system information. These warnings are intended to be informational - // messages for the user, and are not intended to be parsed / used for - // other purposes, as they do not have a fixed format. - Warnings []string -} - -// KeyValue holds a key/value pair -type KeyValue struct { - Key, Value string -} - -// NetworkAddressPool is a temp struct used by Info struct -type NetworkAddressPool struct { - Base string - Size int -} - -// SecurityOpt contains the name and options of a security option -type SecurityOpt struct { - Name string - Options []KeyValue -} - -// DecodeSecurityOptions decodes a security options string slice to a type safe -// SecurityOpt -func DecodeSecurityOptions(opts []string) ([]SecurityOpt, error) { - so := []SecurityOpt{} - for _, opt := range opts { - // support output from a < 1.13 docker daemon - if !strings.Contains(opt, "=") { - so = append(so, SecurityOpt{Name: opt}) - continue - } - secopt := SecurityOpt{} - for _, s := range strings.Split(opt, ",") { - k, v, ok := strings.Cut(s, "=") - if !ok { - return nil, fmt.Errorf("invalid security option %q", s) - } - if k == "" || v == "" { - return nil, errors.New("invalid empty security option") - } - if k == "name" { - secopt.Name = v - continue - } - secopt.Options = append(secopt.Options, KeyValue{Key: k, Value: v}) - } - so = append(so, secopt) - } - return so, nil -} - -// PluginsInfo is a temp struct holding Plugins name -// registered with docker daemon. It is used by Info struct -type PluginsInfo struct { - // List of Volume plugins registered - Volume []string - // List of Network plugins registered - Network []string - // List of Authorization plugins registered - Authorization []string - // List of Log plugins registered - Log []string -} - -// ExecStartCheck is a temp struct used by execStart -// Config fields is part of ExecConfig in runconfig package -type ExecStartCheck struct { - // ExecStart will first check if it's detached - Detach bool - // Check if there's a tty - Tty bool - // Terminal size [height, width], unused if Tty == false - ConsoleSize *[2]uint `json:",omitempty"` -} - -// HealthcheckResult stores information about a single run of a healthcheck probe -type HealthcheckResult struct { - Start time.Time // Start is the time this check started - End time.Time // End is the time this check ended - ExitCode int // ExitCode meanings: 0=healthy, 1=unhealthy, 2=reserved (considered unhealthy), else=error running probe - Output string // Output from last check -} - -// Health states -const ( - NoHealthcheck = "none" // Indicates there is no healthcheck - Starting = "starting" // Starting indicates that the container is not yet ready - Healthy = "healthy" // Healthy indicates that the container is running correctly - Unhealthy = "unhealthy" // Unhealthy indicates that the container has a problem -) - -// Health stores information about the container's healthcheck results -type Health struct { - Status string // Status is one of Starting, Healthy or Unhealthy - FailingStreak int // FailingStreak is the number of consecutive failures - Log []*HealthcheckResult // Log contains the last few results (oldest first) -} - -// ContainerState stores container's running state -// it's part of ContainerJSONBase and will return by "inspect" command -type ContainerState struct { - Status string // String representation of the container state. Can be one of "created", "running", "paused", "restarting", "removing", "exited", or "dead" - Running bool - Paused bool - Restarting bool - OOMKilled bool - Dead bool - Pid int - ExitCode int - Error string - StartedAt string - FinishedAt string - Health *Health `json:",omitempty"` -} - -// ContainerNode stores information about the node that a container -// is running on. It's only used by the Docker Swarm standalone API -type ContainerNode struct { - ID string - IPAddress string `json:"IP"` - Addr string - Name string - Cpus int - Memory int64 - Labels map[string]string -} - -// ContainerJSONBase contains response of Engine API: -// GET "/containers/{name:.*}/json" -type ContainerJSONBase struct { - ID string `json:"Id"` - Created string - Path string - Args []string - State *ContainerState - Image string - ResolvConfPath string - HostnamePath string - HostsPath string - LogPath string - Node *ContainerNode `json:",omitempty"` // Node is only propagated by Docker Swarm standalone API - Name string - RestartCount int - Driver string - Platform string - MountLabel string - ProcessLabel string - AppArmorProfile string - ExecIDs []string - HostConfig *container.HostConfig - GraphDriver GraphDriverData - SizeRw *int64 `json:",omitempty"` - SizeRootFs *int64 `json:",omitempty"` -} - -// ContainerJSON is newly used struct along with MountPoint -type ContainerJSON struct { - *ContainerJSONBase - Mounts []MountPoint - Config *container.Config - NetworkSettings *NetworkSettings -} - -// NetworkSettings exposes the network settings in the api -type NetworkSettings struct { - NetworkSettingsBase - DefaultNetworkSettings - Networks map[string]*network.EndpointSettings -} - -// SummaryNetworkSettings provides a summary of container's networks -// in /containers/json -type SummaryNetworkSettings struct { - Networks map[string]*network.EndpointSettings -} - -// NetworkSettingsBase holds basic information about networks -type NetworkSettingsBase struct { - Bridge string // Bridge is the Bridge name the network uses(e.g. `docker0`) - SandboxID string // SandboxID uniquely represents a container's network stack - HairpinMode bool // HairpinMode specifies if hairpin NAT should be enabled on the virtual interface - LinkLocalIPv6Address string // LinkLocalIPv6Address is an IPv6 unicast address using the link-local prefix - LinkLocalIPv6PrefixLen int // LinkLocalIPv6PrefixLen is the prefix length of an IPv6 unicast address - Ports nat.PortMap // Ports is a collection of PortBinding indexed by Port - SandboxKey string // SandboxKey identifies the sandbox - SecondaryIPAddresses []network.Address - SecondaryIPv6Addresses []network.Address -} - -// DefaultNetworkSettings holds network information -// during the 2 release deprecation period. -// It will be removed in Docker 1.11. -type DefaultNetworkSettings struct { - EndpointID string // EndpointID uniquely represents a service endpoint in a Sandbox - Gateway string // Gateway holds the gateway address for the network - GlobalIPv6Address string // GlobalIPv6Address holds network's global IPv6 address - GlobalIPv6PrefixLen int // GlobalIPv6PrefixLen represents mask length of network's global IPv6 address - IPAddress string // IPAddress holds the IPv4 address for the network - IPPrefixLen int // IPPrefixLen represents mask length of network's IPv4 address - IPv6Gateway string // IPv6Gateway holds gateway address specific for IPv6 - MacAddress string // MacAddress holds the MAC address for the network -} - -// MountPoint represents a mount point configuration inside the container. -// This is used for reporting the mountpoints in use by a container. -type MountPoint struct { - // Type is the type of mount, see `Type` definitions in - // github.com/docker/docker/api/types/mount.Type - Type mount.Type `json:",omitempty"` - - // Name is the name reference to the underlying data defined by `Source` - // e.g., the volume name. - Name string `json:",omitempty"` - - // Source is the source location of the mount. - // - // For volumes, this contains the storage location of the volume (within - // `/var/lib/docker/volumes/`). For bind-mounts, and `npipe`, this contains - // the source (host) part of the bind-mount. For `tmpfs` mount points, this - // field is empty. - Source string - - // Destination is the path relative to the container root (`/`) where the - // Source is mounted inside the container. - Destination string - - // Driver is the volume driver used to create the volume (if it is a volume). - Driver string `json:",omitempty"` - - // Mode is a comma separated list of options supplied by the user when - // creating the bind/volume mount. - // - // The default is platform-specific (`"z"` on Linux, empty on Windows). - Mode string - - // RW indicates whether the mount is mounted writable (read-write). - RW bool - - // Propagation describes how mounts are propagated from the host into the - // mount point, and vice-versa. Refer to the Linux kernel documentation - // for details: - // https://www.kernel.org/doc/Documentation/filesystems/sharedsubtree.txt - // - // This field is not used on Windows. - Propagation mount.Propagation -} - -// NetworkResource is the body of the "get network" http response message -type NetworkResource struct { - Name string // Name is the requested name of the network - ID string `json:"Id"` // ID uniquely identifies a network on a single machine - Created time.Time // Created is the time the network created - Scope string // Scope describes the level at which the network exists (e.g. `swarm` for cluster-wide or `local` for machine level) - Driver string // Driver is the Driver name used to create the network (e.g. `bridge`, `overlay`) - EnableIPv6 bool // EnableIPv6 represents whether to enable IPv6 - IPAM network.IPAM // IPAM is the network's IP Address Management - Internal bool // Internal represents if the network is used internal only - Attachable bool // Attachable represents if the global scope is manually attachable by regular containers from workers in swarm mode. - Ingress bool // Ingress indicates the network is providing the routing-mesh for the swarm cluster. - ConfigFrom network.ConfigReference // ConfigFrom specifies the source which will provide the configuration for this network. - ConfigOnly bool // ConfigOnly networks are place-holder networks for network configurations to be used by other networks. ConfigOnly networks cannot be used directly to run containers or services. - Containers map[string]EndpointResource // Containers contains endpoints belonging to the network - Options map[string]string // Options holds the network specific options to use for when creating the network - Labels map[string]string // Labels holds metadata specific to the network being created - Peers []network.PeerInfo `json:",omitempty"` // List of peer nodes for an overlay network - Services map[string]network.ServiceInfo `json:",omitempty"` -} - -// EndpointResource contains network resources allocated and used for a container in a network -type EndpointResource struct { - Name string - EndpointID string - MacAddress string - IPv4Address string - IPv6Address string -} - -// NetworkCreate is the expected body of the "create network" http request message -type NetworkCreate struct { - // Check for networks with duplicate names. - // Network is primarily keyed based on a random ID and not on the name. - // Network name is strictly a user-friendly alias to the network - // which is uniquely identified using ID. - // And there is no guaranteed way to check for duplicates. - // Option CheckDuplicate is there to provide a best effort checking of any networks - // which has the same name but it is not guaranteed to catch all name collisions. - CheckDuplicate bool - Driver string - Scope string - EnableIPv6 bool - IPAM *network.IPAM - Internal bool - Attachable bool - Ingress bool - ConfigOnly bool - ConfigFrom *network.ConfigReference - Options map[string]string - Labels map[string]string -} - -// NetworkCreateRequest is the request message sent to the server for network create call. -type NetworkCreateRequest struct { - NetworkCreate - Name string -} - -// NetworkCreateResponse is the response message sent by the server for network create call -type NetworkCreateResponse struct { - ID string `json:"Id"` - Warning string -} - -// NetworkConnect represents the data to be used to connect a container to the network -type NetworkConnect struct { - Container string - EndpointConfig *network.EndpointSettings `json:",omitempty"` -} - -// NetworkDisconnect represents the data to be used to disconnect a container from the network -type NetworkDisconnect struct { - Container string - Force bool -} - -// NetworkInspectOptions holds parameters to inspect network -type NetworkInspectOptions struct { - Scope string - Verbose bool -} - -// Checkpoint represents the details of a checkpoint -type Checkpoint struct { - Name string // Name is the name of the checkpoint -} - -// Runtime describes an OCI runtime -type Runtime struct { - // "Legacy" runtime configuration for runc-compatible runtimes. - - Path string `json:"path,omitempty"` - Args []string `json:"runtimeArgs,omitempty"` - - // Shimv2 runtime configuration. Mutually exclusive with the legacy config above. - - Type string `json:"runtimeType,omitempty"` - Options map[string]interface{} `json:"options,omitempty"` - - // This is exposed here only for internal use - ShimConfig *ShimConfig `json:"-"` -} - -// ShimConfig is used by runtime to configure containerd shims -type ShimConfig struct { - Binary string - Opts interface{} -} - -// DiskUsageObject represents an object type used for disk usage query filtering. -type DiskUsageObject string - -const ( - // ContainerObject represents a container DiskUsageObject. - ContainerObject DiskUsageObject = "container" - // ImageObject represents an image DiskUsageObject. - ImageObject DiskUsageObject = "image" - // VolumeObject represents a volume DiskUsageObject. - VolumeObject DiskUsageObject = "volume" - // BuildCacheObject represents a build-cache DiskUsageObject. - BuildCacheObject DiskUsageObject = "build-cache" -) - -// DiskUsageOptions holds parameters for system disk usage query. -type DiskUsageOptions struct { - // Types specifies what object types to include in the response. If empty, - // all object types are returned. - Types []DiskUsageObject -} - -// DiskUsage contains response of Engine API: -// GET "/system/df" -type DiskUsage struct { - LayersSize int64 - Images []*ImageSummary - Containers []*Container - Volumes []*volume.Volume - BuildCache []*BuildCache - BuilderSize int64 `json:",omitempty"` // Deprecated: deprecated in API 1.38, and no longer used since API 1.40. -} - -// ContainersPruneReport contains the response for Engine API: -// POST "/containers/prune" -type ContainersPruneReport struct { - ContainersDeleted []string - SpaceReclaimed uint64 -} - -// VolumesPruneReport contains the response for Engine API: -// POST "/volumes/prune" -type VolumesPruneReport struct { - VolumesDeleted []string - SpaceReclaimed uint64 -} - -// ImagesPruneReport contains the response for Engine API: -// POST "/images/prune" -type ImagesPruneReport struct { - ImagesDeleted []ImageDeleteResponseItem - SpaceReclaimed uint64 -} - -// BuildCachePruneReport contains the response for Engine API: -// POST "/build/prune" -type BuildCachePruneReport struct { - CachesDeleted []string - SpaceReclaimed uint64 -} - -// NetworksPruneReport contains the response for Engine API: -// POST "/networks/prune" -type NetworksPruneReport struct { - NetworksDeleted []string -} - -// SecretCreateResponse contains the information returned to a client -// on the creation of a new secret. -type SecretCreateResponse struct { - // ID is the id of the created secret. - ID string -} - -// SecretListOptions holds parameters to list secrets -type SecretListOptions struct { - Filters filters.Args -} - -// ConfigCreateResponse contains the information returned to a client -// on the creation of a new config. -type ConfigCreateResponse struct { - // ID is the id of the created config. - ID string -} - -// ConfigListOptions holds parameters to list configs -type ConfigListOptions struct { - Filters filters.Args -} - -// PushResult contains the tag, manifest digest, and manifest size from the -// push. It's used to signal this information to the trust code in the client -// so it can sign the manifest if necessary. -type PushResult struct { - Tag string - Digest string - Size int -} - -// BuildResult contains the image id of a successful build -type BuildResult struct { - ID string -} - -// BuildCache contains information about a build cache record. -type BuildCache struct { - // ID is the unique ID of the build cache record. - ID string - // Parent is the ID of the parent build cache record. - // - // Deprecated: deprecated in API v1.42 and up, as it was deprecated in BuildKit; use Parents instead. - Parent string `json:"Parent,omitempty"` - // Parents is the list of parent build cache record IDs. - Parents []string `json:" Parents,omitempty"` - // Type is the cache record type. - Type string - // Description is a description of the build-step that produced the build cache. - Description string - // InUse indicates if the build cache is in use. - InUse bool - // Shared indicates if the build cache is shared. - Shared bool - // Size is the amount of disk space used by the build cache (in bytes). - Size int64 - // CreatedAt is the date and time at which the build cache was created. - CreatedAt time.Time - // LastUsedAt is the date and time at which the build cache was last used. - LastUsedAt *time.Time - UsageCount int -} - -// BuildCachePruneOptions hold parameters to prune the build cache -type BuildCachePruneOptions struct { - All bool - KeepStorage int64 - Filters filters.Args -} diff --git a/vendor/github.com/docker/docker/api/types/versions/README.md b/vendor/github.com/docker/docker/api/types/versions/README.md deleted file mode 100644 index 1ef911edb..000000000 --- a/vendor/github.com/docker/docker/api/types/versions/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# Legacy API type versions - -This package includes types for legacy API versions. The stable version of the API types live in `api/types/*.go`. - -Consider moving a type here when you need to keep backwards compatibility in the API. This legacy types are organized by the latest API version they appear in. For instance, types in the `v1p19` package are valid for API versions below or equal `1.19`. Types in the `v1p20` package are valid for the API version `1.20`, since the versions below that will use the legacy types in `v1p19`. - -## Package name conventions - -The package name convention is to use `v` as a prefix for the version number and `p`(patch) as a separator. We use this nomenclature due to a few restrictions in the Go package name convention: - -1. We cannot use `.` because it's interpreted by the language, think of `v1.20.CallFunction`. -2. We cannot use `_` because golint complains about it. The code is actually valid, but it looks probably more weird: `v1_20.CallFunction`. - -For instance, if you want to modify a type that was available in the version `1.21` of the API but it will have different fields in the version `1.22`, you want to create a new package under `api/types/versions/v1p21`. diff --git a/vendor/github.com/docker/docker/api/types/versions/compare.go b/vendor/github.com/docker/docker/api/types/versions/compare.go deleted file mode 100644 index 621725a36..000000000 --- a/vendor/github.com/docker/docker/api/types/versions/compare.go +++ /dev/null @@ -1,65 +0,0 @@ -package versions // import "github.com/docker/docker/api/types/versions" - -import ( - "strconv" - "strings" -) - -// compare compares two version strings -// returns -1 if v1 < v2, 1 if v1 > v2, 0 otherwise. -func compare(v1, v2 string) int { - if v1 == v2 { - return 0 - } - var ( - currTab = strings.Split(v1, ".") - otherTab = strings.Split(v2, ".") - ) - - maxVer := len(currTab) - if len(otherTab) > maxVer { - maxVer = len(otherTab) - } - for i := 0; i < maxVer; i++ { - var currInt, otherInt int - - if len(currTab) > i { - currInt, _ = strconv.Atoi(currTab[i]) - } - if len(otherTab) > i { - otherInt, _ = strconv.Atoi(otherTab[i]) - } - if currInt > otherInt { - return 1 - } - if otherInt > currInt { - return -1 - } - } - return 0 -} - -// LessThan checks if a version is less than another -func LessThan(v, other string) bool { - return compare(v, other) == -1 -} - -// LessThanOrEqualTo checks if a version is less than or equal to another -func LessThanOrEqualTo(v, other string) bool { - return compare(v, other) <= 0 -} - -// GreaterThan checks if a version is greater than another -func GreaterThan(v, other string) bool { - return compare(v, other) == 1 -} - -// GreaterThanOrEqualTo checks if a version is greater than or equal to another -func GreaterThanOrEqualTo(v, other string) bool { - return compare(v, other) >= 0 -} - -// Equal checks if a version is equal to another -func Equal(v, other string) bool { - return compare(v, other) == 0 -} diff --git a/vendor/github.com/docker/docker/api/types/volume/cluster_volume.go b/vendor/github.com/docker/docker/api/types/volume/cluster_volume.go deleted file mode 100644 index 55fc5d389..000000000 --- a/vendor/github.com/docker/docker/api/types/volume/cluster_volume.go +++ /dev/null @@ -1,420 +0,0 @@ -package volume - -import ( - "github.com/docker/docker/api/types/swarm" -) - -// ClusterVolume contains options and information specific to, and only present -// on, Swarm CSI cluster volumes. -type ClusterVolume struct { - // ID is the Swarm ID of the volume. Because cluster volumes are Swarm - // objects, they have an ID, unlike non-cluster volumes, which only have a - // Name. This ID can be used to refer to the cluster volume. - ID string - - // Meta is the swarm metadata about this volume. - swarm.Meta - - // Spec is the cluster-specific options from which this volume is derived. - Spec ClusterVolumeSpec - - // PublishStatus contains the status of the volume as it pertains to its - // publishing on Nodes. - PublishStatus []*PublishStatus `json:",omitempty"` - - // Info is information about the global status of the volume. - Info *Info `json:",omitempty"` -} - -// ClusterVolumeSpec contains the spec used to create this volume. -type ClusterVolumeSpec struct { - // Group defines the volume group of this volume. Volumes belonging to the - // same group can be referred to by group name when creating Services. - // Referring to a volume by group instructs swarm to treat volumes in that - // group interchangeably for the purpose of scheduling. Volumes with an - // empty string for a group technically all belong to the same, emptystring - // group. - Group string `json:",omitempty"` - - // AccessMode defines how the volume is used by tasks. - AccessMode *AccessMode `json:",omitempty"` - - // AccessibilityRequirements specifies where in the cluster a volume must - // be accessible from. - // - // This field must be empty if the plugin does not support - // VOLUME_ACCESSIBILITY_CONSTRAINTS capabilities. If it is present but the - // plugin does not support it, volume will not be created. - // - // If AccessibilityRequirements is empty, but the plugin does support - // VOLUME_ACCESSIBILITY_CONSTRAINTS, then Swarmkit will assume the entire - // cluster is a valid target for the volume. - AccessibilityRequirements *TopologyRequirement `json:",omitempty"` - - // CapacityRange defines the desired capacity that the volume should be - // created with. If nil, the plugin will decide the capacity. - CapacityRange *CapacityRange `json:",omitempty"` - - // Secrets defines Swarm Secrets that are passed to the CSI storage plugin - // when operating on this volume. - Secrets []Secret `json:",omitempty"` - - // Availability is the Volume's desired availability. Analogous to Node - // Availability, this allows the user to take volumes offline in order to - // update or delete them. - Availability Availability `json:",omitempty"` -} - -// Availability specifies the availability of the volume. -type Availability string - -const ( - // AvailabilityActive indicates that the volume is active and fully - // schedulable on the cluster. - AvailabilityActive Availability = "active" - - // AvailabilityPause indicates that no new workloads should use the - // volume, but existing workloads can continue to use it. - AvailabilityPause Availability = "pause" - - // AvailabilityDrain indicates that all workloads using this volume - // should be rescheduled, and the volume unpublished from all nodes. - AvailabilityDrain Availability = "drain" -) - -// AccessMode defines the access mode of a volume. -type AccessMode struct { - // Scope defines the set of nodes this volume can be used on at one time. - Scope Scope `json:",omitempty"` - - // Sharing defines the number and way that different tasks can use this - // volume at one time. - Sharing SharingMode `json:",omitempty"` - - // MountVolume defines options for using this volume as a Mount-type - // volume. - // - // Either BlockVolume or MountVolume, but not both, must be present. - MountVolume *TypeMount `json:",omitempty"` - - // BlockVolume defines options for using this volume as a Block-type - // volume. - // - // Either BlockVolume or MountVolume, but not both, must be present. - BlockVolume *TypeBlock `json:",omitempty"` -} - -// Scope defines the Scope of a Cluster Volume. This is how many nodes a -// Volume can be accessed simultaneously on. -type Scope string - -const ( - // ScopeSingleNode indicates the volume can be used on one node at a - // time. - ScopeSingleNode Scope = "single" - - // ScopeMultiNode indicates the volume can be used on many nodes at - // the same time. - ScopeMultiNode Scope = "multi" -) - -// SharingMode defines the Sharing of a Cluster Volume. This is how Tasks using a -// Volume at the same time can use it. -type SharingMode string - -const ( - // SharingNone indicates that only one Task may use the Volume at a - // time. - SharingNone SharingMode = "none" - - // SharingReadOnly indicates that the Volume may be shared by any - // number of Tasks, but they must be read-only. - SharingReadOnly SharingMode = "readonly" - - // SharingOneWriter indicates that the Volume may be shared by any - // number of Tasks, but all after the first must be read-only. - SharingOneWriter SharingMode = "onewriter" - - // SharingAll means that the Volume may be shared by any number of - // Tasks, as readers or writers. - SharingAll SharingMode = "all" -) - -// TypeBlock defines options for using a volume as a block-type volume. -// -// Intentionally empty. -type TypeBlock struct{} - -// TypeMount contains options for using a volume as a Mount-type -// volume. -type TypeMount struct { - // FsType specifies the filesystem type for the mount volume. Optional. - FsType string `json:",omitempty"` - - // MountFlags defines flags to pass when mounting the volume. Optional. - MountFlags []string `json:",omitempty"` -} - -// TopologyRequirement expresses the user's requirements for a volume's -// accessible topology. -type TopologyRequirement struct { - // Requisite specifies a list of Topologies, at least one of which the - // volume must be accessible from. - // - // Taken verbatim from the CSI Spec: - // - // Specifies the list of topologies the provisioned volume MUST be - // accessible from. - // This field is OPTIONAL. If TopologyRequirement is specified either - // requisite or preferred or both MUST be specified. - // - // If requisite is specified, the provisioned volume MUST be - // accessible from at least one of the requisite topologies. - // - // Given - // x = number of topologies provisioned volume is accessible from - // n = number of requisite topologies - // The CO MUST ensure n >= 1. The SP MUST ensure x >= 1 - // If x==n, then the SP MUST make the provisioned volume available to - // all topologies from the list of requisite topologies. If it is - // unable to do so, the SP MUST fail the CreateVolume call. - // For example, if a volume should be accessible from a single zone, - // and requisite = - // {"region": "R1", "zone": "Z2"} - // then the provisioned volume MUST be accessible from the "region" - // "R1" and the "zone" "Z2". - // Similarly, if a volume should be accessible from two zones, and - // requisite = - // {"region": "R1", "zone": "Z2"}, - // {"region": "R1", "zone": "Z3"} - // then the provisioned volume MUST be accessible from the "region" - // "R1" and both "zone" "Z2" and "zone" "Z3". - // - // If xn, then the SP MUST make the provisioned volume available from - // all topologies from the list of requisite topologies and MAY choose - // the remaining x-n unique topologies from the list of all possible - // topologies. If it is unable to do so, the SP MUST fail the - // CreateVolume call. - // For example, if a volume should be accessible from two zones, and - // requisite = - // {"region": "R1", "zone": "Z2"} - // then the provisioned volume MUST be accessible from the "region" - // "R1" and the "zone" "Z2" and the SP may select the second zone - // independently, e.g. "R1/Z4". - Requisite []Topology `json:",omitempty"` - - // Preferred is a list of Topologies that the volume should attempt to be - // provisioned in. - // - // Taken from the CSI spec: - // - // Specifies the list of topologies the CO would prefer the volume to - // be provisioned in. - // - // This field is OPTIONAL. If TopologyRequirement is specified either - // requisite or preferred or both MUST be specified. - // - // An SP MUST attempt to make the provisioned volume available using - // the preferred topologies in order from first to last. - // - // If requisite is specified, all topologies in preferred list MUST - // also be present in the list of requisite topologies. - // - // If the SP is unable to to make the provisioned volume available - // from any of the preferred topologies, the SP MAY choose a topology - // from the list of requisite topologies. - // If the list of requisite topologies is not specified, then the SP - // MAY choose from the list of all possible topologies. - // If the list of requisite topologies is specified and the SP is - // unable to to make the provisioned volume available from any of the - // requisite topologies it MUST fail the CreateVolume call. - // - // Example 1: - // Given a volume should be accessible from a single zone, and - // requisite = - // {"region": "R1", "zone": "Z2"}, - // {"region": "R1", "zone": "Z3"} - // preferred = - // {"region": "R1", "zone": "Z3"} - // then the the SP SHOULD first attempt to make the provisioned volume - // available from "zone" "Z3" in the "region" "R1" and fall back to - // "zone" "Z2" in the "region" "R1" if that is not possible. - // - // Example 2: - // Given a volume should be accessible from a single zone, and - // requisite = - // {"region": "R1", "zone": "Z2"}, - // {"region": "R1", "zone": "Z3"}, - // {"region": "R1", "zone": "Z4"}, - // {"region": "R1", "zone": "Z5"} - // preferred = - // {"region": "R1", "zone": "Z4"}, - // {"region": "R1", "zone": "Z2"} - // then the the SP SHOULD first attempt to make the provisioned volume - // accessible from "zone" "Z4" in the "region" "R1" and fall back to - // "zone" "Z2" in the "region" "R1" if that is not possible. If that - // is not possible, the SP may choose between either the "zone" - // "Z3" or "Z5" in the "region" "R1". - // - // Example 3: - // Given a volume should be accessible from TWO zones (because an - // opaque parameter in CreateVolumeRequest, for example, specifies - // the volume is accessible from two zones, aka synchronously - // replicated), and - // requisite = - // {"region": "R1", "zone": "Z2"}, - // {"region": "R1", "zone": "Z3"}, - // {"region": "R1", "zone": "Z4"}, - // {"region": "R1", "zone": "Z5"} - // preferred = - // {"region": "R1", "zone": "Z5"}, - // {"region": "R1", "zone": "Z3"} - // then the the SP SHOULD first attempt to make the provisioned volume - // accessible from the combination of the two "zones" "Z5" and "Z3" in - // the "region" "R1". If that's not possible, it should fall back to - // a combination of "Z5" and other possibilities from the list of - // requisite. If that's not possible, it should fall back to a - // combination of "Z3" and other possibilities from the list of - // requisite. If that's not possible, it should fall back to a - // combination of other possibilities from the list of requisite. - Preferred []Topology `json:",omitempty"` -} - -// Topology is a map of topological domains to topological segments. -// -// This description is taken verbatim from the CSI Spec: -// -// A topological domain is a sub-division of a cluster, like "region", -// "zone", "rack", etc. -// A topological segment is a specific instance of a topological domain, -// like "zone3", "rack3", etc. -// For example {"com.company/zone": "Z1", "com.company/rack": "R3"} -// Valid keys have two segments: an OPTIONAL prefix and name, separated -// by a slash (/), for example: "com.company.example/zone". -// The key name segment is REQUIRED. The prefix is OPTIONAL. -// The key name MUST be 63 characters or less, begin and end with an -// alphanumeric character ([a-z0-9A-Z]), and contain only dashes (-), -// underscores (_), dots (.), or alphanumerics in between, for example -// "zone". -// The key prefix MUST be 63 characters or less, begin and end with a -// lower-case alphanumeric character ([a-z0-9]), contain only -// dashes (-), dots (.), or lower-case alphanumerics in between, and -// follow domain name notation format -// (https://tools.ietf.org/html/rfc1035#section-2.3.1). -// The key prefix SHOULD include the plugin's host company name and/or -// the plugin name, to minimize the possibility of collisions with keys -// from other plugins. -// If a key prefix is specified, it MUST be identical across all -// topology keys returned by the SP (across all RPCs). -// Keys MUST be case-insensitive. Meaning the keys "Zone" and "zone" -// MUST not both exist. -// Each value (topological segment) MUST contain 1 or more strings. -// Each string MUST be 63 characters or less and begin and end with an -// alphanumeric character with '-', '_', '.', or alphanumerics in -// between. -type Topology struct { - Segments map[string]string `json:",omitempty"` -} - -// CapacityRange describes the minimum and maximum capacity a volume should be -// created with -type CapacityRange struct { - // RequiredBytes specifies that a volume must be at least this big. The - // value of 0 indicates an unspecified minimum. - RequiredBytes int64 - - // LimitBytes specifies that a volume must not be bigger than this. The - // value of 0 indicates an unspecified maximum - LimitBytes int64 -} - -// Secret represents a Swarm Secret value that must be passed to the CSI -// storage plugin when operating on this Volume. It represents one key-value -// pair of possibly many. -type Secret struct { - // Key is the name of the key of the key-value pair passed to the plugin. - Key string - - // Secret is the swarm Secret object from which to read data. This can be a - // Secret name or ID. The Secret data is retrieved by Swarm and used as the - // value of the key-value pair passed to the plugin. - Secret string -} - -// PublishState represents the state of a Volume as it pertains to its -// use on a particular Node. -type PublishState string - -const ( - // StatePending indicates that the volume should be published on - // this node, but the call to ControllerPublishVolume has not been - // successfully completed yet and the result recorded by swarmkit. - StatePending PublishState = "pending-publish" - - // StatePublished means the volume is published successfully to the node. - StatePublished PublishState = "published" - - // StatePendingNodeUnpublish indicates that the Volume should be - // unpublished on the Node, and we're waiting for confirmation that it has - // done so. After the Node has confirmed that the Volume has been - // unpublished, the state will move to StatePendingUnpublish. - StatePendingNodeUnpublish PublishState = "pending-node-unpublish" - - // StatePendingUnpublish means the volume is still published to the node - // by the controller, awaiting the operation to unpublish it. - StatePendingUnpublish PublishState = "pending-controller-unpublish" -) - -// PublishStatus represents the status of the volume as published to an -// individual node -type PublishStatus struct { - // NodeID is the ID of the swarm node this Volume is published to. - NodeID string `json:",omitempty"` - - // State is the publish state of the volume. - State PublishState `json:",omitempty"` - - // PublishContext is the PublishContext returned by the CSI plugin when - // a volume is published. - PublishContext map[string]string `json:",omitempty"` -} - -// Info contains information about the Volume as a whole as provided by -// the CSI storage plugin. -type Info struct { - // CapacityBytes is the capacity of the volume in bytes. A value of 0 - // indicates that the capacity is unknown. - CapacityBytes int64 `json:",omitempty"` - - // VolumeContext is the context originating from the CSI storage plugin - // when the Volume is created. - VolumeContext map[string]string `json:",omitempty"` - - // VolumeID is the ID of the Volume as seen by the CSI storage plugin. This - // is distinct from the Volume's Swarm ID, which is the ID used by all of - // the Docker Engine to refer to the Volume. If this field is blank, then - // the Volume has not been successfully created yet. - VolumeID string `json:",omitempty"` - - // AccessibleTopolgoy is the topology this volume is actually accessible - // from. - AccessibleTopology []Topology `json:",omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/volume/create_options.go b/vendor/github.com/docker/docker/api/types/volume/create_options.go deleted file mode 100644 index 37c41a609..000000000 --- a/vendor/github.com/docker/docker/api/types/volume/create_options.go +++ /dev/null @@ -1,29 +0,0 @@ -package volume - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// CreateOptions VolumeConfig -// -// Volume configuration -// swagger:model CreateOptions -type CreateOptions struct { - - // cluster volume spec - ClusterVolumeSpec *ClusterVolumeSpec `json:"ClusterVolumeSpec,omitempty"` - - // Name of the volume driver to use. - Driver string `json:"Driver,omitempty"` - - // A mapping of driver options and values. These options are - // passed directly to the driver and are driver specific. - // - DriverOpts map[string]string `json:"DriverOpts,omitempty"` - - // User-defined key/value metadata. - Labels map[string]string `json:"Labels,omitempty"` - - // The new volume's name. If not specified, Docker generates a name. - // - Name string `json:"Name,omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/volume/list_response.go b/vendor/github.com/docker/docker/api/types/volume/list_response.go deleted file mode 100644 index ca5192a2a..000000000 --- a/vendor/github.com/docker/docker/api/types/volume/list_response.go +++ /dev/null @@ -1,18 +0,0 @@ -package volume - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// ListResponse VolumeListResponse -// -// Volume list response -// swagger:model ListResponse -type ListResponse struct { - - // List of volumes - Volumes []*Volume `json:"Volumes"` - - // Warnings that occurred when fetching the list of volumes. - // - Warnings []string `json:"Warnings"` -} diff --git a/vendor/github.com/docker/docker/api/types/volume/options.go b/vendor/github.com/docker/docker/api/types/volume/options.go deleted file mode 100644 index 8b0dd1389..000000000 --- a/vendor/github.com/docker/docker/api/types/volume/options.go +++ /dev/null @@ -1,8 +0,0 @@ -package volume // import "github.com/docker/docker/api/types/volume" - -import "github.com/docker/docker/api/types/filters" - -// ListOptions holds parameters to list volumes. -type ListOptions struct { - Filters filters.Args -} diff --git a/vendor/github.com/docker/docker/api/types/volume/volume.go b/vendor/github.com/docker/docker/api/types/volume/volume.go deleted file mode 100644 index ea7d555e5..000000000 --- a/vendor/github.com/docker/docker/api/types/volume/volume.go +++ /dev/null @@ -1,75 +0,0 @@ -package volume - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// Volume volume -// swagger:model Volume -type Volume struct { - - // cluster volume - ClusterVolume *ClusterVolume `json:"ClusterVolume,omitempty"` - - // Date/Time the volume was created. - CreatedAt string `json:"CreatedAt,omitempty"` - - // Name of the volume driver used by the volume. - // Required: true - Driver string `json:"Driver"` - - // User-defined key/value metadata. - // Required: true - Labels map[string]string `json:"Labels"` - - // Mount path of the volume on the host. - // Required: true - Mountpoint string `json:"Mountpoint"` - - // Name of the volume. - // Required: true - Name string `json:"Name"` - - // The driver specific options used when creating the volume. - // - // Required: true - Options map[string]string `json:"Options"` - - // The level at which the volume exists. Either `global` for cluster-wide, - // or `local` for machine level. - // - // Required: true - Scope string `json:"Scope"` - - // Low-level details about the volume, provided by the volume driver. - // Details are returned as a map with key/value pairs: - // `{"key":"value","key2":"value2"}`. - // - // The `Status` field is optional, and is omitted if the volume driver - // does not support this feature. - // - Status map[string]interface{} `json:"Status,omitempty"` - - // usage data - UsageData *UsageData `json:"UsageData,omitempty"` -} - -// UsageData Usage details about the volume. This information is used by the -// `GET /system/df` endpoint, and omitted in other endpoints. -// -// swagger:model UsageData -type UsageData struct { - - // The number of containers referencing this volume. This field - // is set to `-1` if the reference-count is not available. - // - // Required: true - RefCount int64 `json:"RefCount"` - - // Amount of disk space used by the volume (in bytes). This information - // is only available for volumes created with the `"local"` volume - // driver. For volumes created with other volume drivers, this field - // is set to `-1` ("not available") - // - // Required: true - Size int64 `json:"Size"` -} diff --git a/vendor/github.com/docker/docker/api/types/volume/volume_update.go b/vendor/github.com/docker/docker/api/types/volume/volume_update.go deleted file mode 100644 index f958f80a6..000000000 --- a/vendor/github.com/docker/docker/api/types/volume/volume_update.go +++ /dev/null @@ -1,7 +0,0 @@ -package volume // import "github.com/docker/docker/api/types/volume" - -// UpdateOptions is configuration to update a Volume with. -type UpdateOptions struct { - // Spec is the ClusterVolumeSpec to update the volume to. - Spec *ClusterVolumeSpec `json:"Spec,omitempty"` -} diff --git a/vendor/github.com/docker/docker/builder/remotecontext/git/gitutils.go b/vendor/github.com/docker/docker/builder/remotecontext/git/gitutils.go deleted file mode 100644 index f9b2b4b9c..000000000 --- a/vendor/github.com/docker/docker/builder/remotecontext/git/gitutils.go +++ /dev/null @@ -1,242 +0,0 @@ -package git // import "github.com/docker/docker/builder/remotecontext/git" - -import ( - "net/http" - "net/url" - "os" - "os/exec" - "path/filepath" - "strings" - - "github.com/moby/sys/symlink" - "github.com/pkg/errors" -) - -type gitRepo struct { - remote string - ref string - subdir string - - isolateConfig bool -} - -// CloneOption changes the behaviour of Clone(). -type CloneOption func(*gitRepo) - -// WithIsolatedConfig disables reading the user or system gitconfig files when -// performing Git operations. -func WithIsolatedConfig(v bool) CloneOption { - return func(gr *gitRepo) { - gr.isolateConfig = v - } -} - -// Clone clones a repository into a newly created directory which -// will be under "docker-build-git" -func Clone(remoteURL string, opts ...CloneOption) (string, error) { - repo, err := parseRemoteURL(remoteURL) - - if err != nil { - return "", err - } - - for _, opt := range opts { - opt(&repo) - } - - return repo.clone() -} - -func (repo gitRepo) clone() (checkoutDir string, err error) { - fetch := fetchArgs(repo.remote, repo.ref) - - root, err := os.MkdirTemp("", "docker-build-git") - if err != nil { - return "", err - } - - defer func() { - if err != nil { - os.RemoveAll(root) - } - }() - - if out, err := repo.gitWithinDir(root, "init"); err != nil { - return "", errors.Wrapf(err, "failed to init repo at %s: %s", root, out) - } - - // Add origin remote for compatibility with previous implementation that - // used "git clone" and also to make sure local refs are created for branches - if out, err := repo.gitWithinDir(root, "remote", "add", "origin", repo.remote); err != nil { - return "", errors.Wrapf(err, "failed add origin repo at %s: %s", repo.remote, out) - } - - if output, err := repo.gitWithinDir(root, fetch...); err != nil { - return "", errors.Wrapf(err, "error fetching: %s", output) - } - - checkoutDir, err = repo.checkout(root) - if err != nil { - return "", err - } - - cmd := exec.Command("git", "submodule", "update", "--init", "--recursive", "--depth=1") - cmd.Dir = root - output, err := cmd.CombinedOutput() - if err != nil { - return "", errors.Wrapf(err, "error initializing submodules: %s", output) - } - - return checkoutDir, nil -} - -func parseRemoteURL(remoteURL string) (gitRepo, error) { - repo := gitRepo{} - - if !isGitTransport(remoteURL) { - remoteURL = "https://" + remoteURL - } - - if strings.HasPrefix(remoteURL, "git@") { - // git@.. is not an URL, so cannot be parsed as URL - var fragment string - repo.remote, fragment, _ = strings.Cut(remoteURL, "#") - repo.ref, repo.subdir = getRefAndSubdir(fragment) - } else { - u, err := url.Parse(remoteURL) - if err != nil { - return repo, err - } - - repo.ref, repo.subdir = getRefAndSubdir(u.Fragment) - u.Fragment = "" - repo.remote = u.String() - } - - if strings.HasPrefix(repo.ref, "-") { - return gitRepo{}, errors.Errorf("invalid refspec: %s", repo.ref) - } - - return repo, nil -} - -func getRefAndSubdir(fragment string) (ref string, subdir string) { - ref, subdir, _ = strings.Cut(fragment, ":") - if ref == "" { - ref = "master" - } - return ref, subdir -} - -func fetchArgs(remoteURL string, ref string) []string { - args := []string{"fetch"} - - if supportsShallowClone(remoteURL) { - args = append(args, "--depth", "1") - } - - return append(args, "origin", "--", ref) -} - -// Check if a given git URL supports a shallow git clone, -// i.e. it is a non-HTTP server or a smart HTTP server. -func supportsShallowClone(remoteURL string) bool { - if scheme := getScheme(remoteURL); scheme == "http" || scheme == "https" { - // Check if the HTTP server is smart - - // Smart servers must correctly respond to a query for the git-upload-pack service - serviceURL := remoteURL + "/info/refs?service=git-upload-pack" - - // Try a HEAD request and fallback to a Get request on error - res, err := http.Head(serviceURL) // #nosec G107 - if err != nil || res.StatusCode != http.StatusOK { - res, err = http.Get(serviceURL) // #nosec G107 - if err == nil { - res.Body.Close() - } - if err != nil || res.StatusCode != http.StatusOK { - // request failed - return false - } - } - - if res.Header.Get("Content-Type") != "application/x-git-upload-pack-advertisement" { - // Fallback, not a smart server - return false - } - return true - } - // Non-HTTP protocols always support shallow clones - return true -} - -func (repo gitRepo) checkout(root string) (string, error) { - // Try checking out by ref name first. This will work on branches and sets - // .git/HEAD to the current branch name - if output, err := repo.gitWithinDir(root, "checkout", repo.ref); err != nil { - // If checking out by branch name fails check out the last fetched ref - if _, err2 := repo.gitWithinDir(root, "checkout", "FETCH_HEAD"); err2 != nil { - return "", errors.Wrapf(err, "error checking out %s: %s", repo.ref, output) - } - } - - if repo.subdir != "" { - newCtx, err := symlink.FollowSymlinkInScope(filepath.Join(root, repo.subdir), root) - if err != nil { - return "", errors.Wrapf(err, "error setting git context, %q not within git root", repo.subdir) - } - - fi, err := os.Stat(newCtx) - if err != nil { - return "", err - } - if !fi.IsDir() { - return "", errors.Errorf("error setting git context, not a directory: %s", newCtx) - } - root = newCtx - } - - return root, nil -} - -func (repo gitRepo) gitWithinDir(dir string, args ...string) ([]byte, error) { - args = append([]string{"-c", "protocol.file.allow=never"}, args...) // Block sneaky repositories from using repos from the filesystem as submodules. - cmd := exec.Command("git", args...) - cmd.Dir = dir - // Disable unsafe remote protocols. - cmd.Env = append(os.Environ(), "GIT_PROTOCOL_FROM_USER=0") - - if repo.isolateConfig { - cmd.Env = append(cmd.Env, - "GIT_CONFIG_NOSYSTEM=1", // Disable reading from system gitconfig. - "HOME=/dev/null", // Disable reading from user gitconfig. - ) - } - - return cmd.CombinedOutput() -} - -// isGitTransport returns true if the provided str is a git transport by inspecting -// the prefix of the string for known protocols used in git. -func isGitTransport(str string) bool { - if strings.HasPrefix(str, "git@") { - return true - } - - switch getScheme(str) { - case "git", "http", "https", "ssh": - return true - } - - return false -} - -// getScheme returns addresses' scheme in lowercase, or an empty -// string in case address is an invalid URL. -func getScheme(address string) string { - u, err := url.Parse(address) - if err != nil { - return "" - } - return u.Scheme -} diff --git a/vendor/github.com/docker/docker/builder/remotecontext/urlutil/urlutil.go b/vendor/github.com/docker/docker/builder/remotecontext/urlutil/urlutil.go deleted file mode 100644 index e38988a30..000000000 --- a/vendor/github.com/docker/docker/builder/remotecontext/urlutil/urlutil.go +++ /dev/null @@ -1,86 +0,0 @@ -// Package urlutil provides helper function to check if a given build-context -// location should be considered a URL or a remote Git repository. -// -// This package is specifically written for use with docker build contexts, and -// should not be used as a general-purpose utility. -package urlutil // import "github.com/docker/docker/builder/remotecontext/urlutil" - -import ( - "regexp" - "strings" -) - -// urlPathWithFragmentSuffix matches fragments to use as Git reference and build -// context from the Git repository. See IsGitURL for details. -var urlPathWithFragmentSuffix = regexp.MustCompile(".git(?:#.+)?$") - -// IsURL returns true if the provided str is an HTTP(S) URL by checking if it -// has a http:// or https:// scheme. No validation is performed to verify if the -// URL is well-formed. -func IsURL(str string) bool { - return strings.HasPrefix(str, "https://") || strings.HasPrefix(str, "http://") -} - -// IsGitURL returns true if the provided str is a remote git repository "URL". -// -// This function only performs a rudimentary check (no validation is performed -// to ensure the URL is well-formed), and is written specifically for use with -// docker build, with some logic for backward compatibility with older versions -// of docker: do not use this function as a general-purpose utility. -// -// The following patterns are considered to be a Git URL: -// -// - https://(.*).git(?:#.+)?$ git repository URL with optional fragment, as known to be used by GitHub and GitLab. -// - http://(.*).git(?:#.+)?$ same, but non-TLS -// - git://(.*) URLs using git:// scheme -// - git@(.*) -// - github.com/ see description below -// -// The github.com/ prefix is a special case used to treat context-paths -// starting with "github.com/" as a git URL if the given path does not -// exist locally. The "github.com/" prefix is kept for backward compatibility, -// and is a legacy feature. -// -// Going forward, no additional prefixes should be added, and users should -// be encouraged to use explicit URLs (https://github.com/user/repo.git) instead. -// -// Note that IsGitURL does not check if "github.com/" prefixes exist as a local -// path. Code using this function should check if the path exists locally before -// using it as a URL. -// -// # Fragments -// -// Git URLs accept context configuration in their fragment section, separated by -// a colon (`:`). The first part represents the reference to check out, and can -// be either a branch, a tag, or a remote reference. The second part represents -// a subdirectory inside the repository to use as the build context. -// -// For example,the following URL uses a directory named "docker" in the branch -// "container" in the https://github.com/myorg/my-repo.git repository: -// -// https://github.com/myorg/my-repo.git#container:docker -// -// The following table represents all the valid suffixes with their build -// contexts: -// -// | Build Syntax Suffix | Git reference used | Build Context Used | -// |--------------------------------|----------------------|--------------------| -// | my-repo.git | refs/heads/master | / | -// | my-repo.git#mytag | refs/tags/my-tag | / | -// | my-repo.git#mybranch | refs/heads/my-branch | / | -// | my-repo.git#pull/42/head | refs/pull/42/head | / | -// | my-repo.git#:directory | refs/heads/master | /directory | -// | my-repo.git#master:directory | refs/heads/master | /directory | -// | my-repo.git#mytag:directory | refs/tags/my-tag | /directory | -// | my-repo.git#mybranch:directory | refs/heads/my-branch | /directory | -func IsGitURL(str string) bool { - if IsURL(str) && urlPathWithFragmentSuffix.MatchString(str) { - return true - } - for _, prefix := range []string{"git://", "github.com/", "git@"} { - if strings.HasPrefix(str, prefix) { - return true - } - } - return false -} diff --git a/vendor/github.com/docker/docker/client/README.md b/vendor/github.com/docker/docker/client/README.md deleted file mode 100644 index 992f18117..000000000 --- a/vendor/github.com/docker/docker/client/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# Go client for the Docker Engine API - -The `docker` command uses this package to communicate with the daemon. It can also be used by your own Go applications to do anything the command-line interface does – running containers, pulling images, managing swarms, etc. - -For example, to list running containers (the equivalent of `docker ps`): - -```go -package main - -import ( - "context" - "fmt" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/client" -) - -func main() { - cli, err := client.NewClientWithOpts(client.FromEnv) - if err != nil { - panic(err) - } - - containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{}) - if err != nil { - panic(err) - } - - for _, container := range containers { - fmt.Printf("%s %s\n", container.ID[:10], container.Image) - } -} -``` - -[Full documentation is available on GoDoc.](https://godoc.org/github.com/docker/docker/client) diff --git a/vendor/github.com/docker/docker/client/build_cancel.go b/vendor/github.com/docker/docker/client/build_cancel.go deleted file mode 100644 index b76bf366b..000000000 --- a/vendor/github.com/docker/docker/client/build_cancel.go +++ /dev/null @@ -1,16 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" -) - -// BuildCancel requests the daemon to cancel the ongoing build request. -func (cli *Client) BuildCancel(ctx context.Context, id string) error { - query := url.Values{} - query.Set("id", id) - - serverResp, err := cli.post(ctx, "/build/cancel", query, nil, nil) - ensureReaderClosed(serverResp) - return err -} diff --git a/vendor/github.com/docker/docker/client/build_prune.go b/vendor/github.com/docker/docker/client/build_prune.go deleted file mode 100644 index 2b6606236..000000000 --- a/vendor/github.com/docker/docker/client/build_prune.go +++ /dev/null @@ -1,45 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - "strconv" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/pkg/errors" -) - -// BuildCachePrune requests the daemon to delete unused cache data -func (cli *Client) BuildCachePrune(ctx context.Context, opts types.BuildCachePruneOptions) (*types.BuildCachePruneReport, error) { - if err := cli.NewVersionError("1.31", "build prune"); err != nil { - return nil, err - } - - report := types.BuildCachePruneReport{} - - query := url.Values{} - if opts.All { - query.Set("all", "1") - } - query.Set("keep-storage", strconv.Itoa(int(opts.KeepStorage))) - f, err := filters.ToJSON(opts.Filters) - if err != nil { - return nil, errors.Wrap(err, "prune could not marshal filters option") - } - query.Set("filters", f) - - serverResp, err := cli.post(ctx, "/build/prune", query, nil, nil) - defer ensureReaderClosed(serverResp) - - if err != nil { - return nil, err - } - - if err := json.NewDecoder(serverResp.body).Decode(&report); err != nil { - return nil, errors.Wrap(err, "error retrieving disk usage") - } - - return &report, nil -} diff --git a/vendor/github.com/docker/docker/client/checkpoint_create.go b/vendor/github.com/docker/docker/client/checkpoint_create.go deleted file mode 100644 index 921024fe4..000000000 --- a/vendor/github.com/docker/docker/client/checkpoint_create.go +++ /dev/null @@ -1,14 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - - "github.com/docker/docker/api/types" -) - -// CheckpointCreate creates a checkpoint from the given container with the given name -func (cli *Client) CheckpointCreate(ctx context.Context, container string, options types.CheckpointCreateOptions) error { - resp, err := cli.post(ctx, "/containers/"+container+"/checkpoints", nil, options, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/checkpoint_delete.go b/vendor/github.com/docker/docker/client/checkpoint_delete.go deleted file mode 100644 index 54f55fa76..000000000 --- a/vendor/github.com/docker/docker/client/checkpoint_delete.go +++ /dev/null @@ -1,20 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - - "github.com/docker/docker/api/types" -) - -// CheckpointDelete deletes the checkpoint with the given name from the given container -func (cli *Client) CheckpointDelete(ctx context.Context, containerID string, options types.CheckpointDeleteOptions) error { - query := url.Values{} - if options.CheckpointDir != "" { - query.Set("dir", options.CheckpointDir) - } - - resp, err := cli.delete(ctx, "/containers/"+containerID+"/checkpoints/"+options.CheckpointID, query, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/checkpoint_list.go b/vendor/github.com/docker/docker/client/checkpoint_list.go deleted file mode 100644 index 39cfb959f..000000000 --- a/vendor/github.com/docker/docker/client/checkpoint_list.go +++ /dev/null @@ -1,28 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" -) - -// CheckpointList returns the checkpoints of the given container in the docker host -func (cli *Client) CheckpointList(ctx context.Context, container string, options types.CheckpointListOptions) ([]types.Checkpoint, error) { - var checkpoints []types.Checkpoint - - query := url.Values{} - if options.CheckpointDir != "" { - query.Set("dir", options.CheckpointDir) - } - - resp, err := cli.get(ctx, "/containers/"+container+"/checkpoints", query, nil) - defer ensureReaderClosed(resp) - if err != nil { - return checkpoints, err - } - - err = json.NewDecoder(resp.body).Decode(&checkpoints) - return checkpoints, err -} diff --git a/vendor/github.com/docker/docker/client/client.go b/vendor/github.com/docker/docker/client/client.go deleted file mode 100644 index 54fa36cca..000000000 --- a/vendor/github.com/docker/docker/client/client.go +++ /dev/null @@ -1,354 +0,0 @@ -/* -Package client is a Go client for the Docker Engine API. - -For more information about the Engine API, see the documentation: -https://docs.docker.com/engine/api/ - -# Usage - -You use the library by constructing a client object using [NewClientWithOpts] -and calling methods on it. The client can be configured from environment -variables by passing the [FromEnv] option, or configured manually by passing any -of the other available [Opts]. - -For example, to list running containers (the equivalent of "docker ps"): - - package main - - import ( - "context" - "fmt" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/client" - ) - - func main() { - cli, err := client.NewClientWithOpts(client.FromEnv) - if err != nil { - panic(err) - } - - containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{}) - if err != nil { - panic(err) - } - - for _, container := range containers { - fmt.Printf("%s %s\n", container.ID[:10], container.Image) - } - } -*/ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net" - "net/http" - "net/url" - "path" - "strings" - - "github.com/docker/docker/api" - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/versions" - "github.com/docker/go-connections/sockets" - "github.com/pkg/errors" -) - -// DummyHost is a hostname used for local communication. -// -// It acts as a valid formatted hostname for local connections (such as "unix://" -// or "npipe://") which do not require a hostname. It should never be resolved, -// but uses the special-purpose ".localhost" TLD (as defined in [RFC 2606, Section 2] -// and [RFC 6761, Section 6.3]). -// -// [RFC 7230, Section 5.4] defines that an empty header must be used for such -// cases: -// -// If the authority component is missing or undefined for the target URI, -// then a client MUST send a Host header field with an empty field-value. -// -// However, [Go stdlib] enforces the semantics of HTTP(S) over TCP, does not -// allow an empty header to be used, and requires req.URL.Scheme to be either -// "http" or "https". -// -// For further details, refer to: -// -// - https://github.com/docker/engine-api/issues/189 -// - https://github.com/golang/go/issues/13624 -// - https://github.com/golang/go/issues/61076 -// - https://github.com/moby/moby/issues/45935 -// -// [RFC 2606, Section 2]: https://www.rfc-editor.org/rfc/rfc2606.html#section-2 -// [RFC 6761, Section 6.3]: https://www.rfc-editor.org/rfc/rfc6761#section-6.3 -// [RFC 7230, Section 5.4]: https://datatracker.ietf.org/doc/html/rfc7230#section-5.4 -// [Go stdlib]: https://github.com/golang/go/blob/6244b1946bc2101b01955468f1be502dbadd6807/src/net/http/transport.go#L558-L569 -const DummyHost = "api.moby.localhost" - -// ErrRedirect is the error returned by checkRedirect when the request is non-GET. -var ErrRedirect = errors.New("unexpected redirect in response") - -// Client is the API client that performs all operations -// against a docker server. -type Client struct { - // scheme sets the scheme for the client - scheme string - // host holds the server address to connect to - host string - // proto holds the client protocol i.e. unix. - proto string - // addr holds the client address. - addr string - // basePath holds the path to prepend to the requests. - basePath string - // client used to send and receive http requests. - client *http.Client - // version of the server to talk to. - version string - // custom http headers configured by users. - customHTTPHeaders map[string]string - // manualOverride is set to true when the version was set by users. - manualOverride bool - - // negotiateVersion indicates if the client should automatically negotiate - // the API version to use when making requests. API version negotiation is - // performed on the first request, after which negotiated is set to "true" - // so that subsequent requests do not re-negotiate. - negotiateVersion bool - - // negotiated indicates that API version negotiation took place - negotiated bool -} - -// CheckRedirect specifies the policy for dealing with redirect responses: -// If the request is non-GET return ErrRedirect, otherwise use the last response. -// -// Go 1.8 changes behavior for HTTP redirects (specifically 301, 307, and 308) -// in the client. The Docker client (and by extension docker API client) can be -// made to send a request like POST /containers//start where what would normally -// be in the name section of the URL is empty. This triggers an HTTP 301 from -// the daemon. -// -// In go 1.8 this 301 will be converted to a GET request, and ends up getting -// a 404 from the daemon. This behavior change manifests in the client in that -// before, the 301 was not followed and the client did not generate an error, -// but now results in a message like Error response from daemon: page not found. -func CheckRedirect(req *http.Request, via []*http.Request) error { - if via[0].Method == http.MethodGet { - return http.ErrUseLastResponse - } - return ErrRedirect -} - -// NewClientWithOpts initializes a new API client with a default HTTPClient, and -// default API host and version. It also initializes the custom HTTP headers to -// add to each request. -// -// It takes an optional list of Opt functional arguments, which are applied in -// the order they're provided, which allows modifying the defaults when creating -// the client. For example, the following initializes a client that configures -// itself with values from environment variables (client.FromEnv), and has -// automatic API version negotiation enabled (client.WithAPIVersionNegotiation()). -// -// cli, err := client.NewClientWithOpts( -// client.FromEnv, -// client.WithAPIVersionNegotiation(), -// ) -func NewClientWithOpts(ops ...Opt) (*Client, error) { - hostURL, err := ParseHostURL(DefaultDockerHost) - if err != nil { - return nil, err - } - - client, err := defaultHTTPClient(hostURL) - if err != nil { - return nil, err - } - c := &Client{ - host: DefaultDockerHost, - version: api.DefaultVersion, - client: client, - proto: hostURL.Scheme, - addr: hostURL.Host, - } - - for _, op := range ops { - if err := op(c); err != nil { - return nil, err - } - } - - if c.scheme == "" { - c.scheme = "http" - - tlsConfig := resolveTLSConfig(c.client.Transport) - if tlsConfig != nil { - // TODO(stevvooe): This isn't really the right way to write clients in Go. - // `NewClient` should probably only take an `*http.Client` and work from there. - // Unfortunately, the model of having a host-ish/url-thingy as the connection - // string has us confusing protocol and transport layers. We continue doing - // this to avoid breaking existing clients but this should be addressed. - c.scheme = "https" - } - } - - return c, nil -} - -func defaultHTTPClient(hostURL *url.URL) (*http.Client, error) { - transport := &http.Transport{} - err := sockets.ConfigureTransport(transport, hostURL.Scheme, hostURL.Host) - if err != nil { - return nil, err - } - return &http.Client{ - Transport: transport, - CheckRedirect: CheckRedirect, - }, nil -} - -// Close the transport used by the client -func (cli *Client) Close() error { - if t, ok := cli.client.Transport.(*http.Transport); ok { - t.CloseIdleConnections() - } - return nil -} - -// getAPIPath returns the versioned request path to call the api. -// It appends the query parameters to the path if they are not empty. -func (cli *Client) getAPIPath(ctx context.Context, p string, query url.Values) string { - var apiPath string - if cli.negotiateVersion && !cli.negotiated { - cli.NegotiateAPIVersion(ctx) - } - if cli.version != "" { - v := strings.TrimPrefix(cli.version, "v") - apiPath = path.Join(cli.basePath, "/v"+v, p) - } else { - apiPath = path.Join(cli.basePath, p) - } - return (&url.URL{Path: apiPath, RawQuery: query.Encode()}).String() -} - -// ClientVersion returns the API version used by this client. -func (cli *Client) ClientVersion() string { - return cli.version -} - -// NegotiateAPIVersion queries the API and updates the version to match the API -// version. NegotiateAPIVersion downgrades the client's API version to match the -// APIVersion if the ping version is lower than the default version. If the API -// version reported by the server is higher than the maximum version supported -// by the client, it uses the client's maximum version. -// -// If a manual override is in place, either through the "DOCKER_API_VERSION" -// (EnvOverrideAPIVersion) environment variable, or if the client is initialized -// with a fixed version (WithVersion(xx)), no negotiation is performed. -// -// If the API server's ping response does not contain an API version, or if the -// client did not get a successful ping response, it assumes it is connected with -// an old daemon that does not support API version negotiation, in which case it -// downgrades to the latest version of the API before version negotiation was -// added (1.24). -func (cli *Client) NegotiateAPIVersion(ctx context.Context) { - if !cli.manualOverride { - ping, _ := cli.Ping(ctx) - cli.negotiateAPIVersionPing(ping) - } -} - -// NegotiateAPIVersionPing downgrades the client's API version to match the -// APIVersion in the ping response. If the API version in pingResponse is higher -// than the maximum version supported by the client, it uses the client's maximum -// version. -// -// If a manual override is in place, either through the "DOCKER_API_VERSION" -// (EnvOverrideAPIVersion) environment variable, or if the client is initialized -// with a fixed version (WithVersion(xx)), no negotiation is performed. -// -// If the API server's ping response does not contain an API version, we assume -// we are connected with an old daemon without API version negotiation support, -// and downgrade to the latest version of the API before version negotiation was -// added (1.24). -func (cli *Client) NegotiateAPIVersionPing(pingResponse types.Ping) { - if !cli.manualOverride { - cli.negotiateAPIVersionPing(pingResponse) - } -} - -// negotiateAPIVersionPing queries the API and updates the version to match the -// API version from the ping response. -func (cli *Client) negotiateAPIVersionPing(pingResponse types.Ping) { - // default to the latest version before versioning headers existed - if pingResponse.APIVersion == "" { - pingResponse.APIVersion = "1.24" - } - - // if the client is not initialized with a version, start with the latest supported version - if cli.version == "" { - cli.version = api.DefaultVersion - } - - // if server version is lower than the client version, downgrade - if versions.LessThan(pingResponse.APIVersion, cli.version) { - cli.version = pingResponse.APIVersion - } - - // Store the results, so that automatic API version negotiation (if enabled) - // won't be performed on the next request. - if cli.negotiateVersion { - cli.negotiated = true - } -} - -// DaemonHost returns the host address used by the client -func (cli *Client) DaemonHost() string { - return cli.host -} - -// HTTPClient returns a copy of the HTTP client bound to the server -func (cli *Client) HTTPClient() *http.Client { - c := *cli.client - return &c -} - -// ParseHostURL parses a url string, validates the string is a host url, and -// returns the parsed URL -func ParseHostURL(host string) (*url.URL, error) { - proto, addr, ok := strings.Cut(host, "://") - if !ok || addr == "" { - return nil, errors.Errorf("unable to parse docker host `%s`", host) - } - - var basePath string - if proto == "tcp" { - parsed, err := url.Parse("tcp://" + addr) - if err != nil { - return nil, err - } - addr = parsed.Host - basePath = parsed.Path - } - return &url.URL{ - Scheme: proto, - Host: addr, - Path: basePath, - }, nil -} - -// Dialer returns a dialer for a raw stream connection, with an HTTP/1.1 header, -// that can be used for proxying the daemon connection. -// -// Used by `docker dial-stdio` (docker/cli#889). -func (cli *Client) Dialer() func(context.Context) (net.Conn, error) { - return func(ctx context.Context) (net.Conn, error) { - if transport, ok := cli.client.Transport.(*http.Transport); ok { - if transport.DialContext != nil && transport.TLSClientConfig == nil { - return transport.DialContext(ctx, cli.proto, cli.addr) - } - } - return fallbackDial(cli.proto, cli.addr, resolveTLSConfig(cli.client.Transport)) - } -} diff --git a/vendor/github.com/docker/docker/client/client_deprecated.go b/vendor/github.com/docker/docker/client/client_deprecated.go deleted file mode 100644 index 9e366ce20..000000000 --- a/vendor/github.com/docker/docker/client/client_deprecated.go +++ /dev/null @@ -1,27 +0,0 @@ -package client - -import "net/http" - -// NewClient initializes a new API client for the given host and API version. -// It uses the given http client as transport. -// It also initializes the custom http headers to add to each request. -// -// It won't send any version information if the version number is empty. It is -// highly recommended that you set a version or your client may break if the -// server is upgraded. -// -// Deprecated: use [NewClientWithOpts] passing the [WithHost], [WithVersion], -// [WithHTTPClient] and [WithHTTPHeaders] options. We recommend enabling API -// version negotiation by passing the [WithAPIVersionNegotiation] option instead -// of WithVersion. -func NewClient(host string, version string, client *http.Client, httpHeaders map[string]string) (*Client, error) { - return NewClientWithOpts(WithHost(host), WithVersion(version), WithHTTPClient(client), WithHTTPHeaders(httpHeaders)) -} - -// NewEnvClient initializes a new API client based on environment variables. -// See FromEnv for a list of support environment variables. -// -// Deprecated: use [NewClientWithOpts] passing the [FromEnv] option. -func NewEnvClient() (*Client, error) { - return NewClientWithOpts(FromEnv) -} diff --git a/vendor/github.com/docker/docker/client/client_unix.go b/vendor/github.com/docker/docker/client/client_unix.go deleted file mode 100644 index 319b738d3..000000000 --- a/vendor/github.com/docker/docker/client/client_unix.go +++ /dev/null @@ -1,8 +0,0 @@ -//go:build !windows -// +build !windows - -package client // import "github.com/docker/docker/client" - -// DefaultDockerHost defines OS-specific default host if the DOCKER_HOST -// (EnvOverrideHost) environment variable is unset or empty. -const DefaultDockerHost = "unix:///var/run/docker.sock" diff --git a/vendor/github.com/docker/docker/client/client_windows.go b/vendor/github.com/docker/docker/client/client_windows.go deleted file mode 100644 index 56572d1a2..000000000 --- a/vendor/github.com/docker/docker/client/client_windows.go +++ /dev/null @@ -1,5 +0,0 @@ -package client // import "github.com/docker/docker/client" - -// DefaultDockerHost defines OS-specific default host if the DOCKER_HOST -// (EnvOverrideHost) environment variable is unset or empty. -const DefaultDockerHost = "npipe:////./pipe/docker_engine" diff --git a/vendor/github.com/docker/docker/client/config_create.go b/vendor/github.com/docker/docker/client/config_create.go deleted file mode 100644 index f6b1881fc..000000000 --- a/vendor/github.com/docker/docker/client/config_create.go +++ /dev/null @@ -1,25 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/swarm" -) - -// ConfigCreate creates a new config. -func (cli *Client) ConfigCreate(ctx context.Context, config swarm.ConfigSpec) (types.ConfigCreateResponse, error) { - var response types.ConfigCreateResponse - if err := cli.NewVersionError("1.30", "config create"); err != nil { - return response, err - } - resp, err := cli.post(ctx, "/configs/create", nil, config, nil) - defer ensureReaderClosed(resp) - if err != nil { - return response, err - } - - err = json.NewDecoder(resp.body).Decode(&response) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/config_inspect.go b/vendor/github.com/docker/docker/client/config_inspect.go deleted file mode 100644 index 9be7882c3..000000000 --- a/vendor/github.com/docker/docker/client/config_inspect.go +++ /dev/null @@ -1,36 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "bytes" - "context" - "encoding/json" - "io" - - "github.com/docker/docker/api/types/swarm" -) - -// ConfigInspectWithRaw returns the config information with raw data -func (cli *Client) ConfigInspectWithRaw(ctx context.Context, id string) (swarm.Config, []byte, error) { - if id == "" { - return swarm.Config{}, nil, objectNotFoundError{object: "config", id: id} - } - if err := cli.NewVersionError("1.30", "config inspect"); err != nil { - return swarm.Config{}, nil, err - } - resp, err := cli.get(ctx, "/configs/"+id, nil, nil) - defer ensureReaderClosed(resp) - if err != nil { - return swarm.Config{}, nil, err - } - - body, err := io.ReadAll(resp.body) - if err != nil { - return swarm.Config{}, nil, err - } - - var config swarm.Config - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&config) - - return config, body, err -} diff --git a/vendor/github.com/docker/docker/client/config_list.go b/vendor/github.com/docker/docker/client/config_list.go deleted file mode 100644 index 565acc6e2..000000000 --- a/vendor/github.com/docker/docker/client/config_list.go +++ /dev/null @@ -1,38 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/swarm" -) - -// ConfigList returns the list of configs. -func (cli *Client) ConfigList(ctx context.Context, options types.ConfigListOptions) ([]swarm.Config, error) { - if err := cli.NewVersionError("1.30", "config list"); err != nil { - return nil, err - } - query := url.Values{} - - if options.Filters.Len() > 0 { - filterJSON, err := filters.ToJSON(options.Filters) - if err != nil { - return nil, err - } - - query.Set("filters", filterJSON) - } - - resp, err := cli.get(ctx, "/configs", query, nil) - defer ensureReaderClosed(resp) - if err != nil { - return nil, err - } - - var configs []swarm.Config - err = json.NewDecoder(resp.body).Decode(&configs) - return configs, err -} diff --git a/vendor/github.com/docker/docker/client/config_remove.go b/vendor/github.com/docker/docker/client/config_remove.go deleted file mode 100644 index 24b94e9c1..000000000 --- a/vendor/github.com/docker/docker/client/config_remove.go +++ /dev/null @@ -1,13 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import "context" - -// ConfigRemove removes a config. -func (cli *Client) ConfigRemove(ctx context.Context, id string) error { - if err := cli.NewVersionError("1.30", "config remove"); err != nil { - return err - } - resp, err := cli.delete(ctx, "/configs/"+id, nil, nil) - defer ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/config_update.go b/vendor/github.com/docker/docker/client/config_update.go deleted file mode 100644 index 1ac298543..000000000 --- a/vendor/github.com/docker/docker/client/config_update.go +++ /dev/null @@ -1,20 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - - "github.com/docker/docker/api/types/swarm" -) - -// ConfigUpdate attempts to update a config -func (cli *Client) ConfigUpdate(ctx context.Context, id string, version swarm.Version, config swarm.ConfigSpec) error { - if err := cli.NewVersionError("1.30", "config update"); err != nil { - return err - } - query := url.Values{} - query.Set("version", version.String()) - resp, err := cli.post(ctx, "/configs/"+id+"/update", query, config, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_attach.go b/vendor/github.com/docker/docker/client/container_attach.go deleted file mode 100644 index ba92117d3..000000000 --- a/vendor/github.com/docker/docker/client/container_attach.go +++ /dev/null @@ -1,59 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - - "github.com/docker/docker/api/types" -) - -// ContainerAttach attaches a connection to a container in the server. -// It returns a types.HijackedConnection with the hijacked connection -// and the a reader to get output. It's up to the called to close -// the hijacked connection by calling types.HijackedResponse.Close. -// -// The stream format on the response will be in one of two formats: -// -// If the container is using a TTY, there is only a single stream (stdout), and -// data is copied directly from the container output stream, no extra -// multiplexing or headers. -// -// If the container is *not* using a TTY, streams for stdout and stderr are -// multiplexed. -// The format of the multiplexed stream is as follows: -// -// [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4}[]byte{OUTPUT} -// -// STREAM_TYPE can be 1 for stdout and 2 for stderr -// -// SIZE1, SIZE2, SIZE3, and SIZE4 are four bytes of uint32 encoded as big endian. -// This is the size of OUTPUT. -// -// You can use github.com/docker/docker/pkg/stdcopy.StdCopy to demultiplex this -// stream. -func (cli *Client) ContainerAttach(ctx context.Context, container string, options types.ContainerAttachOptions) (types.HijackedResponse, error) { - query := url.Values{} - if options.Stream { - query.Set("stream", "1") - } - if options.Stdin { - query.Set("stdin", "1") - } - if options.Stdout { - query.Set("stdout", "1") - } - if options.Stderr { - query.Set("stderr", "1") - } - if options.DetachKeys != "" { - query.Set("detachKeys", options.DetachKeys) - } - if options.Logs { - query.Set("logs", "1") - } - - headers := map[string][]string{ - "Content-Type": {"text/plain"}, - } - return cli.postHijacked(ctx, "/containers/"+container+"/attach", query, nil, headers) -} diff --git a/vendor/github.com/docker/docker/client/container_commit.go b/vendor/github.com/docker/docker/client/container_commit.go deleted file mode 100644 index cd7f76346..000000000 --- a/vendor/github.com/docker/docker/client/container_commit.go +++ /dev/null @@ -1,55 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "errors" - "net/url" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" -) - -// ContainerCommit applies changes to a container and creates a new tagged image. -func (cli *Client) ContainerCommit(ctx context.Context, container string, options types.ContainerCommitOptions) (types.IDResponse, error) { - var repository, tag string - if options.Reference != "" { - ref, err := reference.ParseNormalizedNamed(options.Reference) - if err != nil { - return types.IDResponse{}, err - } - - if _, isCanonical := ref.(reference.Canonical); isCanonical { - return types.IDResponse{}, errors.New("refusing to create a tag with a digest reference") - } - ref = reference.TagNameOnly(ref) - - if tagged, ok := ref.(reference.Tagged); ok { - tag = tagged.Tag() - } - repository = reference.FamiliarName(ref) - } - - query := url.Values{} - query.Set("container", container) - query.Set("repo", repository) - query.Set("tag", tag) - query.Set("comment", options.Comment) - query.Set("author", options.Author) - for _, change := range options.Changes { - query.Add("changes", change) - } - if !options.Pause { - query.Set("pause", "0") - } - - var response types.IDResponse - resp, err := cli.post(ctx, "/commit", query, options.Config, nil) - defer ensureReaderClosed(resp) - if err != nil { - return response, err - } - - err = json.NewDecoder(resp.body).Decode(&response) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/container_copy.go b/vendor/github.com/docker/docker/client/container_copy.go deleted file mode 100644 index 883be7fa3..000000000 --- a/vendor/github.com/docker/docker/client/container_copy.go +++ /dev/null @@ -1,93 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "path/filepath" - "strings" - - "github.com/docker/docker/api/types" -) - -// ContainerStatPath returns stat information about a path inside the container filesystem. -func (cli *Client) ContainerStatPath(ctx context.Context, containerID, path string) (types.ContainerPathStat, error) { - query := url.Values{} - query.Set("path", filepath.ToSlash(path)) // Normalize the paths used in the API. - - urlStr := "/containers/" + containerID + "/archive" - response, err := cli.head(ctx, urlStr, query, nil) - defer ensureReaderClosed(response) - if err != nil { - return types.ContainerPathStat{}, err - } - return getContainerPathStatFromHeader(response.header) -} - -// CopyToContainer copies content into the container filesystem. -// Note that `content` must be a Reader for a TAR archive -func (cli *Client) CopyToContainer(ctx context.Context, containerID, dstPath string, content io.Reader, options types.CopyToContainerOptions) error { - query := url.Values{} - query.Set("path", filepath.ToSlash(dstPath)) // Normalize the paths used in the API. - // Do not allow for an existing directory to be overwritten by a non-directory and vice versa. - if !options.AllowOverwriteDirWithFile { - query.Set("noOverwriteDirNonDir", "true") - } - - if options.CopyUIDGID { - query.Set("copyUIDGID", "true") - } - - apiPath := "/containers/" + containerID + "/archive" - - response, err := cli.putRaw(ctx, apiPath, query, content, nil) - defer ensureReaderClosed(response) - if err != nil { - return err - } - - return nil -} - -// CopyFromContainer gets the content from the container and returns it as a Reader -// for a TAR archive to manipulate it in the host. It's up to the caller to close the reader. -func (cli *Client) CopyFromContainer(ctx context.Context, containerID, srcPath string) (io.ReadCloser, types.ContainerPathStat, error) { - query := make(url.Values, 1) - query.Set("path", filepath.ToSlash(srcPath)) // Normalize the paths used in the API. - - apiPath := "/containers/" + containerID + "/archive" - response, err := cli.get(ctx, apiPath, query, nil) - if err != nil { - return nil, types.ContainerPathStat{}, err - } - - // In order to get the copy behavior right, we need to know information - // about both the source and the destination. The response headers include - // stat info about the source that we can use in deciding exactly how to - // copy it locally. Along with the stat info about the local destination, - // we have everything we need to handle the multiple possibilities there - // can be when copying a file/dir from one location to another file/dir. - stat, err := getContainerPathStatFromHeader(response.header) - if err != nil { - return nil, stat, fmt.Errorf("unable to get resource stat from response: %s", err) - } - return response.body, stat, err -} - -func getContainerPathStatFromHeader(header http.Header) (types.ContainerPathStat, error) { - var stat types.ContainerPathStat - - encodedStat := header.Get("X-Docker-Container-Path-Stat") - statDecoder := base64.NewDecoder(base64.StdEncoding, strings.NewReader(encodedStat)) - - err := json.NewDecoder(statDecoder).Decode(&stat) - if err != nil { - err = fmt.Errorf("unable to decode container path stat header: %s", err) - } - - return stat, err -} diff --git a/vendor/github.com/docker/docker/client/container_create.go b/vendor/github.com/docker/docker/client/container_create.go deleted file mode 100644 index 193a2bb56..000000000 --- a/vendor/github.com/docker/docker/client/container_create.go +++ /dev/null @@ -1,83 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - "path" - - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/network" - "github.com/docker/docker/api/types/versions" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" -) - -type configWrapper struct { - *container.Config - HostConfig *container.HostConfig - NetworkingConfig *network.NetworkingConfig -} - -// ContainerCreate creates a new container based on the given configuration. -// It can be associated with a name, but it's not mandatory. -func (cli *Client) ContainerCreate(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, platform *ocispec.Platform, containerName string) (container.CreateResponse, error) { - var response container.CreateResponse - - if err := cli.NewVersionError("1.25", "stop timeout"); config != nil && config.StopTimeout != nil && err != nil { - return response, err - } - if err := cli.NewVersionError("1.41", "specify container image platform"); platform != nil && err != nil { - return response, err - } - - if hostConfig != nil { - if versions.LessThan(cli.ClientVersion(), "1.25") { - // When using API 1.24 and under, the client is responsible for removing the container - hostConfig.AutoRemove = false - } - if versions.GreaterThanOrEqualTo(cli.ClientVersion(), "1.42") || versions.LessThan(cli.ClientVersion(), "1.40") { - // KernelMemory was added in API 1.40, and deprecated in API 1.42 - hostConfig.KernelMemory = 0 - } - if platform != nil && platform.OS == "linux" && versions.LessThan(cli.ClientVersion(), "1.42") { - // When using API under 1.42, the Linux daemon doesn't respect the ConsoleSize - hostConfig.ConsoleSize = [2]uint{0, 0} - } - } - - query := url.Values{} - if p := formatPlatform(platform); p != "" { - query.Set("platform", p) - } - - if containerName != "" { - query.Set("name", containerName) - } - - body := configWrapper{ - Config: config, - HostConfig: hostConfig, - NetworkingConfig: networkingConfig, - } - - serverResp, err := cli.post(ctx, "/containers/create", query, body, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return response, err - } - - err = json.NewDecoder(serverResp.body).Decode(&response) - return response, err -} - -// formatPlatform returns a formatted string representing platform (e.g. linux/arm/v7). -// -// Similar to containerd's platforms.Format(), but does allow components to be -// omitted (e.g. pass "architecture" only, without "os": -// https://github.com/containerd/containerd/blob/v1.5.2/platforms/platforms.go#L243-L263 -func formatPlatform(platform *ocispec.Platform) string { - if platform == nil { - return "" - } - return path.Join(platform.OS, platform.Architecture, platform.Variant) -} diff --git a/vendor/github.com/docker/docker/client/container_diff.go b/vendor/github.com/docker/docker/client/container_diff.go deleted file mode 100644 index c22c819a7..000000000 --- a/vendor/github.com/docker/docker/client/container_diff.go +++ /dev/null @@ -1,23 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types/container" -) - -// ContainerDiff shows differences in a container filesystem since it was started. -func (cli *Client) ContainerDiff(ctx context.Context, containerID string) ([]container.FilesystemChange, error) { - var changes []container.FilesystemChange - - serverResp, err := cli.get(ctx, "/containers/"+containerID+"/changes", url.Values{}, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return changes, err - } - - err = json.NewDecoder(serverResp.body).Decode(&changes) - return changes, err -} diff --git a/vendor/github.com/docker/docker/client/container_exec.go b/vendor/github.com/docker/docker/client/container_exec.go deleted file mode 100644 index 6a2cb006f..000000000 --- a/vendor/github.com/docker/docker/client/container_exec.go +++ /dev/null @@ -1,66 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/versions" -) - -// ContainerExecCreate creates a new exec configuration to run an exec process. -func (cli *Client) ContainerExecCreate(ctx context.Context, container string, config types.ExecConfig) (types.IDResponse, error) { - var response types.IDResponse - - if err := cli.NewVersionError("1.25", "env"); len(config.Env) != 0 && err != nil { - return response, err - } - if versions.LessThan(cli.ClientVersion(), "1.42") { - config.ConsoleSize = nil - } - - resp, err := cli.post(ctx, "/containers/"+container+"/exec", nil, config, nil) - defer ensureReaderClosed(resp) - if err != nil { - return response, err - } - err = json.NewDecoder(resp.body).Decode(&response) - return response, err -} - -// ContainerExecStart starts an exec process already created in the docker host. -func (cli *Client) ContainerExecStart(ctx context.Context, execID string, config types.ExecStartCheck) error { - if versions.LessThan(cli.ClientVersion(), "1.42") { - config.ConsoleSize = nil - } - resp, err := cli.post(ctx, "/exec/"+execID+"/start", nil, config, nil) - ensureReaderClosed(resp) - return err -} - -// ContainerExecAttach attaches a connection to an exec process in the server. -// It returns a types.HijackedConnection with the hijacked connection -// and the a reader to get output. It's up to the called to close -// the hijacked connection by calling types.HijackedResponse.Close. -func (cli *Client) ContainerExecAttach(ctx context.Context, execID string, config types.ExecStartCheck) (types.HijackedResponse, error) { - if versions.LessThan(cli.ClientVersion(), "1.42") { - config.ConsoleSize = nil - } - headers := map[string][]string{ - "Content-Type": {"application/json"}, - } - return cli.postHijacked(ctx, "/exec/"+execID+"/start", nil, config, headers) -} - -// ContainerExecInspect returns information about a specific exec process on the docker host. -func (cli *Client) ContainerExecInspect(ctx context.Context, execID string) (types.ContainerExecInspect, error) { - var response types.ContainerExecInspect - resp, err := cli.get(ctx, "/exec/"+execID+"/json", nil, nil) - if err != nil { - return response, err - } - - err = json.NewDecoder(resp.body).Decode(&response) - ensureReaderClosed(resp) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/container_export.go b/vendor/github.com/docker/docker/client/container_export.go deleted file mode 100644 index d0c0a5cba..000000000 --- a/vendor/github.com/docker/docker/client/container_export.go +++ /dev/null @@ -1,19 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" - "net/url" -) - -// ContainerExport retrieves the raw contents of a container -// and returns them as an io.ReadCloser. It's up to the caller -// to close the stream. -func (cli *Client) ContainerExport(ctx context.Context, containerID string) (io.ReadCloser, error) { - serverResp, err := cli.get(ctx, "/containers/"+containerID+"/export", url.Values{}, nil) - if err != nil { - return nil, err - } - - return serverResp.body, nil -} diff --git a/vendor/github.com/docker/docker/client/container_inspect.go b/vendor/github.com/docker/docker/client/container_inspect.go deleted file mode 100644 index d48f0d3a6..000000000 --- a/vendor/github.com/docker/docker/client/container_inspect.go +++ /dev/null @@ -1,53 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "bytes" - "context" - "encoding/json" - "io" - "net/url" - - "github.com/docker/docker/api/types" -) - -// ContainerInspect returns the container information. -func (cli *Client) ContainerInspect(ctx context.Context, containerID string) (types.ContainerJSON, error) { - if containerID == "" { - return types.ContainerJSON{}, objectNotFoundError{object: "container", id: containerID} - } - serverResp, err := cli.get(ctx, "/containers/"+containerID+"/json", nil, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return types.ContainerJSON{}, err - } - - var response types.ContainerJSON - err = json.NewDecoder(serverResp.body).Decode(&response) - return response, err -} - -// ContainerInspectWithRaw returns the container information and its raw representation. -func (cli *Client) ContainerInspectWithRaw(ctx context.Context, containerID string, getSize bool) (types.ContainerJSON, []byte, error) { - if containerID == "" { - return types.ContainerJSON{}, nil, objectNotFoundError{object: "container", id: containerID} - } - query := url.Values{} - if getSize { - query.Set("size", "1") - } - serverResp, err := cli.get(ctx, "/containers/"+containerID+"/json", query, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return types.ContainerJSON{}, nil, err - } - - body, err := io.ReadAll(serverResp.body) - if err != nil { - return types.ContainerJSON{}, nil, err - } - - var response types.ContainerJSON - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&response) - return response, body, err -} diff --git a/vendor/github.com/docker/docker/client/container_kill.go b/vendor/github.com/docker/docker/client/container_kill.go deleted file mode 100644 index 7c9529f1e..000000000 --- a/vendor/github.com/docker/docker/client/container_kill.go +++ /dev/null @@ -1,18 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" -) - -// ContainerKill terminates the container process but does not remove the container from the docker host. -func (cli *Client) ContainerKill(ctx context.Context, containerID, signal string) error { - query := url.Values{} - if signal != "" { - query.Set("signal", signal) - } - - resp, err := cli.post(ctx, "/containers/"+containerID+"/kill", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_list.go b/vendor/github.com/docker/docker/client/container_list.go deleted file mode 100644 index bd491b3db..000000000 --- a/vendor/github.com/docker/docker/client/container_list.go +++ /dev/null @@ -1,57 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - "strconv" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" -) - -// ContainerList returns the list of containers in the docker host. -func (cli *Client) ContainerList(ctx context.Context, options types.ContainerListOptions) ([]types.Container, error) { - query := url.Values{} - - if options.All { - query.Set("all", "1") - } - - if options.Limit > 0 { - query.Set("limit", strconv.Itoa(options.Limit)) - } - - if options.Since != "" { - query.Set("since", options.Since) - } - - if options.Before != "" { - query.Set("before", options.Before) - } - - if options.Size { - query.Set("size", "1") - } - - if options.Filters.Len() > 0 { - //nolint:staticcheck // ignore SA1019 for old code - filterJSON, err := filters.ToParamWithVersion(cli.version, options.Filters) - - if err != nil { - return nil, err - } - - query.Set("filters", filterJSON) - } - - resp, err := cli.get(ctx, "/containers/json", query, nil) - defer ensureReaderClosed(resp) - if err != nil { - return nil, err - } - - var containers []types.Container - err = json.NewDecoder(resp.body).Decode(&containers) - return containers, err -} diff --git a/vendor/github.com/docker/docker/client/container_logs.go b/vendor/github.com/docker/docker/client/container_logs.go deleted file mode 100644 index 9bdf2b0fa..000000000 --- a/vendor/github.com/docker/docker/client/container_logs.go +++ /dev/null @@ -1,80 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" - "net/url" - "time" - - "github.com/docker/docker/api/types" - timetypes "github.com/docker/docker/api/types/time" - "github.com/pkg/errors" -) - -// ContainerLogs returns the logs generated by a container in an io.ReadCloser. -// It's up to the caller to close the stream. -// -// The stream format on the response will be in one of two formats: -// -// If the container is using a TTY, there is only a single stream (stdout), and -// data is copied directly from the container output stream, no extra -// multiplexing or headers. -// -// If the container is *not* using a TTY, streams for stdout and stderr are -// multiplexed. -// The format of the multiplexed stream is as follows: -// -// [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4}[]byte{OUTPUT} -// -// STREAM_TYPE can be 1 for stdout and 2 for stderr -// -// SIZE1, SIZE2, SIZE3, and SIZE4 are four bytes of uint32 encoded as big endian. -// This is the size of OUTPUT. -// -// You can use github.com/docker/docker/pkg/stdcopy.StdCopy to demultiplex this -// stream. -func (cli *Client) ContainerLogs(ctx context.Context, container string, options types.ContainerLogsOptions) (io.ReadCloser, error) { - query := url.Values{} - if options.ShowStdout { - query.Set("stdout", "1") - } - - if options.ShowStderr { - query.Set("stderr", "1") - } - - if options.Since != "" { - ts, err := timetypes.GetTimestamp(options.Since, time.Now()) - if err != nil { - return nil, errors.Wrap(err, `invalid value for "since"`) - } - query.Set("since", ts) - } - - if options.Until != "" { - ts, err := timetypes.GetTimestamp(options.Until, time.Now()) - if err != nil { - return nil, errors.Wrap(err, `invalid value for "until"`) - } - query.Set("until", ts) - } - - if options.Timestamps { - query.Set("timestamps", "1") - } - - if options.Details { - query.Set("details", "1") - } - - if options.Follow { - query.Set("follow", "1") - } - query.Set("tail", options.Tail) - - resp, err := cli.get(ctx, "/containers/"+container+"/logs", query, nil) - if err != nil { - return nil, err - } - return resp.body, nil -} diff --git a/vendor/github.com/docker/docker/client/container_pause.go b/vendor/github.com/docker/docker/client/container_pause.go deleted file mode 100644 index 5e7271a37..000000000 --- a/vendor/github.com/docker/docker/client/container_pause.go +++ /dev/null @@ -1,10 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import "context" - -// ContainerPause pauses the main process of a given container without terminating it. -func (cli *Client) ContainerPause(ctx context.Context, containerID string) error { - resp, err := cli.post(ctx, "/containers/"+containerID+"/pause", nil, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_prune.go b/vendor/github.com/docker/docker/client/container_prune.go deleted file mode 100644 index 04383deaa..000000000 --- a/vendor/github.com/docker/docker/client/container_prune.go +++ /dev/null @@ -1,36 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "fmt" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" -) - -// ContainersPrune requests the daemon to delete unused data -func (cli *Client) ContainersPrune(ctx context.Context, pruneFilters filters.Args) (types.ContainersPruneReport, error) { - var report types.ContainersPruneReport - - if err := cli.NewVersionError("1.25", "container prune"); err != nil { - return report, err - } - - query, err := getFiltersQuery(pruneFilters) - if err != nil { - return report, err - } - - serverResp, err := cli.post(ctx, "/containers/prune", query, nil, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return report, err - } - - if err := json.NewDecoder(serverResp.body).Decode(&report); err != nil { - return report, fmt.Errorf("Error retrieving disk usage: %v", err) - } - - return report, nil -} diff --git a/vendor/github.com/docker/docker/client/container_remove.go b/vendor/github.com/docker/docker/client/container_remove.go deleted file mode 100644 index c21de609b..000000000 --- a/vendor/github.com/docker/docker/client/container_remove.go +++ /dev/null @@ -1,27 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - - "github.com/docker/docker/api/types" -) - -// ContainerRemove kills and removes a container from the docker host. -func (cli *Client) ContainerRemove(ctx context.Context, containerID string, options types.ContainerRemoveOptions) error { - query := url.Values{} - if options.RemoveVolumes { - query.Set("v", "1") - } - if options.RemoveLinks { - query.Set("link", "1") - } - - if options.Force { - query.Set("force", "1") - } - - resp, err := cli.delete(ctx, "/containers/"+containerID, query, nil) - defer ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_rename.go b/vendor/github.com/docker/docker/client/container_rename.go deleted file mode 100644 index 240fdf552..000000000 --- a/vendor/github.com/docker/docker/client/container_rename.go +++ /dev/null @@ -1,15 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" -) - -// ContainerRename changes the name of a given container. -func (cli *Client) ContainerRename(ctx context.Context, containerID, newContainerName string) error { - query := url.Values{} - query.Set("name", newContainerName) - resp, err := cli.post(ctx, "/containers/"+containerID+"/rename", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_resize.go b/vendor/github.com/docker/docker/client/container_resize.go deleted file mode 100644 index a9d4c0c79..000000000 --- a/vendor/github.com/docker/docker/client/container_resize.go +++ /dev/null @@ -1,29 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - "strconv" - - "github.com/docker/docker/api/types" -) - -// ContainerResize changes the size of the tty for a container. -func (cli *Client) ContainerResize(ctx context.Context, containerID string, options types.ResizeOptions) error { - return cli.resize(ctx, "/containers/"+containerID, options.Height, options.Width) -} - -// ContainerExecResize changes the size of the tty for an exec process running inside a container. -func (cli *Client) ContainerExecResize(ctx context.Context, execID string, options types.ResizeOptions) error { - return cli.resize(ctx, "/exec/"+execID, options.Height, options.Width) -} - -func (cli *Client) resize(ctx context.Context, basePath string, height, width uint) error { - query := url.Values{} - query.Set("h", strconv.Itoa(int(height))) - query.Set("w", strconv.Itoa(int(width))) - - resp, err := cli.post(ctx, basePath+"/resize", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_restart.go b/vendor/github.com/docker/docker/client/container_restart.go deleted file mode 100644 index 1e0ad9998..000000000 --- a/vendor/github.com/docker/docker/client/container_restart.go +++ /dev/null @@ -1,26 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - "strconv" - - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/versions" -) - -// ContainerRestart stops and starts a container again. -// It makes the daemon wait for the container to be up again for -// a specific amount of time, given the timeout. -func (cli *Client) ContainerRestart(ctx context.Context, containerID string, options container.StopOptions) error { - query := url.Values{} - if options.Timeout != nil { - query.Set("t", strconv.Itoa(*options.Timeout)) - } - if options.Signal != "" && versions.GreaterThanOrEqualTo(cli.version, "1.42") { - query.Set("signal", options.Signal) - } - resp, err := cli.post(ctx, "/containers/"+containerID+"/restart", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_start.go b/vendor/github.com/docker/docker/client/container_start.go deleted file mode 100644 index c2e0b15dc..000000000 --- a/vendor/github.com/docker/docker/client/container_start.go +++ /dev/null @@ -1,23 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - - "github.com/docker/docker/api/types" -) - -// ContainerStart sends a request to the docker daemon to start a container. -func (cli *Client) ContainerStart(ctx context.Context, containerID string, options types.ContainerStartOptions) error { - query := url.Values{} - if len(options.CheckpointID) != 0 { - query.Set("checkpoint", options.CheckpointID) - } - if len(options.CheckpointDir) != 0 { - query.Set("checkpoint-dir", options.CheckpointDir) - } - - resp, err := cli.post(ctx, "/containers/"+containerID+"/start", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_stats.go b/vendor/github.com/docker/docker/client/container_stats.go deleted file mode 100644 index 0a6488dde..000000000 --- a/vendor/github.com/docker/docker/client/container_stats.go +++ /dev/null @@ -1,42 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - - "github.com/docker/docker/api/types" -) - -// ContainerStats returns near realtime stats for a given container. -// It's up to the caller to close the io.ReadCloser returned. -func (cli *Client) ContainerStats(ctx context.Context, containerID string, stream bool) (types.ContainerStats, error) { - query := url.Values{} - query.Set("stream", "0") - if stream { - query.Set("stream", "1") - } - - resp, err := cli.get(ctx, "/containers/"+containerID+"/stats", query, nil) - if err != nil { - return types.ContainerStats{}, err - } - - osType := getDockerOS(resp.header.Get("Server")) - return types.ContainerStats{Body: resp.body, OSType: osType}, err -} - -// ContainerStatsOneShot gets a single stat entry from a container. -// It differs from `ContainerStats` in that the API should not wait to prime the stats -func (cli *Client) ContainerStatsOneShot(ctx context.Context, containerID string) (types.ContainerStats, error) { - query := url.Values{} - query.Set("stream", "0") - query.Set("one-shot", "1") - - resp, err := cli.get(ctx, "/containers/"+containerID+"/stats", query, nil) - if err != nil { - return types.ContainerStats{}, err - } - - osType := getDockerOS(resp.header.Get("Server")) - return types.ContainerStats{Body: resp.body, OSType: osType}, err -} diff --git a/vendor/github.com/docker/docker/client/container_stop.go b/vendor/github.com/docker/docker/client/container_stop.go deleted file mode 100644 index 2a43ce227..000000000 --- a/vendor/github.com/docker/docker/client/container_stop.go +++ /dev/null @@ -1,30 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - "strconv" - - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/versions" -) - -// ContainerStop stops a container. In case the container fails to stop -// gracefully within a time frame specified by the timeout argument, -// it is forcefully terminated (killed). -// -// If the timeout is nil, the container's StopTimeout value is used, if set, -// otherwise the engine default. A negative timeout value can be specified, -// meaning no timeout, i.e. no forceful termination is performed. -func (cli *Client) ContainerStop(ctx context.Context, containerID string, options container.StopOptions) error { - query := url.Values{} - if options.Timeout != nil { - query.Set("t", strconv.Itoa(*options.Timeout)) - } - if options.Signal != "" && versions.GreaterThanOrEqualTo(cli.version, "1.42") { - query.Set("signal", options.Signal) - } - resp, err := cli.post(ctx, "/containers/"+containerID+"/stop", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_top.go b/vendor/github.com/docker/docker/client/container_top.go deleted file mode 100644 index a5b78999b..000000000 --- a/vendor/github.com/docker/docker/client/container_top.go +++ /dev/null @@ -1,28 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - "strings" - - "github.com/docker/docker/api/types/container" -) - -// ContainerTop shows process information from within a container. -func (cli *Client) ContainerTop(ctx context.Context, containerID string, arguments []string) (container.ContainerTopOKBody, error) { - var response container.ContainerTopOKBody - query := url.Values{} - if len(arguments) > 0 { - query.Set("ps_args", strings.Join(arguments, " ")) - } - - resp, err := cli.get(ctx, "/containers/"+containerID+"/top", query, nil) - defer ensureReaderClosed(resp) - if err != nil { - return response, err - } - - err = json.NewDecoder(resp.body).Decode(&response) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/container_unpause.go b/vendor/github.com/docker/docker/client/container_unpause.go deleted file mode 100644 index 1d8f87316..000000000 --- a/vendor/github.com/docker/docker/client/container_unpause.go +++ /dev/null @@ -1,10 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import "context" - -// ContainerUnpause resumes the process execution within a container -func (cli *Client) ContainerUnpause(ctx context.Context, containerID string) error { - resp, err := cli.post(ctx, "/containers/"+containerID+"/unpause", nil, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_update.go b/vendor/github.com/docker/docker/client/container_update.go deleted file mode 100644 index bf68a5300..000000000 --- a/vendor/github.com/docker/docker/client/container_update.go +++ /dev/null @@ -1,21 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - - "github.com/docker/docker/api/types/container" -) - -// ContainerUpdate updates the resources of a container. -func (cli *Client) ContainerUpdate(ctx context.Context, containerID string, updateConfig container.UpdateConfig) (container.ContainerUpdateOKBody, error) { - var response container.ContainerUpdateOKBody - serverResp, err := cli.post(ctx, "/containers/"+containerID+"/update", nil, updateConfig, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return response, err - } - - err = json.NewDecoder(serverResp.body).Decode(&response) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/container_wait.go b/vendor/github.com/docker/docker/client/container_wait.go deleted file mode 100644 index b7d80542c..000000000 --- a/vendor/github.com/docker/docker/client/container_wait.go +++ /dev/null @@ -1,108 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "io" - "net/url" - - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/versions" -) - -const containerWaitErrorMsgLimit = 2 * 1024 /* Max: 2KiB */ - -// ContainerWait waits until the specified container is in a certain state -// indicated by the given condition, either "not-running" (default), -// "next-exit", or "removed". -// -// If this client's API version is before 1.30, condition is ignored and -// ContainerWait will return immediately with the two channels, as the server -// will wait as if the condition were "not-running". -// -// If this client's API version is at least 1.30, ContainerWait blocks until -// the request has been acknowledged by the server (with a response header), -// then returns two channels on which the caller can wait for the exit status -// of the container or an error if there was a problem either beginning the -// wait request or in getting the response. This allows the caller to -// synchronize ContainerWait with other calls, such as specifying a -// "next-exit" condition before issuing a ContainerStart request. -func (cli *Client) ContainerWait(ctx context.Context, containerID string, condition container.WaitCondition) (<-chan container.WaitResponse, <-chan error) { - if versions.LessThan(cli.ClientVersion(), "1.30") { - return cli.legacyContainerWait(ctx, containerID) - } - - resultC := make(chan container.WaitResponse) - errC := make(chan error, 1) - - query := url.Values{} - if condition != "" { - query.Set("condition", string(condition)) - } - - resp, err := cli.post(ctx, "/containers/"+containerID+"/wait", query, nil, nil) - if err != nil { - defer ensureReaderClosed(resp) - errC <- err - return resultC, errC - } - - go func() { - defer ensureReaderClosed(resp) - - body := resp.body - responseText := bytes.NewBuffer(nil) - stream := io.TeeReader(body, responseText) - - var res container.WaitResponse - if err := json.NewDecoder(stream).Decode(&res); err != nil { - // NOTE(nicks): The /wait API does not work well with HTTP proxies. - // At any time, the proxy could cut off the response stream. - // - // But because the HTTP status has already been written, the proxy's - // only option is to write a plaintext error message. - // - // If there's a JSON parsing error, read the real error message - // off the body and send it to the client. - if errors.As(err, new(*json.SyntaxError)) { - _, _ = io.ReadAll(io.LimitReader(stream, containerWaitErrorMsgLimit)) - errC <- errors.New(responseText.String()) - } else { - errC <- err - } - return - } - - resultC <- res - }() - - return resultC, errC -} - -// legacyContainerWait returns immediately and doesn't have an option to wait -// until the container is removed. -func (cli *Client) legacyContainerWait(ctx context.Context, containerID string) (<-chan container.WaitResponse, <-chan error) { - resultC := make(chan container.WaitResponse) - errC := make(chan error) - - go func() { - resp, err := cli.post(ctx, "/containers/"+containerID+"/wait", nil, nil, nil) - if err != nil { - errC <- err - return - } - defer ensureReaderClosed(resp) - - var res container.WaitResponse - if err := json.NewDecoder(resp.body).Decode(&res); err != nil { - errC <- err - return - } - - resultC <- res - }() - - return resultC, errC -} diff --git a/vendor/github.com/docker/docker/client/disk_usage.go b/vendor/github.com/docker/docker/client/disk_usage.go deleted file mode 100644 index ba0d92e9e..000000000 --- a/vendor/github.com/docker/docker/client/disk_usage.go +++ /dev/null @@ -1,33 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "fmt" - "net/url" - - "github.com/docker/docker/api/types" -) - -// DiskUsage requests the current data usage from the daemon -func (cli *Client) DiskUsage(ctx context.Context, options types.DiskUsageOptions) (types.DiskUsage, error) { - var query url.Values - if len(options.Types) > 0 { - query = url.Values{} - for _, t := range options.Types { - query.Add("type", string(t)) - } - } - - serverResp, err := cli.get(ctx, "/system/df", query, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return types.DiskUsage{}, err - } - - var du types.DiskUsage - if err := json.NewDecoder(serverResp.body).Decode(&du); err != nil { - return types.DiskUsage{}, fmt.Errorf("Error retrieving disk usage: %v", err) - } - return du, nil -} diff --git a/vendor/github.com/docker/docker/client/distribution_inspect.go b/vendor/github.com/docker/docker/client/distribution_inspect.go deleted file mode 100644 index efab066d3..000000000 --- a/vendor/github.com/docker/docker/client/distribution_inspect.go +++ /dev/null @@ -1,38 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types/registry" -) - -// DistributionInspect returns the image digest with the full manifest. -func (cli *Client) DistributionInspect(ctx context.Context, image, encodedRegistryAuth string) (registry.DistributionInspect, error) { - // Contact the registry to retrieve digest and platform information - var distributionInspect registry.DistributionInspect - if image == "" { - return distributionInspect, objectNotFoundError{object: "distribution", id: image} - } - - if err := cli.NewVersionError("1.30", "distribution inspect"); err != nil { - return distributionInspect, err - } - var headers map[string][]string - - if encodedRegistryAuth != "" { - headers = map[string][]string{ - registry.AuthHeader: {encodedRegistryAuth}, - } - } - - resp, err := cli.get(ctx, "/distribution/"+image+"/json", url.Values{}, headers) - defer ensureReaderClosed(resp) - if err != nil { - return distributionInspect, err - } - - err = json.NewDecoder(resp.body).Decode(&distributionInspect) - return distributionInspect, err -} diff --git a/vendor/github.com/docker/docker/client/envvars.go b/vendor/github.com/docker/docker/client/envvars.go deleted file mode 100644 index 61dd45c1d..000000000 --- a/vendor/github.com/docker/docker/client/envvars.go +++ /dev/null @@ -1,90 +0,0 @@ -package client // import "github.com/docker/docker/client" - -const ( - // EnvOverrideHost is the name of the environment variable that can be used - // to override the default host to connect to (DefaultDockerHost). - // - // This env-var is read by FromEnv and WithHostFromEnv and when set to a - // non-empty value, takes precedence over the default host (which is platform - // specific), or any host already set. - EnvOverrideHost = "DOCKER_HOST" - - // EnvOverrideAPIVersion is the name of the environment variable that can - // be used to override the API version to use. Value should be - // formatted as MAJOR.MINOR, for example, "1.19". - // - // This env-var is read by FromEnv and WithVersionFromEnv and when set to a - // non-empty value, takes precedence over API version negotiation. - // - // This environment variable should be used for debugging purposes only, as - // it can set the client to use an incompatible (or invalid) API version. - EnvOverrideAPIVersion = "DOCKER_API_VERSION" - - // EnvOverrideCertPath is the name of the environment variable that can be - // used to specify the directory from which to load the TLS certificates - // (ca.pem, cert.pem, key.pem) from. These certificates are used to configure - // the Client for a TCP connection protected by TLS client authentication. - // - // TLS certificate verification is enabled by default if the Client is configured - // to use a TLS connection. Refer to EnvTLSVerify below to learn how to - // disable verification for testing purposes. - // - // WARNING: Access to the remote API is equivalent to root access to the - // host where the daemon runs. Do not expose the API without protection, - // and only if needed. Make sure you are familiar with the "daemon attack - // surface" (https://docs.docker.com/go/attack-surface/). - // - // For local access to the API, it is recommended to connect with the daemon - // using the default local socket connection (on Linux), or the named pipe - // (on Windows). - // - // If you need to access the API of a remote daemon, consider using an SSH - // (ssh://) connection, which is easier to set up, and requires no additional - // configuration if the host is accessible using ssh. - // - // If you cannot use the alternatives above, and you must expose the API over - // a TCP connection, refer to https://docs.docker.com/engine/security/protect-access/ - // to learn how to configure the daemon and client to use a TCP connection - // with TLS client authentication. Make sure you know the differences between - // a regular TLS connection and a TLS connection protected by TLS client - // authentication, and verify that the API cannot be accessed by other clients. - EnvOverrideCertPath = "DOCKER_CERT_PATH" - - // EnvTLSVerify is the name of the environment variable that can be used to - // enable or disable TLS certificate verification. When set to a non-empty - // value, TLS certificate verification is enabled, and the client is configured - // to use a TLS connection, using certificates from the default directories - // (within `~/.docker`); refer to EnvOverrideCertPath above for additional - // details. - // - // WARNING: Access to the remote API is equivalent to root access to the - // host where the daemon runs. Do not expose the API without protection, - // and only if needed. Make sure you are familiar with the "daemon attack - // surface" (https://docs.docker.com/go/attack-surface/). - // - // Before setting up your client and daemon to use a TCP connection with TLS - // client authentication, consider using one of the alternatives mentioned - // in EnvOverrideCertPath above. - // - // Disabling TLS certificate verification (for testing purposes) - // - // TLS certificate verification is enabled by default if the Client is configured - // to use a TLS connection, and it is highly recommended to keep verification - // enabled to prevent machine-in-the-middle attacks. Refer to the documentation - // at https://docs.docker.com/engine/security/protect-access/ and pages linked - // from that page to learn how to configure the daemon and client to use a - // TCP connection with TLS client authentication enabled. - // - // Set the "DOCKER_TLS_VERIFY" environment to an empty string ("") to - // disable TLS certificate verification. Disabling verification is insecure, - // so should only be done for testing purposes. From the Go documentation - // (https://pkg.go.dev/crypto/tls#Config): - // - // InsecureSkipVerify controls whether a client verifies the server's - // certificate chain and host name. If InsecureSkipVerify is true, crypto/tls - // accepts any certificate presented by the server and any host name in that - // certificate. In this mode, TLS is susceptible to machine-in-the-middle - // attacks unless custom verification is used. This should be used only for - // testing or in combination with VerifyConnection or VerifyPeerCertificate. - EnvTLSVerify = "DOCKER_TLS_VERIFY" -) diff --git a/vendor/github.com/docker/docker/client/errors.go b/vendor/github.com/docker/docker/client/errors.go deleted file mode 100644 index 6878144c4..000000000 --- a/vendor/github.com/docker/docker/client/errors.go +++ /dev/null @@ -1,68 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "fmt" - - "github.com/docker/docker/api/types/versions" - "github.com/docker/docker/errdefs" - "github.com/pkg/errors" -) - -// errConnectionFailed implements an error returned when connection failed. -type errConnectionFailed struct { - host string -} - -// Error returns a string representation of an errConnectionFailed -func (err errConnectionFailed) Error() string { - if err.host == "" { - return "Cannot connect to the Docker daemon. Is the docker daemon running on this host?" - } - return fmt.Sprintf("Cannot connect to the Docker daemon at %s. Is the docker daemon running?", err.host) -} - -// IsErrConnectionFailed returns true if the error is caused by connection failed. -func IsErrConnectionFailed(err error) bool { - return errors.As(err, &errConnectionFailed{}) -} - -// ErrorConnectionFailed returns an error with host in the error message when connection to docker daemon failed. -func ErrorConnectionFailed(host string) error { - return errConnectionFailed{host: host} -} - -// Deprecated: use the errdefs.NotFound() interface instead. Kept for backward compatibility -type notFound interface { - error - NotFound() bool -} - -// IsErrNotFound returns true if the error is a NotFound error, which is returned -// by the API when some object is not found. -func IsErrNotFound(err error) bool { - if errdefs.IsNotFound(err) { - return true - } - var e notFound - return errors.As(err, &e) -} - -type objectNotFoundError struct { - object string - id string -} - -func (e objectNotFoundError) NotFound() {} - -func (e objectNotFoundError) Error() string { - return fmt.Sprintf("Error: No such %s: %s", e.object, e.id) -} - -// NewVersionError returns an error if the APIVersion required -// if less than the current supported version -func (cli *Client) NewVersionError(APIrequired, feature string) error { - if cli.version != "" && versions.LessThan(cli.version, APIrequired) { - return fmt.Errorf("%q requires API version %s, but the Docker daemon API version is %s", feature, APIrequired, cli.version) - } - return nil -} diff --git a/vendor/github.com/docker/docker/client/events.go b/vendor/github.com/docker/docker/client/events.go deleted file mode 100644 index a9c48a928..000000000 --- a/vendor/github.com/docker/docker/client/events.go +++ /dev/null @@ -1,101 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - "time" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/events" - "github.com/docker/docker/api/types/filters" - timetypes "github.com/docker/docker/api/types/time" -) - -// Events returns a stream of events in the daemon. It's up to the caller to close the stream -// by cancelling the context. Once the stream has been completely read an io.EOF error will -// be sent over the error channel. If an error is sent all processing will be stopped. It's up -// to the caller to reopen the stream in the event of an error by reinvoking this method. -func (cli *Client) Events(ctx context.Context, options types.EventsOptions) (<-chan events.Message, <-chan error) { - messages := make(chan events.Message) - errs := make(chan error, 1) - - started := make(chan struct{}) - go func() { - defer close(errs) - - query, err := buildEventsQueryParams(cli.version, options) - if err != nil { - close(started) - errs <- err - return - } - - resp, err := cli.get(ctx, "/events", query, nil) - if err != nil { - close(started) - errs <- err - return - } - defer resp.body.Close() - - decoder := json.NewDecoder(resp.body) - - close(started) - for { - select { - case <-ctx.Done(): - errs <- ctx.Err() - return - default: - var event events.Message - if err := decoder.Decode(&event); err != nil { - errs <- err - return - } - - select { - case messages <- event: - case <-ctx.Done(): - errs <- ctx.Err() - return - } - } - } - }() - <-started - - return messages, errs -} - -func buildEventsQueryParams(cliVersion string, options types.EventsOptions) (url.Values, error) { - query := url.Values{} - ref := time.Now() - - if options.Since != "" { - ts, err := timetypes.GetTimestamp(options.Since, ref) - if err != nil { - return nil, err - } - query.Set("since", ts) - } - - if options.Until != "" { - ts, err := timetypes.GetTimestamp(options.Until, ref) - if err != nil { - return nil, err - } - query.Set("until", ts) - } - - if options.Filters.Len() > 0 { - //nolint:staticcheck // ignore SA1019 for old code - filterJSON, err := filters.ToParamWithVersion(cliVersion, options.Filters) - if err != nil { - return nil, err - } - query.Set("filters", filterJSON) - } - - return query, nil -} diff --git a/vendor/github.com/docker/docker/client/hijack.go b/vendor/github.com/docker/docker/client/hijack.go deleted file mode 100644 index 7e84865f6..000000000 --- a/vendor/github.com/docker/docker/client/hijack.go +++ /dev/null @@ -1,148 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "bufio" - "context" - "crypto/tls" - "fmt" - "net" - "net/http" - "net/http/httputil" - "net/url" - "time" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/versions" - "github.com/docker/go-connections/sockets" - "github.com/pkg/errors" -) - -// postHijacked sends a POST request and hijacks the connection. -func (cli *Client) postHijacked(ctx context.Context, path string, query url.Values, body interface{}, headers map[string][]string) (types.HijackedResponse, error) { - bodyEncoded, err := encodeData(body) - if err != nil { - return types.HijackedResponse{}, err - } - req, err := cli.buildRequest(http.MethodPost, cli.getAPIPath(ctx, path, query), bodyEncoded, headers) - if err != nil { - return types.HijackedResponse{}, err - } - conn, mediaType, err := cli.setupHijackConn(ctx, req, "tcp") - if err != nil { - return types.HijackedResponse{}, err - } - - return types.NewHijackedResponse(conn, mediaType), err -} - -// DialHijack returns a hijacked connection with negotiated protocol proto. -func (cli *Client) DialHijack(ctx context.Context, url, proto string, meta map[string][]string) (net.Conn, error) { - req, err := http.NewRequest(http.MethodPost, url, nil) - if err != nil { - return nil, err - } - req = cli.addHeaders(req, meta) - - conn, _, err := cli.setupHijackConn(ctx, req, proto) - return conn, err -} - -// fallbackDial is used when WithDialer() was not called. -// See cli.Dialer(). -func fallbackDial(proto, addr string, tlsConfig *tls.Config) (net.Conn, error) { - if tlsConfig != nil && proto != "unix" && proto != "npipe" { - return tls.Dial(proto, addr, tlsConfig) - } - if proto == "npipe" { - return sockets.DialPipe(addr, 32*time.Second) - } - return net.Dial(proto, addr) -} - -func (cli *Client) setupHijackConn(ctx context.Context, req *http.Request, proto string) (net.Conn, string, error) { - req.Header.Set("Connection", "Upgrade") - req.Header.Set("Upgrade", proto) - - dialer := cli.Dialer() - conn, err := dialer(ctx) - if err != nil { - return nil, "", errors.Wrap(err, "cannot connect to the Docker daemon. Is 'docker daemon' running on this host?") - } - - // When we set up a TCP connection for hijack, there could be long periods - // of inactivity (a long running command with no output) that in certain - // network setups may cause ECONNTIMEOUT, leaving the client in an unknown - // state. Setting TCP KeepAlive on the socket connection will prohibit - // ECONNTIMEOUT unless the socket connection truly is broken - if tcpConn, ok := conn.(*net.TCPConn); ok { - _ = tcpConn.SetKeepAlive(true) - _ = tcpConn.SetKeepAlivePeriod(30 * time.Second) - } - - clientconn := httputil.NewClientConn(conn, nil) - defer clientconn.Close() - - // Server hijacks the connection, error 'connection closed' expected - resp, err := clientconn.Do(req) - - //nolint:staticcheck // ignore SA1019 for connecting to old (pre go1.8) daemons - if err != httputil.ErrPersistEOF { - if err != nil { - return nil, "", err - } - if resp.StatusCode != http.StatusSwitchingProtocols { - _ = resp.Body.Close() - return nil, "", fmt.Errorf("unable to upgrade to %s, received %d", proto, resp.StatusCode) - } - } - - c, br := clientconn.Hijack() - if br.Buffered() > 0 { - // If there is buffered content, wrap the connection. We return an - // object that implements CloseWrite if the underlying connection - // implements it. - if _, ok := c.(types.CloseWriter); ok { - c = &hijackedConnCloseWriter{&hijackedConn{c, br}} - } else { - c = &hijackedConn{c, br} - } - } else { - br.Reset(nil) - } - - var mediaType string - if versions.GreaterThanOrEqualTo(cli.ClientVersion(), "1.42") { - // Prior to 1.42, Content-Type is always set to raw-stream and not relevant - mediaType = resp.Header.Get("Content-Type") - } - - return c, mediaType, nil -} - -// hijackedConn wraps a net.Conn and is returned by setupHijackConn in the case -// that a) there was already buffered data in the http layer when Hijack() was -// called, and b) the underlying net.Conn does *not* implement CloseWrite(). -// hijackedConn does not implement CloseWrite() either. -type hijackedConn struct { - net.Conn - r *bufio.Reader -} - -func (c *hijackedConn) Read(b []byte) (int, error) { - return c.r.Read(b) -} - -// hijackedConnCloseWriter is a hijackedConn which additionally implements -// CloseWrite(). It is returned by setupHijackConn in the case that a) there -// was already buffered data in the http layer when Hijack() was called, and b) -// the underlying net.Conn *does* implement CloseWrite(). -type hijackedConnCloseWriter struct { - *hijackedConn -} - -var _ types.CloseWriter = &hijackedConnCloseWriter{} - -func (c *hijackedConnCloseWriter) CloseWrite() error { - conn := c.Conn.(types.CloseWriter) - return conn.CloseWrite() -} diff --git a/vendor/github.com/docker/docker/client/image_build.go b/vendor/github.com/docker/docker/client/image_build.go deleted file mode 100644 index d16e1d8ea..000000000 --- a/vendor/github.com/docker/docker/client/image_build.go +++ /dev/null @@ -1,146 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/base64" - "encoding/json" - "io" - "net/http" - "net/url" - "strconv" - "strings" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/container" -) - -// ImageBuild sends a request to the daemon to build images. -// The Body in the response implements an io.ReadCloser and it's up to the caller to -// close it. -func (cli *Client) ImageBuild(ctx context.Context, buildContext io.Reader, options types.ImageBuildOptions) (types.ImageBuildResponse, error) { - query, err := cli.imageBuildOptionsToQuery(options) - if err != nil { - return types.ImageBuildResponse{}, err - } - - headers := http.Header(make(map[string][]string)) - buf, err := json.Marshal(options.AuthConfigs) - if err != nil { - return types.ImageBuildResponse{}, err - } - headers.Add("X-Registry-Config", base64.URLEncoding.EncodeToString(buf)) - - headers.Set("Content-Type", "application/x-tar") - - serverResp, err := cli.postRaw(ctx, "/build", query, buildContext, headers) - if err != nil { - return types.ImageBuildResponse{}, err - } - - osType := getDockerOS(serverResp.header.Get("Server")) - - return types.ImageBuildResponse{ - Body: serverResp.body, - OSType: osType, - }, nil -} - -func (cli *Client) imageBuildOptionsToQuery(options types.ImageBuildOptions) (url.Values, error) { - query := url.Values{ - "t": options.Tags, - "securityopt": options.SecurityOpt, - "extrahosts": options.ExtraHosts, - } - if options.SuppressOutput { - query.Set("q", "1") - } - if options.RemoteContext != "" { - query.Set("remote", options.RemoteContext) - } - if options.NoCache { - query.Set("nocache", "1") - } - if options.Remove { - query.Set("rm", "1") - } else { - query.Set("rm", "0") - } - - if options.ForceRemove { - query.Set("forcerm", "1") - } - - if options.PullParent { - query.Set("pull", "1") - } - - if options.Squash { - if err := cli.NewVersionError("1.25", "squash"); err != nil { - return query, err - } - query.Set("squash", "1") - } - - if !container.Isolation.IsDefault(options.Isolation) { - query.Set("isolation", string(options.Isolation)) - } - - query.Set("cpusetcpus", options.CPUSetCPUs) - query.Set("networkmode", options.NetworkMode) - query.Set("cpusetmems", options.CPUSetMems) - query.Set("cpushares", strconv.FormatInt(options.CPUShares, 10)) - query.Set("cpuquota", strconv.FormatInt(options.CPUQuota, 10)) - query.Set("cpuperiod", strconv.FormatInt(options.CPUPeriod, 10)) - query.Set("memory", strconv.FormatInt(options.Memory, 10)) - query.Set("memswap", strconv.FormatInt(options.MemorySwap, 10)) - query.Set("cgroupparent", options.CgroupParent) - query.Set("shmsize", strconv.FormatInt(options.ShmSize, 10)) - query.Set("dockerfile", options.Dockerfile) - query.Set("target", options.Target) - - ulimitsJSON, err := json.Marshal(options.Ulimits) - if err != nil { - return query, err - } - query.Set("ulimits", string(ulimitsJSON)) - - buildArgsJSON, err := json.Marshal(options.BuildArgs) - if err != nil { - return query, err - } - query.Set("buildargs", string(buildArgsJSON)) - - labelsJSON, err := json.Marshal(options.Labels) - if err != nil { - return query, err - } - query.Set("labels", string(labelsJSON)) - - cacheFromJSON, err := json.Marshal(options.CacheFrom) - if err != nil { - return query, err - } - query.Set("cachefrom", string(cacheFromJSON)) - if options.SessionID != "" { - query.Set("session", options.SessionID) - } - if options.Platform != "" { - if err := cli.NewVersionError("1.32", "platform"); err != nil { - return query, err - } - query.Set("platform", strings.ToLower(options.Platform)) - } - if options.BuildID != "" { - query.Set("buildid", options.BuildID) - } - query.Set("version", string(options.Version)) - - if options.Outputs != nil { - outputsJSON, err := json.Marshal(options.Outputs) - if err != nil { - return query, err - } - query.Set("outputs", string(outputsJSON)) - } - return query, nil -} diff --git a/vendor/github.com/docker/docker/client/image_create.go b/vendor/github.com/docker/docker/client/image_create.go deleted file mode 100644 index 6a9b708f7..000000000 --- a/vendor/github.com/docker/docker/client/image_create.go +++ /dev/null @@ -1,38 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" - "net/url" - "strings" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/registry" -) - -// ImageCreate creates a new image based on the parent options. -// It returns the JSON content in the response body. -func (cli *Client) ImageCreate(ctx context.Context, parentReference string, options types.ImageCreateOptions) (io.ReadCloser, error) { - ref, err := reference.ParseNormalizedNamed(parentReference) - if err != nil { - return nil, err - } - - query := url.Values{} - query.Set("fromImage", reference.FamiliarName(ref)) - query.Set("tag", getAPITagFromNamedRef(ref)) - if options.Platform != "" { - query.Set("platform", strings.ToLower(options.Platform)) - } - resp, err := cli.tryImageCreate(ctx, query, options.RegistryAuth) - if err != nil { - return nil, err - } - return resp.body, nil -} - -func (cli *Client) tryImageCreate(ctx context.Context, query url.Values, registryAuth string) (serverResponse, error) { - headers := map[string][]string{registry.AuthHeader: {registryAuth}} - return cli.post(ctx, "/images/create", query, nil, headers) -} diff --git a/vendor/github.com/docker/docker/client/image_history.go b/vendor/github.com/docker/docker/client/image_history.go deleted file mode 100644 index b5bea10d8..000000000 --- a/vendor/github.com/docker/docker/client/image_history.go +++ /dev/null @@ -1,22 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types/image" -) - -// ImageHistory returns the changes in an image in history format. -func (cli *Client) ImageHistory(ctx context.Context, imageID string) ([]image.HistoryResponseItem, error) { - var history []image.HistoryResponseItem - serverResp, err := cli.get(ctx, "/images/"+imageID+"/history", url.Values{}, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return history, err - } - - err = json.NewDecoder(serverResp.body).Decode(&history) - return history, err -} diff --git a/vendor/github.com/docker/docker/client/image_import.go b/vendor/github.com/docker/docker/client/image_import.go deleted file mode 100644 index c5de42cb7..000000000 --- a/vendor/github.com/docker/docker/client/image_import.go +++ /dev/null @@ -1,40 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" - "net/url" - "strings" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" -) - -// ImageImport creates a new image based on the source options. -// It returns the JSON content in the response body. -func (cli *Client) ImageImport(ctx context.Context, source types.ImageImportSource, ref string, options types.ImageImportOptions) (io.ReadCloser, error) { - if ref != "" { - // Check if the given image name can be resolved - if _, err := reference.ParseNormalizedNamed(ref); err != nil { - return nil, err - } - } - - query := url.Values{} - query.Set("fromSrc", source.SourceName) - query.Set("repo", ref) - query.Set("tag", options.Tag) - query.Set("message", options.Message) - if options.Platform != "" { - query.Set("platform", strings.ToLower(options.Platform)) - } - for _, change := range options.Changes { - query.Add("changes", change) - } - - resp, err := cli.postRaw(ctx, "/images/create", query, source.Source, nil) - if err != nil { - return nil, err - } - return resp.body, nil -} diff --git a/vendor/github.com/docker/docker/client/image_inspect.go b/vendor/github.com/docker/docker/client/image_inspect.go deleted file mode 100644 index 1de10e5a0..000000000 --- a/vendor/github.com/docker/docker/client/image_inspect.go +++ /dev/null @@ -1,32 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "bytes" - "context" - "encoding/json" - "io" - - "github.com/docker/docker/api/types" -) - -// ImageInspectWithRaw returns the image information and its raw representation. -func (cli *Client) ImageInspectWithRaw(ctx context.Context, imageID string) (types.ImageInspect, []byte, error) { - if imageID == "" { - return types.ImageInspect{}, nil, objectNotFoundError{object: "image", id: imageID} - } - serverResp, err := cli.get(ctx, "/images/"+imageID+"/json", nil, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return types.ImageInspect{}, nil, err - } - - body, err := io.ReadAll(serverResp.body) - if err != nil { - return types.ImageInspect{}, nil, err - } - - var response types.ImageInspect - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&response) - return response, body, err -} diff --git a/vendor/github.com/docker/docker/client/image_list.go b/vendor/github.com/docker/docker/client/image_list.go deleted file mode 100644 index 950d51333..000000000 --- a/vendor/github.com/docker/docker/client/image_list.go +++ /dev/null @@ -1,49 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/versions" -) - -// ImageList returns a list of images in the docker host. -func (cli *Client) ImageList(ctx context.Context, options types.ImageListOptions) ([]types.ImageSummary, error) { - var images []types.ImageSummary - query := url.Values{} - - optionFilters := options.Filters - referenceFilters := optionFilters.Get("reference") - if versions.LessThan(cli.version, "1.25") && len(referenceFilters) > 0 { - query.Set("filter", referenceFilters[0]) - for _, filterValue := range referenceFilters { - optionFilters.Del("reference", filterValue) - } - } - if optionFilters.Len() > 0 { - //nolint:staticcheck // ignore SA1019 for old code - filterJSON, err := filters.ToParamWithVersion(cli.version, optionFilters) - if err != nil { - return images, err - } - query.Set("filters", filterJSON) - } - if options.All { - query.Set("all", "1") - } - if options.SharedSize && versions.GreaterThanOrEqualTo(cli.version, "1.42") { - query.Set("shared-size", "1") - } - - serverResp, err := cli.get(ctx, "/images/json", query, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return images, err - } - - err = json.NewDecoder(serverResp.body).Decode(&images) - return images, err -} diff --git a/vendor/github.com/docker/docker/client/image_load.go b/vendor/github.com/docker/docker/client/image_load.go deleted file mode 100644 index 91016e493..000000000 --- a/vendor/github.com/docker/docker/client/image_load.go +++ /dev/null @@ -1,29 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" - "net/url" - - "github.com/docker/docker/api/types" -) - -// ImageLoad loads an image in the docker host from the client host. -// It's up to the caller to close the io.ReadCloser in the -// ImageLoadResponse returned by this function. -func (cli *Client) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (types.ImageLoadResponse, error) { - v := url.Values{} - v.Set("quiet", "0") - if quiet { - v.Set("quiet", "1") - } - headers := map[string][]string{"Content-Type": {"application/x-tar"}} - resp, err := cli.postRaw(ctx, "/images/load", v, input, headers) - if err != nil { - return types.ImageLoadResponse{}, err - } - return types.ImageLoadResponse{ - Body: resp.body, - JSON: resp.header.Get("Content-Type") == "application/json", - }, nil -} diff --git a/vendor/github.com/docker/docker/client/image_prune.go b/vendor/github.com/docker/docker/client/image_prune.go deleted file mode 100644 index 56af6d7f9..000000000 --- a/vendor/github.com/docker/docker/client/image_prune.go +++ /dev/null @@ -1,36 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "fmt" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" -) - -// ImagesPrune requests the daemon to delete unused data -func (cli *Client) ImagesPrune(ctx context.Context, pruneFilters filters.Args) (types.ImagesPruneReport, error) { - var report types.ImagesPruneReport - - if err := cli.NewVersionError("1.25", "image prune"); err != nil { - return report, err - } - - query, err := getFiltersQuery(pruneFilters) - if err != nil { - return report, err - } - - serverResp, err := cli.post(ctx, "/images/prune", query, nil, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return report, err - } - - if err := json.NewDecoder(serverResp.body).Decode(&report); err != nil { - return report, fmt.Errorf("Error retrieving disk usage: %v", err) - } - - return report, nil -} diff --git a/vendor/github.com/docker/docker/client/image_pull.go b/vendor/github.com/docker/docker/client/image_pull.go deleted file mode 100644 index a23975591..000000000 --- a/vendor/github.com/docker/docker/client/image_pull.go +++ /dev/null @@ -1,64 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" - "net/url" - "strings" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" - "github.com/docker/docker/errdefs" -) - -// ImagePull requests the docker host to pull an image from a remote registry. -// It executes the privileged function if the operation is unauthorized -// and it tries one more time. -// It's up to the caller to handle the io.ReadCloser and close it properly. -// -// FIXME(vdemeester): there is currently used in a few way in docker/docker -// - if not in trusted content, ref is used to pass the whole reference, and tag is empty -// - if in trusted content, ref is used to pass the reference name, and tag for the digest -func (cli *Client) ImagePull(ctx context.Context, refStr string, options types.ImagePullOptions) (io.ReadCloser, error) { - ref, err := reference.ParseNormalizedNamed(refStr) - if err != nil { - return nil, err - } - - query := url.Values{} - query.Set("fromImage", reference.FamiliarName(ref)) - if !options.All { - query.Set("tag", getAPITagFromNamedRef(ref)) - } - if options.Platform != "" { - query.Set("platform", strings.ToLower(options.Platform)) - } - - resp, err := cli.tryImageCreate(ctx, query, options.RegistryAuth) - if errdefs.IsUnauthorized(err) && options.PrivilegeFunc != nil { - newAuthHeader, privilegeErr := options.PrivilegeFunc() - if privilegeErr != nil { - return nil, privilegeErr - } - resp, err = cli.tryImageCreate(ctx, query, newAuthHeader) - } - if err != nil { - return nil, err - } - return resp.body, nil -} - -// getAPITagFromNamedRef returns a tag from the specified reference. -// This function is necessary as long as the docker "server" api expects -// digests to be sent as tags and makes a distinction between the name -// and tag/digest part of a reference. -func getAPITagFromNamedRef(ref reference.Named) string { - if digested, ok := ref.(reference.Digested); ok { - return digested.Digest().String() - } - ref = reference.TagNameOnly(ref) - if tagged, ok := ref.(reference.Tagged); ok { - return tagged.Tag() - } - return "" -} diff --git a/vendor/github.com/docker/docker/client/image_push.go b/vendor/github.com/docker/docker/client/image_push.go deleted file mode 100644 index dd1b8f347..000000000 --- a/vendor/github.com/docker/docker/client/image_push.go +++ /dev/null @@ -1,55 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "errors" - "io" - "net/url" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/registry" - "github.com/docker/docker/errdefs" -) - -// ImagePush requests the docker host to push an image to a remote registry. -// It executes the privileged function if the operation is unauthorized -// and it tries one more time. -// It's up to the caller to handle the io.ReadCloser and close it properly. -func (cli *Client) ImagePush(ctx context.Context, image string, options types.ImagePushOptions) (io.ReadCloser, error) { - ref, err := reference.ParseNormalizedNamed(image) - if err != nil { - return nil, err - } - - if _, isCanonical := ref.(reference.Canonical); isCanonical { - return nil, errors.New("cannot push a digest reference") - } - - name := reference.FamiliarName(ref) - query := url.Values{} - if !options.All { - ref = reference.TagNameOnly(ref) - if tagged, ok := ref.(reference.Tagged); ok { - query.Set("tag", tagged.Tag()) - } - } - - resp, err := cli.tryImagePush(ctx, name, query, options.RegistryAuth) - if errdefs.IsUnauthorized(err) && options.PrivilegeFunc != nil { - newAuthHeader, privilegeErr := options.PrivilegeFunc() - if privilegeErr != nil { - return nil, privilegeErr - } - resp, err = cli.tryImagePush(ctx, name, query, newAuthHeader) - } - if err != nil { - return nil, err - } - return resp.body, nil -} - -func (cli *Client) tryImagePush(ctx context.Context, imageID string, query url.Values, registryAuth string) (serverResponse, error) { - headers := map[string][]string{registry.AuthHeader: {registryAuth}} - return cli.post(ctx, "/images/"+imageID+"/push", query, nil, headers) -} diff --git a/vendor/github.com/docker/docker/client/image_remove.go b/vendor/github.com/docker/docker/client/image_remove.go deleted file mode 100644 index 6a9fb3f41..000000000 --- a/vendor/github.com/docker/docker/client/image_remove.go +++ /dev/null @@ -1,31 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" -) - -// ImageRemove removes an image from the docker host. -func (cli *Client) ImageRemove(ctx context.Context, imageID string, options types.ImageRemoveOptions) ([]types.ImageDeleteResponseItem, error) { - query := url.Values{} - - if options.Force { - query.Set("force", "1") - } - if !options.PruneChildren { - query.Set("noprune", "1") - } - - var dels []types.ImageDeleteResponseItem - resp, err := cli.delete(ctx, "/images/"+imageID, query, nil) - defer ensureReaderClosed(resp) - if err != nil { - return dels, err - } - - err = json.NewDecoder(resp.body).Decode(&dels) - return dels, err -} diff --git a/vendor/github.com/docker/docker/client/image_save.go b/vendor/github.com/docker/docker/client/image_save.go deleted file mode 100644 index d1314e4b2..000000000 --- a/vendor/github.com/docker/docker/client/image_save.go +++ /dev/null @@ -1,21 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" - "net/url" -) - -// ImageSave retrieves one or more images from the docker host as an io.ReadCloser. -// It's up to the caller to store the images and close the stream. -func (cli *Client) ImageSave(ctx context.Context, imageIDs []string) (io.ReadCloser, error) { - query := url.Values{ - "names": imageIDs, - } - - resp, err := cli.get(ctx, "/images/get", query, nil) - if err != nil { - return nil, err - } - return resp.body, nil -} diff --git a/vendor/github.com/docker/docker/client/image_search.go b/vendor/github.com/docker/docker/client/image_search.go deleted file mode 100644 index 5f0c49ed3..000000000 --- a/vendor/github.com/docker/docker/client/image_search.go +++ /dev/null @@ -1,53 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - "strconv" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/registry" - "github.com/docker/docker/errdefs" -) - -// ImageSearch makes the docker host search by a term in a remote registry. -// The list of results is not sorted in any fashion. -func (cli *Client) ImageSearch(ctx context.Context, term string, options types.ImageSearchOptions) ([]registry.SearchResult, error) { - var results []registry.SearchResult - query := url.Values{} - query.Set("term", term) - if options.Limit > 0 { - query.Set("limit", strconv.Itoa(options.Limit)) - } - - if options.Filters.Len() > 0 { - filterJSON, err := filters.ToJSON(options.Filters) - if err != nil { - return results, err - } - query.Set("filters", filterJSON) - } - - resp, err := cli.tryImageSearch(ctx, query, options.RegistryAuth) - defer ensureReaderClosed(resp) - if errdefs.IsUnauthorized(err) && options.PrivilegeFunc != nil { - newAuthHeader, privilegeErr := options.PrivilegeFunc() - if privilegeErr != nil { - return results, privilegeErr - } - resp, err = cli.tryImageSearch(ctx, query, newAuthHeader) - } - if err != nil { - return results, err - } - - err = json.NewDecoder(resp.body).Decode(&results) - return results, err -} - -func (cli *Client) tryImageSearch(ctx context.Context, query url.Values, registryAuth string) (serverResponse, error) { - headers := map[string][]string{registry.AuthHeader: {registryAuth}} - return cli.get(ctx, "/images/search", query, headers) -} diff --git a/vendor/github.com/docker/docker/client/image_tag.go b/vendor/github.com/docker/docker/client/image_tag.go deleted file mode 100644 index 5652bfc25..000000000 --- a/vendor/github.com/docker/docker/client/image_tag.go +++ /dev/null @@ -1,37 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - - "github.com/docker/distribution/reference" - "github.com/pkg/errors" -) - -// ImageTag tags an image in the docker host -func (cli *Client) ImageTag(ctx context.Context, source, target string) error { - if _, err := reference.ParseAnyReference(source); err != nil { - return errors.Wrapf(err, "Error parsing reference: %q is not a valid repository/tag", source) - } - - ref, err := reference.ParseNormalizedNamed(target) - if err != nil { - return errors.Wrapf(err, "Error parsing reference: %q is not a valid repository/tag", target) - } - - if _, isCanonical := ref.(reference.Canonical); isCanonical { - return errors.New("refusing to create a tag with a digest reference") - } - - ref = reference.TagNameOnly(ref) - - query := url.Values{} - query.Set("repo", reference.FamiliarName(ref)) - if tagged, ok := ref.(reference.Tagged); ok { - query.Set("tag", tagged.Tag()) - } - - resp, err := cli.post(ctx, "/images/"+source+"/tag", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/info.go b/vendor/github.com/docker/docker/client/info.go deleted file mode 100644 index c856704e2..000000000 --- a/vendor/github.com/docker/docker/client/info.go +++ /dev/null @@ -1,26 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "fmt" - "net/url" - - "github.com/docker/docker/api/types" -) - -// Info returns information about the docker server. -func (cli *Client) Info(ctx context.Context) (types.Info, error) { - var info types.Info - serverResp, err := cli.get(ctx, "/info", url.Values{}, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return info, err - } - - if err := json.NewDecoder(serverResp.body).Decode(&info); err != nil { - return info, fmt.Errorf("Error reading remote info: %v", err) - } - - return info, nil -} diff --git a/vendor/github.com/docker/docker/client/interface.go b/vendor/github.com/docker/docker/client/interface.go deleted file mode 100644 index 7993c5a48..000000000 --- a/vendor/github.com/docker/docker/client/interface.go +++ /dev/null @@ -1,201 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" - "net" - "net/http" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/events" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/image" - "github.com/docker/docker/api/types/network" - "github.com/docker/docker/api/types/registry" - "github.com/docker/docker/api/types/swarm" - "github.com/docker/docker/api/types/volume" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" -) - -// CommonAPIClient is the common methods between stable and experimental versions of APIClient. -type CommonAPIClient interface { - ConfigAPIClient - ContainerAPIClient - DistributionAPIClient - ImageAPIClient - NodeAPIClient - NetworkAPIClient - PluginAPIClient - ServiceAPIClient - SwarmAPIClient - SecretAPIClient - SystemAPIClient - VolumeAPIClient - ClientVersion() string - DaemonHost() string - HTTPClient() *http.Client - ServerVersion(ctx context.Context) (types.Version, error) - NegotiateAPIVersion(ctx context.Context) - NegotiateAPIVersionPing(types.Ping) - DialHijack(ctx context.Context, url, proto string, meta map[string][]string) (net.Conn, error) - Dialer() func(context.Context) (net.Conn, error) - Close() error -} - -// ContainerAPIClient defines API client methods for the containers -type ContainerAPIClient interface { - ContainerAttach(ctx context.Context, container string, options types.ContainerAttachOptions) (types.HijackedResponse, error) - ContainerCommit(ctx context.Context, container string, options types.ContainerCommitOptions) (types.IDResponse, error) - ContainerCreate(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, platform *ocispec.Platform, containerName string) (container.CreateResponse, error) - ContainerDiff(ctx context.Context, container string) ([]container.FilesystemChange, error) - ContainerExecAttach(ctx context.Context, execID string, config types.ExecStartCheck) (types.HijackedResponse, error) - ContainerExecCreate(ctx context.Context, container string, config types.ExecConfig) (types.IDResponse, error) - ContainerExecInspect(ctx context.Context, execID string) (types.ContainerExecInspect, error) - ContainerExecResize(ctx context.Context, execID string, options types.ResizeOptions) error - ContainerExecStart(ctx context.Context, execID string, config types.ExecStartCheck) error - ContainerExport(ctx context.Context, container string) (io.ReadCloser, error) - ContainerInspect(ctx context.Context, container string) (types.ContainerJSON, error) - ContainerInspectWithRaw(ctx context.Context, container string, getSize bool) (types.ContainerJSON, []byte, error) - ContainerKill(ctx context.Context, container, signal string) error - ContainerList(ctx context.Context, options types.ContainerListOptions) ([]types.Container, error) - ContainerLogs(ctx context.Context, container string, options types.ContainerLogsOptions) (io.ReadCloser, error) - ContainerPause(ctx context.Context, container string) error - ContainerRemove(ctx context.Context, container string, options types.ContainerRemoveOptions) error - ContainerRename(ctx context.Context, container, newContainerName string) error - ContainerResize(ctx context.Context, container string, options types.ResizeOptions) error - ContainerRestart(ctx context.Context, container string, options container.StopOptions) error - ContainerStatPath(ctx context.Context, container, path string) (types.ContainerPathStat, error) - ContainerStats(ctx context.Context, container string, stream bool) (types.ContainerStats, error) - ContainerStatsOneShot(ctx context.Context, container string) (types.ContainerStats, error) - ContainerStart(ctx context.Context, container string, options types.ContainerStartOptions) error - ContainerStop(ctx context.Context, container string, options container.StopOptions) error - ContainerTop(ctx context.Context, container string, arguments []string) (container.ContainerTopOKBody, error) - ContainerUnpause(ctx context.Context, container string) error - ContainerUpdate(ctx context.Context, container string, updateConfig container.UpdateConfig) (container.ContainerUpdateOKBody, error) - ContainerWait(ctx context.Context, container string, condition container.WaitCondition) (<-chan container.WaitResponse, <-chan error) - CopyFromContainer(ctx context.Context, container, srcPath string) (io.ReadCloser, types.ContainerPathStat, error) - CopyToContainer(ctx context.Context, container, path string, content io.Reader, options types.CopyToContainerOptions) error - ContainersPrune(ctx context.Context, pruneFilters filters.Args) (types.ContainersPruneReport, error) -} - -// DistributionAPIClient defines API client methods for the registry -type DistributionAPIClient interface { - DistributionInspect(ctx context.Context, image, encodedRegistryAuth string) (registry.DistributionInspect, error) -} - -// ImageAPIClient defines API client methods for the images -type ImageAPIClient interface { - ImageBuild(ctx context.Context, context io.Reader, options types.ImageBuildOptions) (types.ImageBuildResponse, error) - BuildCachePrune(ctx context.Context, opts types.BuildCachePruneOptions) (*types.BuildCachePruneReport, error) - BuildCancel(ctx context.Context, id string) error - ImageCreate(ctx context.Context, parentReference string, options types.ImageCreateOptions) (io.ReadCloser, error) - ImageHistory(ctx context.Context, image string) ([]image.HistoryResponseItem, error) - ImageImport(ctx context.Context, source types.ImageImportSource, ref string, options types.ImageImportOptions) (io.ReadCloser, error) - ImageInspectWithRaw(ctx context.Context, image string) (types.ImageInspect, []byte, error) - ImageList(ctx context.Context, options types.ImageListOptions) ([]types.ImageSummary, error) - ImageLoad(ctx context.Context, input io.Reader, quiet bool) (types.ImageLoadResponse, error) - ImagePull(ctx context.Context, ref string, options types.ImagePullOptions) (io.ReadCloser, error) - ImagePush(ctx context.Context, ref string, options types.ImagePushOptions) (io.ReadCloser, error) - ImageRemove(ctx context.Context, image string, options types.ImageRemoveOptions) ([]types.ImageDeleteResponseItem, error) - ImageSearch(ctx context.Context, term string, options types.ImageSearchOptions) ([]registry.SearchResult, error) - ImageSave(ctx context.Context, images []string) (io.ReadCloser, error) - ImageTag(ctx context.Context, image, ref string) error - ImagesPrune(ctx context.Context, pruneFilter filters.Args) (types.ImagesPruneReport, error) -} - -// NetworkAPIClient defines API client methods for the networks -type NetworkAPIClient interface { - NetworkConnect(ctx context.Context, network, container string, config *network.EndpointSettings) error - NetworkCreate(ctx context.Context, name string, options types.NetworkCreate) (types.NetworkCreateResponse, error) - NetworkDisconnect(ctx context.Context, network, container string, force bool) error - NetworkInspect(ctx context.Context, network string, options types.NetworkInspectOptions) (types.NetworkResource, error) - NetworkInspectWithRaw(ctx context.Context, network string, options types.NetworkInspectOptions) (types.NetworkResource, []byte, error) - NetworkList(ctx context.Context, options types.NetworkListOptions) ([]types.NetworkResource, error) - NetworkRemove(ctx context.Context, network string) error - NetworksPrune(ctx context.Context, pruneFilter filters.Args) (types.NetworksPruneReport, error) -} - -// NodeAPIClient defines API client methods for the nodes -type NodeAPIClient interface { - NodeInspectWithRaw(ctx context.Context, nodeID string) (swarm.Node, []byte, error) - NodeList(ctx context.Context, options types.NodeListOptions) ([]swarm.Node, error) - NodeRemove(ctx context.Context, nodeID string, options types.NodeRemoveOptions) error - NodeUpdate(ctx context.Context, nodeID string, version swarm.Version, node swarm.NodeSpec) error -} - -// PluginAPIClient defines API client methods for the plugins -type PluginAPIClient interface { - PluginList(ctx context.Context, filter filters.Args) (types.PluginsListResponse, error) - PluginRemove(ctx context.Context, name string, options types.PluginRemoveOptions) error - PluginEnable(ctx context.Context, name string, options types.PluginEnableOptions) error - PluginDisable(ctx context.Context, name string, options types.PluginDisableOptions) error - PluginInstall(ctx context.Context, name string, options types.PluginInstallOptions) (io.ReadCloser, error) - PluginUpgrade(ctx context.Context, name string, options types.PluginInstallOptions) (io.ReadCloser, error) - PluginPush(ctx context.Context, name string, registryAuth string) (io.ReadCloser, error) - PluginSet(ctx context.Context, name string, args []string) error - PluginInspectWithRaw(ctx context.Context, name string) (*types.Plugin, []byte, error) - PluginCreate(ctx context.Context, createContext io.Reader, options types.PluginCreateOptions) error -} - -// ServiceAPIClient defines API client methods for the services -type ServiceAPIClient interface { - ServiceCreate(ctx context.Context, service swarm.ServiceSpec, options types.ServiceCreateOptions) (types.ServiceCreateResponse, error) - ServiceInspectWithRaw(ctx context.Context, serviceID string, options types.ServiceInspectOptions) (swarm.Service, []byte, error) - ServiceList(ctx context.Context, options types.ServiceListOptions) ([]swarm.Service, error) - ServiceRemove(ctx context.Context, serviceID string) error - ServiceUpdate(ctx context.Context, serviceID string, version swarm.Version, service swarm.ServiceSpec, options types.ServiceUpdateOptions) (types.ServiceUpdateResponse, error) - ServiceLogs(ctx context.Context, serviceID string, options types.ContainerLogsOptions) (io.ReadCloser, error) - TaskLogs(ctx context.Context, taskID string, options types.ContainerLogsOptions) (io.ReadCloser, error) - TaskInspectWithRaw(ctx context.Context, taskID string) (swarm.Task, []byte, error) - TaskList(ctx context.Context, options types.TaskListOptions) ([]swarm.Task, error) -} - -// SwarmAPIClient defines API client methods for the swarm -type SwarmAPIClient interface { - SwarmInit(ctx context.Context, req swarm.InitRequest) (string, error) - SwarmJoin(ctx context.Context, req swarm.JoinRequest) error - SwarmGetUnlockKey(ctx context.Context) (types.SwarmUnlockKeyResponse, error) - SwarmUnlock(ctx context.Context, req swarm.UnlockRequest) error - SwarmLeave(ctx context.Context, force bool) error - SwarmInspect(ctx context.Context) (swarm.Swarm, error) - SwarmUpdate(ctx context.Context, version swarm.Version, swarm swarm.Spec, flags swarm.UpdateFlags) error -} - -// SystemAPIClient defines API client methods for the system -type SystemAPIClient interface { - Events(ctx context.Context, options types.EventsOptions) (<-chan events.Message, <-chan error) - Info(ctx context.Context) (types.Info, error) - RegistryLogin(ctx context.Context, auth registry.AuthConfig) (registry.AuthenticateOKBody, error) - DiskUsage(ctx context.Context, options types.DiskUsageOptions) (types.DiskUsage, error) - Ping(ctx context.Context) (types.Ping, error) -} - -// VolumeAPIClient defines API client methods for the volumes -type VolumeAPIClient interface { - VolumeCreate(ctx context.Context, options volume.CreateOptions) (volume.Volume, error) - VolumeInspect(ctx context.Context, volumeID string) (volume.Volume, error) - VolumeInspectWithRaw(ctx context.Context, volumeID string) (volume.Volume, []byte, error) - VolumeList(ctx context.Context, options volume.ListOptions) (volume.ListResponse, error) - VolumeRemove(ctx context.Context, volumeID string, force bool) error - VolumesPrune(ctx context.Context, pruneFilter filters.Args) (types.VolumesPruneReport, error) - VolumeUpdate(ctx context.Context, volumeID string, version swarm.Version, options volume.UpdateOptions) error -} - -// SecretAPIClient defines API client methods for secrets -type SecretAPIClient interface { - SecretList(ctx context.Context, options types.SecretListOptions) ([]swarm.Secret, error) - SecretCreate(ctx context.Context, secret swarm.SecretSpec) (types.SecretCreateResponse, error) - SecretRemove(ctx context.Context, id string) error - SecretInspectWithRaw(ctx context.Context, name string) (swarm.Secret, []byte, error) - SecretUpdate(ctx context.Context, id string, version swarm.Version, secret swarm.SecretSpec) error -} - -// ConfigAPIClient defines API client methods for configs -type ConfigAPIClient interface { - ConfigList(ctx context.Context, options types.ConfigListOptions) ([]swarm.Config, error) - ConfigCreate(ctx context.Context, config swarm.ConfigSpec) (types.ConfigCreateResponse, error) - ConfigRemove(ctx context.Context, id string) error - ConfigInspectWithRaw(ctx context.Context, name string) (swarm.Config, []byte, error) - ConfigUpdate(ctx context.Context, id string, version swarm.Version, config swarm.ConfigSpec) error -} diff --git a/vendor/github.com/docker/docker/client/interface_experimental.go b/vendor/github.com/docker/docker/client/interface_experimental.go deleted file mode 100644 index 402ffb512..000000000 --- a/vendor/github.com/docker/docker/client/interface_experimental.go +++ /dev/null @@ -1,18 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - - "github.com/docker/docker/api/types" -) - -type apiClientExperimental interface { - CheckpointAPIClient -} - -// CheckpointAPIClient defines API client methods for the checkpoints -type CheckpointAPIClient interface { - CheckpointCreate(ctx context.Context, container string, options types.CheckpointCreateOptions) error - CheckpointDelete(ctx context.Context, container string, options types.CheckpointDeleteOptions) error - CheckpointList(ctx context.Context, container string, options types.CheckpointListOptions) ([]types.Checkpoint, error) -} diff --git a/vendor/github.com/docker/docker/client/interface_stable.go b/vendor/github.com/docker/docker/client/interface_stable.go deleted file mode 100644 index 5502cd742..000000000 --- a/vendor/github.com/docker/docker/client/interface_stable.go +++ /dev/null @@ -1,10 +0,0 @@ -package client // import "github.com/docker/docker/client" - -// APIClient is an interface that clients that talk with a docker server must implement. -type APIClient interface { - CommonAPIClient - apiClientExperimental -} - -// Ensure that Client always implements APIClient. -var _ APIClient = &Client{} diff --git a/vendor/github.com/docker/docker/client/login.go b/vendor/github.com/docker/docker/client/login.go deleted file mode 100644 index 19e985e0b..000000000 --- a/vendor/github.com/docker/docker/client/login.go +++ /dev/null @@ -1,24 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types/registry" -) - -// RegistryLogin authenticates the docker server with a given docker registry. -// It returns unauthorizedError when the authentication fails. -func (cli *Client) RegistryLogin(ctx context.Context, auth registry.AuthConfig) (registry.AuthenticateOKBody, error) { - resp, err := cli.post(ctx, "/auth", url.Values{}, auth, nil) - defer ensureReaderClosed(resp) - - if err != nil { - return registry.AuthenticateOKBody{}, err - } - - var response registry.AuthenticateOKBody - err = json.NewDecoder(resp.body).Decode(&response) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/network_connect.go b/vendor/github.com/docker/docker/client/network_connect.go deleted file mode 100644 index 571894613..000000000 --- a/vendor/github.com/docker/docker/client/network_connect.go +++ /dev/null @@ -1,19 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/network" -) - -// NetworkConnect connects a container to an existent network in the docker host. -func (cli *Client) NetworkConnect(ctx context.Context, networkID, containerID string, config *network.EndpointSettings) error { - nc := types.NetworkConnect{ - Container: containerID, - EndpointConfig: config, - } - resp, err := cli.post(ctx, "/networks/"+networkID+"/connect", nil, nc, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/network_create.go b/vendor/github.com/docker/docker/client/network_create.go deleted file mode 100644 index 278d9383a..000000000 --- a/vendor/github.com/docker/docker/client/network_create.go +++ /dev/null @@ -1,25 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - - "github.com/docker/docker/api/types" -) - -// NetworkCreate creates a new network in the docker host. -func (cli *Client) NetworkCreate(ctx context.Context, name string, options types.NetworkCreate) (types.NetworkCreateResponse, error) { - networkCreateRequest := types.NetworkCreateRequest{ - NetworkCreate: options, - Name: name, - } - var response types.NetworkCreateResponse - serverResp, err := cli.post(ctx, "/networks/create", nil, networkCreateRequest, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return response, err - } - - err = json.NewDecoder(serverResp.body).Decode(&response) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/network_disconnect.go b/vendor/github.com/docker/docker/client/network_disconnect.go deleted file mode 100644 index dd1567665..000000000 --- a/vendor/github.com/docker/docker/client/network_disconnect.go +++ /dev/null @@ -1,15 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - - "github.com/docker/docker/api/types" -) - -// NetworkDisconnect disconnects a container from an existent network in the docker host. -func (cli *Client) NetworkDisconnect(ctx context.Context, networkID, containerID string, force bool) error { - nd := types.NetworkDisconnect{Container: containerID, Force: force} - resp, err := cli.post(ctx, "/networks/"+networkID+"/disconnect", nil, nd, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/network_inspect.go b/vendor/github.com/docker/docker/client/network_inspect.go deleted file mode 100644 index 0f90e2bb9..000000000 --- a/vendor/github.com/docker/docker/client/network_inspect.go +++ /dev/null @@ -1,49 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "bytes" - "context" - "encoding/json" - "io" - "net/url" - - "github.com/docker/docker/api/types" -) - -// NetworkInspect returns the information for a specific network configured in the docker host. -func (cli *Client) NetworkInspect(ctx context.Context, networkID string, options types.NetworkInspectOptions) (types.NetworkResource, error) { - networkResource, _, err := cli.NetworkInspectWithRaw(ctx, networkID, options) - return networkResource, err -} - -// NetworkInspectWithRaw returns the information for a specific network configured in the docker host and its raw representation. -func (cli *Client) NetworkInspectWithRaw(ctx context.Context, networkID string, options types.NetworkInspectOptions) (types.NetworkResource, []byte, error) { - if networkID == "" { - return types.NetworkResource{}, nil, objectNotFoundError{object: "network", id: networkID} - } - var ( - networkResource types.NetworkResource - resp serverResponse - err error - ) - query := url.Values{} - if options.Verbose { - query.Set("verbose", "true") - } - if options.Scope != "" { - query.Set("scope", options.Scope) - } - resp, err = cli.get(ctx, "/networks/"+networkID, query, nil) - defer ensureReaderClosed(resp) - if err != nil { - return networkResource, nil, err - } - - body, err := io.ReadAll(resp.body) - if err != nil { - return networkResource, nil, err - } - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&networkResource) - return networkResource, body, err -} diff --git a/vendor/github.com/docker/docker/client/network_list.go b/vendor/github.com/docker/docker/client/network_list.go deleted file mode 100644 index ed2acb557..000000000 --- a/vendor/github.com/docker/docker/client/network_list.go +++ /dev/null @@ -1,32 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" -) - -// NetworkList returns the list of networks configured in the docker host. -func (cli *Client) NetworkList(ctx context.Context, options types.NetworkListOptions) ([]types.NetworkResource, error) { - query := url.Values{} - if options.Filters.Len() > 0 { - //nolint:staticcheck // ignore SA1019 for old code - filterJSON, err := filters.ToParamWithVersion(cli.version, options.Filters) - if err != nil { - return nil, err - } - - query.Set("filters", filterJSON) - } - var networkResources []types.NetworkResource - resp, err := cli.get(ctx, "/networks", query, nil) - defer ensureReaderClosed(resp) - if err != nil { - return networkResources, err - } - err = json.NewDecoder(resp.body).Decode(&networkResources) - return networkResources, err -} diff --git a/vendor/github.com/docker/docker/client/network_prune.go b/vendor/github.com/docker/docker/client/network_prune.go deleted file mode 100644 index cebb18821..000000000 --- a/vendor/github.com/docker/docker/client/network_prune.go +++ /dev/null @@ -1,36 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "fmt" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" -) - -// NetworksPrune requests the daemon to delete unused networks -func (cli *Client) NetworksPrune(ctx context.Context, pruneFilters filters.Args) (types.NetworksPruneReport, error) { - var report types.NetworksPruneReport - - if err := cli.NewVersionError("1.25", "network prune"); err != nil { - return report, err - } - - query, err := getFiltersQuery(pruneFilters) - if err != nil { - return report, err - } - - serverResp, err := cli.post(ctx, "/networks/prune", query, nil, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return report, err - } - - if err := json.NewDecoder(serverResp.body).Decode(&report); err != nil { - return report, fmt.Errorf("Error retrieving network prune report: %v", err) - } - - return report, nil -} diff --git a/vendor/github.com/docker/docker/client/network_remove.go b/vendor/github.com/docker/docker/client/network_remove.go deleted file mode 100644 index 9d6c6cef0..000000000 --- a/vendor/github.com/docker/docker/client/network_remove.go +++ /dev/null @@ -1,10 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import "context" - -// NetworkRemove removes an existent network from the docker host. -func (cli *Client) NetworkRemove(ctx context.Context, networkID string) error { - resp, err := cli.delete(ctx, "/networks/"+networkID, nil, nil) - defer ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/node_inspect.go b/vendor/github.com/docker/docker/client/node_inspect.go deleted file mode 100644 index 95ab9b1be..000000000 --- a/vendor/github.com/docker/docker/client/node_inspect.go +++ /dev/null @@ -1,32 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "bytes" - "context" - "encoding/json" - "io" - - "github.com/docker/docker/api/types/swarm" -) - -// NodeInspectWithRaw returns the node information. -func (cli *Client) NodeInspectWithRaw(ctx context.Context, nodeID string) (swarm.Node, []byte, error) { - if nodeID == "" { - return swarm.Node{}, nil, objectNotFoundError{object: "node", id: nodeID} - } - serverResp, err := cli.get(ctx, "/nodes/"+nodeID, nil, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return swarm.Node{}, nil, err - } - - body, err := io.ReadAll(serverResp.body) - if err != nil { - return swarm.Node{}, nil, err - } - - var response swarm.Node - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&response) - return response, body, err -} diff --git a/vendor/github.com/docker/docker/client/node_list.go b/vendor/github.com/docker/docker/client/node_list.go deleted file mode 100644 index c212906bc..000000000 --- a/vendor/github.com/docker/docker/client/node_list.go +++ /dev/null @@ -1,36 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/swarm" -) - -// NodeList returns the list of nodes. -func (cli *Client) NodeList(ctx context.Context, options types.NodeListOptions) ([]swarm.Node, error) { - query := url.Values{} - - if options.Filters.Len() > 0 { - filterJSON, err := filters.ToJSON(options.Filters) - - if err != nil { - return nil, err - } - - query.Set("filters", filterJSON) - } - - resp, err := cli.get(ctx, "/nodes", query, nil) - defer ensureReaderClosed(resp) - if err != nil { - return nil, err - } - - var nodes []swarm.Node - err = json.NewDecoder(resp.body).Decode(&nodes) - return nodes, err -} diff --git a/vendor/github.com/docker/docker/client/node_remove.go b/vendor/github.com/docker/docker/client/node_remove.go deleted file mode 100644 index e44436deb..000000000 --- a/vendor/github.com/docker/docker/client/node_remove.go +++ /dev/null @@ -1,20 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - - "github.com/docker/docker/api/types" -) - -// NodeRemove removes a Node. -func (cli *Client) NodeRemove(ctx context.Context, nodeID string, options types.NodeRemoveOptions) error { - query := url.Values{} - if options.Force { - query.Set("force", "1") - } - - resp, err := cli.delete(ctx, "/nodes/"+nodeID, query, nil) - defer ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/node_update.go b/vendor/github.com/docker/docker/client/node_update.go deleted file mode 100644 index 0d0fc3b78..000000000 --- a/vendor/github.com/docker/docker/client/node_update.go +++ /dev/null @@ -1,17 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - - "github.com/docker/docker/api/types/swarm" -) - -// NodeUpdate updates a Node. -func (cli *Client) NodeUpdate(ctx context.Context, nodeID string, version swarm.Version, node swarm.NodeSpec) error { - query := url.Values{} - query.Set("version", version.String()) - resp, err := cli.post(ctx, "/nodes/"+nodeID+"/update", query, node, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/options.go b/vendor/github.com/docker/docker/client/options.go deleted file mode 100644 index 099ad4184..000000000 --- a/vendor/github.com/docker/docker/client/options.go +++ /dev/null @@ -1,210 +0,0 @@ -package client - -import ( - "context" - "net" - "net/http" - "os" - "path/filepath" - "time" - - "github.com/docker/go-connections/sockets" - "github.com/docker/go-connections/tlsconfig" - "github.com/pkg/errors" -) - -// Opt is a configuration option to initialize a client -type Opt func(*Client) error - -// FromEnv configures the client with values from environment variables. -// -// FromEnv uses the following environment variables: -// -// DOCKER_HOST (EnvOverrideHost) to set the URL to the docker server. -// -// DOCKER_API_VERSION (EnvOverrideAPIVersion) to set the version of the API to -// use, leave empty for latest. -// -// DOCKER_CERT_PATH (EnvOverrideCertPath) to specify the directory from which to -// load the TLS certificates (ca.pem, cert.pem, key.pem). -// -// DOCKER_TLS_VERIFY (EnvTLSVerify) to enable or disable TLS verification (off by -// default). -func FromEnv(c *Client) error { - ops := []Opt{ - WithTLSClientConfigFromEnv(), - WithHostFromEnv(), - WithVersionFromEnv(), - } - for _, op := range ops { - if err := op(c); err != nil { - return err - } - } - return nil -} - -// WithDialContext applies the dialer to the client transport. This can be -// used to set the Timeout and KeepAlive settings of the client. -func WithDialContext(dialContext func(ctx context.Context, network, addr string) (net.Conn, error)) Opt { - return func(c *Client) error { - if transport, ok := c.client.Transport.(*http.Transport); ok { - transport.DialContext = dialContext - return nil - } - return errors.Errorf("cannot apply dialer to transport: %T", c.client.Transport) - } -} - -// WithHost overrides the client host with the specified one. -func WithHost(host string) Opt { - return func(c *Client) error { - hostURL, err := ParseHostURL(host) - if err != nil { - return err - } - c.host = host - c.proto = hostURL.Scheme - c.addr = hostURL.Host - c.basePath = hostURL.Path - if transport, ok := c.client.Transport.(*http.Transport); ok { - return sockets.ConfigureTransport(transport, c.proto, c.addr) - } - return errors.Errorf("cannot apply host to transport: %T", c.client.Transport) - } -} - -// WithHostFromEnv overrides the client host with the host specified in the -// DOCKER_HOST (EnvOverrideHost) environment variable. If DOCKER_HOST is not set, -// or set to an empty value, the host is not modified. -func WithHostFromEnv() Opt { - return func(c *Client) error { - if host := os.Getenv(EnvOverrideHost); host != "" { - return WithHost(host)(c) - } - return nil - } -} - -// WithHTTPClient overrides the client http client with the specified one -func WithHTTPClient(client *http.Client) Opt { - return func(c *Client) error { - if client != nil { - c.client = client - } - return nil - } -} - -// WithTimeout configures the time limit for requests made by the HTTP client -func WithTimeout(timeout time.Duration) Opt { - return func(c *Client) error { - c.client.Timeout = timeout - return nil - } -} - -// WithHTTPHeaders overrides the client default http headers -func WithHTTPHeaders(headers map[string]string) Opt { - return func(c *Client) error { - c.customHTTPHeaders = headers - return nil - } -} - -// WithScheme overrides the client scheme with the specified one -func WithScheme(scheme string) Opt { - return func(c *Client) error { - c.scheme = scheme - return nil - } -} - -// WithTLSClientConfig applies a tls config to the client transport. -func WithTLSClientConfig(cacertPath, certPath, keyPath string) Opt { - return func(c *Client) error { - opts := tlsconfig.Options{ - CAFile: cacertPath, - CertFile: certPath, - KeyFile: keyPath, - ExclusiveRootPools: true, - } - config, err := tlsconfig.Client(opts) - if err != nil { - return errors.Wrap(err, "failed to create tls config") - } - if transport, ok := c.client.Transport.(*http.Transport); ok { - transport.TLSClientConfig = config - return nil - } - return errors.Errorf("cannot apply tls config to transport: %T", c.client.Transport) - } -} - -// WithTLSClientConfigFromEnv configures the client's TLS settings with the -// settings in the DOCKER_CERT_PATH and DOCKER_TLS_VERIFY environment variables. -// If DOCKER_CERT_PATH is not set or empty, TLS configuration is not modified. -// -// WithTLSClientConfigFromEnv uses the following environment variables: -// -// DOCKER_CERT_PATH (EnvOverrideCertPath) to specify the directory from which to -// load the TLS certificates (ca.pem, cert.pem, key.pem). -// -// DOCKER_TLS_VERIFY (EnvTLSVerify) to enable or disable TLS verification (off by -// default). -func WithTLSClientConfigFromEnv() Opt { - return func(c *Client) error { - dockerCertPath := os.Getenv(EnvOverrideCertPath) - if dockerCertPath == "" { - return nil - } - options := tlsconfig.Options{ - CAFile: filepath.Join(dockerCertPath, "ca.pem"), - CertFile: filepath.Join(dockerCertPath, "cert.pem"), - KeyFile: filepath.Join(dockerCertPath, "key.pem"), - InsecureSkipVerify: os.Getenv(EnvTLSVerify) == "", - } - tlsc, err := tlsconfig.Client(options) - if err != nil { - return err - } - - c.client = &http.Client{ - Transport: &http.Transport{TLSClientConfig: tlsc}, - CheckRedirect: CheckRedirect, - } - return nil - } -} - -// WithVersion overrides the client version with the specified one. If an empty -// version is specified, the value will be ignored to allow version negotiation. -func WithVersion(version string) Opt { - return func(c *Client) error { - if version != "" { - c.version = version - c.manualOverride = true - } - return nil - } -} - -// WithVersionFromEnv overrides the client version with the version specified in -// the DOCKER_API_VERSION environment variable. If DOCKER_API_VERSION is not set, -// the version is not modified. -func WithVersionFromEnv() Opt { - return func(c *Client) error { - return WithVersion(os.Getenv(EnvOverrideAPIVersion))(c) - } -} - -// WithAPIVersionNegotiation enables automatic API version negotiation for the client. -// With this option enabled, the client automatically negotiates the API version -// to use when making requests. API version negotiation is performed on the first -// request; subsequent requests will not re-negotiate. -func WithAPIVersionNegotiation() Opt { - return func(c *Client) error { - c.negotiateVersion = true - return nil - } -} diff --git a/vendor/github.com/docker/docker/client/ping.go b/vendor/github.com/docker/docker/client/ping.go deleted file mode 100644 index 347ae71e0..000000000 --- a/vendor/github.com/docker/docker/client/ping.go +++ /dev/null @@ -1,75 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/http" - "path" - "strings" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/swarm" - "github.com/docker/docker/errdefs" -) - -// Ping pings the server and returns the value of the "Docker-Experimental", -// "Builder-Version", "OS-Type" & "API-Version" headers. It attempts to use -// a HEAD request on the endpoint, but falls back to GET if HEAD is not supported -// by the daemon. -func (cli *Client) Ping(ctx context.Context) (types.Ping, error) { - var ping types.Ping - - // Using cli.buildRequest() + cli.doRequest() instead of cli.sendRequest() - // because ping requests are used during API version negotiation, so we want - // to hit the non-versioned /_ping endpoint, not /v1.xx/_ping - req, err := cli.buildRequest(http.MethodHead, path.Join(cli.basePath, "/_ping"), nil, nil) - if err != nil { - return ping, err - } - serverResp, err := cli.doRequest(ctx, req) - if err == nil { - defer ensureReaderClosed(serverResp) - switch serverResp.statusCode { - case http.StatusOK, http.StatusInternalServerError: - // Server handled the request, so parse the response - return parsePingResponse(cli, serverResp) - } - } else if IsErrConnectionFailed(err) { - return ping, err - } - - req, err = cli.buildRequest(http.MethodGet, path.Join(cli.basePath, "/_ping"), nil, nil) - if err != nil { - return ping, err - } - serverResp, err = cli.doRequest(ctx, req) - defer ensureReaderClosed(serverResp) - if err != nil { - return ping, err - } - return parsePingResponse(cli, serverResp) -} - -func parsePingResponse(cli *Client, resp serverResponse) (types.Ping, error) { - var ping types.Ping - if resp.header == nil { - err := cli.checkResponseErr(resp) - return ping, errdefs.FromStatusCode(err, resp.statusCode) - } - ping.APIVersion = resp.header.Get("API-Version") - ping.OSType = resp.header.Get("OSType") - if resp.header.Get("Docker-Experimental") == "true" { - ping.Experimental = true - } - if bv := resp.header.Get("Builder-Version"); bv != "" { - ping.BuilderVersion = types.BuilderVersion(bv) - } - if si := resp.header.Get("Swarm"); si != "" { - state, role, _ := strings.Cut(si, "/") - ping.SwarmStatus = &swarm.Status{ - NodeState: swarm.LocalNodeState(state), - ControlAvailable: role == "manager", - } - } - err := cli.checkResponseErr(resp) - return ping, errdefs.FromStatusCode(err, resp.statusCode) -} diff --git a/vendor/github.com/docker/docker/client/plugin_create.go b/vendor/github.com/docker/docker/client/plugin_create.go deleted file mode 100644 index b95dbaf68..000000000 --- a/vendor/github.com/docker/docker/client/plugin_create.go +++ /dev/null @@ -1,23 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" - "net/http" - "net/url" - - "github.com/docker/docker/api/types" -) - -// PluginCreate creates a plugin -func (cli *Client) PluginCreate(ctx context.Context, createContext io.Reader, createOptions types.PluginCreateOptions) error { - headers := http.Header(make(map[string][]string)) - headers.Set("Content-Type", "application/x-tar") - - query := url.Values{} - query.Set("name", createOptions.RepoName) - - resp, err := cli.postRaw(ctx, "/plugins/create", query, createContext, headers) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/plugin_disable.go b/vendor/github.com/docker/docker/client/plugin_disable.go deleted file mode 100644 index 01f6574f9..000000000 --- a/vendor/github.com/docker/docker/client/plugin_disable.go +++ /dev/null @@ -1,19 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - - "github.com/docker/docker/api/types" -) - -// PluginDisable disables a plugin -func (cli *Client) PluginDisable(ctx context.Context, name string, options types.PluginDisableOptions) error { - query := url.Values{} - if options.Force { - query.Set("force", "1") - } - resp, err := cli.post(ctx, "/plugins/"+name+"/disable", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/plugin_enable.go b/vendor/github.com/docker/docker/client/plugin_enable.go deleted file mode 100644 index 736da48bd..000000000 --- a/vendor/github.com/docker/docker/client/plugin_enable.go +++ /dev/null @@ -1,19 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - "strconv" - - "github.com/docker/docker/api/types" -) - -// PluginEnable enables a plugin -func (cli *Client) PluginEnable(ctx context.Context, name string, options types.PluginEnableOptions) error { - query := url.Values{} - query.Set("timeout", strconv.Itoa(options.Timeout)) - - resp, err := cli.post(ctx, "/plugins/"+name+"/enable", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/plugin_inspect.go b/vendor/github.com/docker/docker/client/plugin_inspect.go deleted file mode 100644 index f09e46066..000000000 --- a/vendor/github.com/docker/docker/client/plugin_inspect.go +++ /dev/null @@ -1,31 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "bytes" - "context" - "encoding/json" - "io" - - "github.com/docker/docker/api/types" -) - -// PluginInspectWithRaw inspects an existing plugin -func (cli *Client) PluginInspectWithRaw(ctx context.Context, name string) (*types.Plugin, []byte, error) { - if name == "" { - return nil, nil, objectNotFoundError{object: "plugin", id: name} - } - resp, err := cli.get(ctx, "/plugins/"+name+"/json", nil, nil) - defer ensureReaderClosed(resp) - if err != nil { - return nil, nil, err - } - - body, err := io.ReadAll(resp.body) - if err != nil { - return nil, nil, err - } - var p types.Plugin - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&p) - return &p, body, err -} diff --git a/vendor/github.com/docker/docker/client/plugin_install.go b/vendor/github.com/docker/docker/client/plugin_install.go deleted file mode 100644 index 3a740ec4f..000000000 --- a/vendor/github.com/docker/docker/client/plugin_install.go +++ /dev/null @@ -1,114 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "io" - "net/url" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/registry" - "github.com/docker/docker/errdefs" - "github.com/pkg/errors" -) - -// PluginInstall installs a plugin -func (cli *Client) PluginInstall(ctx context.Context, name string, options types.PluginInstallOptions) (rc io.ReadCloser, err error) { - query := url.Values{} - if _, err := reference.ParseNormalizedNamed(options.RemoteRef); err != nil { - return nil, errors.Wrap(err, "invalid remote reference") - } - query.Set("remote", options.RemoteRef) - - privileges, err := cli.checkPluginPermissions(ctx, query, options) - if err != nil { - return nil, err - } - - // set name for plugin pull, if empty should default to remote reference - query.Set("name", name) - - resp, err := cli.tryPluginPull(ctx, query, privileges, options.RegistryAuth) - if err != nil { - return nil, err - } - - name = resp.header.Get("Docker-Plugin-Name") - - pr, pw := io.Pipe() - go func() { // todo: the client should probably be designed more around the actual api - _, err := io.Copy(pw, resp.body) - if err != nil { - pw.CloseWithError(err) - return - } - defer func() { - if err != nil { - delResp, _ := cli.delete(ctx, "/plugins/"+name, nil, nil) - ensureReaderClosed(delResp) - } - }() - if len(options.Args) > 0 { - if err := cli.PluginSet(ctx, name, options.Args); err != nil { - pw.CloseWithError(err) - return - } - } - - if options.Disabled { - pw.Close() - return - } - - enableErr := cli.PluginEnable(ctx, name, types.PluginEnableOptions{Timeout: 0}) - pw.CloseWithError(enableErr) - }() - return pr, nil -} - -func (cli *Client) tryPluginPrivileges(ctx context.Context, query url.Values, registryAuth string) (serverResponse, error) { - headers := map[string][]string{registry.AuthHeader: {registryAuth}} - return cli.get(ctx, "/plugins/privileges", query, headers) -} - -func (cli *Client) tryPluginPull(ctx context.Context, query url.Values, privileges types.PluginPrivileges, registryAuth string) (serverResponse, error) { - headers := map[string][]string{registry.AuthHeader: {registryAuth}} - return cli.post(ctx, "/plugins/pull", query, privileges, headers) -} - -func (cli *Client) checkPluginPermissions(ctx context.Context, query url.Values, options types.PluginInstallOptions) (types.PluginPrivileges, error) { - resp, err := cli.tryPluginPrivileges(ctx, query, options.RegistryAuth) - if errdefs.IsUnauthorized(err) && options.PrivilegeFunc != nil { - // todo: do inspect before to check existing name before checking privileges - newAuthHeader, privilegeErr := options.PrivilegeFunc() - if privilegeErr != nil { - ensureReaderClosed(resp) - return nil, privilegeErr - } - options.RegistryAuth = newAuthHeader - resp, err = cli.tryPluginPrivileges(ctx, query, options.RegistryAuth) - } - if err != nil { - ensureReaderClosed(resp) - return nil, err - } - - var privileges types.PluginPrivileges - if err := json.NewDecoder(resp.body).Decode(&privileges); err != nil { - ensureReaderClosed(resp) - return nil, err - } - ensureReaderClosed(resp) - - if !options.AcceptAllPermissions && options.AcceptPermissionsFunc != nil && len(privileges) > 0 { - accept, err := options.AcceptPermissionsFunc(privileges) - if err != nil { - return nil, err - } - if !accept { - return nil, errors.Errorf("permission denied while installing plugin %s", options.RemoteRef) - } - } - return privileges, nil -} diff --git a/vendor/github.com/docker/docker/client/plugin_list.go b/vendor/github.com/docker/docker/client/plugin_list.go deleted file mode 100644 index 2091a054d..000000000 --- a/vendor/github.com/docker/docker/client/plugin_list.go +++ /dev/null @@ -1,33 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" -) - -// PluginList returns the installed plugins -func (cli *Client) PluginList(ctx context.Context, filter filters.Args) (types.PluginsListResponse, error) { - var plugins types.PluginsListResponse - query := url.Values{} - - if filter.Len() > 0 { - //nolint:staticcheck // ignore SA1019 for old code - filterJSON, err := filters.ToParamWithVersion(cli.version, filter) - if err != nil { - return plugins, err - } - query.Set("filters", filterJSON) - } - resp, err := cli.get(ctx, "/plugins", query, nil) - defer ensureReaderClosed(resp) - if err != nil { - return plugins, err - } - - err = json.NewDecoder(resp.body).Decode(&plugins) - return plugins, err -} diff --git a/vendor/github.com/docker/docker/client/plugin_push.go b/vendor/github.com/docker/docker/client/plugin_push.go deleted file mode 100644 index 18f9754c4..000000000 --- a/vendor/github.com/docker/docker/client/plugin_push.go +++ /dev/null @@ -1,18 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" - - "github.com/docker/docker/api/types/registry" -) - -// PluginPush pushes a plugin to a registry -func (cli *Client) PluginPush(ctx context.Context, name string, registryAuth string) (io.ReadCloser, error) { - headers := map[string][]string{registry.AuthHeader: {registryAuth}} - resp, err := cli.post(ctx, "/plugins/"+name+"/push", nil, nil, headers) - if err != nil { - return nil, err - } - return resp.body, nil -} diff --git a/vendor/github.com/docker/docker/client/plugin_remove.go b/vendor/github.com/docker/docker/client/plugin_remove.go deleted file mode 100644 index 4cd66958c..000000000 --- a/vendor/github.com/docker/docker/client/plugin_remove.go +++ /dev/null @@ -1,20 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - - "github.com/docker/docker/api/types" -) - -// PluginRemove removes a plugin -func (cli *Client) PluginRemove(ctx context.Context, name string, options types.PluginRemoveOptions) error { - query := url.Values{} - if options.Force { - query.Set("force", "1") - } - - resp, err := cli.delete(ctx, "/plugins/"+name, query, nil) - defer ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/plugin_set.go b/vendor/github.com/docker/docker/client/plugin_set.go deleted file mode 100644 index dcf5752ca..000000000 --- a/vendor/github.com/docker/docker/client/plugin_set.go +++ /dev/null @@ -1,12 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" -) - -// PluginSet modifies settings for an existing plugin -func (cli *Client) PluginSet(ctx context.Context, name string, args []string) error { - resp, err := cli.post(ctx, "/plugins/"+name+"/set", nil, args, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/plugin_upgrade.go b/vendor/github.com/docker/docker/client/plugin_upgrade.go deleted file mode 100644 index 995d1fd2c..000000000 --- a/vendor/github.com/docker/docker/client/plugin_upgrade.go +++ /dev/null @@ -1,40 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" - "net/url" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/registry" - "github.com/pkg/errors" -) - -// PluginUpgrade upgrades a plugin -func (cli *Client) PluginUpgrade(ctx context.Context, name string, options types.PluginInstallOptions) (rc io.ReadCloser, err error) { - if err := cli.NewVersionError("1.26", "plugin upgrade"); err != nil { - return nil, err - } - query := url.Values{} - if _, err := reference.ParseNormalizedNamed(options.RemoteRef); err != nil { - return nil, errors.Wrap(err, "invalid remote reference") - } - query.Set("remote", options.RemoteRef) - - privileges, err := cli.checkPluginPermissions(ctx, query, options) - if err != nil { - return nil, err - } - - resp, err := cli.tryPluginUpgrade(ctx, query, privileges, name, options.RegistryAuth) - if err != nil { - return nil, err - } - return resp.body, nil -} - -func (cli *Client) tryPluginUpgrade(ctx context.Context, query url.Values, privileges types.PluginPrivileges, name, registryAuth string) (serverResponse, error) { - headers := map[string][]string{registry.AuthHeader: {registryAuth}} - return cli.post(ctx, "/plugins/"+name+"/upgrade", query, privileges, headers) -} diff --git a/vendor/github.com/docker/docker/client/request.go b/vendor/github.com/docker/docker/client/request.go deleted file mode 100644 index bcedcf3bd..000000000 --- a/vendor/github.com/docker/docker/client/request.go +++ /dev/null @@ -1,275 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "net" - "net/http" - "net/url" - "os" - "strings" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/versions" - "github.com/docker/docker/errdefs" - "github.com/pkg/errors" -) - -// serverResponse is a wrapper for http API responses. -type serverResponse struct { - body io.ReadCloser - header http.Header - statusCode int - reqURL *url.URL -} - -// head sends an http request to the docker API using the method HEAD. -func (cli *Client) head(ctx context.Context, path string, query url.Values, headers map[string][]string) (serverResponse, error) { - return cli.sendRequest(ctx, http.MethodHead, path, query, nil, headers) -} - -// get sends an http request to the docker API using the method GET with a specific Go context. -func (cli *Client) get(ctx context.Context, path string, query url.Values, headers map[string][]string) (serverResponse, error) { - return cli.sendRequest(ctx, http.MethodGet, path, query, nil, headers) -} - -// post sends an http request to the docker API using the method POST with a specific Go context. -func (cli *Client) post(ctx context.Context, path string, query url.Values, obj interface{}, headers map[string][]string) (serverResponse, error) { - body, headers, err := encodeBody(obj, headers) - if err != nil { - return serverResponse{}, err - } - return cli.sendRequest(ctx, http.MethodPost, path, query, body, headers) -} - -func (cli *Client) postRaw(ctx context.Context, path string, query url.Values, body io.Reader, headers map[string][]string) (serverResponse, error) { - return cli.sendRequest(ctx, http.MethodPost, path, query, body, headers) -} - -func (cli *Client) put(ctx context.Context, path string, query url.Values, obj interface{}, headers map[string][]string) (serverResponse, error) { - body, headers, err := encodeBody(obj, headers) - if err != nil { - return serverResponse{}, err - } - return cli.sendRequest(ctx, http.MethodPut, path, query, body, headers) -} - -// putRaw sends an http request to the docker API using the method PUT. -func (cli *Client) putRaw(ctx context.Context, path string, query url.Values, body io.Reader, headers map[string][]string) (serverResponse, error) { - return cli.sendRequest(ctx, http.MethodPut, path, query, body, headers) -} - -// delete sends an http request to the docker API using the method DELETE. -func (cli *Client) delete(ctx context.Context, path string, query url.Values, headers map[string][]string) (serverResponse, error) { - return cli.sendRequest(ctx, http.MethodDelete, path, query, nil, headers) -} - -type headers map[string][]string - -func encodeBody(obj interface{}, headers headers) (io.Reader, headers, error) { - if obj == nil { - return nil, headers, nil - } - - body, err := encodeData(obj) - if err != nil { - return nil, headers, err - } - if headers == nil { - headers = make(map[string][]string) - } - headers["Content-Type"] = []string{"application/json"} - return body, headers, nil -} - -func (cli *Client) buildRequest(method, path string, body io.Reader, headers headers) (*http.Request, error) { - expectedPayload := (method == http.MethodPost || method == http.MethodPut) - if expectedPayload && body == nil { - body = bytes.NewReader([]byte{}) - } - - req, err := http.NewRequest(method, path, body) - if err != nil { - return nil, err - } - req = cli.addHeaders(req, headers) - req.URL.Scheme = cli.scheme - req.URL.Host = cli.addr - - if cli.proto == "unix" || cli.proto == "npipe" { - // Override host header for non-tcp connections. - req.Host = DummyHost - } - - if expectedPayload && req.Header.Get("Content-Type") == "" { - req.Header.Set("Content-Type", "text/plain") - } - return req, nil -} - -func (cli *Client) sendRequest(ctx context.Context, method, path string, query url.Values, body io.Reader, headers headers) (serverResponse, error) { - req, err := cli.buildRequest(method, cli.getAPIPath(ctx, path, query), body, headers) - if err != nil { - return serverResponse{}, err - } - - resp, err := cli.doRequest(ctx, req) - switch { - case errors.Is(err, context.Canceled): - return serverResponse{}, errdefs.Cancelled(err) - case errors.Is(err, context.DeadlineExceeded): - return serverResponse{}, errdefs.Deadline(err) - case err == nil: - err = cli.checkResponseErr(resp) - } - return resp, errdefs.FromStatusCode(err, resp.statusCode) -} - -func (cli *Client) doRequest(ctx context.Context, req *http.Request) (serverResponse, error) { - serverResp := serverResponse{statusCode: -1, reqURL: req.URL} - - req = req.WithContext(ctx) - resp, err := cli.client.Do(req) - if err != nil { - if cli.scheme != "https" && strings.Contains(err.Error(), "malformed HTTP response") { - return serverResp, fmt.Errorf("%v.\n* Are you trying to connect to a TLS-enabled daemon without TLS?", err) - } - - if cli.scheme == "https" && strings.Contains(err.Error(), "bad certificate") { - return serverResp, errors.Wrap(err, "the server probably has client authentication (--tlsverify) enabled; check your TLS client certification settings") - } - - // Don't decorate context sentinel errors; users may be comparing to - // them directly. - if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { - return serverResp, err - } - - if nErr, ok := err.(*url.Error); ok { - if nErr, ok := nErr.Err.(*net.OpError); ok { - if os.IsPermission(nErr.Err) { - return serverResp, errors.Wrapf(err, "permission denied while trying to connect to the Docker daemon socket at %v", cli.host) - } - } - } - - if err, ok := err.(net.Error); ok { - if err.Timeout() { - return serverResp, ErrorConnectionFailed(cli.host) - } - if strings.Contains(err.Error(), "connection refused") || strings.Contains(err.Error(), "dial unix") { - return serverResp, ErrorConnectionFailed(cli.host) - } - } - - // Although there's not a strongly typed error for this in go-winio, - // lots of people are using the default configuration for the docker - // daemon on Windows where the daemon is listening on a named pipe - // `//./pipe/docker_engine, and the client must be running elevated. - // Give users a clue rather than the not-overly useful message - // such as `error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.26/info: - // open //./pipe/docker_engine: The system cannot find the file specified.`. - // Note we can't string compare "The system cannot find the file specified" as - // this is localised - for example in French the error would be - // `open //./pipe/docker_engine: Le fichier spécifié est introuvable.` - if strings.Contains(err.Error(), `open //./pipe/docker_engine`) { - // Checks if client is running with elevated privileges - if f, elevatedErr := os.Open("\\\\.\\PHYSICALDRIVE0"); elevatedErr == nil { - err = errors.Wrap(err, "in the default daemon configuration on Windows, the docker client must be run with elevated privileges to connect") - } else { - f.Close() - err = errors.Wrap(err, "this error may indicate that the docker daemon is not running") - } - } - - return serverResp, errors.Wrap(err, "error during connect") - } - - if resp != nil { - serverResp.statusCode = resp.StatusCode - serverResp.body = resp.Body - serverResp.header = resp.Header - } - return serverResp, nil -} - -func (cli *Client) checkResponseErr(serverResp serverResponse) error { - if serverResp.statusCode >= 200 && serverResp.statusCode < 400 { - return nil - } - - var body []byte - var err error - if serverResp.body != nil { - bodyMax := 1 * 1024 * 1024 // 1 MiB - bodyR := &io.LimitedReader{ - R: serverResp.body, - N: int64(bodyMax), - } - body, err = io.ReadAll(bodyR) - if err != nil { - return err - } - if bodyR.N == 0 { - return fmt.Errorf("request returned %s with a message (> %d bytes) for API route and version %s, check if the server supports the requested API version", http.StatusText(serverResp.statusCode), bodyMax, serverResp.reqURL) - } - } - if len(body) == 0 { - return fmt.Errorf("request returned %s for API route and version %s, check if the server supports the requested API version", http.StatusText(serverResp.statusCode), serverResp.reqURL) - } - - var ct string - if serverResp.header != nil { - ct = serverResp.header.Get("Content-Type") - } - - var errorMessage string - if (cli.version == "" || versions.GreaterThan(cli.version, "1.23")) && ct == "application/json" { - var errorResponse types.ErrorResponse - if err := json.Unmarshal(body, &errorResponse); err != nil { - return errors.Wrap(err, "Error reading JSON") - } - errorMessage = strings.TrimSpace(errorResponse.Message) - } else { - errorMessage = strings.TrimSpace(string(body)) - } - - return errors.Wrap(errors.New(errorMessage), "Error response from daemon") -} - -func (cli *Client) addHeaders(req *http.Request, headers headers) *http.Request { - // Add CLI Config's HTTP Headers BEFORE we set the Docker headers - // then the user can't change OUR headers - for k, v := range cli.customHTTPHeaders { - if versions.LessThan(cli.version, "1.25") && http.CanonicalHeaderKey(k) == "User-Agent" { - continue - } - req.Header.Set(k, v) - } - - for k, v := range headers { - req.Header[http.CanonicalHeaderKey(k)] = v - } - return req -} - -func encodeData(data interface{}) (*bytes.Buffer, error) { - params := bytes.NewBuffer(nil) - if data != nil { - if err := json.NewEncoder(params).Encode(data); err != nil { - return nil, err - } - } - return params, nil -} - -func ensureReaderClosed(response serverResponse) { - if response.body != nil { - // Drain up to 512 bytes and close the body to let the Transport reuse the connection - io.CopyN(io.Discard, response.body, 512) - response.body.Close() - } -} diff --git a/vendor/github.com/docker/docker/client/secret_create.go b/vendor/github.com/docker/docker/client/secret_create.go deleted file mode 100644 index c65d38a19..000000000 --- a/vendor/github.com/docker/docker/client/secret_create.go +++ /dev/null @@ -1,25 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/swarm" -) - -// SecretCreate creates a new secret. -func (cli *Client) SecretCreate(ctx context.Context, secret swarm.SecretSpec) (types.SecretCreateResponse, error) { - var response types.SecretCreateResponse - if err := cli.NewVersionError("1.25", "secret create"); err != nil { - return response, err - } - resp, err := cli.post(ctx, "/secrets/create", nil, secret, nil) - defer ensureReaderClosed(resp) - if err != nil { - return response, err - } - - err = json.NewDecoder(resp.body).Decode(&response) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/secret_inspect.go b/vendor/github.com/docker/docker/client/secret_inspect.go deleted file mode 100644 index 5906874b1..000000000 --- a/vendor/github.com/docker/docker/client/secret_inspect.go +++ /dev/null @@ -1,36 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "bytes" - "context" - "encoding/json" - "io" - - "github.com/docker/docker/api/types/swarm" -) - -// SecretInspectWithRaw returns the secret information with raw data -func (cli *Client) SecretInspectWithRaw(ctx context.Context, id string) (swarm.Secret, []byte, error) { - if err := cli.NewVersionError("1.25", "secret inspect"); err != nil { - return swarm.Secret{}, nil, err - } - if id == "" { - return swarm.Secret{}, nil, objectNotFoundError{object: "secret", id: id} - } - resp, err := cli.get(ctx, "/secrets/"+id, nil, nil) - defer ensureReaderClosed(resp) - if err != nil { - return swarm.Secret{}, nil, err - } - - body, err := io.ReadAll(resp.body) - if err != nil { - return swarm.Secret{}, nil, err - } - - var secret swarm.Secret - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&secret) - - return secret, body, err -} diff --git a/vendor/github.com/docker/docker/client/secret_list.go b/vendor/github.com/docker/docker/client/secret_list.go deleted file mode 100644 index a0289c9f4..000000000 --- a/vendor/github.com/docker/docker/client/secret_list.go +++ /dev/null @@ -1,38 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/swarm" -) - -// SecretList returns the list of secrets. -func (cli *Client) SecretList(ctx context.Context, options types.SecretListOptions) ([]swarm.Secret, error) { - if err := cli.NewVersionError("1.25", "secret list"); err != nil { - return nil, err - } - query := url.Values{} - - if options.Filters.Len() > 0 { - filterJSON, err := filters.ToJSON(options.Filters) - if err != nil { - return nil, err - } - - query.Set("filters", filterJSON) - } - - resp, err := cli.get(ctx, "/secrets", query, nil) - defer ensureReaderClosed(resp) - if err != nil { - return nil, err - } - - var secrets []swarm.Secret - err = json.NewDecoder(resp.body).Decode(&secrets) - return secrets, err -} diff --git a/vendor/github.com/docker/docker/client/secret_remove.go b/vendor/github.com/docker/docker/client/secret_remove.go deleted file mode 100644 index f47f68b6e..000000000 --- a/vendor/github.com/docker/docker/client/secret_remove.go +++ /dev/null @@ -1,13 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import "context" - -// SecretRemove removes a secret. -func (cli *Client) SecretRemove(ctx context.Context, id string) error { - if err := cli.NewVersionError("1.25", "secret remove"); err != nil { - return err - } - resp, err := cli.delete(ctx, "/secrets/"+id, nil, nil) - defer ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/secret_update.go b/vendor/github.com/docker/docker/client/secret_update.go deleted file mode 100644 index 2e939e8ce..000000000 --- a/vendor/github.com/docker/docker/client/secret_update.go +++ /dev/null @@ -1,20 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - - "github.com/docker/docker/api/types/swarm" -) - -// SecretUpdate attempts to update a secret. -func (cli *Client) SecretUpdate(ctx context.Context, id string, version swarm.Version, secret swarm.SecretSpec) error { - if err := cli.NewVersionError("1.25", "secret update"); err != nil { - return err - } - query := url.Values{} - query.Set("version", version.String()) - resp, err := cli.post(ctx, "/secrets/"+id+"/update", query, secret, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/service_create.go b/vendor/github.com/docker/docker/client/service_create.go deleted file mode 100644 index b6065b8ee..000000000 --- a/vendor/github.com/docker/docker/client/service_create.go +++ /dev/null @@ -1,179 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "fmt" - "strings" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/registry" - "github.com/docker/docker/api/types/swarm" - "github.com/opencontainers/go-digest" - "github.com/pkg/errors" -) - -// ServiceCreate creates a new service. -func (cli *Client) ServiceCreate(ctx context.Context, service swarm.ServiceSpec, options types.ServiceCreateOptions) (types.ServiceCreateResponse, error) { - var response types.ServiceCreateResponse - headers := map[string][]string{ - "version": {cli.version}, - } - - if options.EncodedRegistryAuth != "" { - headers[registry.AuthHeader] = []string{options.EncodedRegistryAuth} - } - - // Make sure containerSpec is not nil when no runtime is set or the runtime is set to container - if service.TaskTemplate.ContainerSpec == nil && (service.TaskTemplate.Runtime == "" || service.TaskTemplate.Runtime == swarm.RuntimeContainer) { - service.TaskTemplate.ContainerSpec = &swarm.ContainerSpec{} - } - - if err := validateServiceSpec(service); err != nil { - return response, err - } - - // ensure that the image is tagged - var resolveWarning string - switch { - case service.TaskTemplate.ContainerSpec != nil: - if taggedImg := imageWithTagString(service.TaskTemplate.ContainerSpec.Image); taggedImg != "" { - service.TaskTemplate.ContainerSpec.Image = taggedImg - } - if options.QueryRegistry { - resolveWarning = resolveContainerSpecImage(ctx, cli, &service.TaskTemplate, options.EncodedRegistryAuth) - } - case service.TaskTemplate.PluginSpec != nil: - if taggedImg := imageWithTagString(service.TaskTemplate.PluginSpec.Remote); taggedImg != "" { - service.TaskTemplate.PluginSpec.Remote = taggedImg - } - if options.QueryRegistry { - resolveWarning = resolvePluginSpecRemote(ctx, cli, &service.TaskTemplate, options.EncodedRegistryAuth) - } - } - - resp, err := cli.post(ctx, "/services/create", nil, service, headers) - defer ensureReaderClosed(resp) - if err != nil { - return response, err - } - - err = json.NewDecoder(resp.body).Decode(&response) - if resolveWarning != "" { - response.Warnings = append(response.Warnings, resolveWarning) - } - - return response, err -} - -func resolveContainerSpecImage(ctx context.Context, cli DistributionAPIClient, taskSpec *swarm.TaskSpec, encodedAuth string) string { - var warning string - if img, imgPlatforms, err := imageDigestAndPlatforms(ctx, cli, taskSpec.ContainerSpec.Image, encodedAuth); err != nil { - warning = digestWarning(taskSpec.ContainerSpec.Image) - } else { - taskSpec.ContainerSpec.Image = img - if len(imgPlatforms) > 0 { - if taskSpec.Placement == nil { - taskSpec.Placement = &swarm.Placement{} - } - taskSpec.Placement.Platforms = imgPlatforms - } - } - return warning -} - -func resolvePluginSpecRemote(ctx context.Context, cli DistributionAPIClient, taskSpec *swarm.TaskSpec, encodedAuth string) string { - var warning string - if img, imgPlatforms, err := imageDigestAndPlatforms(ctx, cli, taskSpec.PluginSpec.Remote, encodedAuth); err != nil { - warning = digestWarning(taskSpec.PluginSpec.Remote) - } else { - taskSpec.PluginSpec.Remote = img - if len(imgPlatforms) > 0 { - if taskSpec.Placement == nil { - taskSpec.Placement = &swarm.Placement{} - } - taskSpec.Placement.Platforms = imgPlatforms - } - } - return warning -} - -func imageDigestAndPlatforms(ctx context.Context, cli DistributionAPIClient, image, encodedAuth string) (string, []swarm.Platform, error) { - distributionInspect, err := cli.DistributionInspect(ctx, image, encodedAuth) - var platforms []swarm.Platform - if err != nil { - return "", nil, err - } - - imageWithDigest := imageWithDigestString(image, distributionInspect.Descriptor.Digest) - - if len(distributionInspect.Platforms) > 0 { - platforms = make([]swarm.Platform, 0, len(distributionInspect.Platforms)) - for _, p := range distributionInspect.Platforms { - // clear architecture field for arm. This is a temporary patch to address - // https://github.com/docker/swarmkit/issues/2294. The issue is that while - // image manifests report "arm" as the architecture, the node reports - // something like "armv7l" (includes the variant), which causes arm images - // to stop working with swarm mode. This patch removes the architecture - // constraint for arm images to ensure tasks get scheduled. - arch := p.Architecture - if strings.ToLower(arch) == "arm" { - arch = "" - } - platforms = append(platforms, swarm.Platform{ - Architecture: arch, - OS: p.OS, - }) - } - } - return imageWithDigest, platforms, err -} - -// imageWithDigestString takes an image string and a digest, and updates -// the image string if it didn't originally contain a digest. It returns -// image unmodified in other situations. -func imageWithDigestString(image string, dgst digest.Digest) string { - namedRef, err := reference.ParseNormalizedNamed(image) - if err == nil { - if _, isCanonical := namedRef.(reference.Canonical); !isCanonical { - // ensure that image gets a default tag if none is provided - img, err := reference.WithDigest(namedRef, dgst) - if err == nil { - return reference.FamiliarString(img) - } - } - } - return image -} - -// imageWithTagString takes an image string, and returns a tagged image -// string, adding a 'latest' tag if one was not provided. It returns an -// empty string if a canonical reference was provided -func imageWithTagString(image string) string { - namedRef, err := reference.ParseNormalizedNamed(image) - if err == nil { - return reference.FamiliarString(reference.TagNameOnly(namedRef)) - } - return "" -} - -// digestWarning constructs a formatted warning string using the -// image name that could not be pinned by digest. The formatting -// is hardcoded, but could me made smarter in the future -func digestWarning(image string) string { - return fmt.Sprintf("image %s could not be accessed on a registry to record\nits digest. Each node will access %s independently,\npossibly leading to different nodes running different\nversions of the image.\n", image, image) -} - -func validateServiceSpec(s swarm.ServiceSpec) error { - if s.TaskTemplate.ContainerSpec != nil && s.TaskTemplate.PluginSpec != nil { - return errors.New("must not specify both a container spec and a plugin spec in the task template") - } - if s.TaskTemplate.PluginSpec != nil && s.TaskTemplate.Runtime != swarm.RuntimePlugin { - return errors.New("mismatched runtime with plugin spec") - } - if s.TaskTemplate.ContainerSpec != nil && (s.TaskTemplate.Runtime != "" && s.TaskTemplate.Runtime != swarm.RuntimeContainer) { - return errors.New("mismatched runtime with container spec") - } - return nil -} diff --git a/vendor/github.com/docker/docker/client/service_inspect.go b/vendor/github.com/docker/docker/client/service_inspect.go deleted file mode 100644 index cee020c98..000000000 --- a/vendor/github.com/docker/docker/client/service_inspect.go +++ /dev/null @@ -1,37 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/swarm" -) - -// ServiceInspectWithRaw returns the service information and the raw data. -func (cli *Client) ServiceInspectWithRaw(ctx context.Context, serviceID string, opts types.ServiceInspectOptions) (swarm.Service, []byte, error) { - if serviceID == "" { - return swarm.Service{}, nil, objectNotFoundError{object: "service", id: serviceID} - } - query := url.Values{} - query.Set("insertDefaults", fmt.Sprintf("%v", opts.InsertDefaults)) - serverResp, err := cli.get(ctx, "/services/"+serviceID, query, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return swarm.Service{}, nil, err - } - - body, err := io.ReadAll(serverResp.body) - if err != nil { - return swarm.Service{}, nil, err - } - - var response swarm.Service - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&response) - return response, body, err -} diff --git a/vendor/github.com/docker/docker/client/service_list.go b/vendor/github.com/docker/docker/client/service_list.go deleted file mode 100644 index f97ec75a5..000000000 --- a/vendor/github.com/docker/docker/client/service_list.go +++ /dev/null @@ -1,39 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/swarm" -) - -// ServiceList returns the list of services. -func (cli *Client) ServiceList(ctx context.Context, options types.ServiceListOptions) ([]swarm.Service, error) { - query := url.Values{} - - if options.Filters.Len() > 0 { - filterJSON, err := filters.ToJSON(options.Filters) - if err != nil { - return nil, err - } - - query.Set("filters", filterJSON) - } - - if options.Status { - query.Set("status", "true") - } - - resp, err := cli.get(ctx, "/services", query, nil) - defer ensureReaderClosed(resp) - if err != nil { - return nil, err - } - - var services []swarm.Service - err = json.NewDecoder(resp.body).Decode(&services) - return services, err -} diff --git a/vendor/github.com/docker/docker/client/service_logs.go b/vendor/github.com/docker/docker/client/service_logs.go deleted file mode 100644 index 906fd4059..000000000 --- a/vendor/github.com/docker/docker/client/service_logs.go +++ /dev/null @@ -1,52 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" - "net/url" - "time" - - "github.com/docker/docker/api/types" - timetypes "github.com/docker/docker/api/types/time" - "github.com/pkg/errors" -) - -// ServiceLogs returns the logs generated by a service in an io.ReadCloser. -// It's up to the caller to close the stream. -func (cli *Client) ServiceLogs(ctx context.Context, serviceID string, options types.ContainerLogsOptions) (io.ReadCloser, error) { - query := url.Values{} - if options.ShowStdout { - query.Set("stdout", "1") - } - - if options.ShowStderr { - query.Set("stderr", "1") - } - - if options.Since != "" { - ts, err := timetypes.GetTimestamp(options.Since, time.Now()) - if err != nil { - return nil, errors.Wrap(err, `invalid value for "since"`) - } - query.Set("since", ts) - } - - if options.Timestamps { - query.Set("timestamps", "1") - } - - if options.Details { - query.Set("details", "1") - } - - if options.Follow { - query.Set("follow", "1") - } - query.Set("tail", options.Tail) - - resp, err := cli.get(ctx, "/services/"+serviceID+"/logs", query, nil) - if err != nil { - return nil, err - } - return resp.body, nil -} diff --git a/vendor/github.com/docker/docker/client/service_remove.go b/vendor/github.com/docker/docker/client/service_remove.go deleted file mode 100644 index 2c46326eb..000000000 --- a/vendor/github.com/docker/docker/client/service_remove.go +++ /dev/null @@ -1,10 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import "context" - -// ServiceRemove kills and removes a service. -func (cli *Client) ServiceRemove(ctx context.Context, serviceID string) error { - resp, err := cli.delete(ctx, "/services/"+serviceID, nil, nil) - defer ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/service_update.go b/vendor/github.com/docker/docker/client/service_update.go deleted file mode 100644 index ff8cded8b..000000000 --- a/vendor/github.com/docker/docker/client/service_update.go +++ /dev/null @@ -1,75 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/registry" - "github.com/docker/docker/api/types/swarm" -) - -// ServiceUpdate updates a Service. The version number is required to avoid conflicting writes. -// It should be the value as set *before* the update. You can find this value in the Meta field -// of swarm.Service, which can be found using ServiceInspectWithRaw. -func (cli *Client) ServiceUpdate(ctx context.Context, serviceID string, version swarm.Version, service swarm.ServiceSpec, options types.ServiceUpdateOptions) (types.ServiceUpdateResponse, error) { - var ( - query = url.Values{} - response = types.ServiceUpdateResponse{} - ) - - headers := map[string][]string{ - "version": {cli.version}, - } - - if options.EncodedRegistryAuth != "" { - headers[registry.AuthHeader] = []string{options.EncodedRegistryAuth} - } - - if options.RegistryAuthFrom != "" { - query.Set("registryAuthFrom", options.RegistryAuthFrom) - } - - if options.Rollback != "" { - query.Set("rollback", options.Rollback) - } - - query.Set("version", version.String()) - - if err := validateServiceSpec(service); err != nil { - return response, err - } - - // ensure that the image is tagged - var resolveWarning string - switch { - case service.TaskTemplate.ContainerSpec != nil: - if taggedImg := imageWithTagString(service.TaskTemplate.ContainerSpec.Image); taggedImg != "" { - service.TaskTemplate.ContainerSpec.Image = taggedImg - } - if options.QueryRegistry { - resolveWarning = resolveContainerSpecImage(ctx, cli, &service.TaskTemplate, options.EncodedRegistryAuth) - } - case service.TaskTemplate.PluginSpec != nil: - if taggedImg := imageWithTagString(service.TaskTemplate.PluginSpec.Remote); taggedImg != "" { - service.TaskTemplate.PluginSpec.Remote = taggedImg - } - if options.QueryRegistry { - resolveWarning = resolvePluginSpecRemote(ctx, cli, &service.TaskTemplate, options.EncodedRegistryAuth) - } - } - - resp, err := cli.post(ctx, "/services/"+serviceID+"/update", query, service, headers) - defer ensureReaderClosed(resp) - if err != nil { - return response, err - } - - err = json.NewDecoder(resp.body).Decode(&response) - if resolveWarning != "" { - response.Warnings = append(response.Warnings, resolveWarning) - } - - return response, err -} diff --git a/vendor/github.com/docker/docker/client/swarm_get_unlock_key.go b/vendor/github.com/docker/docker/client/swarm_get_unlock_key.go deleted file mode 100644 index 19f59dd58..000000000 --- a/vendor/github.com/docker/docker/client/swarm_get_unlock_key.go +++ /dev/null @@ -1,21 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - - "github.com/docker/docker/api/types" -) - -// SwarmGetUnlockKey retrieves the swarm's unlock key. -func (cli *Client) SwarmGetUnlockKey(ctx context.Context) (types.SwarmUnlockKeyResponse, error) { - serverResp, err := cli.get(ctx, "/swarm/unlockkey", nil, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return types.SwarmUnlockKeyResponse{}, err - } - - var response types.SwarmUnlockKeyResponse - err = json.NewDecoder(serverResp.body).Decode(&response) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/swarm_init.go b/vendor/github.com/docker/docker/client/swarm_init.go deleted file mode 100644 index da3c1637e..000000000 --- a/vendor/github.com/docker/docker/client/swarm_init.go +++ /dev/null @@ -1,21 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - - "github.com/docker/docker/api/types/swarm" -) - -// SwarmInit initializes the swarm. -func (cli *Client) SwarmInit(ctx context.Context, req swarm.InitRequest) (string, error) { - serverResp, err := cli.post(ctx, "/swarm/init", nil, req, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return "", err - } - - var response string - err = json.NewDecoder(serverResp.body).Decode(&response) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/swarm_inspect.go b/vendor/github.com/docker/docker/client/swarm_inspect.go deleted file mode 100644 index b52b67a88..000000000 --- a/vendor/github.com/docker/docker/client/swarm_inspect.go +++ /dev/null @@ -1,21 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - - "github.com/docker/docker/api/types/swarm" -) - -// SwarmInspect inspects the swarm. -func (cli *Client) SwarmInspect(ctx context.Context) (swarm.Swarm, error) { - serverResp, err := cli.get(ctx, "/swarm", nil, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return swarm.Swarm{}, err - } - - var response swarm.Swarm - err = json.NewDecoder(serverResp.body).Decode(&response) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/swarm_join.go b/vendor/github.com/docker/docker/client/swarm_join.go deleted file mode 100644 index a1cf0455d..000000000 --- a/vendor/github.com/docker/docker/client/swarm_join.go +++ /dev/null @@ -1,14 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - - "github.com/docker/docker/api/types/swarm" -) - -// SwarmJoin joins the swarm. -func (cli *Client) SwarmJoin(ctx context.Context, req swarm.JoinRequest) error { - resp, err := cli.post(ctx, "/swarm/join", nil, req, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/swarm_leave.go b/vendor/github.com/docker/docker/client/swarm_leave.go deleted file mode 100644 index 90ca84b36..000000000 --- a/vendor/github.com/docker/docker/client/swarm_leave.go +++ /dev/null @@ -1,17 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" -) - -// SwarmLeave leaves the swarm. -func (cli *Client) SwarmLeave(ctx context.Context, force bool) error { - query := url.Values{} - if force { - query.Set("force", "1") - } - resp, err := cli.post(ctx, "/swarm/leave", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/swarm_unlock.go b/vendor/github.com/docker/docker/client/swarm_unlock.go deleted file mode 100644 index d2412f7d4..000000000 --- a/vendor/github.com/docker/docker/client/swarm_unlock.go +++ /dev/null @@ -1,14 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - - "github.com/docker/docker/api/types/swarm" -) - -// SwarmUnlock unlocks locked swarm. -func (cli *Client) SwarmUnlock(ctx context.Context, req swarm.UnlockRequest) error { - serverResp, err := cli.post(ctx, "/swarm/unlock", nil, req, nil) - ensureReaderClosed(serverResp) - return err -} diff --git a/vendor/github.com/docker/docker/client/swarm_update.go b/vendor/github.com/docker/docker/client/swarm_update.go deleted file mode 100644 index 9fde7d75e..000000000 --- a/vendor/github.com/docker/docker/client/swarm_update.go +++ /dev/null @@ -1,21 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - "strconv" - - "github.com/docker/docker/api/types/swarm" -) - -// SwarmUpdate updates the swarm. -func (cli *Client) SwarmUpdate(ctx context.Context, version swarm.Version, swarm swarm.Spec, flags swarm.UpdateFlags) error { - query := url.Values{} - query.Set("version", version.String()) - query.Set("rotateWorkerToken", strconv.FormatBool(flags.RotateWorkerToken)) - query.Set("rotateManagerToken", strconv.FormatBool(flags.RotateManagerToken)) - query.Set("rotateManagerUnlockKey", strconv.FormatBool(flags.RotateManagerUnlockKey)) - resp, err := cli.post(ctx, "/swarm/update", query, swarm, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/task_inspect.go b/vendor/github.com/docker/docker/client/task_inspect.go deleted file mode 100644 index dde1f6c59..000000000 --- a/vendor/github.com/docker/docker/client/task_inspect.go +++ /dev/null @@ -1,32 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "bytes" - "context" - "encoding/json" - "io" - - "github.com/docker/docker/api/types/swarm" -) - -// TaskInspectWithRaw returns the task information and its raw representation. -func (cli *Client) TaskInspectWithRaw(ctx context.Context, taskID string) (swarm.Task, []byte, error) { - if taskID == "" { - return swarm.Task{}, nil, objectNotFoundError{object: "task", id: taskID} - } - serverResp, err := cli.get(ctx, "/tasks/"+taskID, nil, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return swarm.Task{}, nil, err - } - - body, err := io.ReadAll(serverResp.body) - if err != nil { - return swarm.Task{}, nil, err - } - - var response swarm.Task - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&response) - return response, body, err -} diff --git a/vendor/github.com/docker/docker/client/task_list.go b/vendor/github.com/docker/docker/client/task_list.go deleted file mode 100644 index 4869b4449..000000000 --- a/vendor/github.com/docker/docker/client/task_list.go +++ /dev/null @@ -1,35 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/swarm" -) - -// TaskList returns the list of tasks. -func (cli *Client) TaskList(ctx context.Context, options types.TaskListOptions) ([]swarm.Task, error) { - query := url.Values{} - - if options.Filters.Len() > 0 { - filterJSON, err := filters.ToJSON(options.Filters) - if err != nil { - return nil, err - } - - query.Set("filters", filterJSON) - } - - resp, err := cli.get(ctx, "/tasks", query, nil) - defer ensureReaderClosed(resp) - if err != nil { - return nil, err - } - - var tasks []swarm.Task - err = json.NewDecoder(resp.body).Decode(&tasks) - return tasks, err -} diff --git a/vendor/github.com/docker/docker/client/task_logs.go b/vendor/github.com/docker/docker/client/task_logs.go deleted file mode 100644 index 6222fab57..000000000 --- a/vendor/github.com/docker/docker/client/task_logs.go +++ /dev/null @@ -1,51 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" - "net/url" - "time" - - "github.com/docker/docker/api/types" - timetypes "github.com/docker/docker/api/types/time" -) - -// TaskLogs returns the logs generated by a task in an io.ReadCloser. -// It's up to the caller to close the stream. -func (cli *Client) TaskLogs(ctx context.Context, taskID string, options types.ContainerLogsOptions) (io.ReadCloser, error) { - query := url.Values{} - if options.ShowStdout { - query.Set("stdout", "1") - } - - if options.ShowStderr { - query.Set("stderr", "1") - } - - if options.Since != "" { - ts, err := timetypes.GetTimestamp(options.Since, time.Now()) - if err != nil { - return nil, err - } - query.Set("since", ts) - } - - if options.Timestamps { - query.Set("timestamps", "1") - } - - if options.Details { - query.Set("details", "1") - } - - if options.Follow { - query.Set("follow", "1") - } - query.Set("tail", options.Tail) - - resp, err := cli.get(ctx, "/tasks/"+taskID+"/logs", query, nil) - if err != nil { - return nil, err - } - return resp.body, nil -} diff --git a/vendor/github.com/docker/docker/client/transport.go b/vendor/github.com/docker/docker/client/transport.go deleted file mode 100644 index 554134436..000000000 --- a/vendor/github.com/docker/docker/client/transport.go +++ /dev/null @@ -1,17 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "crypto/tls" - "net/http" -) - -// resolveTLSConfig attempts to resolve the TLS configuration from the -// RoundTripper. -func resolveTLSConfig(transport http.RoundTripper) *tls.Config { - switch tr := transport.(type) { - case *http.Transport: - return tr.TLSClientConfig - default: - return nil - } -} diff --git a/vendor/github.com/docker/docker/client/utils.go b/vendor/github.com/docker/docker/client/utils.go deleted file mode 100644 index 7f3ff44eb..000000000 --- a/vendor/github.com/docker/docker/client/utils.go +++ /dev/null @@ -1,34 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "net/url" - "regexp" - - "github.com/docker/docker/api/types/filters" -) - -var headerRegexp = regexp.MustCompile(`\ADocker/.+\s\((.+)\)\z`) - -// getDockerOS returns the operating system based on the server header from the daemon. -func getDockerOS(serverHeader string) string { - var osType string - matches := headerRegexp.FindStringSubmatch(serverHeader) - if len(matches) > 0 { - osType = matches[1] - } - return osType -} - -// getFiltersQuery returns a url query with "filters" query term, based on the -// filters provided. -func getFiltersQuery(f filters.Args) (url.Values, error) { - query := url.Values{} - if f.Len() > 0 { - filterJSON, err := filters.ToJSON(f) - if err != nil { - return query, err - } - query.Set("filters", filterJSON) - } - return query, nil -} diff --git a/vendor/github.com/docker/docker/client/version.go b/vendor/github.com/docker/docker/client/version.go deleted file mode 100644 index 8f17ff4e8..000000000 --- a/vendor/github.com/docker/docker/client/version.go +++ /dev/null @@ -1,21 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - - "github.com/docker/docker/api/types" -) - -// ServerVersion returns information of the docker client and server host. -func (cli *Client) ServerVersion(ctx context.Context) (types.Version, error) { - resp, err := cli.get(ctx, "/version", nil, nil) - defer ensureReaderClosed(resp) - if err != nil { - return types.Version{}, err - } - - var server types.Version - err = json.NewDecoder(resp.body).Decode(&server) - return server, err -} diff --git a/vendor/github.com/docker/docker/client/volume_create.go b/vendor/github.com/docker/docker/client/volume_create.go deleted file mode 100644 index b3b182437..000000000 --- a/vendor/github.com/docker/docker/client/volume_create.go +++ /dev/null @@ -1,20 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - - "github.com/docker/docker/api/types/volume" -) - -// VolumeCreate creates a volume in the docker host. -func (cli *Client) VolumeCreate(ctx context.Context, options volume.CreateOptions) (volume.Volume, error) { - var vol volume.Volume - resp, err := cli.post(ctx, "/volumes/create", nil, options, nil) - defer ensureReaderClosed(resp) - if err != nil { - return vol, err - } - err = json.NewDecoder(resp.body).Decode(&vol) - return vol, err -} diff --git a/vendor/github.com/docker/docker/client/volume_inspect.go b/vendor/github.com/docker/docker/client/volume_inspect.go deleted file mode 100644 index b3ba4e604..000000000 --- a/vendor/github.com/docker/docker/client/volume_inspect.go +++ /dev/null @@ -1,38 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "bytes" - "context" - "encoding/json" - "io" - - "github.com/docker/docker/api/types/volume" -) - -// VolumeInspect returns the information about a specific volume in the docker host. -func (cli *Client) VolumeInspect(ctx context.Context, volumeID string) (volume.Volume, error) { - vol, _, err := cli.VolumeInspectWithRaw(ctx, volumeID) - return vol, err -} - -// VolumeInspectWithRaw returns the information about a specific volume in the docker host and its raw representation -func (cli *Client) VolumeInspectWithRaw(ctx context.Context, volumeID string) (volume.Volume, []byte, error) { - if volumeID == "" { - return volume.Volume{}, nil, objectNotFoundError{object: "volume", id: volumeID} - } - - var vol volume.Volume - resp, err := cli.get(ctx, "/volumes/"+volumeID, nil, nil) - defer ensureReaderClosed(resp) - if err != nil { - return vol, nil, err - } - - body, err := io.ReadAll(resp.body) - if err != nil { - return vol, nil, err - } - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&vol) - return vol, body, err -} diff --git a/vendor/github.com/docker/docker/client/volume_list.go b/vendor/github.com/docker/docker/client/volume_list.go deleted file mode 100644 index d5ea9827c..000000000 --- a/vendor/github.com/docker/docker/client/volume_list.go +++ /dev/null @@ -1,33 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/volume" -) - -// VolumeList returns the volumes configured in the docker host. -func (cli *Client) VolumeList(ctx context.Context, options volume.ListOptions) (volume.ListResponse, error) { - var volumes volume.ListResponse - query := url.Values{} - - if options.Filters.Len() > 0 { - //nolint:staticcheck // ignore SA1019 for old code - filterJSON, err := filters.ToParamWithVersion(cli.version, options.Filters) - if err != nil { - return volumes, err - } - query.Set("filters", filterJSON) - } - resp, err := cli.get(ctx, "/volumes", query, nil) - defer ensureReaderClosed(resp) - if err != nil { - return volumes, err - } - - err = json.NewDecoder(resp.body).Decode(&volumes) - return volumes, err -} diff --git a/vendor/github.com/docker/docker/client/volume_prune.go b/vendor/github.com/docker/docker/client/volume_prune.go deleted file mode 100644 index 6e324708f..000000000 --- a/vendor/github.com/docker/docker/client/volume_prune.go +++ /dev/null @@ -1,36 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "fmt" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" -) - -// VolumesPrune requests the daemon to delete unused data -func (cli *Client) VolumesPrune(ctx context.Context, pruneFilters filters.Args) (types.VolumesPruneReport, error) { - var report types.VolumesPruneReport - - if err := cli.NewVersionError("1.25", "volume prune"); err != nil { - return report, err - } - - query, err := getFiltersQuery(pruneFilters) - if err != nil { - return report, err - } - - serverResp, err := cli.post(ctx, "/volumes/prune", query, nil, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return report, err - } - - if err := json.NewDecoder(serverResp.body).Decode(&report); err != nil { - return report, fmt.Errorf("Error retrieving volume prune report: %v", err) - } - - return report, nil -} diff --git a/vendor/github.com/docker/docker/client/volume_remove.go b/vendor/github.com/docker/docker/client/volume_remove.go deleted file mode 100644 index 1f2643836..000000000 --- a/vendor/github.com/docker/docker/client/volume_remove.go +++ /dev/null @@ -1,21 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - - "github.com/docker/docker/api/types/versions" -) - -// VolumeRemove removes a volume from the docker host. -func (cli *Client) VolumeRemove(ctx context.Context, volumeID string, force bool) error { - query := url.Values{} - if versions.GreaterThanOrEqualTo(cli.version, "1.25") { - if force { - query.Set("force", "1") - } - } - resp, err := cli.delete(ctx, "/volumes/"+volumeID, query, nil) - defer ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/volume_update.go b/vendor/github.com/docker/docker/client/volume_update.go deleted file mode 100644 index 33bd31e53..000000000 --- a/vendor/github.com/docker/docker/client/volume_update.go +++ /dev/null @@ -1,24 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - - "github.com/docker/docker/api/types/swarm" - "github.com/docker/docker/api/types/volume" -) - -// VolumeUpdate updates a volume. This only works for Cluster Volumes, and -// only some fields can be updated. -func (cli *Client) VolumeUpdate(ctx context.Context, volumeID string, version swarm.Version, options volume.UpdateOptions) error { - if err := cli.NewVersionError("1.42", "volume update"); err != nil { - return err - } - - query := url.Values{} - query.Set("version", version.String()) - - resp, err := cli.put(ctx, "/volumes/"+volumeID, query, options, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/errdefs/defs.go b/vendor/github.com/docker/docker/errdefs/defs.go deleted file mode 100644 index 61e7456b4..000000000 --- a/vendor/github.com/docker/docker/errdefs/defs.go +++ /dev/null @@ -1,69 +0,0 @@ -package errdefs // import "github.com/docker/docker/errdefs" - -// ErrNotFound signals that the requested object doesn't exist -type ErrNotFound interface { - NotFound() -} - -// ErrInvalidParameter signals that the user input is invalid -type ErrInvalidParameter interface { - InvalidParameter() -} - -// ErrConflict signals that some internal state conflicts with the requested action and can't be performed. -// A change in state should be able to clear this error. -type ErrConflict interface { - Conflict() -} - -// ErrUnauthorized is used to signify that the user is not authorized to perform a specific action -type ErrUnauthorized interface { - Unauthorized() -} - -// ErrUnavailable signals that the requested action/subsystem is not available. -type ErrUnavailable interface { - Unavailable() -} - -// ErrForbidden signals that the requested action cannot be performed under any circumstances. -// When a ErrForbidden is returned, the caller should never retry the action. -type ErrForbidden interface { - Forbidden() -} - -// ErrSystem signals that some internal error occurred. -// An example of this would be a failed mount request. -type ErrSystem interface { - System() -} - -// ErrNotModified signals that an action can't be performed because it's already in the desired state -type ErrNotModified interface { - NotModified() -} - -// ErrNotImplemented signals that the requested action/feature is not implemented on the system as configured. -type ErrNotImplemented interface { - NotImplemented() -} - -// ErrUnknown signals that the kind of error that occurred is not known. -type ErrUnknown interface { - Unknown() -} - -// ErrCancelled signals that the action was cancelled. -type ErrCancelled interface { - Cancelled() -} - -// ErrDeadline signals that the deadline was reached before the action completed. -type ErrDeadline interface { - DeadlineExceeded() -} - -// ErrDataLoss indicates that data was lost or there is data corruption. -type ErrDataLoss interface { - DataLoss() -} diff --git a/vendor/github.com/docker/docker/errdefs/doc.go b/vendor/github.com/docker/docker/errdefs/doc.go deleted file mode 100644 index c211f174f..000000000 --- a/vendor/github.com/docker/docker/errdefs/doc.go +++ /dev/null @@ -1,8 +0,0 @@ -// Package errdefs defines a set of error interfaces that packages should use for communicating classes of errors. -// Errors that cross the package boundary should implement one (and only one) of these interfaces. -// -// Packages should not reference these interfaces directly, only implement them. -// To check if a particular error implements one of these interfaces, there are helper -// functions provided (e.g. `Is`) which can be used rather than asserting the interfaces directly. -// If you must assert on these interfaces, be sure to check the causal chain (`err.Cause()`). -package errdefs // import "github.com/docker/docker/errdefs" diff --git a/vendor/github.com/docker/docker/errdefs/helpers.go b/vendor/github.com/docker/docker/errdefs/helpers.go deleted file mode 100644 index fe06fb6f7..000000000 --- a/vendor/github.com/docker/docker/errdefs/helpers.go +++ /dev/null @@ -1,279 +0,0 @@ -package errdefs // import "github.com/docker/docker/errdefs" - -import "context" - -type errNotFound struct{ error } - -func (errNotFound) NotFound() {} - -func (e errNotFound) Cause() error { - return e.error -} - -func (e errNotFound) Unwrap() error { - return e.error -} - -// NotFound is a helper to create an error of the class with the same name from any error type -func NotFound(err error) error { - if err == nil || IsNotFound(err) { - return err - } - return errNotFound{err} -} - -type errInvalidParameter struct{ error } - -func (errInvalidParameter) InvalidParameter() {} - -func (e errInvalidParameter) Cause() error { - return e.error -} - -func (e errInvalidParameter) Unwrap() error { - return e.error -} - -// InvalidParameter is a helper to create an error of the class with the same name from any error type -func InvalidParameter(err error) error { - if err == nil || IsInvalidParameter(err) { - return err - } - return errInvalidParameter{err} -} - -type errConflict struct{ error } - -func (errConflict) Conflict() {} - -func (e errConflict) Cause() error { - return e.error -} - -func (e errConflict) Unwrap() error { - return e.error -} - -// Conflict is a helper to create an error of the class with the same name from any error type -func Conflict(err error) error { - if err == nil || IsConflict(err) { - return err - } - return errConflict{err} -} - -type errUnauthorized struct{ error } - -func (errUnauthorized) Unauthorized() {} - -func (e errUnauthorized) Cause() error { - return e.error -} - -func (e errUnauthorized) Unwrap() error { - return e.error -} - -// Unauthorized is a helper to create an error of the class with the same name from any error type -func Unauthorized(err error) error { - if err == nil || IsUnauthorized(err) { - return err - } - return errUnauthorized{err} -} - -type errUnavailable struct{ error } - -func (errUnavailable) Unavailable() {} - -func (e errUnavailable) Cause() error { - return e.error -} - -func (e errUnavailable) Unwrap() error { - return e.error -} - -// Unavailable is a helper to create an error of the class with the same name from any error type -func Unavailable(err error) error { - if err == nil || IsUnavailable(err) { - return err - } - return errUnavailable{err} -} - -type errForbidden struct{ error } - -func (errForbidden) Forbidden() {} - -func (e errForbidden) Cause() error { - return e.error -} - -func (e errForbidden) Unwrap() error { - return e.error -} - -// Forbidden is a helper to create an error of the class with the same name from any error type -func Forbidden(err error) error { - if err == nil || IsForbidden(err) { - return err - } - return errForbidden{err} -} - -type errSystem struct{ error } - -func (errSystem) System() {} - -func (e errSystem) Cause() error { - return e.error -} - -func (e errSystem) Unwrap() error { - return e.error -} - -// System is a helper to create an error of the class with the same name from any error type -func System(err error) error { - if err == nil || IsSystem(err) { - return err - } - return errSystem{err} -} - -type errNotModified struct{ error } - -func (errNotModified) NotModified() {} - -func (e errNotModified) Cause() error { - return e.error -} - -func (e errNotModified) Unwrap() error { - return e.error -} - -// NotModified is a helper to create an error of the class with the same name from any error type -func NotModified(err error) error { - if err == nil || IsNotModified(err) { - return err - } - return errNotModified{err} -} - -type errNotImplemented struct{ error } - -func (errNotImplemented) NotImplemented() {} - -func (e errNotImplemented) Cause() error { - return e.error -} - -func (e errNotImplemented) Unwrap() error { - return e.error -} - -// NotImplemented is a helper to create an error of the class with the same name from any error type -func NotImplemented(err error) error { - if err == nil || IsNotImplemented(err) { - return err - } - return errNotImplemented{err} -} - -type errUnknown struct{ error } - -func (errUnknown) Unknown() {} - -func (e errUnknown) Cause() error { - return e.error -} - -func (e errUnknown) Unwrap() error { - return e.error -} - -// Unknown is a helper to create an error of the class with the same name from any error type -func Unknown(err error) error { - if err == nil || IsUnknown(err) { - return err - } - return errUnknown{err} -} - -type errCancelled struct{ error } - -func (errCancelled) Cancelled() {} - -func (e errCancelled) Cause() error { - return e.error -} - -func (e errCancelled) Unwrap() error { - return e.error -} - -// Cancelled is a helper to create an error of the class with the same name from any error type -func Cancelled(err error) error { - if err == nil || IsCancelled(err) { - return err - } - return errCancelled{err} -} - -type errDeadline struct{ error } - -func (errDeadline) DeadlineExceeded() {} - -func (e errDeadline) Cause() error { - return e.error -} - -func (e errDeadline) Unwrap() error { - return e.error -} - -// Deadline is a helper to create an error of the class with the same name from any error type -func Deadline(err error) error { - if err == nil || IsDeadline(err) { - return err - } - return errDeadline{err} -} - -type errDataLoss struct{ error } - -func (errDataLoss) DataLoss() {} - -func (e errDataLoss) Cause() error { - return e.error -} - -func (e errDataLoss) Unwrap() error { - return e.error -} - -// DataLoss is a helper to create an error of the class with the same name from any error type -func DataLoss(err error) error { - if err == nil || IsDataLoss(err) { - return err - } - return errDataLoss{err} -} - -// FromContext returns the error class from the passed in context -func FromContext(ctx context.Context) error { - e := ctx.Err() - if e == nil { - return nil - } - - if e == context.Canceled { - return Cancelled(e) - } - if e == context.DeadlineExceeded { - return Deadline(e) - } - return Unknown(e) -} diff --git a/vendor/github.com/docker/docker/errdefs/http_helpers.go b/vendor/github.com/docker/docker/errdefs/http_helpers.go deleted file mode 100644 index 77bda389d..000000000 --- a/vendor/github.com/docker/docker/errdefs/http_helpers.go +++ /dev/null @@ -1,46 +0,0 @@ -package errdefs // import "github.com/docker/docker/errdefs" - -import ( - "net/http" -) - -// FromStatusCode creates an errdef error, based on the provided HTTP status-code -func FromStatusCode(err error, statusCode int) error { - if err == nil { - return nil - } - switch statusCode { - case http.StatusNotFound: - err = NotFound(err) - case http.StatusBadRequest: - err = InvalidParameter(err) - case http.StatusConflict: - err = Conflict(err) - case http.StatusUnauthorized: - err = Unauthorized(err) - case http.StatusServiceUnavailable: - err = Unavailable(err) - case http.StatusForbidden: - err = Forbidden(err) - case http.StatusNotModified: - err = NotModified(err) - case http.StatusNotImplemented: - err = NotImplemented(err) - case http.StatusInternalServerError: - if !IsSystem(err) && !IsUnknown(err) && !IsDataLoss(err) && !IsDeadline(err) && !IsCancelled(err) { - err = System(err) - } - default: - switch { - case statusCode >= 200 && statusCode < 400: - // it's a client error - case statusCode >= 400 && statusCode < 500: - err = InvalidParameter(err) - case statusCode >= 500 && statusCode < 600: - err = System(err) - default: - err = Unknown(err) - } - } - return err -} diff --git a/vendor/github.com/docker/docker/errdefs/is.go b/vendor/github.com/docker/docker/errdefs/is.go deleted file mode 100644 index 3abf07d0c..000000000 --- a/vendor/github.com/docker/docker/errdefs/is.go +++ /dev/null @@ -1,107 +0,0 @@ -package errdefs // import "github.com/docker/docker/errdefs" - -type causer interface { - Cause() error -} - -func getImplementer(err error) error { - switch e := err.(type) { - case - ErrNotFound, - ErrInvalidParameter, - ErrConflict, - ErrUnauthorized, - ErrUnavailable, - ErrForbidden, - ErrSystem, - ErrNotModified, - ErrNotImplemented, - ErrCancelled, - ErrDeadline, - ErrDataLoss, - ErrUnknown: - return err - case causer: - return getImplementer(e.Cause()) - default: - return err - } -} - -// IsNotFound returns if the passed in error is an ErrNotFound -func IsNotFound(err error) bool { - _, ok := getImplementer(err).(ErrNotFound) - return ok -} - -// IsInvalidParameter returns if the passed in error is an ErrInvalidParameter -func IsInvalidParameter(err error) bool { - _, ok := getImplementer(err).(ErrInvalidParameter) - return ok -} - -// IsConflict returns if the passed in error is an ErrConflict -func IsConflict(err error) bool { - _, ok := getImplementer(err).(ErrConflict) - return ok -} - -// IsUnauthorized returns if the passed in error is an ErrUnauthorized -func IsUnauthorized(err error) bool { - _, ok := getImplementer(err).(ErrUnauthorized) - return ok -} - -// IsUnavailable returns if the passed in error is an ErrUnavailable -func IsUnavailable(err error) bool { - _, ok := getImplementer(err).(ErrUnavailable) - return ok -} - -// IsForbidden returns if the passed in error is an ErrForbidden -func IsForbidden(err error) bool { - _, ok := getImplementer(err).(ErrForbidden) - return ok -} - -// IsSystem returns if the passed in error is an ErrSystem -func IsSystem(err error) bool { - _, ok := getImplementer(err).(ErrSystem) - return ok -} - -// IsNotModified returns if the passed in error is a NotModified error -func IsNotModified(err error) bool { - _, ok := getImplementer(err).(ErrNotModified) - return ok -} - -// IsNotImplemented returns if the passed in error is an ErrNotImplemented -func IsNotImplemented(err error) bool { - _, ok := getImplementer(err).(ErrNotImplemented) - return ok -} - -// IsUnknown returns if the passed in error is an ErrUnknown -func IsUnknown(err error) bool { - _, ok := getImplementer(err).(ErrUnknown) - return ok -} - -// IsCancelled returns if the passed in error is an ErrCancelled -func IsCancelled(err error) bool { - _, ok := getImplementer(err).(ErrCancelled) - return ok -} - -// IsDeadline returns if the passed in error is an ErrDeadline -func IsDeadline(err error) bool { - _, ok := getImplementer(err).(ErrDeadline) - return ok -} - -// IsDataLoss returns if the passed in error is an ErrDataLoss -func IsDataLoss(err error) bool { - _, ok := getImplementer(err).(ErrDataLoss) - return ok -} diff --git a/vendor/github.com/docker/docker/pkg/archive/archive.go b/vendor/github.com/docker/docker/pkg/archive/archive.go deleted file mode 100644 index 34361a24a..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/archive.go +++ /dev/null @@ -1,1482 +0,0 @@ -// Package archive provides helper functions for dealing with archive files. -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "archive/tar" - "bufio" - "bytes" - "compress/bzip2" - "compress/gzip" - "context" - "encoding/binary" - "fmt" - "io" - "os" - "os/exec" - "path/filepath" - "runtime" - "strconv" - "strings" - "syscall" - "time" - - "github.com/containerd/containerd/pkg/userns" - "github.com/docker/docker/pkg/idtools" - "github.com/docker/docker/pkg/ioutils" - "github.com/docker/docker/pkg/pools" - "github.com/docker/docker/pkg/system" - "github.com/klauspost/compress/zstd" - "github.com/moby/patternmatcher" - "github.com/moby/sys/sequential" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" -) - -// ImpliedDirectoryMode represents the mode (Unix permissions) applied to directories that are implied by files in a -// tar, but that do not have their own header entry. -// -// The permissions mask is stored in a constant instead of locally to ensure that magic numbers do not -// proliferate in the codebase. The default value 0755 has been selected based on the default umask of 0022, and -// a convention of mkdir(1) calling mkdir(2) with permissions of 0777, resulting in a final value of 0755. -// -// This value is currently implementation-defined, and not captured in any cross-runtime specification. Thus, it is -// subject to change in Moby at any time -- image authors who require consistent or known directory permissions -// should explicitly control them by ensuring that header entries exist for any applicable path. -const ImpliedDirectoryMode = 0755 - -type ( - // Compression is the state represents if compressed or not. - Compression int - // WhiteoutFormat is the format of whiteouts unpacked - WhiteoutFormat int - - // TarOptions wraps the tar options. - TarOptions struct { - IncludeFiles []string - ExcludePatterns []string - Compression Compression - NoLchown bool - IDMap idtools.IdentityMapping - ChownOpts *idtools.Identity - IncludeSourceDir bool - // WhiteoutFormat is the expected on disk format for whiteout files. - // This format will be converted to the standard format on pack - // and from the standard format on unpack. - WhiteoutFormat WhiteoutFormat - // When unpacking, specifies whether overwriting a directory with a - // non-directory is allowed and vice versa. - NoOverwriteDirNonDir bool - // For each include when creating an archive, the included name will be - // replaced with the matching name from this map. - RebaseNames map[string]string - InUserNS bool - } -) - -// Archiver implements the Archiver interface and allows the reuse of most utility functions of -// this package with a pluggable Untar function. Also, to facilitate the passing of specific id -// mappings for untar, an Archiver can be created with maps which will then be passed to Untar operations. -type Archiver struct { - Untar func(io.Reader, string, *TarOptions) error - IDMapping idtools.IdentityMapping -} - -// NewDefaultArchiver returns a new Archiver without any IdentityMapping -func NewDefaultArchiver() *Archiver { - return &Archiver{Untar: Untar} -} - -// breakoutError is used to differentiate errors related to breaking out -// When testing archive breakout in the unit tests, this error is expected -// in order for the test to pass. -type breakoutError error - -const ( - // Uncompressed represents the uncompressed. - Uncompressed Compression = iota - // Bzip2 is bzip2 compression algorithm. - Bzip2 - // Gzip is gzip compression algorithm. - Gzip - // Xz is xz compression algorithm. - Xz - // Zstd is zstd compression algorithm. - Zstd -) - -const ( - // AUFSWhiteoutFormat is the default format for whiteouts - AUFSWhiteoutFormat WhiteoutFormat = iota - // OverlayWhiteoutFormat formats whiteout according to the overlay - // standard. - OverlayWhiteoutFormat -) - -// IsArchivePath checks if the (possibly compressed) file at the given path -// starts with a tar file header. -func IsArchivePath(path string) bool { - file, err := os.Open(path) - if err != nil { - return false - } - defer file.Close() - rdr, err := DecompressStream(file) - if err != nil { - return false - } - defer rdr.Close() - r := tar.NewReader(rdr) - _, err = r.Next() - return err == nil -} - -const ( - zstdMagicSkippableStart = 0x184D2A50 - zstdMagicSkippableMask = 0xFFFFFFF0 -) - -var ( - bzip2Magic = []byte{0x42, 0x5A, 0x68} - gzipMagic = []byte{0x1F, 0x8B, 0x08} - xzMagic = []byte{0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00} - zstdMagic = []byte{0x28, 0xb5, 0x2f, 0xfd} -) - -type matcher = func([]byte) bool - -func magicNumberMatcher(m []byte) matcher { - return func(source []byte) bool { - return bytes.HasPrefix(source, m) - } -} - -// zstdMatcher detects zstd compression algorithm. -// Zstandard compressed data is made of one or more frames. -// There are two frame formats defined by Zstandard: Zstandard frames and Skippable frames. -// See https://tools.ietf.org/id/draft-kucherawy-dispatch-zstd-00.html#rfc.section.2 for more details. -func zstdMatcher() matcher { - return func(source []byte) bool { - if bytes.HasPrefix(source, zstdMagic) { - // Zstandard frame - return true - } - // skippable frame - if len(source) < 8 { - return false - } - // magic number from 0x184D2A50 to 0x184D2A5F. - if binary.LittleEndian.Uint32(source[:4])&zstdMagicSkippableMask == zstdMagicSkippableStart { - return true - } - return false - } -} - -// DetectCompression detects the compression algorithm of the source. -func DetectCompression(source []byte) Compression { - compressionMap := map[Compression]matcher{ - Bzip2: magicNumberMatcher(bzip2Magic), - Gzip: magicNumberMatcher(gzipMagic), - Xz: magicNumberMatcher(xzMagic), - Zstd: zstdMatcher(), - } - for _, compression := range []Compression{Bzip2, Gzip, Xz, Zstd} { - fn := compressionMap[compression] - if fn(source) { - return compression - } - } - return Uncompressed -} - -func xzDecompress(ctx context.Context, archive io.Reader) (io.ReadCloser, error) { - args := []string{"xz", "-d", "-c", "-q"} - - return cmdStream(exec.CommandContext(ctx, args[0], args[1:]...), archive) -} - -func gzDecompress(ctx context.Context, buf io.Reader) (io.ReadCloser, error) { - if noPigzEnv := os.Getenv("MOBY_DISABLE_PIGZ"); noPigzEnv != "" { - noPigz, err := strconv.ParseBool(noPigzEnv) - if err != nil { - logrus.WithError(err).Warn("invalid value in MOBY_DISABLE_PIGZ env var") - } - if noPigz { - logrus.Debugf("Use of pigz is disabled due to MOBY_DISABLE_PIGZ=%s", noPigzEnv) - return gzip.NewReader(buf) - } - } - - unpigzPath, err := exec.LookPath("unpigz") - if err != nil { - logrus.Debugf("unpigz binary not found, falling back to go gzip library") - return gzip.NewReader(buf) - } - - logrus.Debugf("Using %s to decompress", unpigzPath) - - return cmdStream(exec.CommandContext(ctx, unpigzPath, "-d", "-c"), buf) -} - -func wrapReadCloser(readBuf io.ReadCloser, cancel context.CancelFunc) io.ReadCloser { - return ioutils.NewReadCloserWrapper(readBuf, func() error { - cancel() - return readBuf.Close() - }) -} - -// DecompressStream decompresses the archive and returns a ReaderCloser with the decompressed archive. -func DecompressStream(archive io.Reader) (io.ReadCloser, error) { - p := pools.BufioReader32KPool - buf := p.Get(archive) - bs, err := buf.Peek(10) - if err != nil && err != io.EOF { - // Note: we'll ignore any io.EOF error because there are some odd - // cases where the layer.tar file will be empty (zero bytes) and - // that results in an io.EOF from the Peek() call. So, in those - // cases we'll just treat it as a non-compressed stream and - // that means just create an empty layer. - // See Issue 18170 - return nil, err - } - - compression := DetectCompression(bs) - switch compression { - case Uncompressed: - readBufWrapper := p.NewReadCloserWrapper(buf, buf) - return readBufWrapper, nil - case Gzip: - ctx, cancel := context.WithCancel(context.Background()) - - gzReader, err := gzDecompress(ctx, buf) - if err != nil { - cancel() - return nil, err - } - readBufWrapper := p.NewReadCloserWrapper(buf, gzReader) - return wrapReadCloser(readBufWrapper, cancel), nil - case Bzip2: - bz2Reader := bzip2.NewReader(buf) - readBufWrapper := p.NewReadCloserWrapper(buf, bz2Reader) - return readBufWrapper, nil - case Xz: - ctx, cancel := context.WithCancel(context.Background()) - - xzReader, err := xzDecompress(ctx, buf) - if err != nil { - cancel() - return nil, err - } - readBufWrapper := p.NewReadCloserWrapper(buf, xzReader) - return wrapReadCloser(readBufWrapper, cancel), nil - case Zstd: - zstdReader, err := zstd.NewReader(buf) - if err != nil { - return nil, err - } - readBufWrapper := p.NewReadCloserWrapper(buf, zstdReader) - return readBufWrapper, nil - default: - return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension()) - } -} - -// CompressStream compresses the dest with specified compression algorithm. -func CompressStream(dest io.Writer, compression Compression) (io.WriteCloser, error) { - p := pools.BufioWriter32KPool - buf := p.Get(dest) - switch compression { - case Uncompressed: - writeBufWrapper := p.NewWriteCloserWrapper(buf, buf) - return writeBufWrapper, nil - case Gzip: - gzWriter := gzip.NewWriter(dest) - writeBufWrapper := p.NewWriteCloserWrapper(buf, gzWriter) - return writeBufWrapper, nil - case Bzip2, Xz: - // archive/bzip2 does not support writing, and there is no xz support at all - // However, this is not a problem as docker only currently generates gzipped tars - return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension()) - default: - return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension()) - } -} - -// TarModifierFunc is a function that can be passed to ReplaceFileTarWrapper to -// modify the contents or header of an entry in the archive. If the file already -// exists in the archive the TarModifierFunc will be called with the Header and -// a reader which will return the files content. If the file does not exist both -// header and content will be nil. -type TarModifierFunc func(path string, header *tar.Header, content io.Reader) (*tar.Header, []byte, error) - -// ReplaceFileTarWrapper converts inputTarStream to a new tar stream. Files in the -// tar stream are modified if they match any of the keys in mods. -func ReplaceFileTarWrapper(inputTarStream io.ReadCloser, mods map[string]TarModifierFunc) io.ReadCloser { - pipeReader, pipeWriter := io.Pipe() - - go func() { - tarReader := tar.NewReader(inputTarStream) - tarWriter := tar.NewWriter(pipeWriter) - defer inputTarStream.Close() - defer tarWriter.Close() - - modify := func(name string, original *tar.Header, modifier TarModifierFunc, tarReader io.Reader) error { - header, data, err := modifier(name, original, tarReader) - switch { - case err != nil: - return err - case header == nil: - return nil - } - - if header.Name == "" { - header.Name = name - } - header.Size = int64(len(data)) - if err := tarWriter.WriteHeader(header); err != nil { - return err - } - if len(data) != 0 { - if _, err := tarWriter.Write(data); err != nil { - return err - } - } - return nil - } - - var err error - var originalHeader *tar.Header - for { - originalHeader, err = tarReader.Next() - if err == io.EOF { - break - } - if err != nil { - pipeWriter.CloseWithError(err) - return - } - - modifier, ok := mods[originalHeader.Name] - if !ok { - // No modifiers for this file, copy the header and data - if err := tarWriter.WriteHeader(originalHeader); err != nil { - pipeWriter.CloseWithError(err) - return - } - if _, err := pools.Copy(tarWriter, tarReader); err != nil { - pipeWriter.CloseWithError(err) - return - } - continue - } - delete(mods, originalHeader.Name) - - if err := modify(originalHeader.Name, originalHeader, modifier, tarReader); err != nil { - pipeWriter.CloseWithError(err) - return - } - } - - // Apply the modifiers that haven't matched any files in the archive - for name, modifier := range mods { - if err := modify(name, nil, modifier, nil); err != nil { - pipeWriter.CloseWithError(err) - return - } - } - - pipeWriter.Close() - }() - return pipeReader -} - -// Extension returns the extension of a file that uses the specified compression algorithm. -func (compression *Compression) Extension() string { - switch *compression { - case Uncompressed: - return "tar" - case Bzip2: - return "tar.bz2" - case Gzip: - return "tar.gz" - case Xz: - return "tar.xz" - case Zstd: - return "tar.zst" - } - return "" -} - -// nosysFileInfo hides the system-dependent info of the wrapped FileInfo to -// prevent tar.FileInfoHeader from introspecting it and potentially calling into -// glibc. -type nosysFileInfo struct { - os.FileInfo -} - -func (fi nosysFileInfo) Sys() interface{} { - // A Sys value of type *tar.Header is safe as it is system-independent. - // The tar.FileInfoHeader function copies the fields into the returned - // header without performing any OS lookups. - if sys, ok := fi.FileInfo.Sys().(*tar.Header); ok { - return sys - } - return nil -} - -// sysStat, if non-nil, populates hdr from system-dependent fields of fi. -var sysStat func(fi os.FileInfo, hdr *tar.Header) error - -// FileInfoHeaderNoLookups creates a partially-populated tar.Header from fi. -// -// Compared to the archive/tar.FileInfoHeader function, this function is safe to -// call from a chrooted process as it does not populate fields which would -// require operating system lookups. It behaves identically to -// tar.FileInfoHeader when fi is a FileInfo value returned from -// tar.Header.FileInfo(). -// -// When fi is a FileInfo for a native file, such as returned from os.Stat() and -// os.Lstat(), the returned Header value differs from one returned from -// tar.FileInfoHeader in the following ways. The Uname and Gname fields are not -// set as OS lookups would be required to populate them. The AccessTime and -// ChangeTime fields are not currently set (not yet implemented) although that -// is subject to change. Callers which require the AccessTime or ChangeTime -// fields to be zeroed should explicitly zero them out in the returned Header -// value to avoid any compatibility issues in the future. -func FileInfoHeaderNoLookups(fi os.FileInfo, link string) (*tar.Header, error) { - hdr, err := tar.FileInfoHeader(nosysFileInfo{fi}, link) - if err != nil { - return nil, err - } - if sysStat != nil { - return hdr, sysStat(fi, hdr) - } - return hdr, nil -} - -// FileInfoHeader creates a populated Header from fi. -// -// Compared to the archive/tar package, this function fills in less information -// but is safe to call from a chrooted process. The AccessTime and ChangeTime -// fields are not set in the returned header, ModTime is truncated to one-second -// precision, and the Uname and Gname fields are only set when fi is a FileInfo -// value returned from tar.Header.FileInfo(). -func FileInfoHeader(name string, fi os.FileInfo, link string) (*tar.Header, error) { - hdr, err := FileInfoHeaderNoLookups(fi, link) - if err != nil { - return nil, err - } - hdr.Format = tar.FormatPAX - hdr.ModTime = hdr.ModTime.Truncate(time.Second) - hdr.AccessTime = time.Time{} - hdr.ChangeTime = time.Time{} - hdr.Mode = int64(chmodTarEntry(os.FileMode(hdr.Mode))) - hdr.Name = canonicalTarName(name, fi.IsDir()) - return hdr, nil -} - -// ReadSecurityXattrToTarHeader reads security.capability xattr from filesystem -// to a tar header -func ReadSecurityXattrToTarHeader(path string, hdr *tar.Header) error { - const ( - // Values based on linux/include/uapi/linux/capability.h - xattrCapsSz2 = 20 - versionOffset = 3 - vfsCapRevision2 = 2 - vfsCapRevision3 = 3 - ) - capability, _ := system.Lgetxattr(path, "security.capability") - if capability != nil { - length := len(capability) - if capability[versionOffset] == vfsCapRevision3 { - // Convert VFS_CAP_REVISION_3 to VFS_CAP_REVISION_2 as root UID makes no - // sense outside the user namespace the archive is built in. - capability[versionOffset] = vfsCapRevision2 - length = xattrCapsSz2 - } - hdr.Xattrs = make(map[string]string) - hdr.Xattrs["security.capability"] = string(capability[:length]) - } - return nil -} - -type tarWhiteoutConverter interface { - ConvertWrite(*tar.Header, string, os.FileInfo) (*tar.Header, error) - ConvertRead(*tar.Header, string) (bool, error) -} - -type tarAppender struct { - TarWriter *tar.Writer - Buffer *bufio.Writer - - // for hardlink mapping - SeenFiles map[uint64]string - IdentityMapping idtools.IdentityMapping - ChownOpts *idtools.Identity - - // For packing and unpacking whiteout files in the - // non standard format. The whiteout files defined - // by the AUFS standard are used as the tar whiteout - // standard. - WhiteoutConverter tarWhiteoutConverter -} - -func newTarAppender(idMapping idtools.IdentityMapping, writer io.Writer, chownOpts *idtools.Identity) *tarAppender { - return &tarAppender{ - SeenFiles: make(map[uint64]string), - TarWriter: tar.NewWriter(writer), - Buffer: pools.BufioWriter32KPool.Get(nil), - IdentityMapping: idMapping, - ChownOpts: chownOpts, - } -} - -// CanonicalTarNameForPath canonicalizes relativePath to a POSIX-style path using -// forward slashes. It is an alias for filepath.ToSlash, which is a no-op on -// Linux and Unix. -func CanonicalTarNameForPath(relativePath string) string { - return filepath.ToSlash(relativePath) -} - -// canonicalTarName provides a platform-independent and consistent POSIX-style -// path for files and directories to be archived regardless of the platform. -func canonicalTarName(name string, isDir bool) string { - name = filepath.ToSlash(name) - - // suffix with '/' for directories - if isDir && !strings.HasSuffix(name, "/") { - name += "/" - } - return name -} - -// addTarFile adds to the tar archive a file from `path` as `name` -func (ta *tarAppender) addTarFile(path, name string) error { - fi, err := os.Lstat(path) - if err != nil { - return err - } - - var link string - if fi.Mode()&os.ModeSymlink != 0 { - var err error - link, err = os.Readlink(path) - if err != nil { - return err - } - } - - hdr, err := FileInfoHeader(name, fi, link) - if err != nil { - return err - } - if err := ReadSecurityXattrToTarHeader(path, hdr); err != nil { - return err - } - - // if it's not a directory and has more than 1 link, - // it's hard linked, so set the type flag accordingly - if !fi.IsDir() && hasHardlinks(fi) { - inode, err := getInodeFromStat(fi.Sys()) - if err != nil { - return err - } - // a link should have a name that it links too - // and that linked name should be first in the tar archive - if oldpath, ok := ta.SeenFiles[inode]; ok { - hdr.Typeflag = tar.TypeLink - hdr.Linkname = oldpath - hdr.Size = 0 // This Must be here for the writer math to add up! - } else { - ta.SeenFiles[inode] = name - } - } - - // check whether the file is overlayfs whiteout - // if yes, skip re-mapping container ID mappings. - isOverlayWhiteout := fi.Mode()&os.ModeCharDevice != 0 && hdr.Devmajor == 0 && hdr.Devminor == 0 - - // handle re-mapping container ID mappings back to host ID mappings before - // writing tar headers/files. We skip whiteout files because they were written - // by the kernel and already have proper ownership relative to the host - if !isOverlayWhiteout && !strings.HasPrefix(filepath.Base(hdr.Name), WhiteoutPrefix) && !ta.IdentityMapping.Empty() { - fileIDPair, err := getFileUIDGID(fi.Sys()) - if err != nil { - return err - } - hdr.Uid, hdr.Gid, err = ta.IdentityMapping.ToContainer(fileIDPair) - if err != nil { - return err - } - } - - // explicitly override with ChownOpts - if ta.ChownOpts != nil { - hdr.Uid = ta.ChownOpts.UID - hdr.Gid = ta.ChownOpts.GID - } - - if ta.WhiteoutConverter != nil { - wo, err := ta.WhiteoutConverter.ConvertWrite(hdr, path, fi) - if err != nil { - return err - } - - // If a new whiteout file exists, write original hdr, then - // replace hdr with wo to be written after. Whiteouts should - // always be written after the original. Note the original - // hdr may have been updated to be a whiteout with returning - // a whiteout header - if wo != nil { - if err := ta.TarWriter.WriteHeader(hdr); err != nil { - return err - } - if hdr.Typeflag == tar.TypeReg && hdr.Size > 0 { - return fmt.Errorf("tar: cannot use whiteout for non-empty file") - } - hdr = wo - } - } - - if err := ta.TarWriter.WriteHeader(hdr); err != nil { - return err - } - - if hdr.Typeflag == tar.TypeReg && hdr.Size > 0 { - // We use sequential file access to avoid depleting the standby list on - // Windows. On Linux, this equates to a regular os.Open. - file, err := sequential.Open(path) - if err != nil { - return err - } - - ta.Buffer.Reset(ta.TarWriter) - defer ta.Buffer.Reset(nil) - _, err = io.Copy(ta.Buffer, file) - file.Close() - if err != nil { - return err - } - err = ta.Buffer.Flush() - if err != nil { - return err - } - } - - return nil -} - -func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader, Lchown bool, chownOpts *idtools.Identity, inUserns bool) error { - // hdr.Mode is in linux format, which we can use for sycalls, - // but for os.Foo() calls we need the mode converted to os.FileMode, - // so use hdrInfo.Mode() (they differ for e.g. setuid bits) - hdrInfo := hdr.FileInfo() - - switch hdr.Typeflag { - case tar.TypeDir: - // Create directory unless it exists as a directory already. - // In that case we just want to merge the two - if fi, err := os.Lstat(path); !(err == nil && fi.IsDir()) { - if err := os.Mkdir(path, hdrInfo.Mode()); err != nil { - return err - } - } - - case tar.TypeReg: - // Source is regular file. We use sequential file access to avoid depleting - // the standby list on Windows. On Linux, this equates to a regular os.OpenFile. - file, err := sequential.OpenFile(path, os.O_CREATE|os.O_WRONLY, hdrInfo.Mode()) - if err != nil { - return err - } - if _, err := io.Copy(file, reader); err != nil { - file.Close() - return err - } - file.Close() - - case tar.TypeBlock, tar.TypeChar: - if inUserns { // cannot create devices in a userns - return nil - } - // Handle this is an OS-specific way - if err := handleTarTypeBlockCharFifo(hdr, path); err != nil { - return err - } - - case tar.TypeFifo: - // Handle this is an OS-specific way - if err := handleTarTypeBlockCharFifo(hdr, path); err != nil { - return err - } - - case tar.TypeLink: - // #nosec G305 -- The target path is checked for path traversal. - targetPath := filepath.Join(extractDir, hdr.Linkname) - // check for hardlink breakout - if !strings.HasPrefix(targetPath, extractDir) { - return breakoutError(fmt.Errorf("invalid hardlink %q -> %q", targetPath, hdr.Linkname)) - } - if err := os.Link(targetPath, path); err != nil { - return err - } - - case tar.TypeSymlink: - // path -> hdr.Linkname = targetPath - // e.g. /extractDir/path/to/symlink -> ../2/file = /extractDir/path/2/file - targetPath := filepath.Join(filepath.Dir(path), hdr.Linkname) // #nosec G305 -- The target path is checked for path traversal. - - // the reason we don't need to check symlinks in the path (with FollowSymlinkInScope) is because - // that symlink would first have to be created, which would be caught earlier, at this very check: - if !strings.HasPrefix(targetPath, extractDir) { - return breakoutError(fmt.Errorf("invalid symlink %q -> %q", path, hdr.Linkname)) - } - if err := os.Symlink(hdr.Linkname, path); err != nil { - return err - } - - case tar.TypeXGlobalHeader: - logrus.Debug("PAX Global Extended Headers found and ignored") - return nil - - default: - return fmt.Errorf("unhandled tar header type %d", hdr.Typeflag) - } - - // Lchown is not supported on Windows. - if Lchown && runtime.GOOS != "windows" { - if chownOpts == nil { - chownOpts = &idtools.Identity{UID: hdr.Uid, GID: hdr.Gid} - } - if err := os.Lchown(path, chownOpts.UID, chownOpts.GID); err != nil { - msg := "failed to Lchown %q for UID %d, GID %d" - if errors.Is(err, syscall.EINVAL) && userns.RunningInUserNS() { - msg += " (try increasing the number of subordinate IDs in /etc/subuid and /etc/subgid)" - } - return errors.Wrapf(err, msg, path, hdr.Uid, hdr.Gid) - } - } - - var errors []string - for key, value := range hdr.Xattrs { - if err := system.Lsetxattr(path, key, []byte(value), 0); err != nil { - if err == syscall.ENOTSUP || err == syscall.EPERM { - // We ignore errors here because not all graphdrivers support - // xattrs *cough* old versions of AUFS *cough*. However only - // ENOTSUP should be emitted in that case, otherwise we still - // bail. - // EPERM occurs if modifying xattrs is not allowed. This can - // happen when running in userns with restrictions (ChromeOS). - errors = append(errors, err.Error()) - continue - } - return err - } - } - - if len(errors) > 0 { - logrus.WithFields(logrus.Fields{ - "errors": errors, - }).Warn("ignored xattrs in archive: underlying filesystem doesn't support them") - } - - // There is no LChmod, so ignore mode for symlink. Also, this - // must happen after chown, as that can modify the file mode - if err := handleLChmod(hdr, path, hdrInfo); err != nil { - return err - } - - aTime := hdr.AccessTime - if aTime.Before(hdr.ModTime) { - // Last access time should never be before last modified time. - aTime = hdr.ModTime - } - - // system.Chtimes doesn't support a NOFOLLOW flag atm - if hdr.Typeflag == tar.TypeLink { - if fi, err := os.Lstat(hdr.Linkname); err == nil && (fi.Mode()&os.ModeSymlink == 0) { - if err := system.Chtimes(path, aTime, hdr.ModTime); err != nil { - return err - } - } - } else if hdr.Typeflag != tar.TypeSymlink { - if err := system.Chtimes(path, aTime, hdr.ModTime); err != nil { - return err - } - } else { - ts := []syscall.Timespec{timeToTimespec(aTime), timeToTimespec(hdr.ModTime)} - if err := system.LUtimesNano(path, ts); err != nil && err != system.ErrNotSupportedPlatform { - return err - } - } - return nil -} - -// Tar creates an archive from the directory at `path`, and returns it as a -// stream of bytes. -func Tar(path string, compression Compression) (io.ReadCloser, error) { - return TarWithOptions(path, &TarOptions{Compression: compression}) -} - -// TarWithOptions creates an archive from the directory at `path`, only including files whose relative -// paths are included in `options.IncludeFiles` (if non-nil) or not in `options.ExcludePatterns`. -func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) { - tb, err := NewTarballer(srcPath, options) - if err != nil { - return nil, err - } - go tb.Do() - return tb.Reader(), nil -} - -// Tarballer is a lower-level interface to TarWithOptions which gives the caller -// control over which goroutine the archiving operation executes on. -type Tarballer struct { - srcPath string - options *TarOptions - pm *patternmatcher.PatternMatcher - pipeReader *io.PipeReader - pipeWriter *io.PipeWriter - compressWriter io.WriteCloser - whiteoutConverter tarWhiteoutConverter -} - -// NewTarballer constructs a new tarballer. The arguments are the same as for -// TarWithOptions. -func NewTarballer(srcPath string, options *TarOptions) (*Tarballer, error) { - pm, err := patternmatcher.New(options.ExcludePatterns) - if err != nil { - return nil, err - } - - pipeReader, pipeWriter := io.Pipe() - - compressWriter, err := CompressStream(pipeWriter, options.Compression) - if err != nil { - return nil, err - } - - whiteoutConverter, err := getWhiteoutConverter(options.WhiteoutFormat, options.InUserNS) - if err != nil { - return nil, err - } - - return &Tarballer{ - // Fix the source path to work with long path names. This is a no-op - // on platforms other than Windows. - srcPath: fixVolumePathPrefix(srcPath), - options: options, - pm: pm, - pipeReader: pipeReader, - pipeWriter: pipeWriter, - compressWriter: compressWriter, - whiteoutConverter: whiteoutConverter, - }, nil -} - -// Reader returns the reader for the created archive. -func (t *Tarballer) Reader() io.ReadCloser { - return t.pipeReader -} - -// Do performs the archiving operation in the background. The resulting archive -// can be read from t.Reader(). Do should only be called once on each Tarballer -// instance. -func (t *Tarballer) Do() { - ta := newTarAppender( - t.options.IDMap, - t.compressWriter, - t.options.ChownOpts, - ) - ta.WhiteoutConverter = t.whiteoutConverter - - defer func() { - // Make sure to check the error on Close. - if err := ta.TarWriter.Close(); err != nil { - logrus.Errorf("Can't close tar writer: %s", err) - } - if err := t.compressWriter.Close(); err != nil { - logrus.Errorf("Can't close compress writer: %s", err) - } - if err := t.pipeWriter.Close(); err != nil { - logrus.Errorf("Can't close pipe writer: %s", err) - } - }() - - // this buffer is needed for the duration of this piped stream - defer pools.BufioWriter32KPool.Put(ta.Buffer) - - // In general we log errors here but ignore them because - // during e.g. a diff operation the container can continue - // mutating the filesystem and we can see transient errors - // from this - - stat, err := os.Lstat(t.srcPath) - if err != nil { - return - } - - if !stat.IsDir() { - // We can't later join a non-dir with any includes because the - // 'walk' will error if "file/." is stat-ed and "file" is not a - // directory. So, we must split the source path and use the - // basename as the include. - if len(t.options.IncludeFiles) > 0 { - logrus.Warn("Tar: Can't archive a file with includes") - } - - dir, base := SplitPathDirEntry(t.srcPath) - t.srcPath = dir - t.options.IncludeFiles = []string{base} - } - - if len(t.options.IncludeFiles) == 0 { - t.options.IncludeFiles = []string{"."} - } - - seen := make(map[string]bool) - - for _, include := range t.options.IncludeFiles { - rebaseName := t.options.RebaseNames[include] - - var ( - parentMatchInfo []patternmatcher.MatchInfo - parentDirs []string - ) - - walkRoot := getWalkRoot(t.srcPath, include) - filepath.WalkDir(walkRoot, func(filePath string, f os.DirEntry, err error) error { - if err != nil { - logrus.Errorf("Tar: Can't stat file %s to tar: %s", t.srcPath, err) - return nil - } - - relFilePath, err := filepath.Rel(t.srcPath, filePath) - if err != nil || (!t.options.IncludeSourceDir && relFilePath == "." && f.IsDir()) { - // Error getting relative path OR we are looking - // at the source directory path. Skip in both situations. - return nil - } - - if t.options.IncludeSourceDir && include == "." && relFilePath != "." { - relFilePath = strings.Join([]string{".", relFilePath}, string(filepath.Separator)) - } - - skip := false - - // If "include" is an exact match for the current file - // then even if there's an "excludePatterns" pattern that - // matches it, don't skip it. IOW, assume an explicit 'include' - // is asking for that file no matter what - which is true - // for some files, like .dockerignore and Dockerfile (sometimes) - if include != relFilePath { - for len(parentDirs) != 0 { - lastParentDir := parentDirs[len(parentDirs)-1] - if strings.HasPrefix(relFilePath, lastParentDir+string(os.PathSeparator)) { - break - } - parentDirs = parentDirs[:len(parentDirs)-1] - parentMatchInfo = parentMatchInfo[:len(parentMatchInfo)-1] - } - - var matchInfo patternmatcher.MatchInfo - if len(parentMatchInfo) != 0 { - skip, matchInfo, err = t.pm.MatchesUsingParentResults(relFilePath, parentMatchInfo[len(parentMatchInfo)-1]) - } else { - skip, matchInfo, err = t.pm.MatchesUsingParentResults(relFilePath, patternmatcher.MatchInfo{}) - } - if err != nil { - logrus.Errorf("Error matching %s: %v", relFilePath, err) - return err - } - - if f.IsDir() { - parentDirs = append(parentDirs, relFilePath) - parentMatchInfo = append(parentMatchInfo, matchInfo) - } - } - - if skip { - // If we want to skip this file and its a directory - // then we should first check to see if there's an - // excludes pattern (e.g. !dir/file) that starts with this - // dir. If so then we can't skip this dir. - - // Its not a dir then so we can just return/skip. - if !f.IsDir() { - return nil - } - - // No exceptions (!...) in patterns so just skip dir - if !t.pm.Exclusions() { - return filepath.SkipDir - } - - dirSlash := relFilePath + string(filepath.Separator) - - for _, pat := range t.pm.Patterns() { - if !pat.Exclusion() { - continue - } - if strings.HasPrefix(pat.String()+string(filepath.Separator), dirSlash) { - // found a match - so can't skip this dir - return nil - } - } - - // No matching exclusion dir so just skip dir - return filepath.SkipDir - } - - if seen[relFilePath] { - return nil - } - seen[relFilePath] = true - - // Rename the base resource. - if rebaseName != "" { - var replacement string - if rebaseName != string(filepath.Separator) { - // Special case the root directory to replace with an - // empty string instead so that we don't end up with - // double slashes in the paths. - replacement = rebaseName - } - - relFilePath = strings.Replace(relFilePath, include, replacement, 1) - } - - if err := ta.addTarFile(filePath, relFilePath); err != nil { - logrus.Errorf("Can't add file %s to tar: %s", filePath, err) - // if pipe is broken, stop writing tar stream to it - if err == io.ErrClosedPipe { - return err - } - } - return nil - }) - } -} - -// Unpack unpacks the decompressedArchive to dest with options. -func Unpack(decompressedArchive io.Reader, dest string, options *TarOptions) error { - tr := tar.NewReader(decompressedArchive) - trBuf := pools.BufioReader32KPool.Get(nil) - defer pools.BufioReader32KPool.Put(trBuf) - - var dirs []*tar.Header - whiteoutConverter, err := getWhiteoutConverter(options.WhiteoutFormat, options.InUserNS) - if err != nil { - return err - } - - // Iterate through the files in the archive. -loop: - for { - hdr, err := tr.Next() - if err == io.EOF { - // end of tar archive - break - } - if err != nil { - return err - } - - // ignore XGlobalHeader early to avoid creating parent directories for them - if hdr.Typeflag == tar.TypeXGlobalHeader { - logrus.Debugf("PAX Global Extended Headers found for %s and ignored", hdr.Name) - continue - } - - // Normalize name, for safety and for a simple is-root check - // This keeps "../" as-is, but normalizes "/../" to "/". Or Windows: - // This keeps "..\" as-is, but normalizes "\..\" to "\". - hdr.Name = filepath.Clean(hdr.Name) - - for _, exclude := range options.ExcludePatterns { - if strings.HasPrefix(hdr.Name, exclude) { - continue loop - } - } - - // Ensure that the parent directory exists. - err = createImpliedDirectories(dest, hdr, options) - if err != nil { - return err - } - - // #nosec G305 -- The joined path is checked for path traversal. - path := filepath.Join(dest, hdr.Name) - rel, err := filepath.Rel(dest, path) - if err != nil { - return err - } - if strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { - return breakoutError(fmt.Errorf("%q is outside of %q", hdr.Name, dest)) - } - - // If path exits we almost always just want to remove and replace it - // The only exception is when it is a directory *and* the file from - // the layer is also a directory. Then we want to merge them (i.e. - // just apply the metadata from the layer). - if fi, err := os.Lstat(path); err == nil { - if options.NoOverwriteDirNonDir && fi.IsDir() && hdr.Typeflag != tar.TypeDir { - // If NoOverwriteDirNonDir is true then we cannot replace - // an existing directory with a non-directory from the archive. - return fmt.Errorf("cannot overwrite directory %q with non-directory %q", path, dest) - } - - if options.NoOverwriteDirNonDir && !fi.IsDir() && hdr.Typeflag == tar.TypeDir { - // If NoOverwriteDirNonDir is true then we cannot replace - // an existing non-directory with a directory from the archive. - return fmt.Errorf("cannot overwrite non-directory %q with directory %q", path, dest) - } - - if fi.IsDir() && hdr.Name == "." { - continue - } - - if !(fi.IsDir() && hdr.Typeflag == tar.TypeDir) { - if err := os.RemoveAll(path); err != nil { - return err - } - } - } - trBuf.Reset(tr) - - if err := remapIDs(options.IDMap, hdr); err != nil { - return err - } - - if whiteoutConverter != nil { - writeFile, err := whiteoutConverter.ConvertRead(hdr, path) - if err != nil { - return err - } - if !writeFile { - continue - } - } - - if err := createTarFile(path, dest, hdr, trBuf, !options.NoLchown, options.ChownOpts, options.InUserNS); err != nil { - return err - } - - // Directory mtimes must be handled at the end to avoid further - // file creation in them to modify the directory mtime - if hdr.Typeflag == tar.TypeDir { - dirs = append(dirs, hdr) - } - } - - for _, hdr := range dirs { - // #nosec G305 -- The header was checked for path traversal before it was appended to the dirs slice. - path := filepath.Join(dest, hdr.Name) - - if err := system.Chtimes(path, hdr.AccessTime, hdr.ModTime); err != nil { - return err - } - } - return nil -} - -// createImpliedDirectories will create all parent directories of the current path with default permissions, if they do -// not already exist. This is possible as the tar format supports 'implicit' directories, where their existence is -// defined by the paths of files in the tar, but there are no header entries for the directories themselves, and thus -// we most both create them and choose metadata like permissions. -// -// The caller should have performed filepath.Clean(hdr.Name), so hdr.Name will now be in the filepath format for the OS -// on which the daemon is running. This precondition is required because this function assumes a OS-specific path -// separator when checking that a path is not the root. -func createImpliedDirectories(dest string, hdr *tar.Header, options *TarOptions) error { - // Not the root directory, ensure that the parent directory exists - if !strings.HasSuffix(hdr.Name, string(os.PathSeparator)) { - parent := filepath.Dir(hdr.Name) - parentPath := filepath.Join(dest, parent) - if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) { - // RootPair() is confined inside this loop as most cases will not require a call, so we can spend some - // unneeded function calls in the uncommon case to encapsulate logic -- implied directories are a niche - // usage that reduces the portability of an image. - rootIDs := options.IDMap.RootPair() - - err = idtools.MkdirAllAndChownNew(parentPath, ImpliedDirectoryMode, rootIDs) - if err != nil { - return err - } - } - } - - return nil -} - -// Untar reads a stream of bytes from `archive`, parses it as a tar archive, -// and unpacks it into the directory at `dest`. -// The archive may be compressed with one of the following algorithms: -// identity (uncompressed), gzip, bzip2, xz. -// -// FIXME: specify behavior when target path exists vs. doesn't exist. -func Untar(tarArchive io.Reader, dest string, options *TarOptions) error { - return untarHandler(tarArchive, dest, options, true) -} - -// UntarUncompressed reads a stream of bytes from `archive`, parses it as a tar archive, -// and unpacks it into the directory at `dest`. -// The archive must be an uncompressed stream. -func UntarUncompressed(tarArchive io.Reader, dest string, options *TarOptions) error { - return untarHandler(tarArchive, dest, options, false) -} - -// Handler for teasing out the automatic decompression -func untarHandler(tarArchive io.Reader, dest string, options *TarOptions, decompress bool) error { - if tarArchive == nil { - return fmt.Errorf("Empty archive") - } - dest = filepath.Clean(dest) - if options == nil { - options = &TarOptions{} - } - if options.ExcludePatterns == nil { - options.ExcludePatterns = []string{} - } - - r := tarArchive - if decompress { - decompressedArchive, err := DecompressStream(tarArchive) - if err != nil { - return err - } - defer decompressedArchive.Close() - r = decompressedArchive - } - - return Unpack(r, dest, options) -} - -// TarUntar is a convenience function which calls Tar and Untar, with the output of one piped into the other. -// If either Tar or Untar fails, TarUntar aborts and returns the error. -func (archiver *Archiver) TarUntar(src, dst string) error { - archive, err := TarWithOptions(src, &TarOptions{Compression: Uncompressed}) - if err != nil { - return err - } - defer archive.Close() - options := &TarOptions{ - IDMap: archiver.IDMapping, - } - return archiver.Untar(archive, dst, options) -} - -// UntarPath untar a file from path to a destination, src is the source tar file path. -func (archiver *Archiver) UntarPath(src, dst string) error { - archive, err := os.Open(src) - if err != nil { - return err - } - defer archive.Close() - options := &TarOptions{ - IDMap: archiver.IDMapping, - } - return archiver.Untar(archive, dst, options) -} - -// CopyWithTar creates a tar archive of filesystem path `src`, and -// unpacks it at filesystem path `dst`. -// The archive is streamed directly with fixed buffering and no -// intermediary disk IO. -func (archiver *Archiver) CopyWithTar(src, dst string) error { - srcSt, err := os.Stat(src) - if err != nil { - return err - } - if !srcSt.IsDir() { - return archiver.CopyFileWithTar(src, dst) - } - - // if this Archiver is set up with ID mapping we need to create - // the new destination directory with the remapped root UID/GID pair - // as owner - rootIDs := archiver.IDMapping.RootPair() - // Create dst, copy src's content into it - if err := idtools.MkdirAllAndChownNew(dst, 0755, rootIDs); err != nil { - return err - } - return archiver.TarUntar(src, dst) -} - -// CopyFileWithTar emulates the behavior of the 'cp' command-line -// for a single file. It copies a regular file from path `src` to -// path `dst`, and preserves all its metadata. -func (archiver *Archiver) CopyFileWithTar(src, dst string) (err error) { - srcSt, err := os.Stat(src) - if err != nil { - return err - } - - if srcSt.IsDir() { - return fmt.Errorf("Can't copy a directory") - } - - // Clean up the trailing slash. This must be done in an operating - // system specific manner. - if dst[len(dst)-1] == os.PathSeparator { - dst = filepath.Join(dst, filepath.Base(src)) - } - // Create the holding directory if necessary - if err := system.MkdirAll(filepath.Dir(dst), 0700); err != nil { - return err - } - - r, w := io.Pipe() - errC := make(chan error, 1) - - go func() { - defer close(errC) - - errC <- func() error { - defer w.Close() - - srcF, err := os.Open(src) - if err != nil { - return err - } - defer srcF.Close() - - hdr, err := FileInfoHeaderNoLookups(srcSt, "") - if err != nil { - return err - } - hdr.Format = tar.FormatPAX - hdr.ModTime = hdr.ModTime.Truncate(time.Second) - hdr.AccessTime = time.Time{} - hdr.ChangeTime = time.Time{} - hdr.Name = filepath.Base(dst) - hdr.Mode = int64(chmodTarEntry(os.FileMode(hdr.Mode))) - - if err := remapIDs(archiver.IDMapping, hdr); err != nil { - return err - } - - tw := tar.NewWriter(w) - defer tw.Close() - if err := tw.WriteHeader(hdr); err != nil { - return err - } - if _, err := io.Copy(tw, srcF); err != nil { - return err - } - return nil - }() - }() - defer func() { - if er := <-errC; err == nil && er != nil { - err = er - } - }() - - err = archiver.Untar(r, filepath.Dir(dst), nil) - if err != nil { - r.CloseWithError(err) - } - return err -} - -// IdentityMapping returns the IdentityMapping of the archiver. -func (archiver *Archiver) IdentityMapping() idtools.IdentityMapping { - return archiver.IDMapping -} - -func remapIDs(idMapping idtools.IdentityMapping, hdr *tar.Header) error { - ids, err := idMapping.ToHost(idtools.Identity{UID: hdr.Uid, GID: hdr.Gid}) - hdr.Uid, hdr.Gid = ids.UID, ids.GID - return err -} - -// cmdStream executes a command, and returns its stdout as a stream. -// If the command fails to run or doesn't complete successfully, an error -// will be returned, including anything written on stderr. -func cmdStream(cmd *exec.Cmd, input io.Reader) (io.ReadCloser, error) { - cmd.Stdin = input - pipeR, pipeW := io.Pipe() - cmd.Stdout = pipeW - var errBuf bytes.Buffer - cmd.Stderr = &errBuf - - // Run the command and return the pipe - if err := cmd.Start(); err != nil { - return nil, err - } - - // Ensure the command has exited before we clean anything up - done := make(chan struct{}) - - // Copy stdout to the returned pipe - go func() { - if err := cmd.Wait(); err != nil { - pipeW.CloseWithError(fmt.Errorf("%s: %s", err, errBuf.String())) - } else { - pipeW.Close() - } - close(done) - }() - - return ioutils.NewReadCloserWrapper(pipeR, func() error { - // Close pipeR, and then wait for the command to complete before returning. We have to close pipeR first, as - // cmd.Wait waits for any non-file stdout/stderr/stdin to close. - err := pipeR.Close() - <-done - return err - }), nil -} - -// NewTempArchive reads the content of src into a temporary file, and returns the contents -// of that file as an archive. The archive can only be read once - as soon as reading completes, -// the file will be deleted. -func NewTempArchive(src io.Reader, dir string) (*TempArchive, error) { - f, err := os.CreateTemp(dir, "") - if err != nil { - return nil, err - } - if _, err := io.Copy(f, src); err != nil { - return nil, err - } - if _, err := f.Seek(0, 0); err != nil { - return nil, err - } - st, err := f.Stat() - if err != nil { - return nil, err - } - size := st.Size() - return &TempArchive{File: f, Size: size}, nil -} - -// TempArchive is a temporary archive. The archive can only be read once - as soon as reading completes, -// the file will be deleted. -type TempArchive struct { - *os.File - Size int64 // Pre-computed from Stat().Size() as a convenience - read int64 - closed bool -} - -// Close closes the underlying file if it's still open, or does a no-op -// to allow callers to try to close the TempArchive multiple times safely. -func (archive *TempArchive) Close() error { - if archive.closed { - return nil - } - - archive.closed = true - - return archive.File.Close() -} - -func (archive *TempArchive) Read(data []byte) (int, error) { - n, err := archive.File.Read(data) - archive.read += int64(n) - if err != nil || archive.read == archive.Size { - archive.Close() - os.Remove(archive.File.Name()) - } - return n, err -} diff --git a/vendor/github.com/docker/docker/pkg/archive/archive_linux.go b/vendor/github.com/docker/docker/pkg/archive/archive_linux.go deleted file mode 100644 index 76321a35e..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/archive_linux.go +++ /dev/null @@ -1,100 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "archive/tar" - "os" - "path/filepath" - "strings" - - "github.com/docker/docker/pkg/system" - "github.com/pkg/errors" - "golang.org/x/sys/unix" -) - -func getWhiteoutConverter(format WhiteoutFormat, inUserNS bool) (tarWhiteoutConverter, error) { - if format == OverlayWhiteoutFormat { - if inUserNS { - return nil, errors.New("specifying OverlayWhiteoutFormat is not allowed in userns") - } - return overlayWhiteoutConverter{}, nil - } - return nil, nil -} - -type overlayWhiteoutConverter struct { -} - -func (overlayWhiteoutConverter) ConvertWrite(hdr *tar.Header, path string, fi os.FileInfo) (wo *tar.Header, err error) { - // convert whiteouts to AUFS format - if fi.Mode()&os.ModeCharDevice != 0 && hdr.Devmajor == 0 && hdr.Devminor == 0 { - // we just rename the file and make it normal - dir, filename := filepath.Split(hdr.Name) - hdr.Name = filepath.Join(dir, WhiteoutPrefix+filename) - hdr.Mode = 0600 - hdr.Typeflag = tar.TypeReg - hdr.Size = 0 - } - - if fi.Mode()&os.ModeDir != 0 { - // convert opaque dirs to AUFS format by writing an empty file with the prefix - opaque, err := system.Lgetxattr(path, "trusted.overlay.opaque") - if err != nil { - return nil, err - } - if len(opaque) == 1 && opaque[0] == 'y' { - if hdr.Xattrs != nil { - delete(hdr.Xattrs, "trusted.overlay.opaque") - } - - // create a header for the whiteout file - // it should inherit some properties from the parent, but be a regular file - wo = &tar.Header{ - Typeflag: tar.TypeReg, - Mode: hdr.Mode & int64(os.ModePerm), - Name: filepath.Join(hdr.Name, WhiteoutOpaqueDir), - Size: 0, - Uid: hdr.Uid, - Uname: hdr.Uname, - Gid: hdr.Gid, - Gname: hdr.Gname, - AccessTime: hdr.AccessTime, - ChangeTime: hdr.ChangeTime, - } //#nosec G305 -- An archive is being created, not extracted. - } - } - - return -} - -func (c overlayWhiteoutConverter) ConvertRead(hdr *tar.Header, path string) (bool, error) { - base := filepath.Base(path) - dir := filepath.Dir(path) - - // if a directory is marked as opaque by the AUFS special file, we need to translate that to overlay - if base == WhiteoutOpaqueDir { - err := unix.Setxattr(dir, "trusted.overlay.opaque", []byte{'y'}, 0) - if err != nil { - return false, errors.Wrapf(err, "setxattr(%q, trusted.overlay.opaque=y)", dir) - } - // don't write the file itself - return false, err - } - - // if a file was deleted and we are using overlay, we need to create a character device - if strings.HasPrefix(base, WhiteoutPrefix) { - originalBase := base[len(WhiteoutPrefix):] - originalPath := filepath.Join(dir, originalBase) - - if err := unix.Mknod(originalPath, unix.S_IFCHR, 0); err != nil { - return false, errors.Wrapf(err, "failed to mknod(%q, S_IFCHR, 0)", originalPath) - } - if err := os.Chown(originalPath, hdr.Uid, hdr.Gid); err != nil { - return false, err - } - - // don't write the file itself - return false, nil - } - - return true, nil -} diff --git a/vendor/github.com/docker/docker/pkg/archive/archive_other.go b/vendor/github.com/docker/docker/pkg/archive/archive_other.go deleted file mode 100644 index 28ae2769c..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/archive_other.go +++ /dev/null @@ -1,8 +0,0 @@ -//go:build !linux -// +build !linux - -package archive // import "github.com/docker/docker/pkg/archive" - -func getWhiteoutConverter(format WhiteoutFormat, inUserNS bool) (tarWhiteoutConverter, error) { - return nil, nil -} diff --git a/vendor/github.com/docker/docker/pkg/archive/archive_unix.go b/vendor/github.com/docker/docker/pkg/archive/archive_unix.go deleted file mode 100644 index 92d8e23dd..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/archive_unix.go +++ /dev/null @@ -1,117 +0,0 @@ -//go:build !windows -// +build !windows - -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "archive/tar" - "errors" - "os" - "path/filepath" - "strings" - "syscall" - - "github.com/containerd/containerd/pkg/userns" - "github.com/docker/docker/pkg/idtools" - "github.com/docker/docker/pkg/system" - "golang.org/x/sys/unix" -) - -func init() { - sysStat = statUnix -} - -// fixVolumePathPrefix does platform specific processing to ensure that if -// the path being passed in is not in a volume path format, convert it to one. -func fixVolumePathPrefix(srcPath string) string { - return srcPath -} - -// getWalkRoot calculates the root path when performing a TarWithOptions. -// We use a separate function as this is platform specific. On Linux, we -// can't use filepath.Join(srcPath,include) because this will clean away -// a trailing "." or "/" which may be important. -func getWalkRoot(srcPath string, include string) string { - return strings.TrimSuffix(srcPath, string(filepath.Separator)) + string(filepath.Separator) + include -} - -// chmodTarEntry is used to adjust the file permissions used in tar header based -// on the platform the archival is done. -func chmodTarEntry(perm os.FileMode) os.FileMode { - return perm // noop for unix as golang APIs provide perm bits correctly -} - -// statUnix populates hdr from system-dependent fields of fi without performing -// any OS lookups. -func statUnix(fi os.FileInfo, hdr *tar.Header) error { - s, ok := fi.Sys().(*syscall.Stat_t) - if !ok { - return nil - } - - hdr.Uid = int(s.Uid) - hdr.Gid = int(s.Gid) - - if s.Mode&unix.S_IFBLK != 0 || - s.Mode&unix.S_IFCHR != 0 { - hdr.Devmajor = int64(unix.Major(uint64(s.Rdev))) //nolint: unconvert - hdr.Devminor = int64(unix.Minor(uint64(s.Rdev))) //nolint: unconvert - } - - return nil -} - -func getInodeFromStat(stat interface{}) (inode uint64, err error) { - s, ok := stat.(*syscall.Stat_t) - - if ok { - inode = s.Ino - } - - return -} - -func getFileUIDGID(stat interface{}) (idtools.Identity, error) { - s, ok := stat.(*syscall.Stat_t) - - if !ok { - return idtools.Identity{}, errors.New("cannot convert stat value to syscall.Stat_t") - } - return idtools.Identity{UID: int(s.Uid), GID: int(s.Gid)}, nil -} - -// handleTarTypeBlockCharFifo is an OS-specific helper function used by -// createTarFile to handle the following types of header: Block; Char; Fifo -func handleTarTypeBlockCharFifo(hdr *tar.Header, path string) error { - mode := uint32(hdr.Mode & 07777) - switch hdr.Typeflag { - case tar.TypeBlock: - mode |= unix.S_IFBLK - case tar.TypeChar: - mode |= unix.S_IFCHR - case tar.TypeFifo: - mode |= unix.S_IFIFO - } - - err := system.Mknod(path, mode, int(system.Mkdev(hdr.Devmajor, hdr.Devminor))) - if errors.Is(err, syscall.EPERM) && userns.RunningInUserNS() { - // In most cases, cannot create a device if running in user namespace - err = nil - } - return err -} - -func handleLChmod(hdr *tar.Header, path string, hdrInfo os.FileInfo) error { - if hdr.Typeflag == tar.TypeLink { - if fi, err := os.Lstat(hdr.Linkname); err == nil && (fi.Mode()&os.ModeSymlink == 0) { - if err := os.Chmod(path, hdrInfo.Mode()); err != nil { - return err - } - } - } else if hdr.Typeflag != tar.TypeSymlink { - if err := os.Chmod(path, hdrInfo.Mode()); err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/docker/docker/pkg/archive/archive_windows.go b/vendor/github.com/docker/docker/pkg/archive/archive_windows.go deleted file mode 100644 index 09a25832e..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/archive_windows.go +++ /dev/null @@ -1,57 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "archive/tar" - "os" - "path/filepath" - - "github.com/docker/docker/pkg/idtools" - "github.com/docker/docker/pkg/longpath" -) - -// fixVolumePathPrefix does platform specific processing to ensure that if -// the path being passed in is not in a volume path format, convert it to one. -func fixVolumePathPrefix(srcPath string) string { - return longpath.AddPrefix(srcPath) -} - -// getWalkRoot calculates the root path when performing a TarWithOptions. -// We use a separate function as this is platform specific. -func getWalkRoot(srcPath string, include string) string { - return filepath.Join(srcPath, include) -} - -// chmodTarEntry is used to adjust the file permissions used in tar header based -// on the platform the archival is done. -func chmodTarEntry(perm os.FileMode) os.FileMode { - // Remove group- and world-writable bits. - perm &= 0o755 - - // Add the x bit: make everything +x on Windows - return perm | 0o111 -} - -func setHeaderForSpecialDevice(hdr *tar.Header, name string, stat interface{}) (err error) { - // do nothing. no notion of Rdev, Nlink in stat on Windows - return -} - -func getInodeFromStat(stat interface{}) (inode uint64, err error) { - // do nothing. no notion of Inode in stat on Windows - return -} - -// handleTarTypeBlockCharFifo is an OS-specific helper function used by -// createTarFile to handle the following types of header: Block; Char; Fifo -func handleTarTypeBlockCharFifo(hdr *tar.Header, path string) error { - return nil -} - -func handleLChmod(hdr *tar.Header, path string, hdrInfo os.FileInfo) error { - return nil -} - -func getFileUIDGID(stat interface{}) (idtools.Identity, error) { - // no notion of file ownership mapping yet on Windows - return idtools.Identity{UID: 0, GID: 0}, nil -} diff --git a/vendor/github.com/docker/docker/pkg/archive/changes.go b/vendor/github.com/docker/docker/pkg/archive/changes.go deleted file mode 100644 index 7f7242be5..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/changes.go +++ /dev/null @@ -1,442 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "archive/tar" - "bytes" - "fmt" - "io" - "os" - "path/filepath" - "sort" - "strings" - "syscall" - "time" - - "github.com/docker/docker/pkg/idtools" - "github.com/docker/docker/pkg/pools" - "github.com/docker/docker/pkg/system" - "github.com/sirupsen/logrus" -) - -// ChangeType represents the change type. -type ChangeType int - -const ( - // ChangeModify represents the modify operation. - ChangeModify = iota - // ChangeAdd represents the add operation. - ChangeAdd - // ChangeDelete represents the delete operation. - ChangeDelete -) - -func (c ChangeType) String() string { - switch c { - case ChangeModify: - return "C" - case ChangeAdd: - return "A" - case ChangeDelete: - return "D" - } - return "" -} - -// Change represents a change, it wraps the change type and path. -// It describes changes of the files in the path respect to the -// parent layers. The change could be modify, add, delete. -// This is used for layer diff. -type Change struct { - Path string - Kind ChangeType -} - -func (change *Change) String() string { - return fmt.Sprintf("%s %s", change.Kind, change.Path) -} - -// for sort.Sort -type changesByPath []Change - -func (c changesByPath) Less(i, j int) bool { return c[i].Path < c[j].Path } -func (c changesByPath) Len() int { return len(c) } -func (c changesByPath) Swap(i, j int) { c[j], c[i] = c[i], c[j] } - -// Gnu tar doesn't have sub-second mtime precision. The go tar -// writer (1.10+) does when using PAX format, but we round times to seconds -// to ensure archives have the same hashes for backwards compatibility. -// See https://github.com/moby/moby/pull/35739/commits/fb170206ba12752214630b269a40ac7be6115ed4. -// -// Non-sub-second is problematic when we apply changes via tar -// files. We handle this by comparing for exact times, *or* same -// second count and either a or b having exactly 0 nanoseconds -func sameFsTime(a, b time.Time) bool { - return a.Equal(b) || - (a.Unix() == b.Unix() && - (a.Nanosecond() == 0 || b.Nanosecond() == 0)) -} - -func sameFsTimeSpec(a, b syscall.Timespec) bool { - return a.Sec == b.Sec && - (a.Nsec == b.Nsec || a.Nsec == 0 || b.Nsec == 0) -} - -// Changes walks the path rw and determines changes for the files in the path, -// with respect to the parent layers -func Changes(layers []string, rw string) ([]Change, error) { - return changes(layers, rw, aufsDeletedFile, aufsMetadataSkip) -} - -func aufsMetadataSkip(path string) (skip bool, err error) { - skip, err = filepath.Match(string(os.PathSeparator)+WhiteoutMetaPrefix+"*", path) - if err != nil { - skip = true - } - return -} - -func aufsDeletedFile(root, path string, fi os.FileInfo) (string, error) { - f := filepath.Base(path) - - // If there is a whiteout, then the file was removed - if strings.HasPrefix(f, WhiteoutPrefix) { - originalFile := f[len(WhiteoutPrefix):] - return filepath.Join(filepath.Dir(path), originalFile), nil - } - - return "", nil -} - -type skipChange func(string) (bool, error) -type deleteChange func(string, string, os.FileInfo) (string, error) - -func changes(layers []string, rw string, dc deleteChange, sc skipChange) ([]Change, error) { - var ( - changes []Change - changedDirs = make(map[string]struct{}) - ) - - err := filepath.Walk(rw, func(path string, f os.FileInfo, err error) error { - if err != nil { - return err - } - - // Rebase path - path, err = filepath.Rel(rw, path) - if err != nil { - return err - } - - // As this runs on the daemon side, file paths are OS specific. - path = filepath.Join(string(os.PathSeparator), path) - - // Skip root - if path == string(os.PathSeparator) { - return nil - } - - if sc != nil { - if skip, err := sc(path); skip { - return err - } - } - - change := Change{ - Path: path, - } - - deletedFile, err := dc(rw, path, f) - if err != nil { - return err - } - - // Find out what kind of modification happened - if deletedFile != "" { - change.Path = deletedFile - change.Kind = ChangeDelete - } else { - // Otherwise, the file was added - change.Kind = ChangeAdd - - // ...Unless it already existed in a top layer, in which case, it's a modification - for _, layer := range layers { - stat, err := os.Stat(filepath.Join(layer, path)) - if err != nil && !os.IsNotExist(err) { - return err - } - if err == nil { - // The file existed in the top layer, so that's a modification - - // However, if it's a directory, maybe it wasn't actually modified. - // If you modify /foo/bar/baz, then /foo will be part of the changed files only because it's the parent of bar - if stat.IsDir() && f.IsDir() { - if f.Size() == stat.Size() && f.Mode() == stat.Mode() && sameFsTime(f.ModTime(), stat.ModTime()) { - // Both directories are the same, don't record the change - return nil - } - } - change.Kind = ChangeModify - break - } - } - } - - // If /foo/bar/file.txt is modified, then /foo/bar must be part of the changed files. - // This block is here to ensure the change is recorded even if the - // modify time, mode and size of the parent directory in the rw and ro layers are all equal. - // Check https://github.com/docker/docker/pull/13590 for details. - if f.IsDir() { - changedDirs[path] = struct{}{} - } - if change.Kind == ChangeAdd || change.Kind == ChangeDelete { - parent := filepath.Dir(path) - if _, ok := changedDirs[parent]; !ok && parent != "/" { - changes = append(changes, Change{Path: parent, Kind: ChangeModify}) - changedDirs[parent] = struct{}{} - } - } - - // Record change - changes = append(changes, change) - return nil - }) - if err != nil && !os.IsNotExist(err) { - return nil, err - } - return changes, nil -} - -// FileInfo describes the information of a file. -type FileInfo struct { - parent *FileInfo - name string - stat *system.StatT - children map[string]*FileInfo - capability []byte - added bool -} - -// LookUp looks up the file information of a file. -func (info *FileInfo) LookUp(path string) *FileInfo { - // As this runs on the daemon side, file paths are OS specific. - parent := info - if path == string(os.PathSeparator) { - return info - } - - pathElements := strings.Split(path, string(os.PathSeparator)) - for _, elem := range pathElements { - if elem != "" { - child := parent.children[elem] - if child == nil { - return nil - } - parent = child - } - } - return parent -} - -func (info *FileInfo) path() string { - if info.parent == nil { - // As this runs on the daemon side, file paths are OS specific. - return string(os.PathSeparator) - } - return filepath.Join(info.parent.path(), info.name) -} - -func (info *FileInfo) addChanges(oldInfo *FileInfo, changes *[]Change) { - sizeAtEntry := len(*changes) - - if oldInfo == nil { - // add - change := Change{ - Path: info.path(), - Kind: ChangeAdd, - } - *changes = append(*changes, change) - info.added = true - } - - // We make a copy so we can modify it to detect additions - // also, we only recurse on the old dir if the new info is a directory - // otherwise any previous delete/change is considered recursive - oldChildren := make(map[string]*FileInfo) - if oldInfo != nil && info.isDir() { - for k, v := range oldInfo.children { - oldChildren[k] = v - } - } - - for name, newChild := range info.children { - oldChild := oldChildren[name] - if oldChild != nil { - // change? - oldStat := oldChild.stat - newStat := newChild.stat - // Note: We can't compare inode or ctime or blocksize here, because these change - // when copying a file into a container. However, that is not generally a problem - // because any content change will change mtime, and any status change should - // be visible when actually comparing the stat fields. The only time this - // breaks down is if some code intentionally hides a change by setting - // back mtime - if statDifferent(oldStat, newStat) || - !bytes.Equal(oldChild.capability, newChild.capability) { - change := Change{ - Path: newChild.path(), - Kind: ChangeModify, - } - *changes = append(*changes, change) - newChild.added = true - } - - // Remove from copy so we can detect deletions - delete(oldChildren, name) - } - - newChild.addChanges(oldChild, changes) - } - for _, oldChild := range oldChildren { - // delete - change := Change{ - Path: oldChild.path(), - Kind: ChangeDelete, - } - *changes = append(*changes, change) - } - - // If there were changes inside this directory, we need to add it, even if the directory - // itself wasn't changed. This is needed to properly save and restore filesystem permissions. - // As this runs on the daemon side, file paths are OS specific. - if len(*changes) > sizeAtEntry && info.isDir() && !info.added && info.path() != string(os.PathSeparator) { - change := Change{ - Path: info.path(), - Kind: ChangeModify, - } - // Let's insert the directory entry before the recently added entries located inside this dir - *changes = append(*changes, change) // just to resize the slice, will be overwritten - copy((*changes)[sizeAtEntry+1:], (*changes)[sizeAtEntry:]) - (*changes)[sizeAtEntry] = change - } -} - -// Changes add changes to file information. -func (info *FileInfo) Changes(oldInfo *FileInfo) []Change { - var changes []Change - - info.addChanges(oldInfo, &changes) - - return changes -} - -func newRootFileInfo() *FileInfo { - // As this runs on the daemon side, file paths are OS specific. - root := &FileInfo{ - name: string(os.PathSeparator), - children: make(map[string]*FileInfo), - } - return root -} - -// ChangesDirs compares two directories and generates an array of Change objects describing the changes. -// If oldDir is "", then all files in newDir will be Add-Changes. -func ChangesDirs(newDir, oldDir string) ([]Change, error) { - var ( - oldRoot, newRoot *FileInfo - ) - if oldDir == "" { - emptyDir, err := os.MkdirTemp("", "empty") - if err != nil { - return nil, err - } - defer os.Remove(emptyDir) - oldDir = emptyDir - } - oldRoot, newRoot, err := collectFileInfoForChanges(oldDir, newDir) - if err != nil { - return nil, err - } - - return newRoot.Changes(oldRoot), nil -} - -// ChangesSize calculates the size in bytes of the provided changes, based on newDir. -func ChangesSize(newDir string, changes []Change) int64 { - var ( - size int64 - sf = make(map[uint64]struct{}) - ) - for _, change := range changes { - if change.Kind == ChangeModify || change.Kind == ChangeAdd { - file := filepath.Join(newDir, change.Path) - fileInfo, err := os.Lstat(file) - if err != nil { - logrus.Errorf("Can not stat %q: %s", file, err) - continue - } - - if fileInfo != nil && !fileInfo.IsDir() { - if hasHardlinks(fileInfo) { - inode := getIno(fileInfo) - if _, ok := sf[inode]; !ok { - size += fileInfo.Size() - sf[inode] = struct{}{} - } - } else { - size += fileInfo.Size() - } - } - } - } - return size -} - -// ExportChanges produces an Archive from the provided changes, relative to dir. -func ExportChanges(dir string, changes []Change, idMap idtools.IdentityMapping) (io.ReadCloser, error) { - reader, writer := io.Pipe() - go func() { - ta := newTarAppender(idMap, writer, nil) - - // this buffer is needed for the duration of this piped stream - defer pools.BufioWriter32KPool.Put(ta.Buffer) - - sort.Sort(changesByPath(changes)) - - // In general we log errors here but ignore them because - // during e.g. a diff operation the container can continue - // mutating the filesystem and we can see transient errors - // from this - for _, change := range changes { - if change.Kind == ChangeDelete { - whiteOutDir := filepath.Dir(change.Path) - whiteOutBase := filepath.Base(change.Path) - whiteOut := filepath.Join(whiteOutDir, WhiteoutPrefix+whiteOutBase) - timestamp := time.Now() - hdr := &tar.Header{ - Name: whiteOut[1:], - Size: 0, - ModTime: timestamp, - AccessTime: timestamp, - ChangeTime: timestamp, - } - if err := ta.TarWriter.WriteHeader(hdr); err != nil { - logrus.Debugf("Can't write whiteout header: %s", err) - } - } else { - path := filepath.Join(dir, change.Path) - if err := ta.addTarFile(path, change.Path[1:]); err != nil { - logrus.Debugf("Can't add file %s to tar: %s", path, err) - } - } - } - - // Make sure to check the error on Close. - if err := ta.TarWriter.Close(); err != nil { - logrus.Debugf("Can't close layer: %s", err) - } - if err := writer.Close(); err != nil { - logrus.Debugf("failed close Changes writer: %s", err) - } - }() - return reader, nil -} diff --git a/vendor/github.com/docker/docker/pkg/archive/changes_linux.go b/vendor/github.com/docker/docker/pkg/archive/changes_linux.go deleted file mode 100644 index f8792b3d4..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/changes_linux.go +++ /dev/null @@ -1,286 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "bytes" - "fmt" - "os" - "path/filepath" - "sort" - "syscall" - "unsafe" - - "github.com/docker/docker/pkg/system" - "golang.org/x/sys/unix" -) - -// walker is used to implement collectFileInfoForChanges on linux. Where this -// method in general returns the entire contents of two directory trees, we -// optimize some FS calls out on linux. In particular, we take advantage of the -// fact that getdents(2) returns the inode of each file in the directory being -// walked, which, when walking two trees in parallel to generate a list of -// changes, can be used to prune subtrees without ever having to lstat(2) them -// directly. Eliminating stat calls in this way can save up to seconds on large -// images. -type walker struct { - dir1 string - dir2 string - root1 *FileInfo - root2 *FileInfo -} - -// collectFileInfoForChanges returns a complete representation of the trees -// rooted at dir1 and dir2, with one important exception: any subtree or -// leaf where the inode and device numbers are an exact match between dir1 -// and dir2 will be pruned from the results. This method is *only* to be used -// to generating a list of changes between the two directories, as it does not -// reflect the full contents. -func collectFileInfoForChanges(dir1, dir2 string) (*FileInfo, *FileInfo, error) { - w := &walker{ - dir1: dir1, - dir2: dir2, - root1: newRootFileInfo(), - root2: newRootFileInfo(), - } - - i1, err := os.Lstat(w.dir1) - if err != nil { - return nil, nil, err - } - i2, err := os.Lstat(w.dir2) - if err != nil { - return nil, nil, err - } - - if err := w.walk("/", i1, i2); err != nil { - return nil, nil, err - } - - return w.root1, w.root2, nil -} - -// Given a FileInfo, its path info, and a reference to the root of the tree -// being constructed, register this file with the tree. -func walkchunk(path string, fi os.FileInfo, dir string, root *FileInfo) error { - if fi == nil { - return nil - } - parent := root.LookUp(filepath.Dir(path)) - if parent == nil { - return fmt.Errorf("walkchunk: Unexpectedly no parent for %s", path) - } - info := &FileInfo{ - name: filepath.Base(path), - children: make(map[string]*FileInfo), - parent: parent, - } - cpath := filepath.Join(dir, path) - stat, err := system.FromStatT(fi.Sys().(*syscall.Stat_t)) - if err != nil { - return err - } - info.stat = stat - info.capability, _ = system.Lgetxattr(cpath, "security.capability") // lgetxattr(2): fs access - parent.children[info.name] = info - return nil -} - -// Walk a subtree rooted at the same path in both trees being iterated. For -// example, /docker/overlay/1234/a/b/c/d and /docker/overlay/8888/a/b/c/d -func (w *walker) walk(path string, i1, i2 os.FileInfo) (err error) { - // Register these nodes with the return trees, unless we're still at the - // (already-created) roots: - if path != "/" { - if err := walkchunk(path, i1, w.dir1, w.root1); err != nil { - return err - } - if err := walkchunk(path, i2, w.dir2, w.root2); err != nil { - return err - } - } - - is1Dir := i1 != nil && i1.IsDir() - is2Dir := i2 != nil && i2.IsDir() - - sameDevice := false - if i1 != nil && i2 != nil { - si1 := i1.Sys().(*syscall.Stat_t) - si2 := i2.Sys().(*syscall.Stat_t) - if si1.Dev == si2.Dev { - sameDevice = true - } - } - - // If these files are both non-existent, or leaves (non-dirs), we are done. - if !is1Dir && !is2Dir { - return nil - } - - // Fetch the names of all the files contained in both directories being walked: - var names1, names2 []nameIno - if is1Dir { - names1, err = readdirnames(filepath.Join(w.dir1, path)) // getdents(2): fs access - if err != nil { - return err - } - } - if is2Dir { - names2, err = readdirnames(filepath.Join(w.dir2, path)) // getdents(2): fs access - if err != nil { - return err - } - } - - // We have lists of the files contained in both parallel directories, sorted - // in the same order. Walk them in parallel, generating a unique merged list - // of all items present in either or both directories. - var names []string - ix1 := 0 - ix2 := 0 - - for { - if ix1 >= len(names1) { - break - } - if ix2 >= len(names2) { - break - } - - ni1 := names1[ix1] - ni2 := names2[ix2] - - switch bytes.Compare([]byte(ni1.name), []byte(ni2.name)) { - case -1: // ni1 < ni2 -- advance ni1 - // we will not encounter ni1 in names2 - names = append(names, ni1.name) - ix1++ - case 0: // ni1 == ni2 - if ni1.ino != ni2.ino || !sameDevice { - names = append(names, ni1.name) - } - ix1++ - ix2++ - case 1: // ni1 > ni2 -- advance ni2 - // we will not encounter ni2 in names1 - names = append(names, ni2.name) - ix2++ - } - } - for ix1 < len(names1) { - names = append(names, names1[ix1].name) - ix1++ - } - for ix2 < len(names2) { - names = append(names, names2[ix2].name) - ix2++ - } - - // For each of the names present in either or both of the directories being - // iterated, stat the name under each root, and recurse the pair of them: - for _, name := range names { - fname := filepath.Join(path, name) - var cInfo1, cInfo2 os.FileInfo - if is1Dir { - cInfo1, err = os.Lstat(filepath.Join(w.dir1, fname)) // lstat(2): fs access - if err != nil && !os.IsNotExist(err) { - return err - } - } - if is2Dir { - cInfo2, err = os.Lstat(filepath.Join(w.dir2, fname)) // lstat(2): fs access - if err != nil && !os.IsNotExist(err) { - return err - } - } - if err = w.walk(fname, cInfo1, cInfo2); err != nil { - return err - } - } - return nil -} - -// {name,inode} pairs used to support the early-pruning logic of the walker type -type nameIno struct { - name string - ino uint64 -} - -type nameInoSlice []nameIno - -func (s nameInoSlice) Len() int { return len(s) } -func (s nameInoSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s nameInoSlice) Less(i, j int) bool { return s[i].name < s[j].name } - -// readdirnames is a hacked-apart version of the Go stdlib code, exposing inode -// numbers further up the stack when reading directory contents. Unlike -// os.Readdirnames, which returns a list of filenames, this function returns a -// list of {filename,inode} pairs. -func readdirnames(dirname string) (names []nameIno, err error) { - var ( - size = 100 - buf = make([]byte, 4096) - nbuf int - bufp int - nb int - ) - - f, err := os.Open(dirname) - if err != nil { - return nil, err - } - defer f.Close() - - names = make([]nameIno, 0, size) // Empty with room to grow. - for { - // Refill the buffer if necessary - if bufp >= nbuf { - bufp = 0 - nbuf, err = unix.ReadDirent(int(f.Fd()), buf) // getdents on linux - if nbuf < 0 { - nbuf = 0 - } - if err != nil { - return nil, os.NewSyscallError("readdirent", err) - } - if nbuf <= 0 { - break // EOF - } - } - - // Drain the buffer - nb, names = parseDirent(buf[bufp:nbuf], names) - bufp += nb - } - - sl := nameInoSlice(names) - sort.Sort(sl) - return sl, nil -} - -// parseDirent is a minor modification of unix.ParseDirent (linux version) -// which returns {name,inode} pairs instead of just names. -func parseDirent(buf []byte, names []nameIno) (consumed int, newnames []nameIno) { - origlen := len(buf) - for len(buf) > 0 { - dirent := (*unix.Dirent)(unsafe.Pointer(&buf[0])) - buf = buf[dirent.Reclen:] - if dirent.Ino == 0 { // File absent in directory. - continue - } - bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) - var name = string(bytes[0:clen(bytes[:])]) - if name == "." || name == ".." { // Useless names - continue - } - names = append(names, nameIno{name, dirent.Ino}) - } - return origlen - len(buf), names -} - -func clen(n []byte) int { - for i := 0; i < len(n); i++ { - if n[i] == 0 { - return i - } - } - return len(n) -} diff --git a/vendor/github.com/docker/docker/pkg/archive/changes_other.go b/vendor/github.com/docker/docker/pkg/archive/changes_other.go deleted file mode 100644 index 833798bd1..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/changes_other.go +++ /dev/null @@ -1,98 +0,0 @@ -//go:build !linux -// +build !linux - -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "fmt" - "os" - "path/filepath" - "runtime" - "strings" - - "github.com/docker/docker/pkg/system" -) - -func collectFileInfoForChanges(oldDir, newDir string) (*FileInfo, *FileInfo, error) { - var ( - oldRoot, newRoot *FileInfo - err1, err2 error - errs = make(chan error, 2) - ) - go func() { - oldRoot, err1 = collectFileInfo(oldDir) - errs <- err1 - }() - go func() { - newRoot, err2 = collectFileInfo(newDir) - errs <- err2 - }() - - // block until both routines have returned - for i := 0; i < 2; i++ { - if err := <-errs; err != nil { - return nil, nil, err - } - } - - return oldRoot, newRoot, nil -} - -func collectFileInfo(sourceDir string) (*FileInfo, error) { - root := newRootFileInfo() - - err := filepath.WalkDir(sourceDir, func(path string, _ os.DirEntry, err error) error { - if err != nil { - return err - } - - // Rebase path - relPath, err := filepath.Rel(sourceDir, path) - if err != nil { - return err - } - - // As this runs on the daemon side, file paths are OS specific. - relPath = filepath.Join(string(os.PathSeparator), relPath) - - // See https://github.com/golang/go/issues/9168 - bug in filepath.Join. - // Temporary workaround. If the returned path starts with two backslashes, - // trim it down to a single backslash. Only relevant on Windows. - if runtime.GOOS == "windows" { - if strings.HasPrefix(relPath, `\\`) { - relPath = relPath[1:] - } - } - - if relPath == string(os.PathSeparator) { - return nil - } - - parent := root.LookUp(filepath.Dir(relPath)) - if parent == nil { - return fmt.Errorf("collectFileInfo: Unexpectedly no parent for %s", relPath) - } - - info := &FileInfo{ - name: filepath.Base(relPath), - children: make(map[string]*FileInfo), - parent: parent, - } - - s, err := system.Lstat(path) - if err != nil { - return err - } - info.stat = s - - info.capability, _ = system.Lgetxattr(path, "security.capability") - - parent.children[info.name] = info - - return nil - }) - if err != nil { - return nil, err - } - return root, nil -} diff --git a/vendor/github.com/docker/docker/pkg/archive/changes_unix.go b/vendor/github.com/docker/docker/pkg/archive/changes_unix.go deleted file mode 100644 index 54aace970..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/changes_unix.go +++ /dev/null @@ -1,44 +0,0 @@ -//go:build !windows -// +build !windows - -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "os" - "syscall" - - "github.com/docker/docker/pkg/system" - "golang.org/x/sys/unix" -) - -func statDifferent(oldStat *system.StatT, newStat *system.StatT) bool { - // Don't look at size for dirs, its not a good measure of change - if oldStat.Mode() != newStat.Mode() || - oldStat.UID() != newStat.UID() || - oldStat.GID() != newStat.GID() || - oldStat.Rdev() != newStat.Rdev() || - // Don't look at size or modification time for dirs, its not a good - // measure of change. See https://github.com/moby/moby/issues/9874 - // for a description of the issue with modification time, and - // https://github.com/moby/moby/pull/11422 for the change. - // (Note that in the Windows implementation of this function, - // modification time IS taken as a change). See - // https://github.com/moby/moby/pull/37982 for more information. - (oldStat.Mode()&unix.S_IFDIR != unix.S_IFDIR && - (!sameFsTimeSpec(oldStat.Mtim(), newStat.Mtim()) || (oldStat.Size() != newStat.Size()))) { - return true - } - return false -} - -func (info *FileInfo) isDir() bool { - return info.parent == nil || info.stat.Mode()&unix.S_IFDIR != 0 -} - -func getIno(fi os.FileInfo) uint64 { - return fi.Sys().(*syscall.Stat_t).Ino -} - -func hasHardlinks(fi os.FileInfo) bool { - return fi.Sys().(*syscall.Stat_t).Nlink > 1 -} diff --git a/vendor/github.com/docker/docker/pkg/archive/changes_windows.go b/vendor/github.com/docker/docker/pkg/archive/changes_windows.go deleted file mode 100644 index 9906685e4..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/changes_windows.go +++ /dev/null @@ -1,34 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "os" - - "github.com/docker/docker/pkg/system" -) - -func statDifferent(oldStat *system.StatT, newStat *system.StatT) bool { - // Note there is slight difference between the Linux and Windows - // implementations here. Due to https://github.com/moby/moby/issues/9874, - // and the fix at https://github.com/moby/moby/pull/11422, Linux does not - // consider a change to the directory time as a change. Windows on NTFS - // does. See https://github.com/moby/moby/pull/37982 for more information. - - if !sameFsTime(oldStat.Mtim(), newStat.Mtim()) || - oldStat.Mode() != newStat.Mode() || - oldStat.Size() != newStat.Size() && !oldStat.Mode().IsDir() { - return true - } - return false -} - -func (info *FileInfo) isDir() bool { - return info.parent == nil || info.stat.Mode().IsDir() -} - -func getIno(fi os.FileInfo) (inode uint64) { - return -} - -func hasHardlinks(fi os.FileInfo) bool { - return false -} diff --git a/vendor/github.com/docker/docker/pkg/archive/copy.go b/vendor/github.com/docker/docker/pkg/archive/copy.go deleted file mode 100644 index 0ea159627..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/copy.go +++ /dev/null @@ -1,485 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "archive/tar" - "errors" - "io" - "os" - "path/filepath" - "strings" - - "github.com/docker/docker/pkg/system" - "github.com/sirupsen/logrus" -) - -// Errors used or returned by this file. -var ( - ErrNotDirectory = errors.New("not a directory") - ErrDirNotExists = errors.New("no such directory") - ErrCannotCopyDir = errors.New("cannot copy directory") - ErrInvalidCopySource = errors.New("invalid copy source content") -) - -// PreserveTrailingDotOrSeparator returns the given cleaned path (after -// processing using any utility functions from the path or filepath stdlib -// packages) and appends a trailing `/.` or `/` if its corresponding original -// path (from before being processed by utility functions from the path or -// filepath stdlib packages) ends with a trailing `/.` or `/`. If the cleaned -// path already ends in a `.` path segment, then another is not added. If the -// clean path already ends in a path separator, then another is not added. -func PreserveTrailingDotOrSeparator(cleanedPath string, originalPath string) string { - // Ensure paths are in platform semantics - cleanedPath = normalizePath(cleanedPath) - originalPath = normalizePath(originalPath) - - if !specifiesCurrentDir(cleanedPath) && specifiesCurrentDir(originalPath) { - if !hasTrailingPathSeparator(cleanedPath) { - // Add a separator if it doesn't already end with one (a cleaned - // path would only end in a separator if it is the root). - cleanedPath += string(filepath.Separator) - } - cleanedPath += "." - } - - if !hasTrailingPathSeparator(cleanedPath) && hasTrailingPathSeparator(originalPath) { - cleanedPath += string(filepath.Separator) - } - - return cleanedPath -} - -// assertsDirectory returns whether the given path is -// asserted to be a directory, i.e., the path ends with -// a trailing '/' or `/.`, assuming a path separator of `/`. -func assertsDirectory(path string) bool { - return hasTrailingPathSeparator(path) || specifiesCurrentDir(path) -} - -// hasTrailingPathSeparator returns whether the given -// path ends with the system's path separator character. -func hasTrailingPathSeparator(path string) bool { - return len(path) > 0 && path[len(path)-1] == filepath.Separator -} - -// specifiesCurrentDir returns whether the given path specifies -// a "current directory", i.e., the last path segment is `.`. -func specifiesCurrentDir(path string) bool { - return filepath.Base(path) == "." -} - -// SplitPathDirEntry splits the given path between its directory name and its -// basename by first cleaning the path but preserves a trailing "." if the -// original path specified the current directory. -func SplitPathDirEntry(path string) (dir, base string) { - cleanedPath := filepath.Clean(filepath.FromSlash(path)) - - if specifiesCurrentDir(path) { - cleanedPath += string(os.PathSeparator) + "." - } - - return filepath.Dir(cleanedPath), filepath.Base(cleanedPath) -} - -// TarResource archives the resource described by the given CopyInfo to a Tar -// archive. A non-nil error is returned if sourcePath does not exist or is -// asserted to be a directory but exists as another type of file. -// -// This function acts as a convenient wrapper around TarWithOptions, which -// requires a directory as the source path. TarResource accepts either a -// directory or a file path and correctly sets the Tar options. -func TarResource(sourceInfo CopyInfo) (content io.ReadCloser, err error) { - return TarResourceRebase(sourceInfo.Path, sourceInfo.RebaseName) -} - -// TarResourceRebase is like TarResource but renames the first path element of -// items in the resulting tar archive to match the given rebaseName if not "". -func TarResourceRebase(sourcePath, rebaseName string) (content io.ReadCloser, err error) { - sourcePath = normalizePath(sourcePath) - if _, err = os.Lstat(sourcePath); err != nil { - // Catches the case where the source does not exist or is not a - // directory if asserted to be a directory, as this also causes an - // error. - return - } - - // Separate the source path between its directory and - // the entry in that directory which we are archiving. - sourceDir, sourceBase := SplitPathDirEntry(sourcePath) - opts := TarResourceRebaseOpts(sourceBase, rebaseName) - - logrus.Debugf("copying %q from %q", sourceBase, sourceDir) - return TarWithOptions(sourceDir, opts) -} - -// TarResourceRebaseOpts does not preform the Tar, but instead just creates the rebase -// parameters to be sent to TarWithOptions (the TarOptions struct) -func TarResourceRebaseOpts(sourceBase string, rebaseName string) *TarOptions { - filter := []string{sourceBase} - return &TarOptions{ - Compression: Uncompressed, - IncludeFiles: filter, - IncludeSourceDir: true, - RebaseNames: map[string]string{ - sourceBase: rebaseName, - }, - } -} - -// CopyInfo holds basic info about the source -// or destination path of a copy operation. -type CopyInfo struct { - Path string - Exists bool - IsDir bool - RebaseName string -} - -// CopyInfoSourcePath stats the given path to create a CopyInfo -// struct representing that resource for the source of an archive copy -// operation. The given path should be an absolute local path. A source path -// has all symlinks evaluated that appear before the last path separator ("/" -// on Unix). As it is to be a copy source, the path must exist. -func CopyInfoSourcePath(path string, followLink bool) (CopyInfo, error) { - // normalize the file path and then evaluate the symbol link - // we will use the target file instead of the symbol link if - // followLink is set - path = normalizePath(path) - - resolvedPath, rebaseName, err := ResolveHostSourcePath(path, followLink) - if err != nil { - return CopyInfo{}, err - } - - stat, err := os.Lstat(resolvedPath) - if err != nil { - return CopyInfo{}, err - } - - return CopyInfo{ - Path: resolvedPath, - Exists: true, - IsDir: stat.IsDir(), - RebaseName: rebaseName, - }, nil -} - -// CopyInfoDestinationPath stats the given path to create a CopyInfo -// struct representing that resource for the destination of an archive copy -// operation. The given path should be an absolute local path. -func CopyInfoDestinationPath(path string) (info CopyInfo, err error) { - maxSymlinkIter := 10 // filepath.EvalSymlinks uses 255, but 10 already seems like a lot. - path = normalizePath(path) - originalPath := path - - stat, err := os.Lstat(path) - - if err == nil && stat.Mode()&os.ModeSymlink == 0 { - // The path exists and is not a symlink. - return CopyInfo{ - Path: path, - Exists: true, - IsDir: stat.IsDir(), - }, nil - } - - // While the path is a symlink. - for n := 0; err == nil && stat.Mode()&os.ModeSymlink != 0; n++ { - if n > maxSymlinkIter { - // Don't follow symlinks more than this arbitrary number of times. - return CopyInfo{}, errors.New("too many symlinks in " + originalPath) - } - - // The path is a symbolic link. We need to evaluate it so that the - // destination of the copy operation is the link target and not the - // link itself. This is notably different than CopyInfoSourcePath which - // only evaluates symlinks before the last appearing path separator. - // Also note that it is okay if the last path element is a broken - // symlink as the copy operation should create the target. - var linkTarget string - - linkTarget, err = os.Readlink(path) - if err != nil { - return CopyInfo{}, err - } - - if !system.IsAbs(linkTarget) { - // Join with the parent directory. - dstParent, _ := SplitPathDirEntry(path) - linkTarget = filepath.Join(dstParent, linkTarget) - } - - path = linkTarget - stat, err = os.Lstat(path) - } - - if err != nil { - // It's okay if the destination path doesn't exist. We can still - // continue the copy operation if the parent directory exists. - if !os.IsNotExist(err) { - return CopyInfo{}, err - } - - // Ensure destination parent dir exists. - dstParent, _ := SplitPathDirEntry(path) - - parentDirStat, err := os.Stat(dstParent) - if err != nil { - return CopyInfo{}, err - } - if !parentDirStat.IsDir() { - return CopyInfo{}, ErrNotDirectory - } - - return CopyInfo{Path: path}, nil - } - - // The path exists after resolving symlinks. - return CopyInfo{ - Path: path, - Exists: true, - IsDir: stat.IsDir(), - }, nil -} - -// PrepareArchiveCopy prepares the given srcContent archive, which should -// contain the archived resource described by srcInfo, to the destination -// described by dstInfo. Returns the possibly modified content archive along -// with the path to the destination directory which it should be extracted to. -func PrepareArchiveCopy(srcContent io.Reader, srcInfo, dstInfo CopyInfo) (dstDir string, content io.ReadCloser, err error) { - // Ensure in platform semantics - srcInfo.Path = normalizePath(srcInfo.Path) - dstInfo.Path = normalizePath(dstInfo.Path) - - // Separate the destination path between its directory and base - // components in case the source archive contents need to be rebased. - dstDir, dstBase := SplitPathDirEntry(dstInfo.Path) - _, srcBase := SplitPathDirEntry(srcInfo.Path) - - switch { - case dstInfo.Exists && dstInfo.IsDir: - // The destination exists as a directory. No alteration - // to srcContent is needed as its contents can be - // simply extracted to the destination directory. - return dstInfo.Path, io.NopCloser(srcContent), nil - case dstInfo.Exists && srcInfo.IsDir: - // The destination exists as some type of file and the source - // content is a directory. This is an error condition since - // you cannot copy a directory to an existing file location. - return "", nil, ErrCannotCopyDir - case dstInfo.Exists: - // The destination exists as some type of file and the source content - // is also a file. The source content entry will have to be renamed to - // have a basename which matches the destination path's basename. - if len(srcInfo.RebaseName) != 0 { - srcBase = srcInfo.RebaseName - } - return dstDir, RebaseArchiveEntries(srcContent, srcBase, dstBase), nil - case srcInfo.IsDir: - // The destination does not exist and the source content is an archive - // of a directory. The archive should be extracted to the parent of - // the destination path instead, and when it is, the directory that is - // created as a result should take the name of the destination path. - // The source content entries will have to be renamed to have a - // basename which matches the destination path's basename. - if len(srcInfo.RebaseName) != 0 { - srcBase = srcInfo.RebaseName - } - return dstDir, RebaseArchiveEntries(srcContent, srcBase, dstBase), nil - case assertsDirectory(dstInfo.Path): - // The destination does not exist and is asserted to be created as a - // directory, but the source content is not a directory. This is an - // error condition since you cannot create a directory from a file - // source. - return "", nil, ErrDirNotExists - default: - // The last remaining case is when the destination does not exist, is - // not asserted to be a directory, and the source content is not an - // archive of a directory. It this case, the destination file will need - // to be created when the archive is extracted and the source content - // entry will have to be renamed to have a basename which matches the - // destination path's basename. - if len(srcInfo.RebaseName) != 0 { - srcBase = srcInfo.RebaseName - } - return dstDir, RebaseArchiveEntries(srcContent, srcBase, dstBase), nil - } -} - -// RebaseArchiveEntries rewrites the given srcContent archive replacing -// an occurrence of oldBase with newBase at the beginning of entry names. -func RebaseArchiveEntries(srcContent io.Reader, oldBase, newBase string) io.ReadCloser { - if oldBase == string(os.PathSeparator) { - // If oldBase specifies the root directory, use an empty string as - // oldBase instead so that newBase doesn't replace the path separator - // that all paths will start with. - oldBase = "" - } - - rebased, w := io.Pipe() - - go func() { - srcTar := tar.NewReader(srcContent) - rebasedTar := tar.NewWriter(w) - - for { - hdr, err := srcTar.Next() - if err == io.EOF { - // Signals end of archive. - rebasedTar.Close() - w.Close() - return - } - if err != nil { - w.CloseWithError(err) - return - } - - // srcContent tar stream, as served by TarWithOptions(), is - // definitely in PAX format, but tar.Next() mistakenly guesses it - // as USTAR, which creates a problem: if the newBase is >100 - // characters long, WriteHeader() returns an error like - // "archive/tar: cannot encode header: Format specifies USTAR; and USTAR cannot encode Name=...". - // - // To fix, set the format to PAX here. See docker/for-linux issue #484. - hdr.Format = tar.FormatPAX - hdr.Name = strings.Replace(hdr.Name, oldBase, newBase, 1) - if hdr.Typeflag == tar.TypeLink { - hdr.Linkname = strings.Replace(hdr.Linkname, oldBase, newBase, 1) - } - - if err = rebasedTar.WriteHeader(hdr); err != nil { - w.CloseWithError(err) - return - } - - // Ignoring GoSec G110. See https://github.com/securego/gosec/pull/433 - // and https://cure53.de/pentest-report_opa.pdf, which recommends to - // replace io.Copy with io.CopyN7. The latter allows to specify the - // maximum number of bytes that should be read. By properly defining - // the limit, it can be assured that a GZip compression bomb cannot - // easily cause a Denial-of-Service. - // After reviewing with @tonistiigi and @cpuguy83, this should not - // affect us, because here we do not read into memory, hence should - // not be vulnerable to this code consuming memory. - //nolint:gosec // G110: Potential DoS vulnerability via decompression bomb (gosec) - if _, err = io.Copy(rebasedTar, srcTar); err != nil { - w.CloseWithError(err) - return - } - } - }() - - return rebased -} - -// CopyResource performs an archive copy from the given source path to the -// given destination path. The source path MUST exist and the destination -// path's parent directory must exist. -func CopyResource(srcPath, dstPath string, followLink bool) error { - var ( - srcInfo CopyInfo - err error - ) - - // Ensure in platform semantics - srcPath = normalizePath(srcPath) - dstPath = normalizePath(dstPath) - - // Clean the source and destination paths. - srcPath = PreserveTrailingDotOrSeparator(filepath.Clean(srcPath), srcPath) - dstPath = PreserveTrailingDotOrSeparator(filepath.Clean(dstPath), dstPath) - - if srcInfo, err = CopyInfoSourcePath(srcPath, followLink); err != nil { - return err - } - - content, err := TarResource(srcInfo) - if err != nil { - return err - } - defer content.Close() - - return CopyTo(content, srcInfo, dstPath) -} - -// CopyTo handles extracting the given content whose -// entries should be sourced from srcInfo to dstPath. -func CopyTo(content io.Reader, srcInfo CopyInfo, dstPath string) error { - // The destination path need not exist, but CopyInfoDestinationPath will - // ensure that at least the parent directory exists. - dstInfo, err := CopyInfoDestinationPath(normalizePath(dstPath)) - if err != nil { - return err - } - - dstDir, copyArchive, err := PrepareArchiveCopy(content, srcInfo, dstInfo) - if err != nil { - return err - } - defer copyArchive.Close() - - options := &TarOptions{ - NoLchown: true, - NoOverwriteDirNonDir: true, - } - - return Untar(copyArchive, dstDir, options) -} - -// ResolveHostSourcePath decides real path need to be copied with parameters such as -// whether to follow symbol link or not, if followLink is true, resolvedPath will return -// link target of any symbol link file, else it will only resolve symlink of directory -// but return symbol link file itself without resolving. -func ResolveHostSourcePath(path string, followLink bool) (resolvedPath, rebaseName string, err error) { - if followLink { - resolvedPath, err = filepath.EvalSymlinks(path) - if err != nil { - return - } - - resolvedPath, rebaseName = GetRebaseName(path, resolvedPath) - } else { - dirPath, basePath := filepath.Split(path) - - // if not follow symbol link, then resolve symbol link of parent dir - var resolvedDirPath string - resolvedDirPath, err = filepath.EvalSymlinks(dirPath) - if err != nil { - return - } - // resolvedDirPath will have been cleaned (no trailing path separators) so - // we can manually join it with the base path element. - resolvedPath = resolvedDirPath + string(filepath.Separator) + basePath - if hasTrailingPathSeparator(path) && - filepath.Base(path) != filepath.Base(resolvedPath) { - rebaseName = filepath.Base(path) - } - } - return resolvedPath, rebaseName, nil -} - -// GetRebaseName normalizes and compares path and resolvedPath, -// return completed resolved path and rebased file name -func GetRebaseName(path, resolvedPath string) (string, string) { - // linkTarget will have been cleaned (no trailing path separators and dot) so - // we can manually join it with them - var rebaseName string - if specifiesCurrentDir(path) && - !specifiesCurrentDir(resolvedPath) { - resolvedPath += string(filepath.Separator) + "." - } - - if hasTrailingPathSeparator(path) && - !hasTrailingPathSeparator(resolvedPath) { - resolvedPath += string(filepath.Separator) - } - - if filepath.Base(path) != filepath.Base(resolvedPath) { - // In the case where the path had a trailing separator and a symlink - // evaluation has changed the last path component, we will need to - // rebase the name in the archive that is being copied to match the - // originally requested name. - rebaseName = filepath.Base(path) - } - return resolvedPath, rebaseName -} diff --git a/vendor/github.com/docker/docker/pkg/archive/copy_unix.go b/vendor/github.com/docker/docker/pkg/archive/copy_unix.go deleted file mode 100644 index 2ac7729f4..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/copy_unix.go +++ /dev/null @@ -1,12 +0,0 @@ -//go:build !windows -// +build !windows - -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "path/filepath" -) - -func normalizePath(path string) string { - return filepath.ToSlash(path) -} diff --git a/vendor/github.com/docker/docker/pkg/archive/copy_windows.go b/vendor/github.com/docker/docker/pkg/archive/copy_windows.go deleted file mode 100644 index a878d1bac..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/copy_windows.go +++ /dev/null @@ -1,9 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "path/filepath" -) - -func normalizePath(path string) string { - return filepath.FromSlash(path) -} diff --git a/vendor/github.com/docker/docker/pkg/archive/diff.go b/vendor/github.com/docker/docker/pkg/archive/diff.go deleted file mode 100644 index 1a2fb971f..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/diff.go +++ /dev/null @@ -1,262 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "archive/tar" - "fmt" - "io" - "os" - "path/filepath" - "runtime" - "strings" - - "github.com/docker/docker/pkg/pools" - "github.com/docker/docker/pkg/system" - "github.com/sirupsen/logrus" -) - -// UnpackLayer unpack `layer` to a `dest`. The stream `layer` can be -// compressed or uncompressed. -// Returns the size in bytes of the contents of the layer. -func UnpackLayer(dest string, layer io.Reader, options *TarOptions) (size int64, err error) { - tr := tar.NewReader(layer) - trBuf := pools.BufioReader32KPool.Get(tr) - defer pools.BufioReader32KPool.Put(trBuf) - - var dirs []*tar.Header - unpackedPaths := make(map[string]struct{}) - - if options == nil { - options = &TarOptions{} - } - if options.ExcludePatterns == nil { - options.ExcludePatterns = []string{} - } - - aufsTempdir := "" - aufsHardlinks := make(map[string]*tar.Header) - - // Iterate through the files in the archive. - for { - hdr, err := tr.Next() - if err == io.EOF { - // end of tar archive - break - } - if err != nil { - return 0, err - } - - size += hdr.Size - - // Normalize name, for safety and for a simple is-root check - hdr.Name = filepath.Clean(hdr.Name) - - // Windows does not support filenames with colons in them. Ignore - // these files. This is not a problem though (although it might - // appear that it is). Let's suppose a client is running docker pull. - // The daemon it points to is Windows. Would it make sense for the - // client to be doing a docker pull Ubuntu for example (which has files - // with colons in the name under /usr/share/man/man3)? No, absolutely - // not as it would really only make sense that they were pulling a - // Windows image. However, for development, it is necessary to be able - // to pull Linux images which are in the repository. - // - // TODO Windows. Once the registry is aware of what images are Windows- - // specific or Linux-specific, this warning should be changed to an error - // to cater for the situation where someone does manage to upload a Linux - // image but have it tagged as Windows inadvertently. - if runtime.GOOS == "windows" { - if strings.Contains(hdr.Name, ":") { - logrus.Warnf("Windows: Ignoring %s (is this a Linux image?)", hdr.Name) - continue - } - } - - // Ensure that the parent directory exists. - err = createImpliedDirectories(dest, hdr, options) - if err != nil { - return 0, err - } - - // Skip AUFS metadata dirs - if strings.HasPrefix(hdr.Name, WhiteoutMetaPrefix) { - // Regular files inside /.wh..wh.plnk can be used as hardlink targets - // We don't want this directory, but we need the files in them so that - // such hardlinks can be resolved. - if strings.HasPrefix(hdr.Name, WhiteoutLinkDir) && hdr.Typeflag == tar.TypeReg { - basename := filepath.Base(hdr.Name) - aufsHardlinks[basename] = hdr - if aufsTempdir == "" { - if aufsTempdir, err = os.MkdirTemp(dest, "dockerplnk"); err != nil { - return 0, err - } - defer os.RemoveAll(aufsTempdir) - } - if err := createTarFile(filepath.Join(aufsTempdir, basename), dest, hdr, tr, true, nil, options.InUserNS); err != nil { - return 0, err - } - } - - if hdr.Name != WhiteoutOpaqueDir { - continue - } - } - //#nosec G305 -- The joined path is guarded against path traversal. - path := filepath.Join(dest, hdr.Name) - rel, err := filepath.Rel(dest, path) - if err != nil { - return 0, err - } - - // Note as these operations are platform specific, so must the slash be. - if strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { - return 0, breakoutError(fmt.Errorf("%q is outside of %q", hdr.Name, dest)) - } - base := filepath.Base(path) - - if strings.HasPrefix(base, WhiteoutPrefix) { - dir := filepath.Dir(path) - if base == WhiteoutOpaqueDir { - _, err := os.Lstat(dir) - if err != nil { - return 0, err - } - err = filepath.WalkDir(dir, func(path string, info os.DirEntry, err error) error { - if err != nil { - if os.IsNotExist(err) { - err = nil // parent was deleted - } - return err - } - if path == dir { - return nil - } - if _, exists := unpackedPaths[path]; !exists { - return os.RemoveAll(path) - } - return nil - }) - if err != nil { - return 0, err - } - } else { - originalBase := base[len(WhiteoutPrefix):] - originalPath := filepath.Join(dir, originalBase) - if err := os.RemoveAll(originalPath); err != nil { - return 0, err - } - } - } else { - // If path exits we almost always just want to remove and replace it. - // The only exception is when it is a directory *and* the file from - // the layer is also a directory. Then we want to merge them (i.e. - // just apply the metadata from the layer). - if fi, err := os.Lstat(path); err == nil { - if !(fi.IsDir() && hdr.Typeflag == tar.TypeDir) { - if err := os.RemoveAll(path); err != nil { - return 0, err - } - } - } - - trBuf.Reset(tr) - srcData := io.Reader(trBuf) - srcHdr := hdr - - // Hard links into /.wh..wh.plnk don't work, as we don't extract that directory, so - // we manually retarget these into the temporary files we extracted them into - if hdr.Typeflag == tar.TypeLink && strings.HasPrefix(filepath.Clean(hdr.Linkname), WhiteoutLinkDir) { - linkBasename := filepath.Base(hdr.Linkname) - srcHdr = aufsHardlinks[linkBasename] - if srcHdr == nil { - return 0, fmt.Errorf("Invalid aufs hardlink") - } - tmpFile, err := os.Open(filepath.Join(aufsTempdir, linkBasename)) - if err != nil { - return 0, err - } - defer tmpFile.Close() - srcData = tmpFile - } - - if err := remapIDs(options.IDMap, srcHdr); err != nil { - return 0, err - } - - if err := createTarFile(path, dest, srcHdr, srcData, !options.NoLchown, nil, options.InUserNS); err != nil { - return 0, err - } - - // Directory mtimes must be handled at the end to avoid further - // file creation in them to modify the directory mtime - if hdr.Typeflag == tar.TypeDir { - dirs = append(dirs, hdr) - } - unpackedPaths[path] = struct{}{} - } - } - - for _, hdr := range dirs { - //#nosec G305 -- The header was checked for path traversal before it was appended to the dirs slice. - path := filepath.Join(dest, hdr.Name) - if err := system.Chtimes(path, hdr.AccessTime, hdr.ModTime); err != nil { - return 0, err - } - } - - return size, nil -} - -// ApplyLayer parses a diff in the standard layer format from `layer`, -// and applies it to the directory `dest`. The stream `layer` can be -// compressed or uncompressed. -// Returns the size in bytes of the contents of the layer. -func ApplyLayer(dest string, layer io.Reader) (int64, error) { - return applyLayerHandler(dest, layer, &TarOptions{}, true) -} - -// ApplyUncompressedLayer parses a diff in the standard layer format from -// `layer`, and applies it to the directory `dest`. The stream `layer` -// can only be uncompressed. -// Returns the size in bytes of the contents of the layer. -func ApplyUncompressedLayer(dest string, layer io.Reader, options *TarOptions) (int64, error) { - return applyLayerHandler(dest, layer, options, false) -} - -// IsEmpty checks if the tar archive is empty (doesn't contain any entries). -func IsEmpty(rd io.Reader) (bool, error) { - decompRd, err := DecompressStream(rd) - if err != nil { - return true, fmt.Errorf("failed to decompress archive: %v", err) - } - defer decompRd.Close() - - tarReader := tar.NewReader(decompRd) - if _, err := tarReader.Next(); err != nil { - if err == io.EOF { - return true, nil - } - return false, fmt.Errorf("failed to read next archive header: %v", err) - } - - return false, nil -} - -// do the bulk load of ApplyLayer, but allow for not calling DecompressStream -func applyLayerHandler(dest string, layer io.Reader, options *TarOptions, decompress bool) (int64, error) { - dest = filepath.Clean(dest) - - // We need to be able to set any perms - restore := overrideUmask(0) - defer restore() - - if decompress { - decompLayer, err := DecompressStream(layer) - if err != nil { - return 0, err - } - defer decompLayer.Close() - layer = decompLayer - } - return UnpackLayer(dest, layer, options) -} diff --git a/vendor/github.com/docker/docker/pkg/archive/diff_unix.go b/vendor/github.com/docker/docker/pkg/archive/diff_unix.go deleted file mode 100644 index d7f806445..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/diff_unix.go +++ /dev/null @@ -1,22 +0,0 @@ -//go:build !windows -// +build !windows - -package archive - -import "golang.org/x/sys/unix" - -// overrideUmask sets current process's file mode creation mask to newmask -// and returns a function to restore it. -// -// WARNING for readers stumbling upon this code. Changing umask in a multi- -// threaded environment isn't safe. Don't use this without understanding the -// risks, and don't export this function for others to use (we shouldn't even -// be using this ourself). -// -// FIXME(thaJeztah): we should get rid of these hacks if possible. -func overrideUmask(newMask int) func() { - oldMask := unix.Umask(newMask) - return func() { - unix.Umask(oldMask) - } -} diff --git a/vendor/github.com/docker/docker/pkg/archive/diff_windows.go b/vendor/github.com/docker/docker/pkg/archive/diff_windows.go deleted file mode 100644 index d28f5b2df..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/diff_windows.go +++ /dev/null @@ -1,6 +0,0 @@ -package archive - -// overrideUmask is a no-op on windows. -func overrideUmask(newmask int) func() { - return func() {} -} diff --git a/vendor/github.com/docker/docker/pkg/archive/path.go b/vendor/github.com/docker/docker/pkg/archive/path.go deleted file mode 100644 index 888a69758..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/path.go +++ /dev/null @@ -1,20 +0,0 @@ -package archive - -// CheckSystemDriveAndRemoveDriveLetter verifies that a path, if it includes a drive letter, -// is the system drive. -// On Linux: this is a no-op. -// On Windows: this does the following> -// CheckSystemDriveAndRemoveDriveLetter verifies and manipulates a Windows path. -// This is used, for example, when validating a user provided path in docker cp. -// If a drive letter is supplied, it must be the system drive. The drive letter -// is always removed. Also, it translates it to OS semantics (IOW / to \). We -// need the path in this syntax so that it can ultimately be concatenated with -// a Windows long-path which doesn't support drive-letters. Examples: -// C: --> Fail -// C:\ --> \ -// a --> a -// /a --> \a -// d:\ --> Fail -func CheckSystemDriveAndRemoveDriveLetter(path string) (string, error) { - return checkSystemDriveAndRemoveDriveLetter(path) -} diff --git a/vendor/github.com/docker/docker/pkg/archive/path_unix.go b/vendor/github.com/docker/docker/pkg/archive/path_unix.go deleted file mode 100644 index 0b135aea7..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/path_unix.go +++ /dev/null @@ -1,10 +0,0 @@ -//go:build !windows -// +build !windows - -package archive - -// checkSystemDriveAndRemoveDriveLetter is the non-Windows implementation -// of CheckSystemDriveAndRemoveDriveLetter -func checkSystemDriveAndRemoveDriveLetter(path string) (string, error) { - return path, nil -} diff --git a/vendor/github.com/docker/docker/pkg/archive/path_windows.go b/vendor/github.com/docker/docker/pkg/archive/path_windows.go deleted file mode 100644 index 7e18c8e44..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/path_windows.go +++ /dev/null @@ -1,22 +0,0 @@ -package archive - -import ( - "fmt" - "path/filepath" - "strings" -) - -// checkSystemDriveAndRemoveDriveLetter is the Windows implementation -// of CheckSystemDriveAndRemoveDriveLetter -func checkSystemDriveAndRemoveDriveLetter(path string) (string, error) { - if len(path) == 2 && string(path[1]) == ":" { - return "", fmt.Errorf("no relative path specified in %q", path) - } - if !filepath.IsAbs(path) || len(path) < 2 { - return filepath.FromSlash(path), nil - } - if string(path[1]) == ":" && !strings.EqualFold(string(path[0]), "c") { - return "", fmt.Errorf("the specified path is not on the system drive (C:)") - } - return filepath.FromSlash(path[2:]), nil -} diff --git a/vendor/github.com/docker/docker/pkg/archive/time_linux.go b/vendor/github.com/docker/docker/pkg/archive/time_linux.go deleted file mode 100644 index 797143ee8..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/time_linux.go +++ /dev/null @@ -1,16 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "syscall" - "time" -) - -func timeToTimespec(time time.Time) (ts syscall.Timespec) { - if time.IsZero() { - // Return UTIME_OMIT special value - ts.Sec = 0 - ts.Nsec = (1 << 30) - 2 - return - } - return syscall.NsecToTimespec(time.UnixNano()) -} diff --git a/vendor/github.com/docker/docker/pkg/archive/time_unsupported.go b/vendor/github.com/docker/docker/pkg/archive/time_unsupported.go deleted file mode 100644 index d08779686..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/time_unsupported.go +++ /dev/null @@ -1,17 +0,0 @@ -//go:build !linux -// +build !linux - -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "syscall" - "time" -) - -func timeToTimespec(time time.Time) (ts syscall.Timespec) { - nsec := int64(0) - if !time.IsZero() { - nsec = time.UnixNano() - } - return syscall.NsecToTimespec(nsec) -} diff --git a/vendor/github.com/docker/docker/pkg/archive/whiteouts.go b/vendor/github.com/docker/docker/pkg/archive/whiteouts.go deleted file mode 100644 index 4c072a87e..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/whiteouts.go +++ /dev/null @@ -1,23 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -// Whiteouts are files with a special meaning for the layered filesystem. -// Docker uses AUFS whiteout files inside exported archives. In other -// filesystems these files are generated/handled on tar creation/extraction. - -// WhiteoutPrefix prefix means file is a whiteout. If this is followed by a -// filename this means that file has been removed from the base layer. -const WhiteoutPrefix = ".wh." - -// WhiteoutMetaPrefix prefix means whiteout has a special meaning and is not -// for removing an actual file. Normally these files are excluded from exported -// archives. -const WhiteoutMetaPrefix = WhiteoutPrefix + WhiteoutPrefix - -// WhiteoutLinkDir is a directory AUFS uses for storing hardlink links to other -// layers. Normally these should not go into exported archives and all changed -// hardlinks should be copied to the top layer. -const WhiteoutLinkDir = WhiteoutMetaPrefix + "plnk" - -// WhiteoutOpaqueDir file means directory has been made opaque - meaning -// readdir calls to this directory do not follow to lower layers. -const WhiteoutOpaqueDir = WhiteoutMetaPrefix + ".opq" diff --git a/vendor/github.com/docker/docker/pkg/archive/wrap.go b/vendor/github.com/docker/docker/pkg/archive/wrap.go deleted file mode 100644 index 032db82ce..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/wrap.go +++ /dev/null @@ -1,59 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "archive/tar" - "bytes" - "io" -) - -// Generate generates a new archive from the content provided -// as input. -// -// `files` is a sequence of path/content pairs. A new file is -// added to the archive for each pair. -// If the last pair is incomplete, the file is created with an -// empty content. For example: -// -// Generate("foo.txt", "hello world", "emptyfile") -// -// The above call will return an archive with 2 files: -// - ./foo.txt with content "hello world" -// - ./empty with empty content -// -// FIXME: stream content instead of buffering -// FIXME: specify permissions and other archive metadata -func Generate(input ...string) (io.Reader, error) { - files := parseStringPairs(input...) - buf := new(bytes.Buffer) - tw := tar.NewWriter(buf) - for _, file := range files { - name, content := file[0], file[1] - hdr := &tar.Header{ - Name: name, - Size: int64(len(content)), - } - if err := tw.WriteHeader(hdr); err != nil { - return nil, err - } - if _, err := tw.Write([]byte(content)); err != nil { - return nil, err - } - } - if err := tw.Close(); err != nil { - return nil, err - } - return buf, nil -} - -func parseStringPairs(input ...string) (output [][2]string) { - output = make([][2]string, 0, len(input)/2+1) - for i := 0; i < len(input); i += 2 { - var pair [2]string - pair[0] = input[i] - if i+1 < len(input) { - pair[1] = input[i+1] - } - output = append(output, pair) - } - return -} diff --git a/vendor/github.com/docker/docker/pkg/homedir/homedir_linux.go b/vendor/github.com/docker/docker/pkg/homedir/homedir_linux.go deleted file mode 100644 index ded1c7c8c..000000000 --- a/vendor/github.com/docker/docker/pkg/homedir/homedir_linux.go +++ /dev/null @@ -1,105 +0,0 @@ -package homedir // import "github.com/docker/docker/pkg/homedir" - -import ( - "errors" - "os" - "path/filepath" - "strings" -) - -// GetRuntimeDir returns XDG_RUNTIME_DIR. -// XDG_RUNTIME_DIR is typically configured via pam_systemd. -// GetRuntimeDir returns non-nil error if XDG_RUNTIME_DIR is not set. -// -// See also https://standards.freedesktop.org/basedir-spec/latest/ar01s03.html -func GetRuntimeDir() (string, error) { - if xdgRuntimeDir := os.Getenv("XDG_RUNTIME_DIR"); xdgRuntimeDir != "" { - return xdgRuntimeDir, nil - } - return "", errors.New("could not get XDG_RUNTIME_DIR") -} - -// StickRuntimeDirContents sets the sticky bit on files that are under -// XDG_RUNTIME_DIR, so that the files won't be periodically removed by the system. -// -// StickyRuntimeDir returns slice of sticked files. -// StickyRuntimeDir returns nil error if XDG_RUNTIME_DIR is not set. -// -// See also https://standards.freedesktop.org/basedir-spec/latest/ar01s03.html -func StickRuntimeDirContents(files []string) ([]string, error) { - runtimeDir, err := GetRuntimeDir() - if err != nil { - // ignore error if runtimeDir is empty - return nil, nil - } - runtimeDir, err = filepath.Abs(runtimeDir) - if err != nil { - return nil, err - } - var sticked []string - for _, f := range files { - f, err = filepath.Abs(f) - if err != nil { - return sticked, err - } - if strings.HasPrefix(f, runtimeDir+"/") { - if err = stick(f); err != nil { - return sticked, err - } - sticked = append(sticked, f) - } - } - return sticked, nil -} - -func stick(f string) error { - st, err := os.Stat(f) - if err != nil { - return err - } - m := st.Mode() - m |= os.ModeSticky - return os.Chmod(f, m) -} - -// GetDataHome returns XDG_DATA_HOME. -// GetDataHome returns $HOME/.local/share and nil error if XDG_DATA_HOME is not set. -// If HOME and XDG_DATA_HOME are not set, getpwent(3) is consulted to determine the users home directory. -// -// See also https://standards.freedesktop.org/basedir-spec/latest/ar01s03.html -func GetDataHome() (string, error) { - if xdgDataHome := os.Getenv("XDG_DATA_HOME"); xdgDataHome != "" { - return xdgDataHome, nil - } - home := Get() - if home == "" { - return "", errors.New("could not get either XDG_DATA_HOME or HOME") - } - return filepath.Join(home, ".local", "share"), nil -} - -// GetConfigHome returns XDG_CONFIG_HOME. -// GetConfigHome returns $HOME/.config and nil error if XDG_CONFIG_HOME is not set. -// If HOME and XDG_CONFIG_HOME are not set, getpwent(3) is consulted to determine the users home directory. -// -// See also https://standards.freedesktop.org/basedir-spec/latest/ar01s03.html -func GetConfigHome() (string, error) { - if xdgConfigHome := os.Getenv("XDG_CONFIG_HOME"); xdgConfigHome != "" { - return xdgConfigHome, nil - } - home := Get() - if home == "" { - return "", errors.New("could not get either XDG_CONFIG_HOME or HOME") - } - return filepath.Join(home, ".config"), nil -} - -// GetLibHome returns $HOME/.local/lib -// If HOME is not set, getpwent(3) is consulted to determine the users home directory. -func GetLibHome() (string, error) { - home := Get() - if home == "" { - return "", errors.New("could not get HOME") - } - return filepath.Join(home, ".local/lib"), nil -} diff --git a/vendor/github.com/docker/docker/pkg/homedir/homedir_others.go b/vendor/github.com/docker/docker/pkg/homedir/homedir_others.go deleted file mode 100644 index 11f1bec98..000000000 --- a/vendor/github.com/docker/docker/pkg/homedir/homedir_others.go +++ /dev/null @@ -1,33 +0,0 @@ -//go:build !linux -// +build !linux - -package homedir // import "github.com/docker/docker/pkg/homedir" - -import ( - "errors" -) - -// GetRuntimeDir is unsupported on non-linux system. -func GetRuntimeDir() (string, error) { - return "", errors.New("homedir.GetRuntimeDir() is not supported on this system") -} - -// StickRuntimeDirContents is unsupported on non-linux system. -func StickRuntimeDirContents(files []string) ([]string, error) { - return nil, errors.New("homedir.StickRuntimeDirContents() is not supported on this system") -} - -// GetDataHome is unsupported on non-linux system. -func GetDataHome() (string, error) { - return "", errors.New("homedir.GetDataHome() is not supported on this system") -} - -// GetConfigHome is unsupported on non-linux system. -func GetConfigHome() (string, error) { - return "", errors.New("homedir.GetConfigHome() is not supported on this system") -} - -// GetLibHome is unsupported on non-linux system. -func GetLibHome() (string, error) { - return "", errors.New("homedir.GetLibHome() is not supported on this system") -} diff --git a/vendor/github.com/docker/docker/pkg/homedir/homedir_unix.go b/vendor/github.com/docker/docker/pkg/homedir/homedir_unix.go deleted file mode 100644 index d1732dee5..000000000 --- a/vendor/github.com/docker/docker/pkg/homedir/homedir_unix.go +++ /dev/null @@ -1,39 +0,0 @@ -//go:build !windows -// +build !windows - -package homedir // import "github.com/docker/docker/pkg/homedir" - -import ( - "os" - "os/user" -) - -// Key returns the env var name for the user's home dir based on -// the platform being run on -func Key() string { - return "HOME" -} - -// Get returns the home directory of the current user with the help of -// environment variables depending on the target operating system. -// Returned path should be used with "path/filepath" to form new paths. -// -// If linking statically with cgo enabled against glibc, ensure the -// osusergo build tag is used. -// -// If needing to do nss lookups, do not disable cgo or set osusergo. -func Get() string { - home := os.Getenv(Key()) - if home == "" { - if u, err := user.Current(); err == nil { - return u.HomeDir - } - } - return home -} - -// GetShortcutString returns the string that is shortcut to user's home directory -// in the native shell of the platform running on. -func GetShortcutString() string { - return "~" -} diff --git a/vendor/github.com/docker/docker/pkg/homedir/homedir_windows.go b/vendor/github.com/docker/docker/pkg/homedir/homedir_windows.go deleted file mode 100644 index 2f81813b2..000000000 --- a/vendor/github.com/docker/docker/pkg/homedir/homedir_windows.go +++ /dev/null @@ -1,24 +0,0 @@ -package homedir // import "github.com/docker/docker/pkg/homedir" - -import ( - "os" -) - -// Key returns the env var name for the user's home dir based on -// the platform being run on -func Key() string { - return "USERPROFILE" -} - -// Get returns the home directory of the current user with the help of -// environment variables depending on the target operating system. -// Returned path should be used with "path/filepath" to form new paths. -func Get() string { - return os.Getenv(Key()) -} - -// GetShortcutString returns the string that is shortcut to user's home directory -// in the native shell of the platform running on. -func GetShortcutString() string { - return "%USERPROFILE%" // be careful while using in format functions -} diff --git a/vendor/github.com/docker/docker/pkg/idtools/idtools.go b/vendor/github.com/docker/docker/pkg/idtools/idtools.go deleted file mode 100644 index 79d682c69..000000000 --- a/vendor/github.com/docker/docker/pkg/idtools/idtools.go +++ /dev/null @@ -1,229 +0,0 @@ -package idtools // import "github.com/docker/docker/pkg/idtools" - -import ( - "bufio" - "fmt" - "os" - "strconv" - "strings" -) - -// IDMap contains a single entry for user namespace range remapping. An array -// of IDMap entries represents the structure that will be provided to the Linux -// kernel for creating a user namespace. -type IDMap struct { - ContainerID int `json:"container_id"` - HostID int `json:"host_id"` - Size int `json:"size"` -} - -type subIDRange struct { - Start int - Length int -} - -type ranges []subIDRange - -func (e ranges) Len() int { return len(e) } -func (e ranges) Swap(i, j int) { e[i], e[j] = e[j], e[i] } -func (e ranges) Less(i, j int) bool { return e[i].Start < e[j].Start } - -const ( - subuidFileName = "/etc/subuid" - subgidFileName = "/etc/subgid" -) - -// MkdirAllAndChown creates a directory (include any along the path) and then modifies -// ownership to the requested uid/gid. If the directory already exists, this -// function will still change ownership and permissions. -func MkdirAllAndChown(path string, mode os.FileMode, owner Identity) error { - return mkdirAs(path, mode, owner, true, true) -} - -// MkdirAndChown creates a directory and then modifies ownership to the requested uid/gid. -// If the directory already exists, this function still changes ownership and permissions. -// Note that unlike os.Mkdir(), this function does not return IsExist error -// in case path already exists. -func MkdirAndChown(path string, mode os.FileMode, owner Identity) error { - return mkdirAs(path, mode, owner, false, true) -} - -// MkdirAllAndChownNew creates a directory (include any along the path) and then modifies -// ownership ONLY of newly created directories to the requested uid/gid. If the -// directories along the path exist, no change of ownership or permissions will be performed -func MkdirAllAndChownNew(path string, mode os.FileMode, owner Identity) error { - return mkdirAs(path, mode, owner, true, false) -} - -// GetRootUIDGID retrieves the remapped root uid/gid pair from the set of maps. -// If the maps are empty, then the root uid/gid will default to "real" 0/0 -func GetRootUIDGID(uidMap, gidMap []IDMap) (int, int, error) { - uid, err := toHost(0, uidMap) - if err != nil { - return -1, -1, err - } - gid, err := toHost(0, gidMap) - if err != nil { - return -1, -1, err - } - return uid, gid, nil -} - -// toContainer takes an id mapping, and uses it to translate a -// host ID to the remapped ID. If no map is provided, then the translation -// assumes a 1-to-1 mapping and returns the passed in id -func toContainer(hostID int, idMap []IDMap) (int, error) { - if idMap == nil { - return hostID, nil - } - for _, m := range idMap { - if (hostID >= m.HostID) && (hostID <= (m.HostID + m.Size - 1)) { - contID := m.ContainerID + (hostID - m.HostID) - return contID, nil - } - } - return -1, fmt.Errorf("Host ID %d cannot be mapped to a container ID", hostID) -} - -// toHost takes an id mapping and a remapped ID, and translates the -// ID to the mapped host ID. If no map is provided, then the translation -// assumes a 1-to-1 mapping and returns the passed in id # -func toHost(contID int, idMap []IDMap) (int, error) { - if idMap == nil { - return contID, nil - } - for _, m := range idMap { - if (contID >= m.ContainerID) && (contID <= (m.ContainerID + m.Size - 1)) { - hostID := m.HostID + (contID - m.ContainerID) - return hostID, nil - } - } - return -1, fmt.Errorf("Container ID %d cannot be mapped to a host ID", contID) -} - -// Identity is either a UID and GID pair or a SID (but not both) -type Identity struct { - UID int - GID int - SID string -} - -// Chown changes the numeric uid and gid of the named file to id.UID and id.GID. -func (id Identity) Chown(name string) error { - return os.Chown(name, id.UID, id.GID) -} - -// IdentityMapping contains a mappings of UIDs and GIDs. -// The zero value represents an empty mapping. -type IdentityMapping struct { - UIDMaps []IDMap `json:"UIDMaps"` - GIDMaps []IDMap `json:"GIDMaps"` -} - -// RootPair returns a uid and gid pair for the root user. The error is ignored -// because a root user always exists, and the defaults are correct when the uid -// and gid maps are empty. -func (i IdentityMapping) RootPair() Identity { - uid, gid, _ := GetRootUIDGID(i.UIDMaps, i.GIDMaps) - return Identity{UID: uid, GID: gid} -} - -// ToHost returns the host UID and GID for the container uid, gid. -// Remapping is only performed if the ids aren't already the remapped root ids -func (i IdentityMapping) ToHost(pair Identity) (Identity, error) { - var err error - target := i.RootPair() - - if pair.UID != target.UID { - target.UID, err = toHost(pair.UID, i.UIDMaps) - if err != nil { - return target, err - } - } - - if pair.GID != target.GID { - target.GID, err = toHost(pair.GID, i.GIDMaps) - } - return target, err -} - -// ToContainer returns the container UID and GID for the host uid and gid -func (i IdentityMapping) ToContainer(pair Identity) (int, int, error) { - uid, err := toContainer(pair.UID, i.UIDMaps) - if err != nil { - return -1, -1, err - } - gid, err := toContainer(pair.GID, i.GIDMaps) - return uid, gid, err -} - -// Empty returns true if there are no id mappings -func (i IdentityMapping) Empty() bool { - return len(i.UIDMaps) == 0 && len(i.GIDMaps) == 0 -} - -func createIDMap(subidRanges ranges) []IDMap { - idMap := []IDMap{} - - containerID := 0 - for _, idrange := range subidRanges { - idMap = append(idMap, IDMap{ - ContainerID: containerID, - HostID: idrange.Start, - Size: idrange.Length, - }) - containerID = containerID + idrange.Length - } - return idMap -} - -func parseSubuid(username string) (ranges, error) { - return parseSubidFile(subuidFileName, username) -} - -func parseSubgid(username string) (ranges, error) { - return parseSubidFile(subgidFileName, username) -} - -// parseSubidFile will read the appropriate file (/etc/subuid or /etc/subgid) -// and return all found ranges for a specified username. If the special value -// "ALL" is supplied for username, then all ranges in the file will be returned -func parseSubidFile(path, username string) (ranges, error) { - var rangeList ranges - - subidFile, err := os.Open(path) - if err != nil { - return rangeList, err - } - defer subidFile.Close() - - s := bufio.NewScanner(subidFile) - for s.Scan() { - text := strings.TrimSpace(s.Text()) - if text == "" || strings.HasPrefix(text, "#") { - continue - } - parts := strings.Split(text, ":") - if len(parts) != 3 { - return rangeList, fmt.Errorf("Cannot parse subuid/gid information: Format not correct for %s file", path) - } - if parts[0] == username || username == "ALL" { - startid, err := strconv.Atoi(parts[1]) - if err != nil { - return rangeList, fmt.Errorf("String to int conversion failed during subuid/gid parsing of %s: %v", path, err) - } - length, err := strconv.Atoi(parts[2]) - if err != nil { - return rangeList, fmt.Errorf("String to int conversion failed during subuid/gid parsing of %s: %v", path, err) - } - rangeList = append(rangeList, subIDRange{startid, length}) - } - } - - return rangeList, s.Err() -} - -// CurrentIdentity returns the identity of the current process -func CurrentIdentity() Identity { - return Identity{UID: os.Getuid(), GID: os.Getegid()} -} diff --git a/vendor/github.com/docker/docker/pkg/idtools/idtools_unix.go b/vendor/github.com/docker/docker/pkg/idtools/idtools_unix.go deleted file mode 100644 index 2194c47d6..000000000 --- a/vendor/github.com/docker/docker/pkg/idtools/idtools_unix.go +++ /dev/null @@ -1,279 +0,0 @@ -//go:build !windows -// +build !windows - -package idtools // import "github.com/docker/docker/pkg/idtools" - -import ( - "bytes" - "fmt" - "io" - "os" - "os/exec" - "path/filepath" - "strconv" - "syscall" - - "github.com/opencontainers/runc/libcontainer/user" -) - -func mkdirAs(path string, mode os.FileMode, owner Identity, mkAll, chownExisting bool) error { - path, err := filepath.Abs(path) - if err != nil { - return err - } - - stat, err := os.Stat(path) - if err == nil { - if !stat.IsDir() { - return &os.PathError{Op: "mkdir", Path: path, Err: syscall.ENOTDIR} - } - if !chownExisting { - return nil - } - - // short-circuit -- we were called with an existing directory and chown was requested - return setPermissions(path, mode, owner, stat) - } - - // make an array containing the original path asked for, plus (for mkAll == true) - // all path components leading up to the complete path that don't exist before we MkdirAll - // so that we can chown all of them properly at the end. If chownExisting is false, we won't - // chown the full directory path if it exists - var paths []string - if os.IsNotExist(err) { - paths = []string{path} - } - - if mkAll { - // walk back to "/" looking for directories which do not exist - // and add them to the paths array for chown after creation - dirPath := path - for { - dirPath = filepath.Dir(dirPath) - if dirPath == "/" { - break - } - if _, err = os.Stat(dirPath); err != nil && os.IsNotExist(err) { - paths = append(paths, dirPath) - } - } - if err = os.MkdirAll(path, mode); err != nil { - return err - } - } else if err = os.Mkdir(path, mode); err != nil { - return err - } - // even if it existed, we will chown the requested path + any subpaths that - // didn't exist when we called MkdirAll - for _, pathComponent := range paths { - if err = setPermissions(pathComponent, mode, owner, nil); err != nil { - return err - } - } - return nil -} - -// LookupUser uses traditional local system files lookup (from libcontainer/user) on a username, -// followed by a call to `getent` for supporting host configured non-files passwd and group dbs -func LookupUser(name string) (user.User, error) { - // first try a local system files lookup using existing capabilities - usr, err := user.LookupUser(name) - if err == nil { - return usr, nil - } - // local files lookup failed; attempt to call `getent` to query configured passwd dbs - usr, err = getentUser(name) - if err != nil { - return user.User{}, err - } - return usr, nil -} - -// LookupUID uses traditional local system files lookup (from libcontainer/user) on a uid, -// followed by a call to `getent` for supporting host configured non-files passwd and group dbs -func LookupUID(uid int) (user.User, error) { - // first try a local system files lookup using existing capabilities - usr, err := user.LookupUid(uid) - if err == nil { - return usr, nil - } - // local files lookup failed; attempt to call `getent` to query configured passwd dbs - return getentUser(strconv.Itoa(uid)) -} - -func getentUser(name string) (user.User, error) { - reader, err := callGetent("passwd", name) - if err != nil { - return user.User{}, err - } - users, err := user.ParsePasswd(reader) - if err != nil { - return user.User{}, err - } - if len(users) == 0 { - return user.User{}, fmt.Errorf("getent failed to find passwd entry for %q", name) - } - return users[0], nil -} - -// LookupGroup uses traditional local system files lookup (from libcontainer/user) on a group name, -// followed by a call to `getent` for supporting host configured non-files passwd and group dbs -func LookupGroup(name string) (user.Group, error) { - // first try a local system files lookup using existing capabilities - group, err := user.LookupGroup(name) - if err == nil { - return group, nil - } - // local files lookup failed; attempt to call `getent` to query configured group dbs - return getentGroup(name) -} - -// LookupGID uses traditional local system files lookup (from libcontainer/user) on a group ID, -// followed by a call to `getent` for supporting host configured non-files passwd and group dbs -func LookupGID(gid int) (user.Group, error) { - // first try a local system files lookup using existing capabilities - group, err := user.LookupGid(gid) - if err == nil { - return group, nil - } - // local files lookup failed; attempt to call `getent` to query configured group dbs - return getentGroup(strconv.Itoa(gid)) -} - -func getentGroup(name string) (user.Group, error) { - reader, err := callGetent("group", name) - if err != nil { - return user.Group{}, err - } - groups, err := user.ParseGroup(reader) - if err != nil { - return user.Group{}, err - } - if len(groups) == 0 { - return user.Group{}, fmt.Errorf("getent failed to find groups entry for %q", name) - } - return groups[0], nil -} - -func callGetent(database, key string) (io.Reader, error) { - getentCmd, err := resolveBinary("getent") - // if no `getent` command within the execution environment, can't do anything else - if err != nil { - return nil, fmt.Errorf("unable to find getent command: %w", err) - } - command := exec.Command(getentCmd, database, key) - // we run getent within container filesystem, but without /dev so /dev/null is not available for exec to mock stdin - command.Stdin = io.NopCloser(bytes.NewReader(nil)) - out, err := command.CombinedOutput() - if err != nil { - exitCode, errC := getExitCode(err) - if errC != nil { - return nil, err - } - switch exitCode { - case 1: - return nil, fmt.Errorf("getent reported invalid parameters/database unknown") - case 2: - return nil, fmt.Errorf("getent unable to find entry %q in %s database", key, database) - case 3: - return nil, fmt.Errorf("getent database doesn't support enumeration") - default: - return nil, err - } - } - return bytes.NewReader(out), nil -} - -// getExitCode returns the ExitStatus of the specified error if its type is -// exec.ExitError, returns 0 and an error otherwise. -func getExitCode(err error) (int, error) { - exitCode := 0 - if exiterr, ok := err.(*exec.ExitError); ok { - if procExit, ok := exiterr.Sys().(syscall.WaitStatus); ok { - return procExit.ExitStatus(), nil - } - } - return exitCode, fmt.Errorf("failed to get exit code") -} - -// setPermissions performs a chown/chmod only if the uid/gid don't match what's requested -// Normally a Chown is a no-op if uid/gid match, but in some cases this can still cause an error, e.g. if the -// dir is on an NFS share, so don't call chown unless we absolutely must. -// Likewise for setting permissions. -func setPermissions(p string, mode os.FileMode, owner Identity, stat os.FileInfo) error { - if stat == nil { - var err error - stat, err = os.Stat(p) - if err != nil { - return err - } - } - if stat.Mode().Perm() != mode.Perm() { - if err := os.Chmod(p, mode.Perm()); err != nil { - return err - } - } - ssi := stat.Sys().(*syscall.Stat_t) - if ssi.Uid == uint32(owner.UID) && ssi.Gid == uint32(owner.GID) { - return nil - } - return os.Chown(p, owner.UID, owner.GID) -} - -// LoadIdentityMapping takes a requested username and -// using the data from /etc/sub{uid,gid} ranges, creates the -// proper uid and gid remapping ranges for that user/group pair -func LoadIdentityMapping(name string) (IdentityMapping, error) { - usr, err := LookupUser(name) - if err != nil { - return IdentityMapping{}, fmt.Errorf("could not get user for username %s: %v", name, err) - } - - subuidRanges, err := lookupSubUIDRanges(usr) - if err != nil { - return IdentityMapping{}, err - } - subgidRanges, err := lookupSubGIDRanges(usr) - if err != nil { - return IdentityMapping{}, err - } - - return IdentityMapping{ - UIDMaps: subuidRanges, - GIDMaps: subgidRanges, - }, nil -} - -func lookupSubUIDRanges(usr user.User) ([]IDMap, error) { - rangeList, err := parseSubuid(strconv.Itoa(usr.Uid)) - if err != nil { - return nil, err - } - if len(rangeList) == 0 { - rangeList, err = parseSubuid(usr.Name) - if err != nil { - return nil, err - } - } - if len(rangeList) == 0 { - return nil, fmt.Errorf("no subuid ranges found for user %q", usr.Name) - } - return createIDMap(rangeList), nil -} - -func lookupSubGIDRanges(usr user.User) ([]IDMap, error) { - rangeList, err := parseSubgid(strconv.Itoa(usr.Uid)) - if err != nil { - return nil, err - } - if len(rangeList) == 0 { - rangeList, err = parseSubgid(usr.Name) - if err != nil { - return nil, err - } - } - if len(rangeList) == 0 { - return nil, fmt.Errorf("no subgid ranges found for user %q", usr.Name) - } - return createIDMap(rangeList), nil -} diff --git a/vendor/github.com/docker/docker/pkg/idtools/idtools_windows.go b/vendor/github.com/docker/docker/pkg/idtools/idtools_windows.go deleted file mode 100644 index 32953f456..000000000 --- a/vendor/github.com/docker/docker/pkg/idtools/idtools_windows.go +++ /dev/null @@ -1,24 +0,0 @@ -package idtools // import "github.com/docker/docker/pkg/idtools" - -import ( - "os" - - "github.com/docker/docker/pkg/system" -) - -const ( - SeTakeOwnershipPrivilege = "SeTakeOwnershipPrivilege" -) - -const ( - ContainerAdministratorSidString = "S-1-5-93-2-1" - ContainerUserSidString = "S-1-5-93-2-2" -) - -// This is currently a wrapper around MkdirAll, however, since currently -// permissions aren't set through this path, the identity isn't utilized. -// Ownership is handled elsewhere, but in the future could be support here -// too. -func mkdirAs(path string, _ os.FileMode, _ Identity, _, _ bool) error { - return system.MkdirAll(path, 0) -} diff --git a/vendor/github.com/docker/docker/pkg/idtools/usergroupadd_linux.go b/vendor/github.com/docker/docker/pkg/idtools/usergroupadd_linux.go deleted file mode 100644 index f0c075e20..000000000 --- a/vendor/github.com/docker/docker/pkg/idtools/usergroupadd_linux.go +++ /dev/null @@ -1,166 +0,0 @@ -package idtools // import "github.com/docker/docker/pkg/idtools" - -import ( - "fmt" - "os/exec" - "regexp" - "sort" - "strconv" - "strings" - "sync" -) - -// add a user and/or group to Linux /etc/passwd, /etc/group using standard -// Linux distribution commands: -// adduser --system --shell /bin/false --disabled-login --disabled-password --no-create-home --group -// useradd -r -s /bin/false - -var ( - once sync.Once - userCommand string - idOutRegexp = regexp.MustCompile(`uid=([0-9]+).*gid=([0-9]+)`) -) - -const ( - // default length for a UID/GID subordinate range - defaultRangeLen = 65536 - defaultRangeStart = 100000 -) - -// AddNamespaceRangesUser takes a username and uses the standard system -// utility to create a system user/group pair used to hold the -// /etc/sub{uid,gid} ranges which will be used for user namespace -// mapping ranges in containers. -func AddNamespaceRangesUser(name string) (int, int, error) { - if err := addUser(name); err != nil { - return -1, -1, fmt.Errorf("error adding user %q: %v", name, err) - } - - // Query the system for the created uid and gid pair - out, err := exec.Command("id", name).CombinedOutput() - if err != nil { - return -1, -1, fmt.Errorf("error trying to find uid/gid for new user %q: %v", name, err) - } - matches := idOutRegexp.FindStringSubmatch(strings.TrimSpace(string(out))) - if len(matches) != 3 { - return -1, -1, fmt.Errorf("can't find uid, gid from `id` output: %q", string(out)) - } - uid, err := strconv.Atoi(matches[1]) - if err != nil { - return -1, -1, fmt.Errorf("can't convert found uid (%s) to int: %v", matches[1], err) - } - gid, err := strconv.Atoi(matches[2]) - if err != nil { - return -1, -1, fmt.Errorf("Can't convert found gid (%s) to int: %v", matches[2], err) - } - - // Now we need to create the subuid/subgid ranges for our new user/group (system users - // do not get auto-created ranges in subuid/subgid) - - if err := createSubordinateRanges(name); err != nil { - return -1, -1, fmt.Errorf("couldn't create subordinate ID ranges: %v", err) - } - return uid, gid, nil -} - -func addUser(name string) error { - once.Do(func() { - // set up which commands are used for adding users/groups dependent on distro - if _, err := resolveBinary("adduser"); err == nil { - userCommand = "adduser" - } else if _, err := resolveBinary("useradd"); err == nil { - userCommand = "useradd" - } - }) - var args []string - switch userCommand { - case "adduser": - args = []string{"--system", "--shell", "/bin/false", "--no-create-home", "--disabled-login", "--disabled-password", "--group", name} - case "useradd": - args = []string{"-r", "-s", "/bin/false", name} - default: - return fmt.Errorf("cannot add user; no useradd/adduser binary found") - } - - if out, err := exec.Command(userCommand, args...).CombinedOutput(); err != nil { - return fmt.Errorf("failed to add user with error: %v; output: %q", err, string(out)) - } - return nil -} - -func createSubordinateRanges(name string) error { - // first, we should verify that ranges weren't automatically created - // by the distro tooling - ranges, err := parseSubuid(name) - if err != nil { - return fmt.Errorf("error while looking for subuid ranges for user %q: %v", name, err) - } - if len(ranges) == 0 { - // no UID ranges; let's create one - startID, err := findNextUIDRange() - if err != nil { - return fmt.Errorf("can't find available subuid range: %v", err) - } - idRange := fmt.Sprintf("%d-%d", startID, startID+defaultRangeLen-1) - out, err := exec.Command("usermod", "-v", idRange, name).CombinedOutput() - if err != nil { - return fmt.Errorf("unable to add subuid range to user: %q; output: %s, err: %v", name, out, err) - } - } - - ranges, err = parseSubgid(name) - if err != nil { - return fmt.Errorf("error while looking for subgid ranges for user %q: %v", name, err) - } - if len(ranges) == 0 { - // no GID ranges; let's create one - startID, err := findNextGIDRange() - if err != nil { - return fmt.Errorf("can't find available subgid range: %v", err) - } - idRange := fmt.Sprintf("%d-%d", startID, startID+defaultRangeLen-1) - out, err := exec.Command("usermod", "-w", idRange, name).CombinedOutput() - if err != nil { - return fmt.Errorf("unable to add subgid range to user: %q; output: %s, err: %v", name, out, err) - } - } - return nil -} - -func findNextUIDRange() (int, error) { - ranges, err := parseSubuid("ALL") - if err != nil { - return -1, fmt.Errorf("couldn't parse all ranges in /etc/subuid file: %v", err) - } - sort.Sort(ranges) - return findNextRangeStart(ranges) -} - -func findNextGIDRange() (int, error) { - ranges, err := parseSubgid("ALL") - if err != nil { - return -1, fmt.Errorf("couldn't parse all ranges in /etc/subgid file: %v", err) - } - sort.Sort(ranges) - return findNextRangeStart(ranges) -} - -func findNextRangeStart(rangeList ranges) (int, error) { - startID := defaultRangeStart - for _, arange := range rangeList { - if wouldOverlap(arange, startID) { - startID = arange.Start + arange.Length - } - } - return startID, nil -} - -func wouldOverlap(arange subIDRange, ID int) bool { - low := ID - high := ID + defaultRangeLen - if (low >= arange.Start && low <= arange.Start+arange.Length) || - (high <= arange.Start+arange.Length && high >= arange.Start) { - return true - } - return false -} diff --git a/vendor/github.com/docker/docker/pkg/idtools/usergroupadd_unsupported.go b/vendor/github.com/docker/docker/pkg/idtools/usergroupadd_unsupported.go deleted file mode 100644 index 5e24577e2..000000000 --- a/vendor/github.com/docker/docker/pkg/idtools/usergroupadd_unsupported.go +++ /dev/null @@ -1,13 +0,0 @@ -//go:build !linux -// +build !linux - -package idtools // import "github.com/docker/docker/pkg/idtools" - -import "fmt" - -// AddNamespaceRangesUser takes a name and finds an unused uid, gid pair -// and calls the appropriate helper function to add the group and then -// the user to the group in /etc/group and /etc/passwd respectively. -func AddNamespaceRangesUser(name string) (int, int, error) { - return -1, -1, fmt.Errorf("No support for adding users or groups on this OS") -} diff --git a/vendor/github.com/docker/docker/pkg/idtools/utils_unix.go b/vendor/github.com/docker/docker/pkg/idtools/utils_unix.go deleted file mode 100644 index 05cc69636..000000000 --- a/vendor/github.com/docker/docker/pkg/idtools/utils_unix.go +++ /dev/null @@ -1,27 +0,0 @@ -//go:build !windows -// +build !windows - -package idtools // import "github.com/docker/docker/pkg/idtools" - -import ( - "fmt" - "os/exec" - "path/filepath" -) - -func resolveBinary(binname string) (string, error) { - binaryPath, err := exec.LookPath(binname) - if err != nil { - return "", err - } - resolvedPath, err := filepath.EvalSymlinks(binaryPath) - if err != nil { - return "", err - } - // only return no error if the final resolved binary basename - // matches what was searched for - if filepath.Base(resolvedPath) == binname { - return resolvedPath, nil - } - return "", fmt.Errorf("Binary %q does not resolve to a binary of that name in $PATH (%q)", binname, resolvedPath) -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/buffer.go b/vendor/github.com/docker/docker/pkg/ioutils/buffer.go deleted file mode 100644 index 466f79294..000000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/buffer.go +++ /dev/null @@ -1,51 +0,0 @@ -package ioutils // import "github.com/docker/docker/pkg/ioutils" - -import ( - "errors" - "io" -) - -var errBufferFull = errors.New("buffer is full") - -type fixedBuffer struct { - buf []byte - pos int - lastRead int -} - -func (b *fixedBuffer) Write(p []byte) (int, error) { - n := copy(b.buf[b.pos:cap(b.buf)], p) - b.pos += n - - if n < len(p) { - if b.pos == cap(b.buf) { - return n, errBufferFull - } - return n, io.ErrShortWrite - } - return n, nil -} - -func (b *fixedBuffer) Read(p []byte) (int, error) { - n := copy(p, b.buf[b.lastRead:b.pos]) - b.lastRead += n - return n, nil -} - -func (b *fixedBuffer) Len() int { - return b.pos - b.lastRead -} - -func (b *fixedBuffer) Cap() int { - return cap(b.buf) -} - -func (b *fixedBuffer) Reset() { - b.pos = 0 - b.lastRead = 0 - b.buf = b.buf[:0] -} - -func (b *fixedBuffer) String() string { - return string(b.buf[b.lastRead:b.pos]) -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/bytespipe.go b/vendor/github.com/docker/docker/pkg/ioutils/bytespipe.go deleted file mode 100644 index c1cfa62fd..000000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/bytespipe.go +++ /dev/null @@ -1,187 +0,0 @@ -package ioutils // import "github.com/docker/docker/pkg/ioutils" - -import ( - "errors" - "io" - "sync" -) - -// maxCap is the highest capacity to use in byte slices that buffer data. -const maxCap = 1e6 - -// minCap is the lowest capacity to use in byte slices that buffer data -const minCap = 64 - -// blockThreshold is the minimum number of bytes in the buffer which will cause -// a write to BytesPipe to block when allocating a new slice. -const blockThreshold = 1e6 - -var ( - // ErrClosed is returned when Write is called on a closed BytesPipe. - ErrClosed = errors.New("write to closed BytesPipe") - - bufPools = make(map[int]*sync.Pool) - bufPoolsLock sync.Mutex -) - -// BytesPipe is io.ReadWriteCloser which works similarly to pipe(queue). -// All written data may be read at most once. Also, BytesPipe allocates -// and releases new byte slices to adjust to current needs, so the buffer -// won't be overgrown after peak loads. -type BytesPipe struct { - mu sync.Mutex - wait *sync.Cond - buf []*fixedBuffer - bufLen int - closeErr error // error to return from next Read. set to nil if not closed. - readBlock bool // check read BytesPipe is Wait() or not -} - -// NewBytesPipe creates new BytesPipe, initialized by specified slice. -// If buf is nil, then it will be initialized with slice which cap is 64. -// buf will be adjusted in a way that len(buf) == 0, cap(buf) == cap(buf). -func NewBytesPipe() *BytesPipe { - bp := &BytesPipe{} - bp.buf = append(bp.buf, getBuffer(minCap)) - bp.wait = sync.NewCond(&bp.mu) - return bp -} - -// Write writes p to BytesPipe. -// It can allocate new []byte slices in a process of writing. -func (bp *BytesPipe) Write(p []byte) (int, error) { - bp.mu.Lock() - defer bp.mu.Unlock() - - written := 0 -loop0: - for { - if bp.closeErr != nil { - return written, ErrClosed - } - - if len(bp.buf) == 0 { - bp.buf = append(bp.buf, getBuffer(64)) - } - // get the last buffer - b := bp.buf[len(bp.buf)-1] - - n, err := b.Write(p) - written += n - bp.bufLen += n - - // errBufferFull is an error we expect to get if the buffer is full - if err != nil && err != errBufferFull { - bp.wait.Broadcast() - return written, err - } - - // if there was enough room to write all then break - if len(p) == n { - break - } - - // more data: write to the next slice - p = p[n:] - - // make sure the buffer doesn't grow too big from this write - for bp.bufLen >= blockThreshold { - if bp.readBlock { - bp.wait.Broadcast() - } - bp.wait.Wait() - if bp.closeErr != nil { - continue loop0 - } - } - - // add new byte slice to the buffers slice and continue writing - nextCap := b.Cap() * 2 - if nextCap > maxCap { - nextCap = maxCap - } - bp.buf = append(bp.buf, getBuffer(nextCap)) - } - bp.wait.Broadcast() - return written, nil -} - -// CloseWithError causes further reads from a BytesPipe to return immediately. -func (bp *BytesPipe) CloseWithError(err error) error { - bp.mu.Lock() - if err != nil { - bp.closeErr = err - } else { - bp.closeErr = io.EOF - } - bp.wait.Broadcast() - bp.mu.Unlock() - return nil -} - -// Close causes further reads from a BytesPipe to return immediately. -func (bp *BytesPipe) Close() error { - return bp.CloseWithError(nil) -} - -// Read reads bytes from BytesPipe. -// Data could be read only once. -func (bp *BytesPipe) Read(p []byte) (n int, err error) { - bp.mu.Lock() - defer bp.mu.Unlock() - if bp.bufLen == 0 { - if bp.closeErr != nil { - return 0, bp.closeErr - } - bp.readBlock = true - bp.wait.Wait() - bp.readBlock = false - if bp.bufLen == 0 && bp.closeErr != nil { - return 0, bp.closeErr - } - } - - for bp.bufLen > 0 { - b := bp.buf[0] - read, _ := b.Read(p) // ignore error since fixedBuffer doesn't really return an error - n += read - bp.bufLen -= read - - if b.Len() == 0 { - // it's empty so return it to the pool and move to the next one - returnBuffer(b) - bp.buf[0] = nil - bp.buf = bp.buf[1:] - } - - if len(p) == read { - break - } - - p = p[read:] - } - - bp.wait.Broadcast() - return -} - -func returnBuffer(b *fixedBuffer) { - b.Reset() - bufPoolsLock.Lock() - pool := bufPools[b.Cap()] - bufPoolsLock.Unlock() - if pool != nil { - pool.Put(b) - } -} - -func getBuffer(size int) *fixedBuffer { - bufPoolsLock.Lock() - pool, ok := bufPools[size] - if !ok { - pool = &sync.Pool{New: func() interface{} { return &fixedBuffer{buf: make([]byte, 0, size)} }} - bufPools[size] = pool - } - bufPoolsLock.Unlock() - return pool.Get().(*fixedBuffer) -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/fswriters.go b/vendor/github.com/docker/docker/pkg/ioutils/fswriters.go deleted file mode 100644 index 82671d8cd..000000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/fswriters.go +++ /dev/null @@ -1,161 +0,0 @@ -package ioutils // import "github.com/docker/docker/pkg/ioutils" - -import ( - "io" - "os" - "path/filepath" -) - -// NewAtomicFileWriter returns WriteCloser so that writing to it writes to a -// temporary file and closing it atomically changes the temporary file to -// destination path. Writing and closing concurrently is not allowed. -func NewAtomicFileWriter(filename string, perm os.FileMode) (io.WriteCloser, error) { - f, err := os.CreateTemp(filepath.Dir(filename), ".tmp-"+filepath.Base(filename)) - if err != nil { - return nil, err - } - - abspath, err := filepath.Abs(filename) - if err != nil { - return nil, err - } - return &atomicFileWriter{ - f: f, - fn: abspath, - perm: perm, - }, nil -} - -// AtomicWriteFile atomically writes data to a file named by filename. -func AtomicWriteFile(filename string, data []byte, perm os.FileMode) error { - f, err := NewAtomicFileWriter(filename, perm) - if err != nil { - return err - } - n, err := f.Write(data) - if err == nil && n < len(data) { - err = io.ErrShortWrite - f.(*atomicFileWriter).writeErr = err - } - if err1 := f.Close(); err == nil { - err = err1 - } - return err -} - -type atomicFileWriter struct { - f *os.File - fn string - writeErr error - perm os.FileMode -} - -func (w *atomicFileWriter) Write(dt []byte) (int, error) { - n, err := w.f.Write(dt) - if err != nil { - w.writeErr = err - } - return n, err -} - -func (w *atomicFileWriter) Close() (retErr error) { - defer func() { - if retErr != nil || w.writeErr != nil { - os.Remove(w.f.Name()) - } - }() - if err := w.f.Sync(); err != nil { - w.f.Close() - return err - } - if err := w.f.Close(); err != nil { - return err - } - if err := os.Chmod(w.f.Name(), w.perm); err != nil { - return err - } - if w.writeErr == nil { - return os.Rename(w.f.Name(), w.fn) - } - return nil -} - -// AtomicWriteSet is used to atomically write a set -// of files and ensure they are visible at the same time. -// Must be committed to a new directory. -type AtomicWriteSet struct { - root string -} - -// NewAtomicWriteSet creates a new atomic write set to -// atomically create a set of files. The given directory -// is used as the base directory for storing files before -// commit. If no temporary directory is given the system -// default is used. -func NewAtomicWriteSet(tmpDir string) (*AtomicWriteSet, error) { - td, err := os.MkdirTemp(tmpDir, "write-set-") - if err != nil { - return nil, err - } - - return &AtomicWriteSet{ - root: td, - }, nil -} - -// WriteFile writes a file to the set, guaranteeing the file -// has been synced. -func (ws *AtomicWriteSet) WriteFile(filename string, data []byte, perm os.FileMode) error { - f, err := ws.FileWriter(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm) - if err != nil { - return err - } - n, err := f.Write(data) - if err == nil && n < len(data) { - err = io.ErrShortWrite - } - if err1 := f.Close(); err == nil { - err = err1 - } - return err -} - -type syncFileCloser struct { - *os.File -} - -func (w syncFileCloser) Close() error { - err := w.File.Sync() - if err1 := w.File.Close(); err == nil { - err = err1 - } - return err -} - -// FileWriter opens a file writer inside the set. The file -// should be synced and closed before calling commit. -func (ws *AtomicWriteSet) FileWriter(name string, flag int, perm os.FileMode) (io.WriteCloser, error) { - f, err := os.OpenFile(filepath.Join(ws.root, name), flag, perm) - if err != nil { - return nil, err - } - return syncFileCloser{f}, nil -} - -// Cancel cancels the set and removes all temporary data -// created in the set. -func (ws *AtomicWriteSet) Cancel() error { - return os.RemoveAll(ws.root) -} - -// Commit moves all created files to the target directory. The -// target directory must not exist and the parent of the target -// directory must exist. -func (ws *AtomicWriteSet) Commit(target string) error { - return os.Rename(ws.root, target) -} - -// String returns the location the set is writing to. -func (ws *AtomicWriteSet) String() string { - return ws.root -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/readers.go b/vendor/github.com/docker/docker/pkg/ioutils/readers.go deleted file mode 100644 index d82ae9303..000000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/readers.go +++ /dev/null @@ -1,172 +0,0 @@ -package ioutils // import "github.com/docker/docker/pkg/ioutils" - -import ( - "context" - "io" - "runtime/debug" - "sync/atomic" - - // make sure crypto.SHA256, crypto.sha512 and crypto.SHA384 are registered - // TODO remove once https://github.com/opencontainers/go-digest/pull/64 is merged. - _ "crypto/sha256" - _ "crypto/sha512" - - "github.com/sirupsen/logrus" -) - -// ReadCloserWrapper wraps an io.Reader, and implements an io.ReadCloser -// It calls the given callback function when closed. It should be constructed -// with NewReadCloserWrapper -type ReadCloserWrapper struct { - io.Reader - closer func() error - closed atomic.Bool -} - -// Close calls back the passed closer function -func (r *ReadCloserWrapper) Close() error { - if !r.closed.CompareAndSwap(false, true) { - subsequentCloseWarn("ReadCloserWrapper") - return nil - } - return r.closer() -} - -// NewReadCloserWrapper returns a new io.ReadCloser. -func NewReadCloserWrapper(r io.Reader, closer func() error) io.ReadCloser { - return &ReadCloserWrapper{ - Reader: r, - closer: closer, - } -} - -type readerErrWrapper struct { - reader io.Reader - closer func() -} - -func (r *readerErrWrapper) Read(p []byte) (int, error) { - n, err := r.reader.Read(p) - if err != nil { - r.closer() - } - return n, err -} - -// NewReaderErrWrapper returns a new io.Reader. -func NewReaderErrWrapper(r io.Reader, closer func()) io.Reader { - return &readerErrWrapper{ - reader: r, - closer: closer, - } -} - -// OnEOFReader wraps an io.ReadCloser and a function -// the function will run at the end of file or close the file. -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 -} - -// Close closes the file and run the function. -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 - } -} - -// cancelReadCloser wraps an io.ReadCloser with a context for cancelling read -// operations. -type cancelReadCloser struct { - cancel func() - pR *io.PipeReader // Stream to read from - pW *io.PipeWriter - closed atomic.Bool -} - -// NewCancelReadCloser creates a wrapper that closes the ReadCloser when the -// context is cancelled. The returned io.ReadCloser must be closed when it is -// no longer needed. -func NewCancelReadCloser(ctx context.Context, in io.ReadCloser) io.ReadCloser { - pR, pW := io.Pipe() - - // Create a context used to signal when the pipe is closed - doneCtx, cancel := context.WithCancel(context.Background()) - - p := &cancelReadCloser{ - cancel: cancel, - pR: pR, - pW: pW, - } - - go func() { - _, err := io.Copy(pW, in) - select { - case <-ctx.Done(): - // If the context was closed, p.closeWithError - // was already called. Calling it again would - // change the error that Read returns. - default: - p.closeWithError(err) - } - in.Close() - }() - go func() { - for { - select { - case <-ctx.Done(): - p.closeWithError(ctx.Err()) - case <-doneCtx.Done(): - return - } - } - }() - - return p -} - -// Read wraps the Read method of the pipe that provides data from the wrapped -// ReadCloser. -func (p *cancelReadCloser) Read(buf []byte) (n int, err error) { - return p.pR.Read(buf) -} - -// closeWithError closes the wrapper and its underlying reader. It will -// cause future calls to Read to return err. -func (p *cancelReadCloser) closeWithError(err error) { - p.pW.CloseWithError(err) - p.cancel() -} - -// Close closes the wrapper its underlying reader. It will cause -// future calls to Read to return io.EOF. -func (p *cancelReadCloser) Close() error { - if !p.closed.CompareAndSwap(false, true) { - subsequentCloseWarn("cancelReadCloser") - return nil - } - p.closeWithError(io.EOF) - return nil -} - -func subsequentCloseWarn(name string) { - logrus.Error("subsequent attempt to close " + name) - if logrus.GetLevel() >= logrus.DebugLevel { - logrus.Errorf("stack trace: %s", string(debug.Stack())) - } -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/tempdir_deprecated.go b/vendor/github.com/docker/docker/pkg/ioutils/tempdir_deprecated.go deleted file mode 100644 index b3321602c..000000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/tempdir_deprecated.go +++ /dev/null @@ -1,10 +0,0 @@ -package ioutils - -import "github.com/docker/docker/pkg/longpath" - -// TempDir is the equivalent of [os.MkdirTemp], except that on Windows -// the result is in Windows longpath format. On Unix systems it is -// equivalent to [os.MkdirTemp]. -// -// Deprecated: use [longpath.MkdirTemp]. -var TempDir = longpath.MkdirTemp diff --git a/vendor/github.com/docker/docker/pkg/ioutils/writeflusher.go b/vendor/github.com/docker/docker/pkg/ioutils/writeflusher.go deleted file mode 100644 index 91b8d1826..000000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/writeflusher.go +++ /dev/null @@ -1,92 +0,0 @@ -package ioutils // import "github.com/docker/docker/pkg/ioutils" - -import ( - "io" - "sync" -) - -// WriteFlusher wraps the Write and Flush operation ensuring that every write -// is a flush. In addition, the Close method can be called to intercept -// Read/Write calls if the targets lifecycle has already ended. -type WriteFlusher struct { - w io.Writer - flusher flusher - flushed chan struct{} - flushedOnce sync.Once - closed chan struct{} - closeLock sync.Mutex -} - -type flusher interface { - Flush() -} - -var errWriteFlusherClosed = io.EOF - -func (wf *WriteFlusher) Write(b []byte) (n int, err error) { - select { - case <-wf.closed: - return 0, errWriteFlusherClosed - default: - } - - n, err = wf.w.Write(b) - wf.Flush() // every write is a flush. - return n, err -} - -// Flush the stream immediately. -func (wf *WriteFlusher) Flush() { - select { - case <-wf.closed: - return - default: - } - - wf.flushedOnce.Do(func() { - close(wf.flushed) - }) - wf.flusher.Flush() -} - -// Flushed returns the state of flushed. -// If it's flushed, return true, or else it return false. -func (wf *WriteFlusher) Flushed() bool { - // BUG(stevvooe): Remove this method. Its use is inherently racy. Seems to - // be used to detect whether or a response code has been issued or not. - // Another hook should be used instead. - var flushed bool - select { - case <-wf.flushed: - flushed = true - default: - } - return flushed -} - -// Close closes the write flusher, disallowing any further writes to the -// target. After the flusher is closed, all calls to write or flush will -// result in an error. -func (wf *WriteFlusher) Close() error { - wf.closeLock.Lock() - defer wf.closeLock.Unlock() - - select { - case <-wf.closed: - return errWriteFlusherClosed - default: - close(wf.closed) - } - return nil -} - -// NewWriteFlusher returns a new WriteFlusher. -func NewWriteFlusher(w io.Writer) *WriteFlusher { - var fl flusher - if f, ok := w.(flusher); ok { - fl = f - } else { - fl = &NopFlusher{} - } - return &WriteFlusher{w: w, flusher: fl, closed: make(chan struct{}), flushed: make(chan struct{})} -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/writers.go b/vendor/github.com/docker/docker/pkg/ioutils/writers.go deleted file mode 100644 index 1f50602f2..000000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/writers.go +++ /dev/null @@ -1,74 +0,0 @@ -package ioutils // import "github.com/docker/docker/pkg/ioutils" - -import ( - "io" - "sync/atomic" -) - -// NopWriter represents a type which write operation is nop. -type NopWriter struct{} - -func (*NopWriter) Write(buf []byte) (int, error) { - return len(buf), nil -} - -type nopWriteCloser struct { - io.Writer -} - -func (w *nopWriteCloser) Close() error { return nil } - -// NopWriteCloser returns a nopWriteCloser. -func NopWriteCloser(w io.Writer) io.WriteCloser { - return &nopWriteCloser{w} -} - -// NopFlusher represents a type which flush operation is nop. -type NopFlusher struct{} - -// Flush is a nop operation. -func (f *NopFlusher) Flush() {} - -type writeCloserWrapper struct { - io.Writer - closer func() error - closed atomic.Bool -} - -func (r *writeCloserWrapper) Close() error { - if !r.closed.CompareAndSwap(false, true) { - subsequentCloseWarn("WriteCloserWrapper") - return nil - } - return r.closer() -} - -// NewWriteCloserWrapper returns a new io.WriteCloser. -func NewWriteCloserWrapper(r io.Writer, closer func() error) io.WriteCloser { - return &writeCloserWrapper{ - Writer: r, - closer: closer, - } -} - -// WriteCounter wraps a concrete io.Writer and hold a count of the number -// of bytes written to the writer during a "session". -// This can be convenient when write return is masked -// (e.g., json.Encoder.Encode()) -type WriteCounter struct { - Count int64 - Writer io.Writer -} - -// NewWriteCounter returns a new WriteCounter. -func NewWriteCounter(w io.Writer) *WriteCounter { - return &WriteCounter{ - Writer: w, - } -} - -func (wc *WriteCounter) Write(p []byte) (count int, err error) { - count, err = wc.Writer.Write(p) - wc.Count += int64(count) - return -} diff --git a/vendor/github.com/docker/docker/pkg/jsonmessage/jsonmessage.go b/vendor/github.com/docker/docker/pkg/jsonmessage/jsonmessage.go deleted file mode 100644 index 035160c83..000000000 --- a/vendor/github.com/docker/docker/pkg/jsonmessage/jsonmessage.go +++ /dev/null @@ -1,307 +0,0 @@ -package jsonmessage // import "github.com/docker/docker/pkg/jsonmessage" - -import ( - "encoding/json" - "fmt" - "io" - "strings" - "time" - - units "github.com/docker/go-units" - "github.com/moby/term" - "github.com/morikuni/aec" -) - -// RFC3339NanoFixed is time.RFC3339Nano with nanoseconds padded using zeros to -// ensure the formatted time isalways the same number of characters. -const RFC3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00" - -// JSONError wraps a concrete Code and Message, Code is -// an integer error code, Message is the error message. -type JSONError struct { - Code int `json:"code,omitempty"` - Message string `json:"message,omitempty"` -} - -func (e *JSONError) Error() string { - return e.Message -} - -// JSONProgress describes a progress message in a JSON stream. -type JSONProgress struct { - // Current is the current status and value of the progress made towards Total. - Current int64 `json:"current,omitempty"` - // Total is the end value describing when we made 100% progress for an operation. - Total int64 `json:"total,omitempty"` - // Start is the initial value for the operation. - Start int64 `json:"start,omitempty"` - // HideCounts. if true, hides the progress count indicator (xB/yB). - HideCounts bool `json:"hidecounts,omitempty"` - // Units is the unit to print for progress. It defaults to "bytes" if empty. - Units string `json:"units,omitempty"` - - // terminalFd is the fd of the current terminal, if any. It is used - // to get the terminal width. - terminalFd uintptr - - // nowFunc is used to override the current time in tests. - nowFunc func() time.Time - - // winSize is used to override the terminal width in tests. - winSize int -} - -func (p *JSONProgress) String() string { - var ( - width = p.width() - pbBox string - numbersBox string - timeLeftBox string - ) - if p.Current <= 0 && p.Total <= 0 { - return "" - } - if p.Total <= 0 { - switch p.Units { - case "": - return fmt.Sprintf("%8v", units.HumanSize(float64(p.Current))) - default: - return fmt.Sprintf("%d %s", p.Current, p.Units) - } - } - - percentage := int(float64(p.Current)/float64(p.Total)*100) / 2 - if percentage > 50 { - percentage = 50 - } - if width > 110 { - // this number can't be negative gh#7136 - numSpaces := 0 - if 50-percentage > 0 { - numSpaces = 50 - percentage - } - pbBox = fmt.Sprintf("[%s>%s] ", strings.Repeat("=", percentage), strings.Repeat(" ", numSpaces)) - } - - switch { - case p.HideCounts: - case p.Units == "": // no units, use bytes - current := units.HumanSize(float64(p.Current)) - total := units.HumanSize(float64(p.Total)) - - numbersBox = fmt.Sprintf("%8v/%v", current, total) - - if p.Current > p.Total { - // remove total display if the reported current is wonky. - numbersBox = fmt.Sprintf("%8v", current) - } - default: - numbersBox = fmt.Sprintf("%d/%d %s", p.Current, p.Total, p.Units) - - if p.Current > p.Total { - // remove total display if the reported current is wonky. - numbersBox = fmt.Sprintf("%d %s", p.Current, p.Units) - } - } - - if p.Current > 0 && p.Start > 0 && percentage < 50 { - fromStart := p.now().Sub(time.Unix(p.Start, 0)) - perEntry := fromStart / time.Duration(p.Current) - left := time.Duration(p.Total-p.Current) * perEntry - left = (left / time.Second) * time.Second - - if width > 50 { - timeLeftBox = " " + left.String() - } - } - return pbBox + numbersBox + timeLeftBox -} - -// now returns the current time in UTC, but can be overridden in tests -// by setting JSONProgress.nowFunc to a custom function. -func (p *JSONProgress) now() time.Time { - if p.nowFunc != nil { - return p.nowFunc() - } - return time.Now().UTC() -} - -// width returns the current terminal's width, but can be overridden -// in tests by setting JSONProgress.winSize to a non-zero value. -func (p *JSONProgress) width() int { - if p.winSize != 0 { - return p.winSize - } - ws, err := term.GetWinsize(p.terminalFd) - if err == nil { - return int(ws.Width) - } - return 200 -} - -// JSONMessage defines a message struct. It describes -// the created time, where it from, status, ID of the -// message. It's used for docker events. -type JSONMessage struct { - Stream string `json:"stream,omitempty"` - Status string `json:"status,omitempty"` - Progress *JSONProgress `json:"progressDetail,omitempty"` - ProgressMessage string `json:"progress,omitempty"` // deprecated - ID string `json:"id,omitempty"` - From string `json:"from,omitempty"` - Time int64 `json:"time,omitempty"` - TimeNano int64 `json:"timeNano,omitempty"` - Error *JSONError `json:"errorDetail,omitempty"` - ErrorMessage string `json:"error,omitempty"` // deprecated - // Aux contains out-of-band data, such as digests for push signing and image id after building. - Aux *json.RawMessage `json:"aux,omitempty"` -} - -func clearLine(out io.Writer) { - eraseMode := aec.EraseModes.All - cl := aec.EraseLine(eraseMode) - fmt.Fprint(out, cl) -} - -func cursorUp(out io.Writer, l uint) { - fmt.Fprint(out, aec.Up(l)) -} - -func cursorDown(out io.Writer, l uint) { - fmt.Fprint(out, aec.Down(l)) -} - -// Display prints the JSONMessage to out. If isTerminal is true, it erases -// the entire current line when displaying the progressbar. It returns an -// error if the [JSONMessage.Error] field is non-nil. -func (jm *JSONMessage) Display(out io.Writer, isTerminal bool) error { - if jm.Error != nil { - return jm.Error - } - var endl string - if isTerminal && jm.Stream == "" && jm.Progress != nil { - clearLine(out) - endl = "\r" - fmt.Fprint(out, endl) - } else if jm.Progress != nil && jm.Progress.String() != "" { // disable progressbar in non-terminal - return nil - } - if jm.TimeNano != 0 { - fmt.Fprintf(out, "%s ", time.Unix(0, jm.TimeNano).Format(RFC3339NanoFixed)) - } else if jm.Time != 0 { - fmt.Fprintf(out, "%s ", time.Unix(jm.Time, 0).Format(RFC3339NanoFixed)) - } - if jm.ID != "" { - fmt.Fprintf(out, "%s: ", jm.ID) - } - if jm.From != "" { - fmt.Fprintf(out, "(from %s) ", jm.From) - } - if jm.Progress != nil && isTerminal { - fmt.Fprintf(out, "%s %s%s", jm.Status, jm.Progress.String(), endl) - } else if jm.ProgressMessage != "" { // deprecated - fmt.Fprintf(out, "%s %s%s", jm.Status, jm.ProgressMessage, endl) - } else if jm.Stream != "" { - fmt.Fprintf(out, "%s%s", jm.Stream, endl) - } else { - fmt.Fprintf(out, "%s%s\n", jm.Status, endl) - } - return nil -} - -// DisplayJSONMessagesStream reads a JSON message stream from in, and writes -// each [JSONMessage] to out. It returns an error if an invalid JSONMessage -// is received, or if a JSONMessage containers a non-zero [JSONMessage.Error]. -// -// Presentation of the JSONMessage depends on whether a terminal is attached, -// and on the terminal width. Progress bars ([JSONProgress]) are suppressed -// on narrower terminals (< 110 characters). -// -// - isTerminal describes if out is a terminal, in which case it prints -// a newline ("\n") at the end of each line and moves the cursor while -// displaying. -// - terminalFd is the fd of the current terminal (if any), and used -// to get the terminal width. -// - auxCallback allows handling the [JSONMessage.Aux] field. It is -// called if a JSONMessage contains an Aux field, in which case -// DisplayJSONMessagesStream does not present the JSONMessage. -func DisplayJSONMessagesStream(in io.Reader, out io.Writer, terminalFd uintptr, isTerminal bool, auxCallback func(JSONMessage)) error { - var ( - dec = json.NewDecoder(in) - ids = make(map[string]uint) - ) - - for { - var diff uint - var jm JSONMessage - if err := dec.Decode(&jm); err != nil { - if err == io.EOF { - break - } - return err - } - - if jm.Aux != nil { - if auxCallback != nil { - auxCallback(jm) - } - continue - } - - if jm.Progress != nil { - jm.Progress.terminalFd = terminalFd - } - if jm.ID != "" && (jm.Progress != nil || jm.ProgressMessage != "") { - line, ok := ids[jm.ID] - if !ok { - // NOTE: This approach of using len(id) to - // figure out the number of lines of history - // only works as long as we clear the history - // when we output something that's not - // accounted for in the map, such as a line - // with no ID. - line = uint(len(ids)) - ids[jm.ID] = line - if isTerminal { - fmt.Fprintf(out, "\n") - } - } - diff = uint(len(ids)) - line - if isTerminal { - cursorUp(out, diff) - } - } else { - // When outputting something that isn't progress - // output, clear the history of previous lines. We - // don't want progress entries from some previous - // operation to be updated (for example, pull -a - // with multiple tags). - ids = make(map[string]uint) - } - err := jm.Display(out, isTerminal) - if jm.ID != "" && isTerminal { - cursorDown(out, diff) - } - if err != nil { - return err - } - } - return nil -} - -// Stream is an io.Writer for output with utilities to get the output's file -// descriptor and to detect wether it's a terminal. -// -// it is subset of the streams.Out type in -// https://pkg.go.dev/github.com/docker/cli@v20.10.17+incompatible/cli/streams#Out -type Stream interface { - io.Writer - FD() uintptr - IsTerminal() bool -} - -// DisplayJSONMessagesToStream prints json messages to the output Stream. It is -// used by the Docker CLI to print JSONMessage streams. -func DisplayJSONMessagesToStream(in io.Reader, stream Stream, auxCallback func(JSONMessage)) error { - return DisplayJSONMessagesStream(in, stream, stream.FD(), stream.IsTerminal(), auxCallback) -} diff --git a/vendor/github.com/docker/docker/pkg/longpath/longpath.go b/vendor/github.com/docker/docker/pkg/longpath/longpath.go deleted file mode 100644 index 1c5dde521..000000000 --- a/vendor/github.com/docker/docker/pkg/longpath/longpath.go +++ /dev/null @@ -1,43 +0,0 @@ -// Package longpath introduces some constants and helper functions for handling -// long paths in Windows. -// -// Long paths are expected to be prepended with "\\?\" and followed by either a -// drive letter, a UNC server\share, or a volume identifier. -package longpath // import "github.com/docker/docker/pkg/longpath" - -import ( - "os" - "runtime" - "strings" -) - -// Prefix is the longpath prefix for Windows file paths. -const Prefix = `\\?\` - -// AddPrefix adds the Windows long path prefix to the path provided if -// it does not already have it. -func AddPrefix(path string) string { - if !strings.HasPrefix(path, Prefix) { - if strings.HasPrefix(path, `\\`) { - // This is a UNC path, so we need to add 'UNC' to the path as well. - path = Prefix + `UNC` + path[1:] - } else { - path = Prefix + path - } - } - return path -} - -// MkdirTemp is the equivalent of [os.MkdirTemp], except that on Windows -// the result is in Windows longpath format. On Unix systems it is -// equivalent to [os.MkdirTemp]. -func MkdirTemp(dir, prefix string) (string, error) { - tempDir, err := os.MkdirTemp(dir, prefix) - if err != nil { - return "", err - } - if runtime.GOOS != "windows" { - return tempDir, nil - } - return AddPrefix(tempDir), nil -} diff --git a/vendor/github.com/docker/docker/pkg/meminfo/meminfo.go b/vendor/github.com/docker/docker/pkg/meminfo/meminfo.go deleted file mode 100644 index 4f33ad26b..000000000 --- a/vendor/github.com/docker/docker/pkg/meminfo/meminfo.go +++ /dev/null @@ -1,26 +0,0 @@ -// Package meminfo provides utilites to retrieve memory statistics of -// the host system. -package meminfo - -// Read retrieves memory statistics of the host system and returns a -// Memory type. It is only supported on Linux and Windows, and returns an -// error on other platforms. -func Read() (*Memory, error) { - return readMemInfo() -} - -// Memory contains memory statistics of the host system. -type Memory struct { - // Total usable RAM (i.e. physical RAM minus a few reserved bits and the - // kernel binary code). - MemTotal int64 - - // Amount of free memory. - MemFree int64 - - // Total amount of swap space available. - SwapTotal int64 - - // Amount of swap space that is currently unused. - SwapFree int64 -} diff --git a/vendor/github.com/docker/docker/pkg/meminfo/meminfo_linux.go b/vendor/github.com/docker/docker/pkg/meminfo/meminfo_linux.go deleted file mode 100644 index 0c1cd21d4..000000000 --- a/vendor/github.com/docker/docker/pkg/meminfo/meminfo_linux.go +++ /dev/null @@ -1,69 +0,0 @@ -package meminfo - -import ( - "bufio" - "io" - "os" - "strconv" - "strings" -) - -// readMemInfo retrieves memory statistics of the host system and returns a -// Memory type. -func readMemInfo() (*Memory, error) { - file, err := os.Open("/proc/meminfo") - if err != nil { - return nil, err - } - defer file.Close() - return parseMemInfo(file) -} - -// parseMemInfo parses the /proc/meminfo file into -// a Memory object given an io.Reader to the file. -// Throws error if there are problems reading from the file -func parseMemInfo(reader io.Reader) (*Memory, error) { - meminfo := &Memory{} - scanner := bufio.NewScanner(reader) - memAvailable := int64(-1) - for scanner.Scan() { - // Expected format: ["MemTotal:", "1234", "kB"] - parts := strings.Fields(scanner.Text()) - - // Sanity checks: Skip malformed entries. - if len(parts) < 3 || parts[2] != "kB" { - continue - } - - // Convert to bytes. - size, err := strconv.Atoi(parts[1]) - if err != nil { - continue - } - // Convert to KiB - bytes := int64(size) * 1024 - - switch parts[0] { - case "MemTotal:": - meminfo.MemTotal = bytes - case "MemFree:": - meminfo.MemFree = bytes - case "MemAvailable:": - memAvailable = bytes - case "SwapTotal:": - meminfo.SwapTotal = bytes - case "SwapFree:": - meminfo.SwapFree = bytes - } - } - if memAvailable != -1 { - meminfo.MemFree = memAvailable - } - - // Handle errors that may have occurred during the reading of the file. - if err := scanner.Err(); err != nil { - return nil, err - } - - return meminfo, nil -} diff --git a/vendor/github.com/docker/docker/pkg/meminfo/meminfo_unsupported.go b/vendor/github.com/docker/docker/pkg/meminfo/meminfo_unsupported.go deleted file mode 100644 index ebfadd534..000000000 --- a/vendor/github.com/docker/docker/pkg/meminfo/meminfo_unsupported.go +++ /dev/null @@ -1,11 +0,0 @@ -//go:build !linux && !windows -// +build !linux,!windows - -package meminfo - -import "errors" - -// readMemInfo is not supported on platforms other than linux and windows. -func readMemInfo() (*Memory, error) { - return nil, errors.New("platform and architecture is not supported") -} diff --git a/vendor/github.com/docker/docker/pkg/meminfo/meminfo_windows.go b/vendor/github.com/docker/docker/pkg/meminfo/meminfo_windows.go deleted file mode 100644 index aa7d9375b..000000000 --- a/vendor/github.com/docker/docker/pkg/meminfo/meminfo_windows.go +++ /dev/null @@ -1,45 +0,0 @@ -package meminfo - -import ( - "unsafe" - - "golang.org/x/sys/windows" -) - -var ( - modkernel32 = windows.NewLazySystemDLL("kernel32.dll") - - procGlobalMemoryStatusEx = modkernel32.NewProc("GlobalMemoryStatusEx") -) - -// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366589(v=vs.85).aspx -// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366770(v=vs.85).aspx -type memorystatusex struct { - dwLength uint32 - dwMemoryLoad uint32 - ullTotalPhys uint64 - ullAvailPhys uint64 - ullTotalPageFile uint64 - ullAvailPageFile uint64 - ullTotalVirtual uint64 - ullAvailVirtual uint64 - ullAvailExtendedVirtual uint64 -} - -// readMemInfo retrieves memory statistics of the host system and returns a -// Memory type. -func readMemInfo() (*Memory, error) { - msi := &memorystatusex{ - dwLength: 64, - } - r1, _, _ := procGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(msi))) - if r1 == 0 { - return &Memory{}, nil - } - return &Memory{ - MemTotal: int64(msi.ullTotalPhys), - MemFree: int64(msi.ullAvailPhys), - SwapTotal: int64(msi.ullTotalPageFile), - SwapFree: int64(msi.ullAvailPageFile), - }, nil -} diff --git a/vendor/github.com/docker/docker/pkg/namesgenerator/names-generator.go b/vendor/github.com/docker/docker/pkg/namesgenerator/names-generator.go deleted file mode 100644 index 7fdf5015c..000000000 --- a/vendor/github.com/docker/docker/pkg/namesgenerator/names-generator.go +++ /dev/null @@ -1,860 +0,0 @@ -// Package namesgenerator generates random names. -// -// This package is officially "frozen" - no new additions will be accepted. -// -// For a long time, this package provided a lot of joy within the project, but -// at some point the conflicts of opinion became greater than the added joy. -// -// At some future time, this may be replaced with something that sparks less -// controversy, but for now it will remain as-is. -// -// See also https://github.com/moby/moby/pull/43210#issuecomment-1029934277 -package namesgenerator // import "github.com/docker/docker/pkg/namesgenerator" - -import ( - "math/rand" - "strconv" -) - -var ( - left = [...]string{ - "admiring", - "adoring", - "affectionate", - "agitated", - "amazing", - "angry", - "awesome", - "beautiful", - "blissful", - "bold", - "boring", - "brave", - "busy", - "charming", - "clever", - "compassionate", - "competent", - "condescending", - "confident", - "cool", - "cranky", - "crazy", - "dazzling", - "determined", - "distracted", - "dreamy", - "eager", - "ecstatic", - "elastic", - "elated", - "elegant", - "eloquent", - "epic", - "exciting", - "fervent", - "festive", - "flamboyant", - "focused", - "friendly", - "frosty", - "funny", - "gallant", - "gifted", - "goofy", - "gracious", - "great", - "happy", - "hardcore", - "heuristic", - "hopeful", - "hungry", - "infallible", - "inspiring", - "intelligent", - "interesting", - "jolly", - "jovial", - "keen", - "kind", - "laughing", - "loving", - "lucid", - "magical", - "modest", - "musing", - "mystifying", - "naughty", - "nervous", - "nice", - "nifty", - "nostalgic", - "objective", - "optimistic", - "peaceful", - "pedantic", - "pensive", - "practical", - "priceless", - "quirky", - "quizzical", - "recursing", - "relaxed", - "reverent", - "romantic", - "sad", - "serene", - "sharp", - "silly", - "sleepy", - "stoic", - "strange", - "stupefied", - "suspicious", - "sweet", - "tender", - "thirsty", - "trusting", - "unruffled", - "upbeat", - "vibrant", - "vigilant", - "vigorous", - "wizardly", - "wonderful", - "xenodochial", - "youthful", - "zealous", - "zen", - } - - // Docker, starting from 0.7.x, generates names from notable scientists and hackers. - // Please, for any amazing man that you add to the list, consider adding an equally amazing woman to it, and vice versa. - right = [...]string{ - // Maria Gaetana Agnesi - Italian mathematician, philosopher, theologian and humanitarian. She was the first woman to write a mathematics handbook and the first woman appointed as a Mathematics Professor at a University. https://en.wikipedia.org/wiki/Maria_Gaetana_Agnesi - "agnesi", - - // Muhammad ibn Jābir al-Ḥarrānī al-Battānī was a founding father of astronomy. https://en.wikipedia.org/wiki/Mu%E1%B8%A5ammad_ibn_J%C4%81bir_al-%E1%B8%A4arr%C4%81n%C4%AB_al-Batt%C4%81n%C4%AB - "albattani", - - // Frances E. Allen, became the first female IBM Fellow in 1989. In 2006, she became the first female recipient of the ACM's Turing Award. https://en.wikipedia.org/wiki/Frances_E._Allen - "allen", - - // June Almeida - Scottish virologist who took the first pictures of the rubella virus - https://en.wikipedia.org/wiki/June_Almeida - "almeida", - - // Kathleen Antonelli, American computer programmer and one of the six original programmers of the ENIAC - https://en.wikipedia.org/wiki/Kathleen_Antonelli - "antonelli", - - // Archimedes was a physicist, engineer and mathematician who invented too many things to list them here. https://en.wikipedia.org/wiki/Archimedes - "archimedes", - - // Maria Ardinghelli - Italian translator, mathematician and physicist - https://en.wikipedia.org/wiki/Maria_Ardinghelli - "ardinghelli", - - // Aryabhata - Ancient Indian mathematician-astronomer during 476-550 CE https://en.wikipedia.org/wiki/Aryabhata - "aryabhata", - - // Wanda Austin - Wanda Austin is the President and CEO of The Aerospace Corporation, a leading architect for the US security space programs. https://en.wikipedia.org/wiki/Wanda_Austin - "austin", - - // Charles Babbage invented the concept of a programmable computer. https://en.wikipedia.org/wiki/Charles_Babbage. - "babbage", - - // Stefan Banach - Polish mathematician, was one of the founders of modern functional analysis. https://en.wikipedia.org/wiki/Stefan_Banach - "banach", - - // Buckaroo Banzai and his mentor Dr. Hikita perfected the "oscillation overthruster", a device that allows one to pass through solid matter. - https://en.wikipedia.org/wiki/The_Adventures_of_Buckaroo_Banzai_Across_the_8th_Dimension - "banzai", - - // John Bardeen co-invented the transistor - https://en.wikipedia.org/wiki/John_Bardeen - "bardeen", - - // Jean Bartik, born Betty Jean Jennings, was one of the original programmers for the ENIAC computer. https://en.wikipedia.org/wiki/Jean_Bartik - "bartik", - - // Laura Bassi, the world's first female professor https://en.wikipedia.org/wiki/Laura_Bassi - "bassi", - - // Hugh Beaver, British engineer, founder of the Guinness Book of World Records https://en.wikipedia.org/wiki/Hugh_Beaver - "beaver", - - // Alexander Graham Bell - an eminent Scottish-born scientist, inventor, engineer and innovator who is credited with inventing the first practical telephone - https://en.wikipedia.org/wiki/Alexander_Graham_Bell - "bell", - - // Karl Friedrich Benz - a German automobile engineer. Inventor of the first practical motorcar. https://en.wikipedia.org/wiki/Karl_Benz - "benz", - - // Homi J Bhabha - was an Indian nuclear physicist, founding director, and professor of physics at the Tata Institute of Fundamental Research. Colloquially known as "father of Indian nuclear programme"- https://en.wikipedia.org/wiki/Homi_J._Bhabha - "bhabha", - - // Bhaskara II - Ancient Indian mathematician-astronomer whose work on calculus predates Newton and Leibniz by over half a millennium - https://en.wikipedia.org/wiki/Bh%C4%81skara_II#Calculus - "bhaskara", - - // Sue Black - British computer scientist and campaigner. She has been instrumental in saving Bletchley Park, the site of World War II codebreaking - https://en.wikipedia.org/wiki/Sue_Black_(computer_scientist) - "black", - - // Elizabeth Helen Blackburn - Australian-American Nobel laureate; best known for co-discovering telomerase. https://en.wikipedia.org/wiki/Elizabeth_Blackburn - "blackburn", - - // Elizabeth Blackwell - American doctor and first American woman to receive a medical degree - https://en.wikipedia.org/wiki/Elizabeth_Blackwell - "blackwell", - - // Niels Bohr is the father of quantum theory. https://en.wikipedia.org/wiki/Niels_Bohr. - "bohr", - - // Kathleen Booth, she's credited with writing the first assembly language. https://en.wikipedia.org/wiki/Kathleen_Booth - "booth", - - // Anita Borg - Anita Borg was the founding director of the Institute for Women and Technology (IWT). https://en.wikipedia.org/wiki/Anita_Borg - "borg", - - // Satyendra Nath Bose - He provided the foundation for Bose–Einstein statistics and the theory of the Bose–Einstein condensate. - https://en.wikipedia.org/wiki/Satyendra_Nath_Bose - "bose", - - // Katherine Louise Bouman is an imaging scientist and Assistant Professor of Computer Science at the California Institute of Technology. She researches computational methods for imaging, and developed an algorithm that made possible the picture first visualization of a black hole using the Event Horizon Telescope. - https://en.wikipedia.org/wiki/Katie_Bouman - "bouman", - - // Evelyn Boyd Granville - She was one of the first African-American woman to receive a Ph.D. in mathematics; she earned it in 1949 from Yale University. https://en.wikipedia.org/wiki/Evelyn_Boyd_Granville - "boyd", - - // Brahmagupta - Ancient Indian mathematician during 598-670 CE who gave rules to compute with zero - https://en.wikipedia.org/wiki/Brahmagupta#Zero - "brahmagupta", - - // Walter Houser Brattain co-invented the transistor - https://en.wikipedia.org/wiki/Walter_Houser_Brattain - "brattain", - - // Emmett Brown invented time travel. https://en.wikipedia.org/wiki/Emmett_Brown (thanks Brian Goff) - "brown", - - // Linda Brown Buck - American biologist and Nobel laureate best known for her genetic and molecular analyses of the mechanisms of smell. https://en.wikipedia.org/wiki/Linda_B._Buck - "buck", - - // Dame Susan Jocelyn Bell Burnell - Northern Irish astrophysicist who discovered radio pulsars and was the first to analyse them. https://en.wikipedia.org/wiki/Jocelyn_Bell_Burnell - "burnell", - - // Annie Jump Cannon - pioneering female astronomer who classified hundreds of thousands of stars and created the system we use to understand stars today. https://en.wikipedia.org/wiki/Annie_Jump_Cannon - "cannon", - - // Rachel Carson - American marine biologist and conservationist, her book Silent Spring and other writings are credited with advancing the global environmental movement. https://en.wikipedia.org/wiki/Rachel_Carson - "carson", - - // Dame Mary Lucy Cartwright - British mathematician who was one of the first to study what is now known as chaos theory. Also known for Cartwright's theorem which finds applications in signal processing. https://en.wikipedia.org/wiki/Mary_Cartwright - "cartwright", - - // George Washington Carver - American agricultural scientist and inventor. He was the most prominent black scientist of the early 20th century. https://en.wikipedia.org/wiki/George_Washington_Carver - "carver", - - // Vinton Gray Cerf - American Internet pioneer, recognised as one of "the fathers of the Internet". With Robert Elliot Kahn, he designed TCP and IP, the primary data communication protocols of the Internet and other computer networks. https://en.wikipedia.org/wiki/Vint_Cerf - "cerf", - - // Subrahmanyan Chandrasekhar - Astrophysicist known for his mathematical theory on different stages and evolution in structures of the stars. He has won nobel prize for physics - https://en.wikipedia.org/wiki/Subrahmanyan_Chandrasekhar - "chandrasekhar", - - // Sergey Alexeyevich Chaplygin (Russian: Серге́й Алексе́евич Чаплы́гин; April 5, 1869 – October 8, 1942) was a Russian and Soviet physicist, mathematician, and mechanical engineer. He is known for mathematical formulas such as Chaplygin's equation and for a hypothetical substance in cosmology called Chaplygin gas, named after him. https://en.wikipedia.org/wiki/Sergey_Chaplygin - "chaplygin", - - // Émilie du Châtelet - French natural philosopher, mathematician, physicist, and author during the early 1730s, known for her translation of and commentary on Isaac Newton's book Principia containing basic laws of physics. https://en.wikipedia.org/wiki/%C3%89milie_du_Ch%C3%A2telet - "chatelet", - - // Asima Chatterjee was an Indian organic chemist noted for her research on vinca alkaloids, development of drugs for treatment of epilepsy and malaria - https://en.wikipedia.org/wiki/Asima_Chatterjee - "chatterjee", - - // David Lee Chaum - American computer scientist and cryptographer. Known for his seminal contributions in the field of anonymous communication. https://en.wikipedia.org/wiki/David_Chaum - "chaum", - - // Pafnuty Chebyshev - Russian mathematician. He is known fo his works on probability, statistics, mechanics, analytical geometry and number theory https://en.wikipedia.org/wiki/Pafnuty_Chebyshev - "chebyshev", - - // Joan Clarke - Bletchley Park code breaker during the Second World War who pioneered techniques that remained top secret for decades. Also an accomplished numismatist https://en.wikipedia.org/wiki/Joan_Clarke - "clarke", - - // Bram Cohen - American computer programmer and author of the BitTorrent peer-to-peer protocol. https://en.wikipedia.org/wiki/Bram_Cohen - "cohen", - - // Jane Colden - American botanist widely considered the first female American botanist - https://en.wikipedia.org/wiki/Jane_Colden - "colden", - - // Gerty Theresa Cori - American biochemist who became the third woman—and first American woman—to win a Nobel Prize in science, and the first woman to be awarded the Nobel Prize in Physiology or Medicine. Cori was born in Prague. https://en.wikipedia.org/wiki/Gerty_Cori - "cori", - - // Seymour Roger Cray was an American electrical engineer and supercomputer architect who designed a series of computers that were the fastest in the world for decades. https://en.wikipedia.org/wiki/Seymour_Cray - "cray", - - // Marie Curie discovered radioactivity. https://en.wikipedia.org/wiki/Marie_Curie. - "curie", - - // This entry reflects a husband and wife team who worked together: - // Joan Curran was a Welsh scientist who developed radar and invented chaff, a radar countermeasure. https://en.wikipedia.org/wiki/Joan_Curran - // Samuel Curran was an Irish physicist who worked alongside his wife during WWII and invented the proximity fuse. https://en.wikipedia.org/wiki/Samuel_Curran - "curran", - - // Charles Darwin established the principles of natural evolution. https://en.wikipedia.org/wiki/Charles_Darwin. - "darwin", - - // Leonardo Da Vinci invented too many things to list here. https://en.wikipedia.org/wiki/Leonardo_da_Vinci. - "davinci", - - // A. K. (Alexander Keewatin) Dewdney, Canadian mathematician, computer scientist, author and filmmaker. Contributor to Scientific American's "Computer Recreations" from 1984 to 1991. Author of Core War (program), The Planiverse, The Armchair Universe, The Magic Machine, The New Turing Omnibus, and more. https://en.wikipedia.org/wiki/Alexander_Dewdney - "dewdney", - - // Satish Dhawan - Indian mathematician and aerospace engineer, known for leading the successful and indigenous development of the Indian space programme. https://en.wikipedia.org/wiki/Satish_Dhawan - "dhawan", - - // Bailey Whitfield Diffie - American cryptographer and one of the pioneers of public-key cryptography. https://en.wikipedia.org/wiki/Whitfield_Diffie - "diffie", - - // Edsger Wybe Dijkstra was a Dutch computer scientist and mathematical scientist. https://en.wikipedia.org/wiki/Edsger_W._Dijkstra. - "dijkstra", - - // Paul Adrien Maurice Dirac - English theoretical physicist who made fundamental contributions to the early development of both quantum mechanics and quantum electrodynamics. https://en.wikipedia.org/wiki/Paul_Dirac - "dirac", - - // Agnes Meyer Driscoll - American cryptanalyst during World Wars I and II who successfully cryptanalysed a number of Japanese ciphers. She was also the co-developer of one of the cipher machines of the US Navy, the CM. https://en.wikipedia.org/wiki/Agnes_Meyer_Driscoll - "driscoll", - - // Donna Dubinsky - played an integral role in the development of personal digital assistants (PDAs) serving as CEO of Palm, Inc. and co-founding Handspring. https://en.wikipedia.org/wiki/Donna_Dubinsky - "dubinsky", - - // Annie Easley - She was a leading member of the team which developed software for the Centaur rocket stage and one of the first African-Americans in her field. https://en.wikipedia.org/wiki/Annie_Easley - "easley", - - // Thomas Alva Edison, prolific inventor https://en.wikipedia.org/wiki/Thomas_Edison - "edison", - - // Albert Einstein invented the general theory of relativity. https://en.wikipedia.org/wiki/Albert_Einstein - "einstein", - - // Alexandra Asanovna Elbakyan (Russian: Алекса́ндра Аса́новна Элбакя́н) is a Kazakhstani graduate student, computer programmer, internet pirate in hiding, and the creator of the site Sci-Hub. Nature has listed her in 2016 in the top ten people that mattered in science, and Ars Technica has compared her to Aaron Swartz. - https://en.wikipedia.org/wiki/Alexandra_Elbakyan - "elbakyan", - - // Taher A. ElGamal - Egyptian cryptographer best known for the ElGamal discrete log cryptosystem and the ElGamal digital signature scheme. https://en.wikipedia.org/wiki/Taher_Elgamal - "elgamal", - - // Gertrude Elion - American biochemist, pharmacologist and the 1988 recipient of the Nobel Prize in Medicine - https://en.wikipedia.org/wiki/Gertrude_Elion - "elion", - - // James Henry Ellis - British engineer and cryptographer employed by the GCHQ. Best known for conceiving for the first time, the idea of public-key cryptography. https://en.wikipedia.org/wiki/James_H._Ellis - "ellis", - - // Douglas Engelbart gave the mother of all demos: https://en.wikipedia.org/wiki/Douglas_Engelbart - "engelbart", - - // Euclid invented geometry. https://en.wikipedia.org/wiki/Euclid - "euclid", - - // Leonhard Euler invented large parts of modern mathematics. https://de.wikipedia.org/wiki/Leonhard_Euler - "euler", - - // Michael Faraday - British scientist who contributed to the study of electromagnetism and electrochemistry. https://en.wikipedia.org/wiki/Michael_Faraday - "faraday", - - // Horst Feistel - German-born American cryptographer who was one of the earliest non-government researchers to study the design and theory of block ciphers. Co-developer of DES and Lucifer. Feistel networks, a symmetric structure used in the construction of block ciphers are named after him. https://en.wikipedia.org/wiki/Horst_Feistel - "feistel", - - // Pierre de Fermat pioneered several aspects of modern mathematics. https://en.wikipedia.org/wiki/Pierre_de_Fermat - "fermat", - - // Enrico Fermi invented the first nuclear reactor. https://en.wikipedia.org/wiki/Enrico_Fermi. - "fermi", - - // Richard Feynman was a key contributor to quantum mechanics and particle physics. https://en.wikipedia.org/wiki/Richard_Feynman - "feynman", - - // Benjamin Franklin is famous for his experiments in electricity and the invention of the lightning rod. - "franklin", - - // Yuri Alekseyevich Gagarin - Soviet pilot and cosmonaut, best known as the first human to journey into outer space. https://en.wikipedia.org/wiki/Yuri_Gagarin - "gagarin", - - // Galileo was a founding father of modern astronomy, and faced politics and obscurantism to establish scientific truth. https://en.wikipedia.org/wiki/Galileo_Galilei - "galileo", - - // Évariste Galois - French mathematician whose work laid the foundations of Galois theory and group theory, two major branches of abstract algebra, and the subfield of Galois connections, all while still in his late teens. https://en.wikipedia.org/wiki/%C3%89variste_Galois - "galois", - - // Kadambini Ganguly - Indian physician, known for being the first South Asian female physician, trained in western medicine, to graduate in South Asia. https://en.wikipedia.org/wiki/Kadambini_Ganguly - "ganguly", - - // William Henry "Bill" Gates III is an American business magnate, philanthropist, investor, computer programmer, and inventor. https://en.wikipedia.org/wiki/Bill_Gates - "gates", - - // Johann Carl Friedrich Gauss - German mathematician who made significant contributions to many fields, including number theory, algebra, statistics, analysis, differential geometry, geodesy, geophysics, mechanics, electrostatics, magnetic fields, astronomy, matrix theory, and optics. https://en.wikipedia.org/wiki/Carl_Friedrich_Gauss - "gauss", - - // Marie-Sophie Germain - French mathematician, physicist and philosopher. Known for her work on elasticity theory, number theory and philosophy. https://en.wikipedia.org/wiki/Sophie_Germain - "germain", - - // Adele Goldberg, was one of the designers and developers of the Smalltalk language. https://en.wikipedia.org/wiki/Adele_Goldberg_(computer_scientist) - "goldberg", - - // Adele Goldstine, born Adele Katz, wrote the complete technical description for the first electronic digital computer, ENIAC. https://en.wikipedia.org/wiki/Adele_Goldstine - "goldstine", - - // Shafi Goldwasser is a computer scientist known for creating theoretical foundations of modern cryptography. Winner of 2012 ACM Turing Award. https://en.wikipedia.org/wiki/Shafi_Goldwasser - "goldwasser", - - // James Golick, all around gangster. - "golick", - - // Jane Goodall - British primatologist, ethologist, and anthropologist who is considered to be the world's foremost expert on chimpanzees - https://en.wikipedia.org/wiki/Jane_Goodall - "goodall", - - // Stephen Jay Gould was was an American paleontologist, evolutionary biologist, and historian of science. He is most famous for the theory of punctuated equilibrium - https://en.wikipedia.org/wiki/Stephen_Jay_Gould - "gould", - - // Carolyn Widney Greider - American molecular biologist and joint winner of the 2009 Nobel Prize for Physiology or Medicine for the discovery of telomerase. https://en.wikipedia.org/wiki/Carol_W._Greider - "greider", - - // Alexander Grothendieck - German-born French mathematician who became a leading figure in the creation of modern algebraic geometry. https://en.wikipedia.org/wiki/Alexander_Grothendieck - "grothendieck", - - // Lois Haibt - American computer scientist, part of the team at IBM that developed FORTRAN - https://en.wikipedia.org/wiki/Lois_Haibt - "haibt", - - // Margaret Hamilton - Director of the Software Engineering Division of the MIT Instrumentation Laboratory, which developed on-board flight software for the Apollo space program. https://en.wikipedia.org/wiki/Margaret_Hamilton_(scientist) - "hamilton", - - // Caroline Harriet Haslett - English electrical engineer, electricity industry administrator and champion of women's rights. Co-author of British Standard 1363 that specifies AC power plugs and sockets used across the United Kingdom (which is widely considered as one of the safest designs). https://en.wikipedia.org/wiki/Caroline_Haslett - "haslett", - - // Stephen Hawking pioneered the field of cosmology by combining general relativity and quantum mechanics. https://en.wikipedia.org/wiki/Stephen_Hawking - "hawking", - - // Werner Heisenberg was a founding father of quantum mechanics. https://en.wikipedia.org/wiki/Werner_Heisenberg - "heisenberg", - - // Martin Edward Hellman - American cryptologist, best known for his invention of public-key cryptography in co-operation with Whitfield Diffie and Ralph Merkle. https://en.wikipedia.org/wiki/Martin_Hellman - "hellman", - - // Grete Hermann was a German philosopher noted for her philosophical work on the foundations of quantum mechanics. https://en.wikipedia.org/wiki/Grete_Hermann - "hermann", - - // Caroline Lucretia Herschel - German astronomer and discoverer of several comets. https://en.wikipedia.org/wiki/Caroline_Herschel - "herschel", - - // Heinrich Rudolf Hertz - German physicist who first conclusively proved the existence of the electromagnetic waves. https://en.wikipedia.org/wiki/Heinrich_Hertz - "hertz", - - // Jaroslav Heyrovský was the inventor of the polarographic method, father of the electroanalytical method, and recipient of the Nobel Prize in 1959. His main field of work was polarography. https://en.wikipedia.org/wiki/Jaroslav_Heyrovsk%C3%BD - "heyrovsky", - - // Dorothy Hodgkin was a British biochemist, credited with the development of protein crystallography. She was awarded the Nobel Prize in Chemistry in 1964. https://en.wikipedia.org/wiki/Dorothy_Hodgkin - "hodgkin", - - // Douglas R. Hofstadter is an American professor of cognitive science and author of the Pulitzer Prize and American Book Award-winning work Goedel, Escher, Bach: An Eternal Golden Braid in 1979. A mind-bending work which coined Hofstadter's Law: "It always takes longer than you expect, even when you take into account Hofstadter's Law." https://en.wikipedia.org/wiki/Douglas_Hofstadter - "hofstadter", - - // Erna Schneider Hoover revolutionized modern communication by inventing a computerized telephone switching method. https://en.wikipedia.org/wiki/Erna_Schneider_Hoover - "hoover", - - // Grace Hopper developed the first compiler for a computer programming language and is credited with popularizing the term "debugging" for fixing computer glitches. https://en.wikipedia.org/wiki/Grace_Hopper - "hopper", - - // Frances Hugle, she was an American scientist, engineer, and inventor who contributed to the understanding of semiconductors, integrated circuitry, and the unique electrical principles of microscopic materials. https://en.wikipedia.org/wiki/Frances_Hugle - "hugle", - - // Hypatia - Greek Alexandrine Neoplatonist philosopher in Egypt who was one of the earliest mothers of mathematics - https://en.wikipedia.org/wiki/Hypatia - "hypatia", - - // Teruko Ishizaka - Japanese scientist and immunologist who co-discovered the antibody class Immunoglobulin E. https://en.wikipedia.org/wiki/Teruko_Ishizaka - "ishizaka", - - // Mary Jackson, American mathematician and aerospace engineer who earned the highest title within NASA's engineering department - https://en.wikipedia.org/wiki/Mary_Jackson_(engineer) - "jackson", - - // Yeong-Sil Jang was a Korean scientist and astronomer during the Joseon Dynasty; he invented the first metal printing press and water gauge. https://en.wikipedia.org/wiki/Jang_Yeong-sil - "jang", - - // Mae Carol Jemison - is an American engineer, physician, and former NASA astronaut. She became the first black woman to travel in space when she served as a mission specialist aboard the Space Shuttle Endeavour - https://en.wikipedia.org/wiki/Mae_Jemison - "jemison", - - // Betty Jennings - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Jean_Bartik - "jennings", - - // Mary Lou Jepsen, was the founder and chief technology officer of One Laptop Per Child (OLPC), and the founder of Pixel Qi. https://en.wikipedia.org/wiki/Mary_Lou_Jepsen - "jepsen", - - // Katherine Coleman Goble Johnson - American physicist and mathematician contributed to the NASA. https://en.wikipedia.org/wiki/Katherine_Johnson - "johnson", - - // Irène Joliot-Curie - French scientist who was awarded the Nobel Prize for Chemistry in 1935. Daughter of Marie and Pierre Curie. https://en.wikipedia.org/wiki/Ir%C3%A8ne_Joliot-Curie - "joliot", - - // Karen Spärck Jones came up with the concept of inverse document frequency, which is used in most search engines today. https://en.wikipedia.org/wiki/Karen_Sp%C3%A4rck_Jones - "jones", - - // A. P. J. Abdul Kalam - is an Indian scientist aka Missile Man of India for his work on the development of ballistic missile and launch vehicle technology - https://en.wikipedia.org/wiki/A._P._J._Abdul_Kalam - "kalam", - - // Sergey Petrovich Kapitsa (Russian: Серге́й Петро́вич Капи́ца; 14 February 1928 – 14 August 2012) was a Russian physicist and demographer. He was best known as host of the popular and long-running Russian scientific TV show, Evident, but Incredible. His father was the Nobel laureate Soviet-era physicist Pyotr Kapitsa, and his brother was the geographer and Antarctic explorer Andrey Kapitsa. - https://en.wikipedia.org/wiki/Sergey_Kapitsa - "kapitsa", - - // Susan Kare, created the icons and many of the interface elements for the original Apple Macintosh in the 1980s, and was an original employee of NeXT, working as the Creative Director. https://en.wikipedia.org/wiki/Susan_Kare - "kare", - - // Mstislav Keldysh - a Soviet scientist in the field of mathematics and mechanics, academician of the USSR Academy of Sciences (1946), President of the USSR Academy of Sciences (1961–1975), three times Hero of Socialist Labor (1956, 1961, 1971), fellow of the Royal Society of Edinburgh (1968). https://en.wikipedia.org/wiki/Mstislav_Keldysh - "keldysh", - - // Mary Kenneth Keller, Sister Mary Kenneth Keller became the first American woman to earn a PhD in Computer Science in 1965. https://en.wikipedia.org/wiki/Mary_Kenneth_Keller - "keller", - - // Johannes Kepler, German astronomer known for his three laws of planetary motion - https://en.wikipedia.org/wiki/Johannes_Kepler - "kepler", - - // Omar Khayyam - Persian mathematician, astronomer and poet. Known for his work on the classification and solution of cubic equations, for his contribution to the understanding of Euclid's fifth postulate and for computing the length of a year very accurately. https://en.wikipedia.org/wiki/Omar_Khayyam - "khayyam", - - // Har Gobind Khorana - Indian-American biochemist who shared the 1968 Nobel Prize for Physiology - https://en.wikipedia.org/wiki/Har_Gobind_Khorana - "khorana", - - // Jack Kilby invented silicon integrated circuits and gave Silicon Valley its name. - https://en.wikipedia.org/wiki/Jack_Kilby - "kilby", - - // Maria Kirch - German astronomer and first woman to discover a comet - https://en.wikipedia.org/wiki/Maria_Margarethe_Kirch - "kirch", - - // Donald Knuth - American computer scientist, author of "The Art of Computer Programming" and creator of the TeX typesetting system. https://en.wikipedia.org/wiki/Donald_Knuth - "knuth", - - // Sophie Kowalevski - Russian mathematician responsible for important original contributions to analysis, differential equations and mechanics - https://en.wikipedia.org/wiki/Sofia_Kovalevskaya - "kowalevski", - - // Marie-Jeanne de Lalande - French astronomer, mathematician and cataloguer of stars - https://en.wikipedia.org/wiki/Marie-Jeanne_de_Lalande - "lalande", - - // Hedy Lamarr - Actress and inventor. The principles of her work are now incorporated into modern Wi-Fi, CDMA and Bluetooth technology. https://en.wikipedia.org/wiki/Hedy_Lamarr - "lamarr", - - // Leslie B. Lamport - American computer scientist. Lamport is best known for his seminal work in distributed systems and was the winner of the 2013 Turing Award. https://en.wikipedia.org/wiki/Leslie_Lamport - "lamport", - - // Mary Leakey - British paleoanthropologist who discovered the first fossilized Proconsul skull - https://en.wikipedia.org/wiki/Mary_Leakey - "leakey", - - // Henrietta Swan Leavitt - she was an American astronomer who discovered the relation between the luminosity and the period of Cepheid variable stars. https://en.wikipedia.org/wiki/Henrietta_Swan_Leavitt - "leavitt", - - // Esther Miriam Zimmer Lederberg - American microbiologist and a pioneer of bacterial genetics. https://en.wikipedia.org/wiki/Esther_Lederberg - "lederberg", - - // Inge Lehmann - Danish seismologist and geophysicist. Known for discovering in 1936 that the Earth has a solid inner core inside a molten outer core. https://en.wikipedia.org/wiki/Inge_Lehmann - "lehmann", - - // Daniel Lewin - Mathematician, Akamai co-founder, soldier, 9/11 victim-- Developed optimization techniques for routing traffic on the internet. Died attempting to stop the 9-11 hijackers. https://en.wikipedia.org/wiki/Daniel_Lewin - "lewin", - - // Ruth Lichterman - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Ruth_Teitelbaum - "lichterman", - - // Barbara Liskov - co-developed the Liskov substitution principle. Liskov was also the winner of the Turing Prize in 2008. - https://en.wikipedia.org/wiki/Barbara_Liskov - "liskov", - - // Ada Lovelace invented the first algorithm. https://en.wikipedia.org/wiki/Ada_Lovelace (thanks James Turnbull) - "lovelace", - - // Auguste and Louis Lumière - the first filmmakers in history - https://en.wikipedia.org/wiki/Auguste_and_Louis_Lumi%C3%A8re - "lumiere", - - // Mahavira - Ancient Indian mathematician during 9th century AD who discovered basic algebraic identities - https://en.wikipedia.org/wiki/Mah%C4%81v%C4%ABra_(mathematician) - "mahavira", - - // Lynn Margulis (b. Lynn Petra Alexander) - an American evolutionary theorist and biologist, science author, educator, and popularizer, and was the primary modern proponent for the significance of symbiosis in evolution. - https://en.wikipedia.org/wiki/Lynn_Margulis - "margulis", - - // Yukihiro Matsumoto - Japanese computer scientist and software programmer best known as the chief designer of the Ruby programming language. https://en.wikipedia.org/wiki/Yukihiro_Matsumoto - "matsumoto", - - // James Clerk Maxwell - Scottish physicist, best known for his formulation of electromagnetic theory. https://en.wikipedia.org/wiki/James_Clerk_Maxwell - "maxwell", - - // Maria Mayer - American theoretical physicist and Nobel laureate in Physics for proposing the nuclear shell model of the atomic nucleus - https://en.wikipedia.org/wiki/Maria_Mayer - "mayer", - - // John McCarthy invented LISP: https://en.wikipedia.org/wiki/John_McCarthy_(computer_scientist) - "mccarthy", - - // Barbara McClintock - a distinguished American cytogeneticist, 1983 Nobel Laureate in Physiology or Medicine for discovering transposons. https://en.wikipedia.org/wiki/Barbara_McClintock - "mcclintock", - - // Anne Laura Dorinthea McLaren - British developmental biologist whose work helped lead to human in-vitro fertilisation. https://en.wikipedia.org/wiki/Anne_McLaren - "mclaren", - - // Malcolm McLean invented the modern shipping container: https://en.wikipedia.org/wiki/Malcom_McLean - "mclean", - - // Kay McNulty - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Kathleen_Antonelli - "mcnulty", - - // Lise Meitner - Austrian/Swedish physicist who was involved in the discovery of nuclear fission. The element meitnerium is named after her - https://en.wikipedia.org/wiki/Lise_Meitner - "meitner", - - // Gregor Johann Mendel - Czech scientist and founder of genetics. https://en.wikipedia.org/wiki/Gregor_Mendel - "mendel", - - // Dmitri Mendeleev - a chemist and inventor. He formulated the Periodic Law, created a farsighted version of the periodic table of elements, and used it to correct the properties of some already discovered elements and also to predict the properties of eight elements yet to be discovered. https://en.wikipedia.org/wiki/Dmitri_Mendeleev - "mendeleev", - - // Carla Meninsky, was the game designer and programmer for Atari 2600 games Dodge 'Em and Warlords. https://en.wikipedia.org/wiki/Carla_Meninsky - "meninsky", - - // Ralph C. Merkle - American computer scientist, known for devising Merkle's puzzles - one of the very first schemes for public-key cryptography. Also, inventor of Merkle trees and co-inventor of the Merkle-Damgård construction for building collision-resistant cryptographic hash functions and the Merkle-Hellman knapsack cryptosystem. https://en.wikipedia.org/wiki/Ralph_Merkle - "merkle", - - // Johanna Mestorf - German prehistoric archaeologist and first female museum director in Germany - https://en.wikipedia.org/wiki/Johanna_Mestorf - "mestorf", - - // Maryam Mirzakhani - an Iranian mathematician and the first woman to win the Fields Medal. https://en.wikipedia.org/wiki/Maryam_Mirzakhani - "mirzakhani", - - // Rita Levi-Montalcini - Won Nobel Prize in Physiology or Medicine jointly with colleague Stanley Cohen for the discovery of nerve growth factor (https://en.wikipedia.org/wiki/Rita_Levi-Montalcini) - "montalcini", - - // Gordon Earle Moore - American engineer, Silicon Valley founding father, author of Moore's law. https://en.wikipedia.org/wiki/Gordon_Moore - "moore", - - // Samuel Morse - contributed to the invention of a single-wire telegraph system based on European telegraphs and was a co-developer of the Morse code - https://en.wikipedia.org/wiki/Samuel_Morse - "morse", - - // May-Britt Moser - Nobel prize winner neuroscientist who contributed to the discovery of grid cells in the brain. https://en.wikipedia.org/wiki/May-Britt_Moser - "moser", - - // Ian Murdock - founder of the Debian project - https://en.wikipedia.org/wiki/Ian_Murdock - "murdock", - - // John Napier of Merchiston - Scottish landowner known as an astronomer, mathematician and physicist. Best known for his discovery of logarithms. https://en.wikipedia.org/wiki/John_Napier - "napier", - - // John Forbes Nash, Jr. - American mathematician who made fundamental contributions to game theory, differential geometry, and the study of partial differential equations. https://en.wikipedia.org/wiki/John_Forbes_Nash_Jr. - "nash", - - // John von Neumann - todays computer architectures are based on the von Neumann architecture. https://en.wikipedia.org/wiki/Von_Neumann_architecture - "neumann", - - // Isaac Newton invented classic mechanics and modern optics. https://en.wikipedia.org/wiki/Isaac_Newton - "newton", - - // Florence Nightingale, more prominently known as a nurse, was also the first female member of the Royal Statistical Society and a pioneer in statistical graphics https://en.wikipedia.org/wiki/Florence_Nightingale#Statistics_and_sanitary_reform - "nightingale", - - // Alfred Nobel - a Swedish chemist, engineer, innovator, and armaments manufacturer (inventor of dynamite) - https://en.wikipedia.org/wiki/Alfred_Nobel - "nobel", - - // Emmy Noether, German mathematician. Noether's Theorem is named after her. https://en.wikipedia.org/wiki/Emmy_Noether - "noether", - - // Poppy Northcutt. Poppy Northcutt was the first woman to work as part of NASA’s Mission Control. http://www.businessinsider.com/poppy-northcutt-helped-apollo-astronauts-2014-12?op=1 - "northcutt", - - // Robert Noyce invented silicon integrated circuits and gave Silicon Valley its name. - https://en.wikipedia.org/wiki/Robert_Noyce - "noyce", - - // Panini - Ancient Indian linguist and grammarian from 4th century CE who worked on the world's first formal system - https://en.wikipedia.org/wiki/P%C4%81%E1%B9%87ini#Comparison_with_modern_formal_systems - "panini", - - // Ambroise Pare invented modern surgery. https://en.wikipedia.org/wiki/Ambroise_Par%C3%A9 - "pare", - - // Blaise Pascal, French mathematician, physicist, and inventor - https://en.wikipedia.org/wiki/Blaise_Pascal - "pascal", - - // Louis Pasteur discovered vaccination, fermentation and pasteurization. https://en.wikipedia.org/wiki/Louis_Pasteur. - "pasteur", - - // Cecilia Payne-Gaposchkin was an astronomer and astrophysicist who, in 1925, proposed in her Ph.D. thesis an explanation for the composition of stars in terms of the relative abundances of hydrogen and helium. https://en.wikipedia.org/wiki/Cecilia_Payne-Gaposchkin - "payne", - - // Radia Perlman is a software designer and network engineer and most famous for her invention of the spanning-tree protocol (STP). https://en.wikipedia.org/wiki/Radia_Perlman - "perlman", - - // Rob Pike was a key contributor to Unix, Plan 9, the X graphic system, utf-8, and the Go programming language. https://en.wikipedia.org/wiki/Rob_Pike - "pike", - - // Henri Poincaré made fundamental contributions in several fields of mathematics. https://en.wikipedia.org/wiki/Henri_Poincar%C3%A9 - "poincare", - - // Laura Poitras is a director and producer whose work, made possible by open source crypto tools, advances the causes of truth and freedom of information by reporting disclosures by whistleblowers such as Edward Snowden. https://en.wikipedia.org/wiki/Laura_Poitras - "poitras", - - // Tat’yana Avenirovna Proskuriakova (Russian: Татья́на Авени́ровна Проскуряко́ва) (January 23 [O.S. January 10] 1909 – August 30, 1985) was a Russian-American Mayanist scholar and archaeologist who contributed significantly to the deciphering of Maya hieroglyphs, the writing system of the pre-Columbian Maya civilization of Mesoamerica. https://en.wikipedia.org/wiki/Tatiana_Proskouriakoff - "proskuriakova", - - // Claudius Ptolemy - a Greco-Egyptian writer of Alexandria, known as a mathematician, astronomer, geographer, astrologer, and poet of a single epigram in the Greek Anthology - https://en.wikipedia.org/wiki/Ptolemy - "ptolemy", - - // C. V. Raman - Indian physicist who won the Nobel Prize in 1930 for proposing the Raman effect. - https://en.wikipedia.org/wiki/C._V._Raman - "raman", - - // Srinivasa Ramanujan - Indian mathematician and autodidact who made extraordinary contributions to mathematical analysis, number theory, infinite series, and continued fractions. - https://en.wikipedia.org/wiki/Srinivasa_Ramanujan - "ramanujan", - - // Ida Rhodes - American pioneer in computer programming, designed the first computer used for Social Security. https://en.wikipedia.org/wiki/Ida_Rhodes - "rhodes", - - // Sally Kristen Ride was an American physicist and astronaut. She was the first American woman in space, and the youngest American astronaut. https://en.wikipedia.org/wiki/Sally_Ride - "ride", - - // Dennis Ritchie - co-creator of UNIX and the C programming language. - https://en.wikipedia.org/wiki/Dennis_Ritchie - "ritchie", - - // Julia Hall Bowman Robinson - American mathematician renowned for her contributions to the fields of computability theory and computational complexity theory. https://en.wikipedia.org/wiki/Julia_Robinson - "robinson", - - // Wilhelm Conrad Röntgen - German physicist who was awarded the first Nobel Prize in Physics in 1901 for the discovery of X-rays (Röntgen rays). https://en.wikipedia.org/wiki/Wilhelm_R%C3%B6ntgen - "roentgen", - - // Rosalind Franklin - British biophysicist and X-ray crystallographer whose research was critical to the understanding of DNA - https://en.wikipedia.org/wiki/Rosalind_Franklin - "rosalind", - - // Vera Rubin - American astronomer who pioneered work on galaxy rotation rates. https://en.wikipedia.org/wiki/Vera_Rubin - "rubin", - - // Meghnad Saha - Indian astrophysicist best known for his development of the Saha equation, used to describe chemical and physical conditions in stars - https://en.wikipedia.org/wiki/Meghnad_Saha - "saha", - - // Jean E. Sammet developed FORMAC, the first widely used computer language for symbolic manipulation of mathematical formulas. https://en.wikipedia.org/wiki/Jean_E._Sammet - "sammet", - - // Mildred Sanderson - American mathematician best known for Sanderson's theorem concerning modular invariants. https://en.wikipedia.org/wiki/Mildred_Sanderson - "sanderson", - - // Satoshi Nakamoto is the name used by the unknown person or group of people who developed bitcoin, authored the bitcoin white paper, and created and deployed bitcoin's original reference implementation. https://en.wikipedia.org/wiki/Satoshi_Nakamoto - "satoshi", - - // Adi Shamir - Israeli cryptographer whose numerous inventions and contributions to cryptography include the Ferge Fiat Shamir identification scheme, the Rivest Shamir Adleman (RSA) public-key cryptosystem, the Shamir's secret sharing scheme, the breaking of the Merkle-Hellman cryptosystem, the TWINKLE and TWIRL factoring devices and the discovery of differential cryptanalysis (with Eli Biham). https://en.wikipedia.org/wiki/Adi_Shamir - "shamir", - - // Claude Shannon - The father of information theory and founder of digital circuit design theory. (https://en.wikipedia.org/wiki/Claude_Shannon) - "shannon", - - // Carol Shaw - Originally an Atari employee, Carol Shaw is said to be the first female video game designer. https://en.wikipedia.org/wiki/Carol_Shaw_(video_game_designer) - "shaw", - - // Dame Stephanie "Steve" Shirley - Founded a software company in 1962 employing women working from home. https://en.wikipedia.org/wiki/Steve_Shirley - "shirley", - - // William Shockley co-invented the transistor - https://en.wikipedia.org/wiki/William_Shockley - "shockley", - - // Lina Solomonovna Stern (or Shtern; Russian: Лина Соломоновна Штерн; 26 August 1878 – 7 March 1968) was a Soviet biochemist, physiologist and humanist whose medical discoveries saved thousands of lives at the fronts of World War II. She is best known for her pioneering work on blood–brain barrier, which she described as hemato-encephalic barrier in 1921. https://en.wikipedia.org/wiki/Lina_Stern - "shtern", - - // Françoise Barré-Sinoussi - French virologist and Nobel Prize Laureate in Physiology or Medicine; her work was fundamental in identifying HIV as the cause of AIDS. https://en.wikipedia.org/wiki/Fran%C3%A7oise_Barr%C3%A9-Sinoussi - "sinoussi", - - // Betty Snyder - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Betty_Holberton - "snyder", - - // Cynthia Solomon - Pioneer in the fields of artificial intelligence, computer science and educational computing. Known for creation of Logo, an educational programming language. https://en.wikipedia.org/wiki/Cynthia_Solomon - "solomon", - - // Frances Spence - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Frances_Spence - "spence", - - // Michael Stonebraker is a database research pioneer and architect of Ingres, Postgres, VoltDB and SciDB. Winner of 2014 ACM Turing Award. https://en.wikipedia.org/wiki/Michael_Stonebraker - "stonebraker", - - // Ivan Edward Sutherland - American computer scientist and Internet pioneer, widely regarded as the father of computer graphics. https://en.wikipedia.org/wiki/Ivan_Sutherland - "sutherland", - - // Janese Swanson (with others) developed the first of the Carmen Sandiego games. She went on to found Girl Tech. https://en.wikipedia.org/wiki/Janese_Swanson - "swanson", - - // Aaron Swartz was influential in creating RSS, Markdown, Creative Commons, Reddit, and much of the internet as we know it today. He was devoted to freedom of information on the web. https://en.wikiquote.org/wiki/Aaron_Swartz - "swartz", - - // Bertha Swirles was a theoretical physicist who made a number of contributions to early quantum theory. https://en.wikipedia.org/wiki/Bertha_Swirles - "swirles", - - // Helen Brooke Taussig - American cardiologist and founder of the field of paediatric cardiology. https://en.wikipedia.org/wiki/Helen_B._Taussig - "taussig", - - // Nikola Tesla invented the AC electric system and every gadget ever used by a James Bond villain. https://en.wikipedia.org/wiki/Nikola_Tesla - "tesla", - - // Marie Tharp - American geologist and oceanic cartographer who co-created the first scientific map of the Atlantic Ocean floor. Her work led to the acceptance of the theories of plate tectonics and continental drift. https://en.wikipedia.org/wiki/Marie_Tharp - "tharp", - - // Ken Thompson - co-creator of UNIX and the C programming language - https://en.wikipedia.org/wiki/Ken_Thompson - "thompson", - - // Linus Torvalds invented Linux and Git. https://en.wikipedia.org/wiki/Linus_Torvalds - "torvalds", - - // Youyou Tu - Chinese pharmaceutical chemist and educator known for discovering artemisinin and dihydroartemisinin, used to treat malaria, which has saved millions of lives. Joint winner of the 2015 Nobel Prize in Physiology or Medicine. https://en.wikipedia.org/wiki/Tu_Youyou - "tu", - - // Alan Turing was a founding father of computer science. https://en.wikipedia.org/wiki/Alan_Turing. - "turing", - - // Varahamihira - Ancient Indian mathematician who discovered trigonometric formulae during 505-587 CE - https://en.wikipedia.org/wiki/Var%C4%81hamihira#Contributions - "varahamihira", - - // Dorothy Vaughan was a NASA mathematician and computer programmer on the SCOUT launch vehicle program that put America's first satellites into space - https://en.wikipedia.org/wiki/Dorothy_Vaughan - "vaughan", - - // Cédric Villani - French mathematician, won Fields Medal, Fermat Prize and Poincaré Price for his work in differential geometry and statistical mechanics. https://en.wikipedia.org/wiki/C%C3%A9dric_Villani - "villani", - - // Sir Mokshagundam Visvesvaraya - is a notable Indian engineer. He is a recipient of the Indian Republic's highest honour, the Bharat Ratna, in 1955. On his birthday, 15 September is celebrated as Engineer's Day in India in his memory - https://en.wikipedia.org/wiki/Visvesvaraya - "visvesvaraya", - - // Christiane Nüsslein-Volhard - German biologist, won Nobel Prize in Physiology or Medicine in 1995 for research on the genetic control of embryonic development. https://en.wikipedia.org/wiki/Christiane_N%C3%BCsslein-Volhard - "volhard", - - // Marlyn Wescoff - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Marlyn_Meltzer - "wescoff", - - // Sylvia B. Wilbur - British computer scientist who helped develop the ARPANET, was one of the first to exchange email in the UK and a leading researcher in computer-supported collaborative work. https://en.wikipedia.org/wiki/Sylvia_Wilbur - "wilbur", - - // Andrew Wiles - Notable British mathematician who proved the enigmatic Fermat's Last Theorem - https://en.wikipedia.org/wiki/Andrew_Wiles - "wiles", - - // Roberta Williams, did pioneering work in graphical adventure games for personal computers, particularly the King's Quest series. https://en.wikipedia.org/wiki/Roberta_Williams - "williams", - - // Malcolm John Williamson - British mathematician and cryptographer employed by the GCHQ. Developed in 1974 what is now known as Diffie-Hellman key exchange (Diffie and Hellman first published the scheme in 1976). https://en.wikipedia.org/wiki/Malcolm_J._Williamson - "williamson", - - // Sophie Wilson designed the first Acorn Micro-Computer and the instruction set for ARM processors. https://en.wikipedia.org/wiki/Sophie_Wilson - "wilson", - - // Jeannette Wing - co-developed the Liskov substitution principle. - https://en.wikipedia.org/wiki/Jeannette_Wing - "wing", - - // Steve Wozniak invented the Apple I and Apple II. https://en.wikipedia.org/wiki/Steve_Wozniak - "wozniak", - - // The Wright brothers, Orville and Wilbur - credited with inventing and building the world's first successful airplane and making the first controlled, powered and sustained heavier-than-air human flight - https://en.wikipedia.org/wiki/Wright_brothers - "wright", - - // Chien-Shiung Wu - Chinese-American experimental physicist who made significant contributions to nuclear physics. https://en.wikipedia.org/wiki/Chien-Shiung_Wu - "wu", - - // Rosalyn Sussman Yalow - Rosalyn Sussman Yalow was an American medical physicist, and a co-winner of the 1977 Nobel Prize in Physiology or Medicine for development of the radioimmunoassay technique. https://en.wikipedia.org/wiki/Rosalyn_Sussman_Yalow - "yalow", - - // Ada Yonath - an Israeli crystallographer, the first woman from the Middle East to win a Nobel prize in the sciences. https://en.wikipedia.org/wiki/Ada_Yonath - "yonath", - - // Nikolay Yegorovich Zhukovsky (Russian: Никола́й Его́рович Жуко́вский, January 17 1847 – March 17, 1921) was a Russian scientist, mathematician and engineer, and a founding father of modern aero- and hydrodynamics. Whereas contemporary scientists scoffed at the idea of human flight, Zhukovsky was the first to undertake the study of airflow. He is often called the Father of Russian Aviation. https://en.wikipedia.org/wiki/Nikolay_Yegorovich_Zhukovsky - "zhukovsky", - } -) - -// GetRandomName generates a random name from the list of adjectives and surnames in this package -// formatted as "adjective_surname". For example 'focused_turing'. If retry is non-zero, a random -// integer between 0 and 10 will be added to the end of the name, e.g `focused_turing3` -func GetRandomName(retry int) string { -begin: - name := left[rand.Intn(len(left))] + "_" + right[rand.Intn(len(right))] //nolint:gosec // G404: Use of weak random number generator (math/rand instead of crypto/rand) - if name == "boring_wozniak" /* Steve Wozniak is not boring */ { - goto begin - } - - if retry > 0 { - name += strconv.Itoa(rand.Intn(10)) //nolint:gosec // G404: Use of weak random number generator (math/rand instead of crypto/rand) - } - return name -} diff --git a/vendor/github.com/docker/docker/pkg/pools/pools.go b/vendor/github.com/docker/docker/pkg/pools/pools.go deleted file mode 100644 index 3792c67a9..000000000 --- a/vendor/github.com/docker/docker/pkg/pools/pools.go +++ /dev/null @@ -1,137 +0,0 @@ -// Package pools provides a collection of pools which provide various -// data types with buffers. These can be used to lower the number of -// memory allocations and reuse buffers. -// -// New pools should be added to this package to allow them to be -// shared across packages. -// -// Utility functions which operate on pools should be added to this -// package to allow them to be reused. -package pools // import "github.com/docker/docker/pkg/pools" - -import ( - "bufio" - "io" - "sync" - - "github.com/docker/docker/pkg/ioutils" -) - -const buffer32K = 32 * 1024 - -var ( - // BufioReader32KPool is a pool which returns bufio.Reader with a 32K buffer. - BufioReader32KPool = newBufioReaderPoolWithSize(buffer32K) - // BufioWriter32KPool is a pool which returns bufio.Writer with a 32K buffer. - BufioWriter32KPool = newBufioWriterPoolWithSize(buffer32K) - buffer32KPool = newBufferPoolWithSize(buffer32K) -) - -// BufioReaderPool is a bufio reader that uses sync.Pool. -type BufioReaderPool struct { - pool sync.Pool -} - -// newBufioReaderPoolWithSize is unexported because new pools should be -// added here to be shared where required. -func newBufioReaderPoolWithSize(size int) *BufioReaderPool { - return &BufioReaderPool{ - pool: sync.Pool{ - New: func() interface{} { return bufio.NewReaderSize(nil, size) }, - }, - } -} - -// Get returns a bufio.Reader which reads from r. The buffer size is that of the pool. -func (bufPool *BufioReaderPool) Get(r io.Reader) *bufio.Reader { - buf := bufPool.pool.Get().(*bufio.Reader) - buf.Reset(r) - return buf -} - -// Put puts the bufio.Reader back into the pool. -func (bufPool *BufioReaderPool) Put(b *bufio.Reader) { - b.Reset(nil) - bufPool.pool.Put(b) -} - -type bufferPool struct { - pool sync.Pool -} - -func newBufferPoolWithSize(size int) *bufferPool { - return &bufferPool{ - pool: sync.Pool{ - New: func() interface{} { s := make([]byte, size); return &s }, - }, - } -} - -func (bp *bufferPool) Get() *[]byte { - return bp.pool.Get().(*[]byte) -} - -func (bp *bufferPool) Put(b *[]byte) { - bp.pool.Put(b) -} - -// Copy is a convenience wrapper which uses a buffer to avoid allocation in io.Copy. -func Copy(dst io.Writer, src io.Reader) (written int64, err error) { - buf := buffer32KPool.Get() - written, err = io.CopyBuffer(dst, src, *buf) - buffer32KPool.Put(buf) - return -} - -// NewReadCloserWrapper returns a wrapper which puts the bufio.Reader back -// into the pool and closes the reader if it's an io.ReadCloser. -func (bufPool *BufioReaderPool) NewReadCloserWrapper(buf *bufio.Reader, r io.Reader) io.ReadCloser { - return ioutils.NewReadCloserWrapper(r, func() error { - if readCloser, ok := r.(io.ReadCloser); ok { - readCloser.Close() - } - bufPool.Put(buf) - return nil - }) -} - -// BufioWriterPool is a bufio writer that uses sync.Pool. -type BufioWriterPool struct { - pool sync.Pool -} - -// newBufioWriterPoolWithSize is unexported because new pools should be -// added here to be shared where required. -func newBufioWriterPoolWithSize(size int) *BufioWriterPool { - return &BufioWriterPool{ - pool: sync.Pool{ - New: func() interface{} { return bufio.NewWriterSize(nil, size) }, - }, - } -} - -// Get returns a bufio.Writer which writes to w. The buffer size is that of the pool. -func (bufPool *BufioWriterPool) Get(w io.Writer) *bufio.Writer { - buf := bufPool.pool.Get().(*bufio.Writer) - buf.Reset(w) - return buf -} - -// Put puts the bufio.Writer back into the pool. -func (bufPool *BufioWriterPool) Put(b *bufio.Writer) { - b.Reset(nil) - bufPool.pool.Put(b) -} - -// NewWriteCloserWrapper returns a wrapper which puts the bufio.Writer back -// into the pool and closes the writer if it's an io.Writecloser. -func (bufPool *BufioWriterPool) NewWriteCloserWrapper(buf *bufio.Writer, w io.Writer) io.WriteCloser { - return ioutils.NewWriteCloserWrapper(w, func() error { - buf.Flush() - if writeCloser, ok := w.(io.WriteCloser); ok { - writeCloser.Close() - } - bufPool.Put(buf) - return nil - }) -} diff --git a/vendor/github.com/docker/docker/pkg/process/doc.go b/vendor/github.com/docker/docker/pkg/process/doc.go deleted file mode 100644 index dae536d7d..000000000 --- a/vendor/github.com/docker/docker/pkg/process/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package process provides a set of basic functions to manage individual -// processes. -package process diff --git a/vendor/github.com/docker/docker/pkg/process/process_unix.go b/vendor/github.com/docker/docker/pkg/process/process_unix.go deleted file mode 100644 index daf392362..000000000 --- a/vendor/github.com/docker/docker/pkg/process/process_unix.go +++ /dev/null @@ -1,82 +0,0 @@ -//go:build !windows -// +build !windows - -package process - -import ( - "bytes" - "fmt" - "os" - "path/filepath" - "runtime" - "strconv" - - "golang.org/x/sys/unix" -) - -// Alive returns true if process with a given pid is running. It only considers -// positive PIDs; 0 (all processes in the current process group), -1 (all processes -// with a PID larger than 1), and negative (-n, all processes in process group -// "n") values for pid are never considered to be alive. -func Alive(pid int) bool { - if pid < 1 { - return false - } - switch runtime.GOOS { - case "darwin": - // OS X does not have a proc filesystem. Use kill -0 pid to judge if the - // process exists. From KILL(2): https://www.freebsd.org/cgi/man.cgi?query=kill&sektion=2&manpath=OpenDarwin+7.2.1 - // - // Sig may be one of the signals specified in sigaction(2) or it may - // be 0, in which case error checking is performed but no signal is - // actually sent. This can be used to check the validity of pid. - err := unix.Kill(pid, 0) - - // Either the PID was found (no error) or we get an EPERM, which means - // the PID exists, but we don't have permissions to signal it. - return err == nil || err == unix.EPERM - default: - _, err := os.Stat(filepath.Join("/proc", strconv.Itoa(pid))) - return err == nil - } -} - -// Kill force-stops a process. It only considers positive PIDs; 0 (all processes -// in the current process group), -1 (all processes with a PID larger than 1), -// and negative (-n, all processes in process group "n") values for pid are -// ignored. Refer to [KILL(2)] for details. -// -// [KILL(2)]: https://man7.org/linux/man-pages/man2/kill.2.html -func Kill(pid int) error { - if pid < 1 { - return fmt.Errorf("invalid PID (%d): only positive PIDs are allowed", pid) - } - err := unix.Kill(pid, unix.SIGKILL) - if err != nil && err != unix.ESRCH { - return err - } - return nil -} - -// Zombie return true if process has a state with "Z". It only considers positive -// PIDs; 0 (all processes in the current process group), -1 (all processes with -// a PID larger than 1), and negative (-n, all processes in process group "n") -// values for pid are ignored. Refer to [PROC(5)] for details. -// -// [PROC(5)]: https://man7.org/linux/man-pages/man5/proc.5.html -func Zombie(pid int) (bool, error) { - if pid < 1 { - return false, nil - } - data, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid)) - if err != nil { - if os.IsNotExist(err) { - return false, nil - } - return false, err - } - if cols := bytes.SplitN(data, []byte(" "), 4); len(cols) >= 3 && string(cols[2]) == "Z" { - return true, nil - } - return false, nil -} diff --git a/vendor/github.com/docker/docker/pkg/process/process_windows.go b/vendor/github.com/docker/docker/pkg/process/process_windows.go deleted file mode 100644 index 26158d09e..000000000 --- a/vendor/github.com/docker/docker/pkg/process/process_windows.go +++ /dev/null @@ -1,52 +0,0 @@ -package process - -import ( - "os" - - "golang.org/x/sys/windows" -) - -// Alive returns true if process with a given pid is running. -func Alive(pid int) bool { - h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid)) - if err != nil { - return false - } - var c uint32 - err = windows.GetExitCodeProcess(h, &c) - _ = windows.CloseHandle(h) - if err != nil { - // From the GetExitCodeProcess function (processthreadsapi.h) API docs: - // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getexitcodeprocess - // - // The GetExitCodeProcess function returns a valid error code defined by the - // application only after the thread terminates. Therefore, an application should - // not use STILL_ACTIVE (259) as an error code (STILL_ACTIVE is a macro for - // STATUS_PENDING (minwinbase.h)). If a thread returns STILL_ACTIVE (259) as - // an error code, then applications that test for that value could interpret it - // to mean that the thread is still running, and continue to test for the - // completion of the thread after the thread has terminated, which could put - // the application into an infinite loop. - return c == uint32(windows.STATUS_PENDING) - } - return true -} - -// Kill force-stops a process. -func Kill(pid int) error { - p, err := os.FindProcess(pid) - if err == nil { - err = p.Kill() - if err != nil && err != os.ErrProcessDone { - return err - } - } - return nil -} - -// Zombie is not supported on Windows. -// -// TODO(thaJeztah): remove once we remove the stubs from pkg/system. -func Zombie(_ int) (bool, error) { - return false, nil -} diff --git a/vendor/github.com/docker/docker/pkg/progress/progress.go b/vendor/github.com/docker/docker/pkg/progress/progress.go deleted file mode 100644 index 32300914e..000000000 --- a/vendor/github.com/docker/docker/pkg/progress/progress.go +++ /dev/null @@ -1,93 +0,0 @@ -package progress // import "github.com/docker/docker/pkg/progress" - -import ( - "fmt" -) - -// Progress represents the progress of a transfer. -type Progress struct { - ID string - - // Progress contains a Message or... - Message string - - // ...progress of an action - Action string - Current int64 - Total int64 - - // If true, don't show xB/yB - HideCounts bool - // If not empty, use units instead of bytes for counts - Units string - - // Aux contains extra information not presented to the user, such as - // digests for push signing. - Aux interface{} - - LastUpdate bool -} - -// Output is an interface for writing progress information. It's -// like a writer for progress, but we don't call it Writer because -// that would be confusing next to ProgressReader (also, because it -// doesn't implement the io.Writer interface). -type Output interface { - WriteProgress(Progress) error -} - -type chanOutput chan<- Progress - -func (out chanOutput) WriteProgress(p Progress) error { - // FIXME: workaround for panic in #37735 - defer func() { - recover() - }() - out <- p - return nil -} - -// ChanOutput returns an Output that writes progress updates to the -// supplied channel. -func ChanOutput(progressChan chan<- Progress) Output { - return chanOutput(progressChan) -} - -type discardOutput struct{} - -func (discardOutput) WriteProgress(Progress) error { - return nil -} - -// DiscardOutput returns an Output that discards progress -func DiscardOutput() Output { - return discardOutput{} -} - -// Update is a convenience function to write a progress update to the channel. -func Update(out Output, id, action string) { - out.WriteProgress(Progress{ID: id, Action: action}) -} - -// Updatef is a convenience function to write a printf-formatted progress update -// to the channel. -func Updatef(out Output, id, format string, a ...interface{}) { - Update(out, id, fmt.Sprintf(format, a...)) -} - -// Message is a convenience function to write a progress message to the channel. -func Message(out Output, id, message string) { - out.WriteProgress(Progress{ID: id, Message: message}) -} - -// Messagef is a convenience function to write a printf-formatted progress -// message to the channel. -func Messagef(out Output, id, format string, a ...interface{}) { - Message(out, id, fmt.Sprintf(format, a...)) -} - -// Aux sends auxiliary information over a progress interface, which will not be -// formatted for the UI. This is used for things such as push signing. -func Aux(out Output, a interface{}) { - out.WriteProgress(Progress{Aux: a}) -} diff --git a/vendor/github.com/docker/docker/pkg/progress/progressreader.go b/vendor/github.com/docker/docker/pkg/progress/progressreader.go deleted file mode 100644 index 07450a2d7..000000000 --- a/vendor/github.com/docker/docker/pkg/progress/progressreader.go +++ /dev/null @@ -1,66 +0,0 @@ -package progress // import "github.com/docker/docker/pkg/progress" - -import ( - "io" - "time" - - "golang.org/x/time/rate" -) - -// Reader is a Reader with progress bar. -type Reader struct { - in io.ReadCloser // Stream to read from - out Output // Where to send progress bar to - size int64 - current int64 - lastUpdate int64 - id string - action string - rateLimiter *rate.Limiter -} - -// NewProgressReader creates a new ProgressReader. -func NewProgressReader(in io.ReadCloser, out Output, size int64, id, action string) *Reader { - return &Reader{ - in: in, - out: out, - size: size, - id: id, - action: action, - rateLimiter: rate.NewLimiter(rate.Every(100*time.Millisecond), 1), - } -} - -func (p *Reader) Read(buf []byte) (n int, err error) { - read, err := p.in.Read(buf) - p.current += int64(read) - updateEvery := int64(1024 * 512) // 512kB - if p.size > 0 { - // Update progress for every 1% read if 1% < 512kB - if increment := int64(0.01 * float64(p.size)); increment < updateEvery { - updateEvery = increment - } - } - if p.current-p.lastUpdate > updateEvery || err != nil { - p.updateProgress(err != nil && read == 0) - p.lastUpdate = p.current - } - - return read, err -} - -// Close closes the progress reader and its underlying reader. -func (p *Reader) Close() error { - if p.current < p.size { - // print a full progress bar when closing prematurely - p.current = p.size - p.updateProgress(false) - } - return p.in.Close() -} - -func (p *Reader) updateProgress(last bool) { - if last || p.current == p.size || p.rateLimiter.Allow() { - p.out.WriteProgress(Progress{ID: p.id, Action: p.action, Current: p.current, Total: p.size, LastUpdate: last}) - } -} diff --git a/vendor/github.com/docker/docker/pkg/stdcopy/stdcopy.go b/vendor/github.com/docker/docker/pkg/stdcopy/stdcopy.go deleted file mode 100644 index 8f6e0a737..000000000 --- a/vendor/github.com/docker/docker/pkg/stdcopy/stdcopy.go +++ /dev/null @@ -1,190 +0,0 @@ -package stdcopy // import "github.com/docker/docker/pkg/stdcopy" - -import ( - "bytes" - "encoding/binary" - "errors" - "fmt" - "io" - "sync" -) - -// StdType is the type of standard stream -// a writer can multiplex to. -type StdType byte - -const ( - // Stdin represents standard input stream type. - Stdin StdType = iota - // Stdout represents standard output stream type. - Stdout - // Stderr represents standard error steam type. - Stderr - // Systemerr represents errors originating from the system that make it - // into the multiplexed stream. - Systemerr - - stdWriterPrefixLen = 8 - stdWriterFdIndex = 0 - stdWriterSizeIndex = 4 - - startingBufLen = 32*1024 + stdWriterPrefixLen + 1 -) - -var bufPool = &sync.Pool{New: func() interface{} { return bytes.NewBuffer(nil) }} - -// stdWriter is wrapper of io.Writer with extra customized info. -type stdWriter struct { - io.Writer - prefix byte -} - -// Write sends the buffer to the underneath writer. -// It inserts the prefix header before the buffer, -// so stdcopy.StdCopy knows where to multiplex the output. -// It makes stdWriter to implement io.Writer. -func (w *stdWriter) Write(p []byte) (n int, err error) { - if w == nil || w.Writer == nil { - return 0, errors.New("Writer not instantiated") - } - if p == nil { - return 0, nil - } - - header := [stdWriterPrefixLen]byte{stdWriterFdIndex: w.prefix} - binary.BigEndian.PutUint32(header[stdWriterSizeIndex:], uint32(len(p))) - buf := bufPool.Get().(*bytes.Buffer) - buf.Write(header[:]) - buf.Write(p) - - n, err = w.Writer.Write(buf.Bytes()) - n -= stdWriterPrefixLen - if n < 0 { - n = 0 - } - - buf.Reset() - bufPool.Put(buf) - return -} - -// NewStdWriter instantiates a new Writer. -// Everything written to it will be encapsulated using a custom format, -// and written to the underlying `w` stream. -// This allows multiple write streams (e.g. stdout and stderr) to be muxed into a single connection. -// `t` indicates the id of the stream to encapsulate. -// It can be stdcopy.Stdin, stdcopy.Stdout, stdcopy.Stderr. -func NewStdWriter(w io.Writer, t StdType) io.Writer { - return &stdWriter{ - Writer: w, - prefix: byte(t), - } -} - -// StdCopy is a modified version of io.Copy. -// -// StdCopy will demultiplex `src`, assuming that it contains two streams, -// previously multiplexed together using a StdWriter instance. -// As it reads from `src`, StdCopy will write to `dstout` and `dsterr`. -// -// StdCopy will read until it hits EOF on `src`. It will then return a nil error. -// In other words: if `err` is non nil, it indicates a real underlying error. -// -// `written` will hold the total number of bytes written to `dstout` and `dsterr`. -func StdCopy(dstout, dsterr io.Writer, src io.Reader) (written int64, err error) { - var ( - buf = make([]byte, startingBufLen) - bufLen = len(buf) - nr, nw int - er, ew error - out io.Writer - frameSize int - ) - - for { - // Make sure we have at least a full header - for nr < stdWriterPrefixLen { - var nr2 int - nr2, er = src.Read(buf[nr:]) - nr += nr2 - if er == io.EOF { - if nr < stdWriterPrefixLen { - return written, nil - } - break - } - if er != nil { - return 0, er - } - } - - stream := StdType(buf[stdWriterFdIndex]) - // Check the first byte to know where to write - switch stream { - case Stdin: - fallthrough - case Stdout: - // Write on stdout - out = dstout - case Stderr: - // Write on stderr - out = dsterr - case Systemerr: - // If we're on Systemerr, we won't write anywhere. - // NB: if this code changes later, make sure you don't try to write - // to outstream if Systemerr is the stream - out = nil - default: - return 0, fmt.Errorf("Unrecognized input header: %d", buf[stdWriterFdIndex]) - } - - // Retrieve the size of the frame - frameSize = int(binary.BigEndian.Uint32(buf[stdWriterSizeIndex : stdWriterSizeIndex+4])) - - // Check if the buffer is big enough to read the frame. - // Extend it if necessary. - if frameSize+stdWriterPrefixLen > bufLen { - buf = append(buf, make([]byte, frameSize+stdWriterPrefixLen-bufLen+1)...) - bufLen = len(buf) - } - - // While the amount of bytes read is less than the size of the frame + header, we keep reading - for nr < frameSize+stdWriterPrefixLen { - var nr2 int - nr2, er = src.Read(buf[nr:]) - nr += nr2 - if er == io.EOF { - if nr < frameSize+stdWriterPrefixLen { - return written, nil - } - break - } - if er != nil { - return 0, er - } - } - - // we might have an error from the source mixed up in our multiplexed - // stream. if we do, return it. - if stream == Systemerr { - return written, fmt.Errorf("error from daemon in stream: %s", string(buf[stdWriterPrefixLen:frameSize+stdWriterPrefixLen])) - } - - // Write the retrieved frame (without header) - nw, ew = out.Write(buf[stdWriterPrefixLen : frameSize+stdWriterPrefixLen]) - if ew != nil { - return 0, ew - } - - // If the frame has not been fully written: error - if nw != frameSize { - return 0, io.ErrShortWrite - } - written += int64(nw) - - // Move the rest of the buffer to the beginning - copy(buf, buf[frameSize+stdWriterPrefixLen:]) - // Move the index - nr -= frameSize + stdWriterPrefixLen - } -} diff --git a/vendor/github.com/docker/docker/pkg/streamformatter/streamformatter.go b/vendor/github.com/docker/docker/pkg/streamformatter/streamformatter.go deleted file mode 100644 index b0456e580..000000000 --- a/vendor/github.com/docker/docker/pkg/streamformatter/streamformatter.go +++ /dev/null @@ -1,159 +0,0 @@ -// Package streamformatter provides helper functions to format a stream. -package streamformatter // import "github.com/docker/docker/pkg/streamformatter" - -import ( - "encoding/json" - "fmt" - "io" - - "github.com/docker/docker/pkg/jsonmessage" - "github.com/docker/docker/pkg/progress" -) - -const streamNewline = "\r\n" - -type jsonProgressFormatter struct{} - -func appendNewline(source []byte) []byte { - return append(source, []byte(streamNewline)...) -} - -// FormatStatus formats the specified objects according to the specified format (and id). -func FormatStatus(id, format string, a ...interface{}) []byte { - str := fmt.Sprintf(format, a...) - b, err := json.Marshal(&jsonmessage.JSONMessage{ID: id, Status: str}) - if err != nil { - return FormatError(err) - } - return appendNewline(b) -} - -// FormatError formats the error as a JSON object -func FormatError(err error) []byte { - jsonError, ok := err.(*jsonmessage.JSONError) - if !ok { - jsonError = &jsonmessage.JSONError{Message: err.Error()} - } - if b, err := json.Marshal(&jsonmessage.JSONMessage{Error: jsonError, ErrorMessage: err.Error()}); err == nil { - return appendNewline(b) - } - return []byte(`{"error":"format error"}` + streamNewline) -} - -func (sf *jsonProgressFormatter) formatStatus(id, format string, a ...interface{}) []byte { - return FormatStatus(id, format, a...) -} - -// formatProgress formats the progress information for a specified action. -func (sf *jsonProgressFormatter) formatProgress(id, action string, progress *jsonmessage.JSONProgress, aux interface{}) []byte { - if progress == nil { - progress = &jsonmessage.JSONProgress{} - } - var auxJSON *json.RawMessage - if aux != nil { - auxJSONBytes, err := json.Marshal(aux) - if err != nil { - return nil - } - auxJSON = new(json.RawMessage) - *auxJSON = auxJSONBytes - } - b, err := json.Marshal(&jsonmessage.JSONMessage{ - Status: action, - ProgressMessage: progress.String(), - Progress: progress, - ID: id, - Aux: auxJSON, - }) - if err != nil { - return nil - } - return appendNewline(b) -} - -type rawProgressFormatter struct{} - -func (sf *rawProgressFormatter) formatStatus(id, format string, a ...interface{}) []byte { - return []byte(fmt.Sprintf(format, a...) + streamNewline) -} - -func (sf *rawProgressFormatter) formatProgress(id, action string, progress *jsonmessage.JSONProgress, aux interface{}) []byte { - if progress == nil { - progress = &jsonmessage.JSONProgress{} - } - endl := "\r" - if progress.String() == "" { - endl += "\n" - } - return []byte(action + " " + progress.String() + endl) -} - -// NewProgressOutput returns a progress.Output object that can be passed to -// progress.NewProgressReader. -func NewProgressOutput(out io.Writer) progress.Output { - return &progressOutput{sf: &rawProgressFormatter{}, out: out, newLines: true} -} - -// NewJSONProgressOutput returns a progress.Output that formats output -// using JSON objects -func NewJSONProgressOutput(out io.Writer, newLines bool) progress.Output { - return &progressOutput{sf: &jsonProgressFormatter{}, out: out, newLines: newLines} -} - -type formatProgress interface { - formatStatus(id, format string, a ...interface{}) []byte - formatProgress(id, action string, progress *jsonmessage.JSONProgress, aux interface{}) []byte -} - -type progressOutput struct { - sf formatProgress - out io.Writer - newLines bool -} - -// WriteProgress formats progress information from a ProgressReader. -func (out *progressOutput) WriteProgress(prog progress.Progress) error { - var formatted []byte - if prog.Message != "" { - formatted = out.sf.formatStatus(prog.ID, prog.Message) - } else { - jsonProgress := jsonmessage.JSONProgress{Current: prog.Current, Total: prog.Total, HideCounts: prog.HideCounts, Units: prog.Units} - formatted = out.sf.formatProgress(prog.ID, prog.Action, &jsonProgress, prog.Aux) - } - _, err := out.out.Write(formatted) - if err != nil { - return err - } - - if out.newLines && prog.LastUpdate { - _, err = out.out.Write(out.sf.formatStatus("", "")) - return err - } - - return nil -} - -// AuxFormatter is a streamFormatter that writes aux progress messages -type AuxFormatter struct { - io.Writer -} - -// Emit emits the given interface as an aux progress message -func (sf *AuxFormatter) Emit(id string, aux interface{}) error { - auxJSONBytes, err := json.Marshal(aux) - if err != nil { - return err - } - auxJSON := new(json.RawMessage) - *auxJSON = auxJSONBytes - msgJSON, err := json.Marshal(&jsonmessage.JSONMessage{ID: id, Aux: auxJSON}) - if err != nil { - return err - } - msgJSON = appendNewline(msgJSON) - n, err := sf.Writer.Write(msgJSON) - if n != len(msgJSON) { - return io.ErrShortWrite - } - return err -} diff --git a/vendor/github.com/docker/docker/pkg/streamformatter/streamwriter.go b/vendor/github.com/docker/docker/pkg/streamformatter/streamwriter.go deleted file mode 100644 index 1473ed974..000000000 --- a/vendor/github.com/docker/docker/pkg/streamformatter/streamwriter.go +++ /dev/null @@ -1,47 +0,0 @@ -package streamformatter // import "github.com/docker/docker/pkg/streamformatter" - -import ( - "encoding/json" - "io" - - "github.com/docker/docker/pkg/jsonmessage" -) - -type streamWriter struct { - io.Writer - lineFormat func([]byte) string -} - -func (sw *streamWriter) Write(buf []byte) (int, error) { - formattedBuf := sw.format(buf) - n, err := sw.Writer.Write(formattedBuf) - if n != len(formattedBuf) { - return n, io.ErrShortWrite - } - return len(buf), err -} - -func (sw *streamWriter) format(buf []byte) []byte { - msg := &jsonmessage.JSONMessage{Stream: sw.lineFormat(buf)} - b, err := json.Marshal(msg) - if err != nil { - return FormatError(err) - } - return appendNewline(b) -} - -// NewStdoutWriter returns a writer which formats the output as json message -// representing stdout lines -func NewStdoutWriter(out io.Writer) io.Writer { - return &streamWriter{Writer: out, lineFormat: func(buf []byte) string { - return string(buf) - }} -} - -// NewStderrWriter returns a writer which formats the output as json message -// representing stderr lines -func NewStderrWriter(out io.Writer) io.Writer { - return &streamWriter{Writer: out, lineFormat: func(buf []byte) string { - return "\033[91m" + string(buf) + "\033[0m" - }} -} diff --git a/vendor/github.com/docker/docker/pkg/stringid/stringid.go b/vendor/github.com/docker/docker/pkg/stringid/stringid.go deleted file mode 100644 index d3d1014ac..000000000 --- a/vendor/github.com/docker/docker/pkg/stringid/stringid.go +++ /dev/null @@ -1,73 +0,0 @@ -// Package stringid provides helper functions for dealing with string identifiers -package stringid // import "github.com/docker/docker/pkg/stringid" - -import ( - "crypto/rand" - "encoding/hex" - "errors" - "regexp" - "strconv" - "strings" -) - -const ( - shortLen = 12 - fullLen = 64 -) - -var ( - validShortID = regexp.MustCompile("^[a-f0-9]{12}$") - validHex = regexp.MustCompile(`^[a-f0-9]{64}$`) -) - -// IsShortID determines if id has the correct format and length for a short ID. -// It checks the IDs length and if it consists of valid characters for IDs (a-f0-9). -func IsShortID(id string) bool { - if len(id) != shortLen { - return false - } - return validShortID.MatchString(id) -} - -// TruncateID returns a shorthand version of a string identifier for convenience. -// A collision with other shorthands is very unlikely, but possible. -// In case of a collision a lookup with TruncIndex.Get() will fail, and the caller -// will need to use a longer prefix, or the full-length Id. -func TruncateID(id string) string { - if i := strings.IndexRune(id, ':'); i >= 0 { - id = id[i+1:] - } - if len(id) > shortLen { - id = id[:shortLen] - } - return id -} - -// GenerateRandomID returns a unique id. -func GenerateRandomID() string { - b := make([]byte, 32) - for { - if _, err := rand.Read(b); err != nil { - panic(err) // This shouldn't happen - } - id := hex.EncodeToString(b) - // if we try to parse the truncated for as an int and we don't have - // an error then the value is all numeric and causes issues when - // used as a hostname. ref #3869 - if _, err := strconv.ParseInt(TruncateID(id), 10, 64); err == nil { - continue - } - return id - } -} - -// ValidateID checks whether an ID string is a valid, full-length image ID. -func ValidateID(id string) error { - if len(id) != fullLen { - return errors.New("image ID '" + id + "' is invalid") - } - if !validHex.MatchString(id) { - return errors.New("image ID '" + id + "' is invalid") - } - return nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/args_windows.go b/vendor/github.com/docker/docker/pkg/system/args_windows.go deleted file mode 100644 index b7c9487a0..000000000 --- a/vendor/github.com/docker/docker/pkg/system/args_windows.go +++ /dev/null @@ -1,16 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "strings" - - "golang.org/x/sys/windows" -) - -// EscapeArgs makes a Windows-style escaped command line from a set of arguments -func EscapeArgs(args []string) string { - escapedArgs := make([]string, len(args)) - for i, a := range args { - escapedArgs[i] = windows.EscapeArg(a) - } - return strings.Join(escapedArgs, " ") -} diff --git a/vendor/github.com/docker/docker/pkg/system/chtimes.go b/vendor/github.com/docker/docker/pkg/system/chtimes.go deleted file mode 100644 index 6a6bca43e..000000000 --- a/vendor/github.com/docker/docker/pkg/system/chtimes.go +++ /dev/null @@ -1,48 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "os" - "syscall" - "time" - "unsafe" -) - -// Used by Chtimes -var unixEpochTime, unixMaxTime time.Time - -func init() { - unixEpochTime = time.Unix(0, 0) - if unsafe.Sizeof(syscall.Timespec{}.Nsec) == 8 { - // This is a 64 bit timespec - // os.Chtimes limits time to the following - // - // Note that this intentionally sets nsec (not sec), which sets both sec - // and nsec internally in time.Unix(); - // https://github.com/golang/go/blob/go1.19.2/src/time/time.go#L1364-L1380 - unixMaxTime = time.Unix(0, 1<<63-1) - } else { - // This is a 32 bit timespec - unixMaxTime = time.Unix(1<<31-1, 0) - } -} - -// Chtimes changes the access time and modified time of a file at the given path. -// If the modified time is prior to the Unix Epoch (unixMinTime), or after the -// end of Unix Time (unixEpochTime), os.Chtimes has undefined behavior. In this -// case, Chtimes defaults to Unix Epoch, just in case. -func Chtimes(name string, atime time.Time, mtime time.Time) error { - if atime.Before(unixEpochTime) || atime.After(unixMaxTime) { - atime = unixEpochTime - } - - if mtime.Before(unixEpochTime) || mtime.After(unixMaxTime) { - mtime = unixEpochTime - } - - if err := os.Chtimes(name, atime, mtime); err != nil { - return err - } - - // Take platform specific action for setting create time. - return setCTime(name, mtime) -} diff --git a/vendor/github.com/docker/docker/pkg/system/chtimes_nowindows.go b/vendor/github.com/docker/docker/pkg/system/chtimes_nowindows.go deleted file mode 100644 index 84ae15705..000000000 --- a/vendor/github.com/docker/docker/pkg/system/chtimes_nowindows.go +++ /dev/null @@ -1,15 +0,0 @@ -//go:build !windows -// +build !windows - -package system // import "github.com/docker/docker/pkg/system" - -import ( - "time" -) - -// setCTime will set the create time on a file. On Unix, the create -// time is updated as a side effect of setting the modified time, so -// no action is required. -func setCTime(path string, ctime time.Time) error { - return nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/chtimes_windows.go b/vendor/github.com/docker/docker/pkg/system/chtimes_windows.go deleted file mode 100644 index ab478f5c3..000000000 --- a/vendor/github.com/docker/docker/pkg/system/chtimes_windows.go +++ /dev/null @@ -1,25 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "time" - - "golang.org/x/sys/windows" -) - -// setCTime will set the create time on a file. On Windows, this requires -// calling SetFileTime and explicitly including the create time. -func setCTime(path string, ctime time.Time) error { - pathp, err := windows.UTF16PtrFromString(path) - if err != nil { - return err - } - h, err := windows.CreateFile(pathp, - windows.FILE_WRITE_ATTRIBUTES, windows.FILE_SHARE_WRITE, nil, - windows.OPEN_EXISTING, windows.FILE_FLAG_BACKUP_SEMANTICS, 0) - if err != nil { - return err - } - defer windows.Close(h) - c := windows.NsecToFiletime(ctime.UnixNano()) - return windows.SetFileTime(h, &c, nil, nil) -} diff --git a/vendor/github.com/docker/docker/pkg/system/errors.go b/vendor/github.com/docker/docker/pkg/system/errors.go deleted file mode 100644 index 2573d7162..000000000 --- a/vendor/github.com/docker/docker/pkg/system/errors.go +++ /dev/null @@ -1,13 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "errors" -) - -var ( - // ErrNotSupportedPlatform means the platform is not supported. - ErrNotSupportedPlatform = errors.New("platform and architecture is not supported") - - // ErrNotSupportedOperatingSystem means the operating system is not supported. - ErrNotSupportedOperatingSystem = errors.New("operating system is not supported") -) diff --git a/vendor/github.com/docker/docker/pkg/system/filesys.go b/vendor/github.com/docker/docker/pkg/system/filesys.go deleted file mode 100644 index ce5990c91..000000000 --- a/vendor/github.com/docker/docker/pkg/system/filesys.go +++ /dev/null @@ -1,19 +0,0 @@ -package system - -import ( - "os" - "path/filepath" - "strings" -) - -// IsAbs is a platform-agnostic wrapper for filepath.IsAbs. -// -// On Windows, golang filepath.IsAbs does not consider a path \windows\system32 -// as absolute as it doesn't start with a drive-letter/colon combination. However, -// in docker we need to verify things such as WORKDIR /windows/system32 in -// a Dockerfile (which gets translated to \windows\system32 when being processed -// by the daemon). This SHOULD be treated as absolute from a docker processing -// perspective. -func IsAbs(path string) bool { - return filepath.IsAbs(path) || strings.HasPrefix(path, string(os.PathSeparator)) -} diff --git a/vendor/github.com/docker/docker/pkg/system/filesys_unix.go b/vendor/github.com/docker/docker/pkg/system/filesys_unix.go deleted file mode 100644 index 380112940..000000000 --- a/vendor/github.com/docker/docker/pkg/system/filesys_unix.go +++ /dev/null @@ -1,17 +0,0 @@ -//go:build !windows -// +build !windows - -package system // import "github.com/docker/docker/pkg/system" - -import "os" - -// MkdirAllWithACL is a wrapper for os.MkdirAll on unix systems. -func MkdirAllWithACL(path string, perm os.FileMode, sddl string) error { - return os.MkdirAll(path, perm) -} - -// MkdirAll creates a directory named path along with any necessary parents, -// with permission specified by attribute perm for all dir created. -func MkdirAll(path string, perm os.FileMode) error { - return os.MkdirAll(path, perm) -} diff --git a/vendor/github.com/docker/docker/pkg/system/filesys_windows.go b/vendor/github.com/docker/docker/pkg/system/filesys_windows.go deleted file mode 100644 index 92e972ea2..000000000 --- a/vendor/github.com/docker/docker/pkg/system/filesys_windows.go +++ /dev/null @@ -1,135 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "os" - "regexp" - "syscall" - "unsafe" - - "golang.org/x/sys/windows" -) - -// SddlAdministratorsLocalSystem is local administrators plus NT AUTHORITY\System. -const SddlAdministratorsLocalSystem = "D:P(A;OICI;GA;;;BA)(A;OICI;GA;;;SY)" - -// volumePath is a regular expression to check if a path is a Windows -// volume path (e.g., "\\?\Volume{4c1b02c1-d990-11dc-99ae-806e6f6e6963}" -// or "\\?\Volume{4c1b02c1-d990-11dc-99ae-806e6f6e6963}\"). -var volumePath = regexp.MustCompile(`^\\\\\?\\Volume{[a-z0-9-]+}\\?$`) - -// MkdirAllWithACL is a custom version of os.MkdirAll modified for use on Windows -// so that it is both volume path aware, and can create a directory with -// an appropriate SDDL defined ACL. -func MkdirAllWithACL(path string, _ os.FileMode, sddl string) error { - sa, err := makeSecurityAttributes(sddl) - if err != nil { - return &os.PathError{Op: "mkdirall", Path: path, Err: err} - } - return mkdirall(path, sa) -} - -// MkdirAll is a custom version of os.MkdirAll that is volume path aware for -// Windows. It can be used as a drop-in replacement for os.MkdirAll. -func MkdirAll(path string, _ os.FileMode) error { - return mkdirall(path, nil) -} - -// mkdirall is a custom version of os.MkdirAll modified for use on Windows -// so that it is both volume path aware, and can create a directory with -// a DACL. -func mkdirall(path string, perm *windows.SecurityAttributes) error { - if volumePath.MatchString(path) { - return nil - } - - // The rest of this method is largely copied from os.MkdirAll and should be kept - // as-is to ensure compatibility. - - // Fast path: if we can tell whether path is a directory or file, stop with success or error. - dir, err := os.Stat(path) - if err == nil { - if dir.IsDir() { - return nil - } - return &os.PathError{Op: "mkdir", Path: path, Err: syscall.ENOTDIR} - } - - // Slow path: make sure parent exists and then call Mkdir for path. - i := len(path) - for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator. - i-- - } - - j := i - for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element. - j-- - } - - if j > 1 { - // Create parent. - err = mkdirall(fixRootDirectory(path[:j-1]), perm) - if err != nil { - return err - } - } - - // Parent now exists; invoke Mkdir and use its result. - err = mkdirWithACL(path, perm) - if err != nil { - // Handle arguments like "foo/." by - // double-checking that directory doesn't exist. - dir, err1 := os.Lstat(path) - if err1 == nil && dir.IsDir() { - return nil - } - return err - } - return nil -} - -// mkdirWithACL creates a new directory. If there is an error, it will be of -// type *PathError. . -// -// This is a modified and combined version of os.Mkdir and windows.Mkdir -// in golang to cater for creating a directory am ACL permitting full -// access, with inheritance, to any subfolder/file for Built-in Administrators -// and Local System. -func mkdirWithACL(name string, sa *windows.SecurityAttributes) error { - if sa == nil { - return os.Mkdir(name, 0) - } - - namep, err := windows.UTF16PtrFromString(name) - if err != nil { - return &os.PathError{Op: "mkdir", Path: name, Err: err} - } - - err = windows.CreateDirectory(namep, sa) - if err != nil { - return &os.PathError{Op: "mkdir", Path: name, Err: err} - } - return nil -} - -// fixRootDirectory fixes a reference to a drive's root directory to -// have the required trailing slash. -func fixRootDirectory(p string) string { - if len(p) == len(`\\?\c:`) { - if os.IsPathSeparator(p[0]) && os.IsPathSeparator(p[1]) && p[2] == '?' && os.IsPathSeparator(p[3]) && p[5] == ':' { - return p + `\` - } - } - return p -} - -func makeSecurityAttributes(sddl string) (*windows.SecurityAttributes, error) { - var sa windows.SecurityAttributes - sa.Length = uint32(unsafe.Sizeof(sa)) - sa.InheritHandle = 1 - var err error - sa.SecurityDescriptor, err = windows.SecurityDescriptorFromString(sddl) - if err != nil { - return nil, err - } - return &sa, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/image_os.go b/vendor/github.com/docker/docker/pkg/system/image_os.go deleted file mode 100644 index e3de86be2..000000000 --- a/vendor/github.com/docker/docker/pkg/system/image_os.go +++ /dev/null @@ -1,10 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" -import ( - "runtime" - "strings" -) - -// IsOSSupported determines if an operating system is supported by the host. -func IsOSSupported(os string) bool { - return strings.EqualFold(runtime.GOOS, os) -} diff --git a/vendor/github.com/docker/docker/pkg/system/init_windows.go b/vendor/github.com/docker/docker/pkg/system/init_windows.go deleted file mode 100644 index 3c2a43ddb..000000000 --- a/vendor/github.com/docker/docker/pkg/system/init_windows.go +++ /dev/null @@ -1,18 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -var ( - // containerdRuntimeSupported determines if containerd should be the runtime. - containerdRuntimeSupported = false -) - -// InitContainerdRuntime sets whether to use containerd for runtime on Windows. -func InitContainerdRuntime(cdPath string) { - if len(cdPath) > 0 { - containerdRuntimeSupported = true - } -} - -// ContainerdRuntimeSupported returns true if the use of containerd runtime is supported. -func ContainerdRuntimeSupported() bool { - return containerdRuntimeSupported -} diff --git a/vendor/github.com/docker/docker/pkg/system/lstat_unix.go b/vendor/github.com/docker/docker/pkg/system/lstat_unix.go deleted file mode 100644 index 654b9f2c9..000000000 --- a/vendor/github.com/docker/docker/pkg/system/lstat_unix.go +++ /dev/null @@ -1,21 +0,0 @@ -//go:build !windows -// +build !windows - -package system // import "github.com/docker/docker/pkg/system" - -import ( - "os" - "syscall" -) - -// Lstat takes a path to a file and returns -// a system.StatT type pertaining to that file. -// -// Throws an error if the file does not exist -func Lstat(path string) (*StatT, error) { - s := &syscall.Stat_t{} - if err := syscall.Lstat(path, s); err != nil { - return nil, &os.PathError{Op: "Lstat", Path: path, Err: err} - } - return fromStatT(s) -} diff --git a/vendor/github.com/docker/docker/pkg/system/lstat_windows.go b/vendor/github.com/docker/docker/pkg/system/lstat_windows.go deleted file mode 100644 index 359c791d9..000000000 --- a/vendor/github.com/docker/docker/pkg/system/lstat_windows.go +++ /dev/null @@ -1,14 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import "os" - -// Lstat calls os.Lstat to get a fileinfo interface back. -// This is then copied into our own locally defined structure. -func Lstat(path string) (*StatT, error) { - fi, err := os.Lstat(path) - if err != nil { - return nil, err - } - - return fromStatT(&fi) -} diff --git a/vendor/github.com/docker/docker/pkg/system/meminfo_deprecated.go b/vendor/github.com/docker/docker/pkg/system/meminfo_deprecated.go deleted file mode 100644 index 216519923..000000000 --- a/vendor/github.com/docker/docker/pkg/system/meminfo_deprecated.go +++ /dev/null @@ -1,16 +0,0 @@ -package system - -import "github.com/docker/docker/pkg/meminfo" - -// MemInfo contains memory statistics of the host system. -// -// Deprecated: use [meminfo.Memory]. -type MemInfo = meminfo.Memory - -// ReadMemInfo retrieves memory statistics of the host system and returns a -// MemInfo type. -// -// Deprecated: use [meminfo.Read]. -func ReadMemInfo() (*meminfo.Memory, error) { - return meminfo.Read() -} diff --git a/vendor/github.com/docker/docker/pkg/system/mknod.go b/vendor/github.com/docker/docker/pkg/system/mknod.go deleted file mode 100644 index d27152c0f..000000000 --- a/vendor/github.com/docker/docker/pkg/system/mknod.go +++ /dev/null @@ -1,17 +0,0 @@ -//go:build !windows -// +build !windows - -package system // import "github.com/docker/docker/pkg/system" - -import ( - "golang.org/x/sys/unix" -) - -// Mkdev is used to build the value of linux devices (in /dev/) which specifies major -// and minor number of the newly created device special file. -// Linux device nodes are a bit weird due to backwards compat with 16 bit device nodes. -// They are, from low to high: the lower 8 bits of the minor, then 12 bits of the major, -// then the top 12 bits of the minor. -func Mkdev(major int64, minor int64) uint32 { - return uint32(unix.Mkdev(uint32(major), uint32(minor))) -} diff --git a/vendor/github.com/docker/docker/pkg/system/mknod_freebsd.go b/vendor/github.com/docker/docker/pkg/system/mknod_freebsd.go deleted file mode 100644 index c890be116..000000000 --- a/vendor/github.com/docker/docker/pkg/system/mknod_freebsd.go +++ /dev/null @@ -1,14 +0,0 @@ -//go:build freebsd -// +build freebsd - -package system // import "github.com/docker/docker/pkg/system" - -import ( - "golang.org/x/sys/unix" -) - -// Mknod creates a filesystem node (file, device special file or named pipe) named path -// with attributes specified by mode and dev. -func Mknod(path string, mode uint32, dev int) error { - return unix.Mknod(path, mode, uint64(dev)) -} diff --git a/vendor/github.com/docker/docker/pkg/system/mknod_unix.go b/vendor/github.com/docker/docker/pkg/system/mknod_unix.go deleted file mode 100644 index 4586aad19..000000000 --- a/vendor/github.com/docker/docker/pkg/system/mknod_unix.go +++ /dev/null @@ -1,14 +0,0 @@ -//go:build !freebsd && !windows -// +build !freebsd,!windows - -package system // import "github.com/docker/docker/pkg/system" - -import ( - "golang.org/x/sys/unix" -) - -// Mknod creates a filesystem node (file, device special file or named pipe) named path -// with attributes specified by mode and dev. -func Mknod(path string, mode uint32, dev int) error { - return unix.Mknod(path, mode, dev) -} diff --git a/vendor/github.com/docker/docker/pkg/system/mknod_windows.go b/vendor/github.com/docker/docker/pkg/system/mknod_windows.go deleted file mode 100644 index ec89d7a15..000000000 --- a/vendor/github.com/docker/docker/pkg/system/mknod_windows.go +++ /dev/null @@ -1,11 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -// Mknod is not implemented on Windows. -func Mknod(path string, mode uint32, dev int) error { - return ErrNotSupportedPlatform -} - -// Mkdev is not implemented on Windows. -func Mkdev(major int64, minor int64) uint32 { - panic("Mkdev not implemented on Windows.") -} diff --git a/vendor/github.com/docker/docker/pkg/system/path_deprecated.go b/vendor/github.com/docker/docker/pkg/system/path_deprecated.go deleted file mode 100644 index 5c95026c3..000000000 --- a/vendor/github.com/docker/docker/pkg/system/path_deprecated.go +++ /dev/null @@ -1,18 +0,0 @@ -package system - -const defaultUnixPathEnv = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" - -// DefaultPathEnv is unix style list of directories to search for -// executables. Each directory is separated from the next by a colon -// ':' character . -// For Windows containers, an empty string is returned as the default -// path will be set by the container, and Docker has no context of what the -// default path should be. -// -// Deprecated: use oci.DefaultPathEnv -func DefaultPathEnv(os string) string { - if os == "windows" { - return "" - } - return defaultUnixPathEnv -} diff --git a/vendor/github.com/docker/docker/pkg/system/process_deprecated.go b/vendor/github.com/docker/docker/pkg/system/process_deprecated.go deleted file mode 100644 index 7b9f19acd..000000000 --- a/vendor/github.com/docker/docker/pkg/system/process_deprecated.go +++ /dev/null @@ -1,27 +0,0 @@ -//go:build linux || freebsd || darwin || windows -// +build linux freebsd darwin windows - -package system - -import "github.com/docker/docker/pkg/process" - -var ( - // IsProcessAlive returns true if process with a given pid is running. - // - // Deprecated: use [process.Alive]. - IsProcessAlive = process.Alive - - // IsProcessZombie return true if process has a state with "Z" - // - // Deprecated: use [process.Zombie]. - // - // TODO(thaJeztah): remove the Windows implementation in process once we remove this stub. - IsProcessZombie = process.Zombie -) - -// KillProcess force-stops a process. -// -// Deprecated: use [process.Kill]. -func KillProcess(pid int) { - _ = process.Kill(pid) -} diff --git a/vendor/github.com/docker/docker/pkg/system/stat_bsd.go b/vendor/github.com/docker/docker/pkg/system/stat_bsd.go deleted file mode 100644 index 8e61d820f..000000000 --- a/vendor/github.com/docker/docker/pkg/system/stat_bsd.go +++ /dev/null @@ -1,16 +0,0 @@ -//go:build freebsd || netbsd -// +build freebsd netbsd - -package system // import "github.com/docker/docker/pkg/system" - -import "syscall" - -// fromStatT converts a syscall.Stat_t type to a system.Stat_t type -func fromStatT(s *syscall.Stat_t) (*StatT, error) { - return &StatT{size: s.Size, - mode: uint32(s.Mode), - uid: s.Uid, - gid: s.Gid, - rdev: uint64(s.Rdev), - mtim: s.Mtimespec}, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/stat_darwin.go b/vendor/github.com/docker/docker/pkg/system/stat_darwin.go deleted file mode 100644 index c1c0ee9f3..000000000 --- a/vendor/github.com/docker/docker/pkg/system/stat_darwin.go +++ /dev/null @@ -1,13 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import "syscall" - -// fromStatT converts a syscall.Stat_t type to a system.Stat_t type -func fromStatT(s *syscall.Stat_t) (*StatT, error) { - return &StatT{size: s.Size, - mode: uint32(s.Mode), - uid: s.Uid, - gid: s.Gid, - rdev: uint64(s.Rdev), - mtim: s.Mtimespec}, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/stat_linux.go b/vendor/github.com/docker/docker/pkg/system/stat_linux.go deleted file mode 100644 index 3ac02393f..000000000 --- a/vendor/github.com/docker/docker/pkg/system/stat_linux.go +++ /dev/null @@ -1,20 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import "syscall" - -// fromStatT converts a syscall.Stat_t type to a system.Stat_t type -func fromStatT(s *syscall.Stat_t) (*StatT, error) { - return &StatT{size: s.Size, - mode: s.Mode, - uid: s.Uid, - gid: s.Gid, - // the type is 32bit on mips - rdev: uint64(s.Rdev), //nolint: unconvert - mtim: s.Mtim}, nil -} - -// FromStatT converts a syscall.Stat_t type to a system.Stat_t type -// This is exposed on Linux as pkg/archive/changes uses it. -func FromStatT(s *syscall.Stat_t) (*StatT, error) { - return fromStatT(s) -} diff --git a/vendor/github.com/docker/docker/pkg/system/stat_openbsd.go b/vendor/github.com/docker/docker/pkg/system/stat_openbsd.go deleted file mode 100644 index 756b92d1e..000000000 --- a/vendor/github.com/docker/docker/pkg/system/stat_openbsd.go +++ /dev/null @@ -1,13 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import "syscall" - -// fromStatT converts a syscall.Stat_t type to a system.Stat_t type -func fromStatT(s *syscall.Stat_t) (*StatT, error) { - return &StatT{size: s.Size, - mode: uint32(s.Mode), - uid: s.Uid, - gid: s.Gid, - rdev: uint64(s.Rdev), - mtim: s.Mtim}, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/stat_unix.go b/vendor/github.com/docker/docker/pkg/system/stat_unix.go deleted file mode 100644 index a45ffddf7..000000000 --- a/vendor/github.com/docker/docker/pkg/system/stat_unix.go +++ /dev/null @@ -1,67 +0,0 @@ -//go:build !windows -// +build !windows - -package system // import "github.com/docker/docker/pkg/system" - -import ( - "os" - "syscall" -) - -// StatT type contains status of a file. It contains metadata -// like permission, owner, group, size, etc about a file. -type StatT struct { - mode uint32 - uid uint32 - gid uint32 - rdev uint64 - size int64 - mtim syscall.Timespec -} - -// Mode returns file's permission mode. -func (s StatT) Mode() uint32 { - return s.mode -} - -// UID returns file's user id of owner. -func (s StatT) UID() uint32 { - return s.uid -} - -// GID returns file's group id of owner. -func (s StatT) GID() uint32 { - return s.gid -} - -// Rdev returns file's device ID (if it's special file). -func (s StatT) Rdev() uint64 { - return s.rdev -} - -// Size returns file's size. -func (s StatT) Size() int64 { - return s.size -} - -// Mtim returns file's last modification time. -func (s StatT) Mtim() syscall.Timespec { - return s.mtim -} - -// IsDir reports whether s describes a directory. -func (s StatT) IsDir() bool { - return s.mode&syscall.S_IFDIR != 0 -} - -// Stat takes a path to a file and returns -// a system.StatT type pertaining to that file. -// -// Throws an error if the file does not exist -func Stat(path string) (*StatT, error) { - s := &syscall.Stat_t{} - if err := syscall.Stat(path, s); err != nil { - return nil, &os.PathError{Op: "Stat", Path: path, Err: err} - } - return fromStatT(s) -} diff --git a/vendor/github.com/docker/docker/pkg/system/stat_windows.go b/vendor/github.com/docker/docker/pkg/system/stat_windows.go deleted file mode 100644 index 0ff3af2fa..000000000 --- a/vendor/github.com/docker/docker/pkg/system/stat_windows.go +++ /dev/null @@ -1,49 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "os" - "time" -) - -// StatT type contains status of a file. It contains metadata -// like permission, size, etc about a file. -type StatT struct { - mode os.FileMode - size int64 - mtim time.Time -} - -// Size returns file's size. -func (s StatT) Size() int64 { - return s.size -} - -// Mode returns file's permission mode. -func (s StatT) Mode() os.FileMode { - return s.mode -} - -// Mtim returns file's last modification time. -func (s StatT) Mtim() time.Time { - return s.mtim -} - -// Stat takes a path to a file and returns -// a system.StatT type pertaining to that file. -// -// Throws an error if the file does not exist -func Stat(path string) (*StatT, error) { - fi, err := os.Stat(path) - if err != nil { - return nil, err - } - return fromStatT(&fi) -} - -// fromStatT converts a os.FileInfo type to a system.StatT type -func fromStatT(fi *os.FileInfo) (*StatT, error) { - return &StatT{ - size: (*fi).Size(), - mode: (*fi).Mode(), - mtim: (*fi).ModTime()}, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/utimes_unix.go b/vendor/github.com/docker/docker/pkg/system/utimes_unix.go deleted file mode 100644 index 2768750a0..000000000 --- a/vendor/github.com/docker/docker/pkg/system/utimes_unix.go +++ /dev/null @@ -1,25 +0,0 @@ -//go:build linux || freebsd -// +build linux freebsd - -package system // import "github.com/docker/docker/pkg/system" - -import ( - "syscall" - - "golang.org/x/sys/unix" -) - -// LUtimesNano is used to change access and modification time of the specified path. -// It's used for symbol link file because unix.UtimesNano doesn't support a NOFOLLOW flag atm. -func LUtimesNano(path string, ts []syscall.Timespec) error { - uts := []unix.Timespec{ - unix.NsecToTimespec(syscall.TimespecToNsec(ts[0])), - unix.NsecToTimespec(syscall.TimespecToNsec(ts[1])), - } - err := unix.UtimesNanoAt(unix.AT_FDCWD, path, uts, unix.AT_SYMLINK_NOFOLLOW) - if err != nil && err != unix.ENOSYS { - return err - } - - return nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/utimes_unsupported.go b/vendor/github.com/docker/docker/pkg/system/utimes_unsupported.go deleted file mode 100644 index bfed4af03..000000000 --- a/vendor/github.com/docker/docker/pkg/system/utimes_unsupported.go +++ /dev/null @@ -1,11 +0,0 @@ -//go:build !linux && !freebsd -// +build !linux,!freebsd - -package system // import "github.com/docker/docker/pkg/system" - -import "syscall" - -// LUtimesNano is only supported on linux and freebsd. -func LUtimesNano(path string, ts []syscall.Timespec) error { - return ErrNotSupportedPlatform -} diff --git a/vendor/github.com/docker/docker/pkg/system/xattrs_linux.go b/vendor/github.com/docker/docker/pkg/system/xattrs_linux.go deleted file mode 100644 index 95b609fe7..000000000 --- a/vendor/github.com/docker/docker/pkg/system/xattrs_linux.go +++ /dev/null @@ -1,37 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import "golang.org/x/sys/unix" - -// Lgetxattr retrieves the value of the extended attribute identified by attr -// and associated with the given path in the file system. -// It will returns a nil slice and nil error if the xattr is not set. -func Lgetxattr(path string, attr string) ([]byte, error) { - // Start with a 128 length byte array - dest := make([]byte, 128) - sz, errno := unix.Lgetxattr(path, attr, dest) - - for errno == unix.ERANGE { - // Buffer too small, use zero-sized buffer to get the actual size - sz, errno = unix.Lgetxattr(path, attr, []byte{}) - if errno != nil { - return nil, errno - } - dest = make([]byte, sz) - sz, errno = unix.Lgetxattr(path, attr, dest) - } - - switch { - case errno == unix.ENODATA: - return nil, nil - case errno != nil: - return nil, errno - } - - return dest[:sz], nil -} - -// Lsetxattr sets the value of the extended attribute identified by attr -// and associated with the given path in the file system. -func Lsetxattr(path string, attr string, data []byte, flags int) error { - return unix.Lsetxattr(path, attr, data, flags) -} diff --git a/vendor/github.com/docker/docker/pkg/system/xattrs_unsupported.go b/vendor/github.com/docker/docker/pkg/system/xattrs_unsupported.go deleted file mode 100644 index b165a5dbf..000000000 --- a/vendor/github.com/docker/docker/pkg/system/xattrs_unsupported.go +++ /dev/null @@ -1,14 +0,0 @@ -//go:build !linux -// +build !linux - -package system // import "github.com/docker/docker/pkg/system" - -// Lgetxattr is not supported on platforms other than linux. -func Lgetxattr(path string, attr string) ([]byte, error) { - return nil, ErrNotSupportedPlatform -} - -// Lsetxattr is not supported on platforms other than linux. -func Lsetxattr(path string, attr string, data []byte, flags int) error { - return ErrNotSupportedPlatform -} diff --git a/vendor/github.com/docker/docker/registry/auth.go b/vendor/github.com/docker/docker/registry/auth.go deleted file mode 100644 index dd75a49f3..000000000 --- a/vendor/github.com/docker/docker/registry/auth.go +++ /dev/null @@ -1,196 +0,0 @@ -package registry // import "github.com/docker/docker/registry" - -import ( - "net/http" - "net/url" - "strings" - "time" - - "github.com/docker/distribution/registry/client/auth" - "github.com/docker/distribution/registry/client/auth/challenge" - "github.com/docker/distribution/registry/client/transport" - "github.com/docker/docker/api/types/registry" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" -) - -// AuthClientID is used the ClientID used for the token server -const AuthClientID = "docker" - -type loginCredentialStore struct { - authConfig *registry.AuthConfig -} - -func (lcs loginCredentialStore) Basic(*url.URL) (string, string) { - return lcs.authConfig.Username, lcs.authConfig.Password -} - -func (lcs loginCredentialStore) RefreshToken(*url.URL, string) string { - return lcs.authConfig.IdentityToken -} - -func (lcs loginCredentialStore) SetRefreshToken(u *url.URL, service, token string) { - lcs.authConfig.IdentityToken = token -} - -type staticCredentialStore struct { - auth *registry.AuthConfig -} - -// NewStaticCredentialStore returns a credential store -// which always returns the same credential values. -func NewStaticCredentialStore(auth *registry.AuthConfig) auth.CredentialStore { - return staticCredentialStore{ - auth: auth, - } -} - -func (scs staticCredentialStore) Basic(*url.URL) (string, string) { - if scs.auth == nil { - return "", "" - } - return scs.auth.Username, scs.auth.Password -} - -func (scs staticCredentialStore) RefreshToken(*url.URL, string) string { - if scs.auth == nil { - return "" - } - return scs.auth.IdentityToken -} - -func (scs staticCredentialStore) SetRefreshToken(*url.URL, string, string) { -} - -// loginV2 tries to login to the v2 registry server. The given registry -// endpoint will be pinged to get authorization challenges. These challenges -// will be used to authenticate against the registry to validate credentials. -func loginV2(authConfig *registry.AuthConfig, endpoint APIEndpoint, userAgent string) (string, string, error) { - var ( - endpointStr = strings.TrimRight(endpoint.URL.String(), "/") + "/v2/" - modifiers = Headers(userAgent, nil) - authTransport = transport.NewTransport(newTransport(endpoint.TLSConfig), modifiers...) - credentialAuthConfig = *authConfig - creds = loginCredentialStore{authConfig: &credentialAuthConfig} - ) - - logrus.Debugf("attempting v2 login to registry endpoint %s", endpointStr) - - loginClient, err := v2AuthHTTPClient(endpoint.URL, authTransport, modifiers, creds, nil) - if err != nil { - return "", "", err - } - - req, err := http.NewRequest(http.MethodGet, endpointStr, nil) - if err != nil { - return "", "", err - } - - resp, err := loginClient.Do(req) - if err != nil { - err = translateV2AuthError(err) - return "", "", err - } - defer resp.Body.Close() - - if resp.StatusCode == http.StatusOK { - return "Login Succeeded", credentialAuthConfig.IdentityToken, nil - } - - // TODO(dmcgowan): Attempt to further interpret result, status code and error code string - return "", "", errors.Errorf("login attempt to %s failed with status: %d %s", endpointStr, resp.StatusCode, http.StatusText(resp.StatusCode)) -} - -func v2AuthHTTPClient(endpoint *url.URL, authTransport http.RoundTripper, modifiers []transport.RequestModifier, creds auth.CredentialStore, scopes []auth.Scope) (*http.Client, error) { - challengeManager, err := PingV2Registry(endpoint, authTransport) - if err != nil { - return nil, err - } - - tokenHandlerOptions := auth.TokenHandlerOptions{ - Transport: authTransport, - Credentials: creds, - OfflineAccess: true, - ClientID: AuthClientID, - Scopes: scopes, - } - tokenHandler := auth.NewTokenHandlerWithOptions(tokenHandlerOptions) - basicHandler := auth.NewBasicHandler(creds) - modifiers = append(modifiers, auth.NewAuthorizer(challengeManager, tokenHandler, basicHandler)) - - return &http.Client{ - Transport: transport.NewTransport(authTransport, modifiers...), - Timeout: 15 * time.Second, - }, nil -} - -// ConvertToHostname converts a registry url which has http|https prepended -// to just an hostname. -func ConvertToHostname(url string) string { - stripped := url - if strings.HasPrefix(url, "http://") { - stripped = strings.TrimPrefix(url, "http://") - } else if strings.HasPrefix(url, "https://") { - stripped = strings.TrimPrefix(url, "https://") - } - return strings.SplitN(stripped, "/", 2)[0] -} - -// ResolveAuthConfig matches an auth configuration to a server address or a URL -func ResolveAuthConfig(authConfigs map[string]registry.AuthConfig, index *registry.IndexInfo) registry.AuthConfig { - configKey := GetAuthConfigKey(index) - // First try the happy case - if c, found := authConfigs[configKey]; found || index.Official { - return c - } - - // Maybe they have a legacy config file, we will iterate the keys converting - // them to the new format and testing - for registry, ac := range authConfigs { - if configKey == ConvertToHostname(registry) { - return ac - } - } - - // When all else fails, return an empty auth config - return registry.AuthConfig{} -} - -// PingResponseError is used when the response from a ping -// was received but invalid. -type PingResponseError struct { - Err error -} - -func (err PingResponseError) Error() string { - return err.Err.Error() -} - -// PingV2Registry attempts to ping a v2 registry and on success return a -// challenge manager for the supported authentication types. -// If a response is received but cannot be interpreted, a PingResponseError will be returned. -func PingV2Registry(endpoint *url.URL, transport http.RoundTripper) (challenge.Manager, error) { - pingClient := &http.Client{ - Transport: transport, - Timeout: 15 * time.Second, - } - endpointStr := strings.TrimRight(endpoint.String(), "/") + "/v2/" - req, err := http.NewRequest(http.MethodGet, endpointStr, nil) - if err != nil { - return nil, err - } - resp, err := pingClient.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - challengeManager := challenge.NewSimpleManager() - if err := challengeManager.AddResponse(resp); err != nil { - return nil, PingResponseError{ - Err: err, - } - } - - return challengeManager, nil -} diff --git a/vendor/github.com/docker/docker/registry/config.go b/vendor/github.com/docker/docker/registry/config.go deleted file mode 100644 index 88f0e64ed..000000000 --- a/vendor/github.com/docker/docker/registry/config.go +++ /dev/null @@ -1,448 +0,0 @@ -package registry // import "github.com/docker/docker/registry" - -import ( - "net" - "net/url" - "regexp" - "strconv" - "strings" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types/registry" - "github.com/sirupsen/logrus" -) - -// ServiceOptions holds command line options. -type ServiceOptions struct { - AllowNondistributableArtifacts []string `json:"allow-nondistributable-artifacts,omitempty"` - Mirrors []string `json:"registry-mirrors,omitempty"` - InsecureRegistries []string `json:"insecure-registries,omitempty"` -} - -// serviceConfig holds daemon configuration for the registry service. -type serviceConfig registry.ServiceConfig - -// TODO(thaJeztah) both the "index.docker.io" and "registry-1.docker.io" domains -// are here for historic reasons and backward-compatibility. These domains -// are still supported by Docker Hub (and will continue to be supported), but -// there are new domains already in use, and plans to consolidate all legacy -// domains to new "canonical" domains. Once those domains are decided on, we -// should update these consts (but making sure to preserve compatibility with -// existing installs, clients, and user configuration). -const ( - // DefaultNamespace is the default namespace - DefaultNamespace = "docker.io" - // DefaultRegistryHost is the hostname for the default (Docker Hub) registry - // used for pushing and pulling images. This hostname is hard-coded to handle - // the conversion from image references without registry name (e.g. "ubuntu", - // or "ubuntu:latest"), as well as references using the "docker.io" domain - // name, which is used as canonical reference for images on Docker Hub, but - // does not match the domain-name of Docker Hub's registry. - DefaultRegistryHost = "registry-1.docker.io" - // IndexHostname is the index hostname, used for authentication and image search. - IndexHostname = "index.docker.io" - // IndexServer is used for user auth and image search - IndexServer = "https://" + IndexHostname + "/v1/" - // IndexName is the name of the index - IndexName = "docker.io" -) - -var ( - // DefaultV2Registry is the URI of the default (Docker Hub) registry. - DefaultV2Registry = &url.URL{ - Scheme: "https", - Host: DefaultRegistryHost, - } - - emptyServiceConfig, _ = newServiceConfig(ServiceOptions{}) - validHostPortRegex = regexp.MustCompile(`^` + reference.DomainRegexp.String() + `$`) - - // for mocking in unit tests - lookupIP = net.LookupIP - - // certsDir is used to override defaultCertsDir. - certsDir string -) - -// SetCertsDir allows the default certs directory to be changed. This function -// is used at daemon startup to set the correct location when running in -// rootless mode. -func SetCertsDir(path string) { - certsDir = path -} - -// CertsDir is the directory where certificates are stored. -func CertsDir() string { - if certsDir != "" { - return certsDir - } - return defaultCertsDir -} - -// newServiceConfig returns a new instance of ServiceConfig -func newServiceConfig(options ServiceOptions) (*serviceConfig, error) { - config := &serviceConfig{} - if err := config.loadAllowNondistributableArtifacts(options.AllowNondistributableArtifacts); err != nil { - return nil, err - } - if err := config.loadMirrors(options.Mirrors); err != nil { - return nil, err - } - if err := config.loadInsecureRegistries(options.InsecureRegistries); err != nil { - return nil, err - } - - return config, nil -} - -// copy constructs a new ServiceConfig with a copy of the configuration in config. -func (config *serviceConfig) copy() *registry.ServiceConfig { - ic := make(map[string]*registry.IndexInfo) - for key, value := range config.IndexConfigs { - ic[key] = value - } - return ®istry.ServiceConfig{ - AllowNondistributableArtifactsCIDRs: append([]*registry.NetIPNet(nil), config.AllowNondistributableArtifactsCIDRs...), - AllowNondistributableArtifactsHostnames: append([]string(nil), config.AllowNondistributableArtifactsHostnames...), - InsecureRegistryCIDRs: append([]*registry.NetIPNet(nil), config.InsecureRegistryCIDRs...), - IndexConfigs: ic, - Mirrors: append([]string(nil), config.Mirrors...), - } -} - -// loadAllowNondistributableArtifacts loads allow-nondistributable-artifacts registries into config. -func (config *serviceConfig) loadAllowNondistributableArtifacts(registries []string) error { - cidrs := map[string]*registry.NetIPNet{} - hostnames := map[string]bool{} - - for _, r := range registries { - if _, err := ValidateIndexName(r); err != nil { - return err - } - if hasScheme(r) { - return invalidParamf("allow-nondistributable-artifacts registry %s should not contain '://'", r) - } - - if _, ipnet, err := net.ParseCIDR(r); err == nil { - // Valid CIDR. - cidrs[ipnet.String()] = (*registry.NetIPNet)(ipnet) - } else if err = validateHostPort(r); err == nil { - // Must be `host:port` if not CIDR. - hostnames[r] = true - } else { - return invalidParamWrapf(err, "allow-nondistributable-artifacts registry %s is not valid", r) - } - } - - config.AllowNondistributableArtifactsCIDRs = make([]*registry.NetIPNet, 0, len(cidrs)) - for _, c := range cidrs { - config.AllowNondistributableArtifactsCIDRs = append(config.AllowNondistributableArtifactsCIDRs, c) - } - - config.AllowNondistributableArtifactsHostnames = make([]string, 0, len(hostnames)) - for h := range hostnames { - config.AllowNondistributableArtifactsHostnames = append(config.AllowNondistributableArtifactsHostnames, h) - } - - return nil -} - -// loadMirrors loads mirrors to config, after removing duplicates. -// Returns an error if mirrors contains an invalid mirror. -func (config *serviceConfig) loadMirrors(mirrors []string) error { - mMap := map[string]struct{}{} - unique := []string{} - - for _, mirror := range mirrors { - m, err := ValidateMirror(mirror) - if err != nil { - return err - } - if _, exist := mMap[m]; !exist { - mMap[m] = struct{}{} - unique = append(unique, m) - } - } - - config.Mirrors = unique - - // Configure public registry since mirrors may have changed. - config.IndexConfigs = map[string]*registry.IndexInfo{ - IndexName: { - Name: IndexName, - Mirrors: unique, - Secure: true, - Official: true, - }, - } - - return nil -} - -// loadInsecureRegistries loads insecure registries to config -func (config *serviceConfig) loadInsecureRegistries(registries []string) error { - // Localhost is by default considered as an insecure registry. This is a - // stop-gap for people who are running a private registry on localhost. - registries = append(registries, "127.0.0.0/8") - - var ( - insecureRegistryCIDRs = make([]*registry.NetIPNet, 0) - indexConfigs = make(map[string]*registry.IndexInfo) - ) - -skip: - for _, r := range registries { - // validate insecure registry - if _, err := ValidateIndexName(r); err != nil { - return err - } - if strings.HasPrefix(strings.ToLower(r), "http://") { - logrus.Warnf("insecure registry %s should not contain 'http://' and 'http://' has been removed from the insecure registry config", r) - r = r[7:] - } else if strings.HasPrefix(strings.ToLower(r), "https://") { - logrus.Warnf("insecure registry %s should not contain 'https://' and 'https://' has been removed from the insecure registry config", r) - r = r[8:] - } else if hasScheme(r) { - return invalidParamf("insecure registry %s should not contain '://'", r) - } - // Check if CIDR was passed to --insecure-registry - _, ipnet, err := net.ParseCIDR(r) - if err == nil { - // Valid CIDR. If ipnet is already in config.InsecureRegistryCIDRs, skip. - data := (*registry.NetIPNet)(ipnet) - for _, value := range insecureRegistryCIDRs { - if value.IP.String() == data.IP.String() && value.Mask.String() == data.Mask.String() { - continue skip - } - } - // ipnet is not found, add it in config.InsecureRegistryCIDRs - insecureRegistryCIDRs = append(insecureRegistryCIDRs, data) - } else { - if err := validateHostPort(r); err != nil { - return invalidParamWrapf(err, "insecure registry %s is not valid", r) - } - // Assume `host:port` if not CIDR. - indexConfigs[r] = ®istry.IndexInfo{ - Name: r, - Mirrors: make([]string, 0), - Secure: false, - Official: false, - } - } - } - - // Configure public registry. - indexConfigs[IndexName] = ®istry.IndexInfo{ - Name: IndexName, - Mirrors: config.Mirrors, - Secure: true, - Official: true, - } - config.InsecureRegistryCIDRs = insecureRegistryCIDRs - config.IndexConfigs = indexConfigs - - return nil -} - -// allowNondistributableArtifacts returns true if the provided hostname is part of the list of registries -// that allow push of nondistributable artifacts. -// -// The list can contain elements with CIDR notation to specify a whole subnet. If the subnet contains an IP -// of the registry specified by hostname, true is returned. -// -// hostname should be a URL.Host (`host:port` or `host`) where the `host` part can be either a domain name -// or an IP address. If it is a domain name, then it will be resolved to IP addresses for matching. If -// resolution fails, CIDR matching is not performed. -func (config *serviceConfig) allowNondistributableArtifacts(hostname string) bool { - for _, h := range config.AllowNondistributableArtifactsHostnames { - if h == hostname { - return true - } - } - - return isCIDRMatch(config.AllowNondistributableArtifactsCIDRs, hostname) -} - -// isSecureIndex returns false if the provided indexName is part of the list of insecure registries -// Insecure registries accept HTTP and/or accept HTTPS with certificates from unknown CAs. -// -// The list of insecure registries can contain an element with CIDR notation to specify a whole subnet. -// If the subnet contains one of the IPs of the registry specified by indexName, the latter is considered -// insecure. -// -// indexName should be a URL.Host (`host:port` or `host`) where the `host` part can be either a domain name -// or an IP address. If it is a domain name, then it will be resolved in order to check if the IP is contained -// in a subnet. If the resolving is not successful, isSecureIndex will only try to match hostname to any element -// of insecureRegistries. -func (config *serviceConfig) isSecureIndex(indexName string) bool { - // Check for configured index, first. This is needed in case isSecureIndex - // is called from anything besides newIndexInfo, in order to honor per-index configurations. - if index, ok := config.IndexConfigs[indexName]; ok { - return index.Secure - } - - return !isCIDRMatch(config.InsecureRegistryCIDRs, indexName) -} - -// isCIDRMatch returns true if URLHost matches an element of cidrs. URLHost is a URL.Host (`host:port` or `host`) -// where the `host` part can be either a domain name or an IP address. If it is a domain name, then it will be -// resolved to IP addresses for matching. If resolution fails, false is returned. -func isCIDRMatch(cidrs []*registry.NetIPNet, URLHost string) bool { - host, _, err := net.SplitHostPort(URLHost) - if err != nil { - // Assume URLHost is of the form `host` without the port and go on. - host = URLHost - } - - addrs, err := lookupIP(host) - if err != nil { - ip := net.ParseIP(host) - if ip != nil { - addrs = []net.IP{ip} - } - - // if ip == nil, then `host` is neither an IP nor it could be looked up, - // either because the index is unreachable, or because the index is behind an HTTP proxy. - // So, len(addrs) == 0 and we're not aborting. - } - - // Try CIDR notation only if addrs has any elements, i.e. if `host`'s IP could be determined. - for _, addr := range addrs { - for _, ipnet := range cidrs { - // check if the addr falls in the subnet - if (*net.IPNet)(ipnet).Contains(addr) { - return true - } - } - } - - return false -} - -// ValidateMirror validates an HTTP(S) registry mirror -func ValidateMirror(val string) (string, error) { - uri, err := url.Parse(val) - if err != nil { - return "", invalidParamWrapf(err, "invalid mirror: %q is not a valid URI", val) - } - if uri.Scheme != "http" && uri.Scheme != "https" { - return "", invalidParamf("invalid mirror: unsupported scheme %q in %q", uri.Scheme, uri) - } - if uri.RawQuery != "" || uri.Fragment != "" { - return "", invalidParamf("invalid mirror: query or fragment at end of the URI %q", uri) - } - if uri.User != nil { - // strip password from output - uri.User = url.UserPassword(uri.User.Username(), "xxxxx") - return "", invalidParamf("invalid mirror: username/password not allowed in URI %q", uri) - } - return strings.TrimSuffix(val, "/") + "/", nil -} - -// ValidateIndexName validates an index name. -func ValidateIndexName(val string) (string, error) { - // TODO: upstream this to check to reference package - if val == "index.docker.io" { - val = "docker.io" - } - if strings.HasPrefix(val, "-") || strings.HasSuffix(val, "-") { - return "", invalidParamf("invalid index name (%s). Cannot begin or end with a hyphen", val) - } - return val, nil -} - -func hasScheme(reposName string) bool { - return strings.Contains(reposName, "://") -} - -func validateHostPort(s string) error { - // Split host and port, and in case s can not be splitted, assume host only - host, port, err := net.SplitHostPort(s) - if err != nil { - host = s - port = "" - } - // If match against the `host:port` pattern fails, - // it might be `IPv6:port`, which will be captured by net.ParseIP(host) - if !validHostPortRegex.MatchString(s) && net.ParseIP(host) == nil { - return invalidParamf("invalid host %q", host) - } - if port != "" { - v, err := strconv.Atoi(port) - if err != nil { - return err - } - if v < 0 || v > 65535 { - return invalidParamf("invalid port %q", port) - } - } - return nil -} - -// newIndexInfo returns IndexInfo configuration from indexName -func newIndexInfo(config *serviceConfig, indexName string) (*registry.IndexInfo, error) { - var err error - indexName, err = ValidateIndexName(indexName) - if err != nil { - return nil, err - } - - // Return any configured index info, first. - if index, ok := config.IndexConfigs[indexName]; ok { - return index, nil - } - - // Construct a non-configured index info. - return ®istry.IndexInfo{ - Name: indexName, - Mirrors: make([]string, 0), - Secure: config.isSecureIndex(indexName), - Official: false, - }, nil -} - -// GetAuthConfigKey special-cases using the full index address of the official -// index as the AuthConfig key, and uses the (host)name[:port] for private indexes. -func GetAuthConfigKey(index *registry.IndexInfo) string { - if index.Official { - return IndexServer - } - return index.Name -} - -// newRepositoryInfo validates and breaks down a repository name into a RepositoryInfo -func newRepositoryInfo(config *serviceConfig, name reference.Named) (*RepositoryInfo, error) { - index, err := newIndexInfo(config, reference.Domain(name)) - if err != nil { - return nil, err - } - official := !strings.ContainsRune(reference.FamiliarName(name), '/') - - return &RepositoryInfo{ - Name: reference.TrimNamed(name), - Index: index, - Official: official, - }, nil -} - -// ParseRepositoryInfo performs the breakdown of a repository name into a RepositoryInfo, but -// lacks registry configuration. -func ParseRepositoryInfo(reposName reference.Named) (*RepositoryInfo, error) { - return newRepositoryInfo(emptyServiceConfig, reposName) -} - -// ParseSearchIndexInfo will use repository name to get back an indexInfo. -// -// TODO(thaJeztah) this function is only used by the CLI, and used to get -// information of the registry (to provide credentials if needed). We should -// move this function (or equivalent) to the CLI, as it's doing too much just -// for that. -func ParseSearchIndexInfo(reposName string) (*registry.IndexInfo, error) { - indexName, _ := splitReposSearchTerm(reposName) - - indexInfo, err := newIndexInfo(emptyServiceConfig, indexName) - if err != nil { - return nil, err - } - return indexInfo, nil -} diff --git a/vendor/github.com/docker/docker/registry/config_unix.go b/vendor/github.com/docker/docker/registry/config_unix.go deleted file mode 100644 index 898c6b8a5..000000000 --- a/vendor/github.com/docker/docker/registry/config_unix.go +++ /dev/null @@ -1,17 +0,0 @@ -//go:build !windows -// +build !windows - -package registry // import "github.com/docker/docker/registry" - -// defaultCertsDir is the platform-specific default directory where certificates -// are stored. On Linux, it may be overridden through certsDir, for example, when -// running in rootless mode. -const defaultCertsDir = "/etc/docker/certs.d" - -// cleanPath is used to ensure that a directory name is valid on the target -// platform. It will be passed in something *similar* to a URL such as -// https:/index.docker.io/v1. Not all platforms support directory names -// which contain those characters (such as : on Windows) -func cleanPath(s string) string { - return s -} diff --git a/vendor/github.com/docker/docker/registry/config_windows.go b/vendor/github.com/docker/docker/registry/config_windows.go deleted file mode 100644 index 2674f2818..000000000 --- a/vendor/github.com/docker/docker/registry/config_windows.go +++ /dev/null @@ -1,20 +0,0 @@ -package registry // import "github.com/docker/docker/registry" - -import ( - "os" - "path/filepath" - "strings" -) - -// defaultCertsDir is the platform-specific default directory where certificates -// are stored. On Linux, it may be overridden through certsDir, for example, when -// running in rootless mode. -var defaultCertsDir = os.Getenv("programdata") + `\docker\certs.d` - -// cleanPath is used to ensure that a directory name is valid on the target -// platform. It will be passed in something *similar* to a URL such as -// https:\index.docker.io\v1. Not all platforms support directory names -// which contain those characters (such as : on Windows) -func cleanPath(s string) string { - return filepath.FromSlash(strings.ReplaceAll(s, ":", "")) -} diff --git a/vendor/github.com/docker/docker/registry/endpoint_v1.go b/vendor/github.com/docker/docker/registry/endpoint_v1.go deleted file mode 100644 index 56257dc79..000000000 --- a/vendor/github.com/docker/docker/registry/endpoint_v1.go +++ /dev/null @@ -1,185 +0,0 @@ -package registry // import "github.com/docker/docker/registry" - -import ( - "crypto/tls" - "encoding/json" - "io" - "net/http" - "net/url" - "strings" - - "github.com/docker/distribution/registry/client/transport" - "github.com/docker/docker/api/types/registry" - "github.com/sirupsen/logrus" -) - -// v1PingResult contains the information returned when pinging a registry. It -// indicates the registry's version and whether the registry claims to be a -// standalone registry. -type v1PingResult struct { - // Version is the registry version supplied by the registry in an HTTP - // header - Version string `json:"version"` - // Standalone is set to true if the registry indicates it is a - // standalone registry in the X-Docker-Registry-Standalone - // header - Standalone bool `json:"standalone"` -} - -// v1Endpoint stores basic information about a V1 registry endpoint. -type v1Endpoint struct { - client *http.Client - URL *url.URL - IsSecure bool -} - -// newV1Endpoint parses the given address to return a registry endpoint. -// TODO: remove. This is only used by search. -func newV1Endpoint(index *registry.IndexInfo, headers http.Header) (*v1Endpoint, error) { - tlsConfig, err := newTLSConfig(index.Name, index.Secure) - if err != nil { - return nil, err - } - - endpoint, err := newV1EndpointFromStr(GetAuthConfigKey(index), tlsConfig, headers) - if err != nil { - return nil, err - } - - err = validateEndpoint(endpoint) - if err != nil { - return nil, err - } - - return endpoint, nil -} - -func validateEndpoint(endpoint *v1Endpoint) error { - logrus.Debugf("pinging registry endpoint %s", endpoint) - - // Try HTTPS ping to registry - endpoint.URL.Scheme = "https" - if _, err := endpoint.ping(); err != nil { - if endpoint.IsSecure { - // If registry is secure and HTTPS failed, show user the error and tell them about `--insecure-registry` - // in case that's what they need. DO NOT accept unknown CA certificates, and DO NOT fallback to HTTP. - return invalidParamf("invalid registry endpoint %s: %v. If this private registry supports only HTTP or HTTPS with an unknown CA certificate, please add `--insecure-registry %s` to the daemon's arguments. In the case of HTTPS, if you have access to the registry's CA certificate, no need for the flag; simply place the CA certificate at /etc/docker/certs.d/%s/ca.crt", endpoint, err, endpoint.URL.Host, endpoint.URL.Host) - } - - // If registry is insecure and HTTPS failed, fallback to HTTP. - logrus.WithError(err).Debugf("error from registry %q marked as insecure - insecurely falling back to HTTP", endpoint) - endpoint.URL.Scheme = "http" - - var err2 error - if _, err2 = endpoint.ping(); err2 == nil { - return nil - } - - return invalidParamf("invalid registry endpoint %q. HTTPS attempt: %v. HTTP attempt: %v", endpoint, err, err2) - } - - return nil -} - -// trimV1Address trims the version off the address and returns the -// trimmed address or an error if there is a non-V1 version. -func trimV1Address(address string) (string, error) { - address = strings.TrimSuffix(address, "/") - chunks := strings.Split(address, "/") - apiVersionStr := chunks[len(chunks)-1] - if apiVersionStr == "v1" { - return strings.Join(chunks[:len(chunks)-1], "/"), nil - } - - for k, v := range apiVersions { - if k != APIVersion1 && apiVersionStr == v { - return "", invalidParamf("unsupported V1 version path %s", apiVersionStr) - } - } - - return address, nil -} - -func newV1EndpointFromStr(address string, tlsConfig *tls.Config, headers http.Header) (*v1Endpoint, error) { - if !strings.HasPrefix(address, "http://") && !strings.HasPrefix(address, "https://") { - address = "https://" + address - } - - address, err := trimV1Address(address) - if err != nil { - return nil, err - } - - uri, err := url.Parse(address) - if err != nil { - return nil, invalidParam(err) - } - - // TODO(tiborvass): make sure a ConnectTimeout transport is used - tr := newTransport(tlsConfig) - - return &v1Endpoint{ - IsSecure: tlsConfig == nil || !tlsConfig.InsecureSkipVerify, - URL: uri, - client: httpClient(transport.NewTransport(tr, Headers("", headers)...)), - }, nil -} - -// Get the formatted URL for the root of this registry Endpoint -func (e *v1Endpoint) String() string { - return e.URL.String() + "/v1/" -} - -// ping returns a v1PingResult which indicates whether the registry is standalone or not. -func (e *v1Endpoint) ping() (v1PingResult, error) { - if e.String() == IndexServer { - // Skip the check, we know this one is valid - // (and we never want to fallback to http in case of error) - return v1PingResult{}, nil - } - - logrus.Debugf("attempting v1 ping for registry endpoint %s", e) - pingURL := e.String() + "_ping" - req, err := http.NewRequest(http.MethodGet, pingURL, nil) - if err != nil { - return v1PingResult{}, invalidParam(err) - } - - resp, err := e.client.Do(req) - if err != nil { - return v1PingResult{}, invalidParam(err) - } - - defer resp.Body.Close() - - jsonString, err := io.ReadAll(resp.Body) - if err != nil { - return v1PingResult{}, invalidParamWrapf(err, "error while reading response from %s", pingURL) - } - - // If the header is absent, we assume true for compatibility with earlier - // versions of the registry. default to true - info := v1PingResult{ - Standalone: true, - } - if err := json.Unmarshal(jsonString, &info); err != nil { - logrus.WithError(err).Debug("error unmarshaling _ping response") - // don't stop here. Just assume sane defaults - } - if hdr := resp.Header.Get("X-Docker-Registry-Version"); hdr != "" { - info.Version = hdr - } - logrus.Debugf("v1PingResult.Version: %q", info.Version) - - standalone := resp.Header.Get("X-Docker-Registry-Standalone") - - // Accepted values are "true" (case-insensitive) and "1". - if strings.EqualFold(standalone, "true") || standalone == "1" { - info.Standalone = true - } else if len(standalone) > 0 { - // there is a header set, and it is not "true" or "1", so assume fails - info.Standalone = false - } - logrus.Debugf("v1PingResult.Standalone: %t", info.Standalone) - return info, nil -} diff --git a/vendor/github.com/docker/docker/registry/errors.go b/vendor/github.com/docker/docker/registry/errors.go deleted file mode 100644 index 7dc20ad8f..000000000 --- a/vendor/github.com/docker/docker/registry/errors.go +++ /dev/null @@ -1,36 +0,0 @@ -package registry // import "github.com/docker/docker/registry" - -import ( - "net/url" - - "github.com/docker/distribution/registry/api/errcode" - "github.com/docker/docker/errdefs" - "github.com/pkg/errors" -) - -func translateV2AuthError(err error) error { - switch e := err.(type) { - case *url.Error: - switch e2 := e.Err.(type) { - case errcode.Error: - switch e2.Code { - case errcode.ErrorCodeUnauthorized: - return errdefs.Unauthorized(err) - } - } - } - - return err -} - -func invalidParam(err error) error { - return errdefs.InvalidParameter(err) -} - -func invalidParamf(format string, args ...interface{}) error { - return errdefs.InvalidParameter(errors.Errorf(format, args...)) -} - -func invalidParamWrapf(err error, format string, args ...interface{}) error { - return errdefs.InvalidParameter(errors.Wrapf(err, format, args...)) -} diff --git a/vendor/github.com/docker/docker/registry/registry.go b/vendor/github.com/docker/docker/registry/registry.go deleted file mode 100644 index 5ff39ce5e..000000000 --- a/vendor/github.com/docker/docker/registry/registry.go +++ /dev/null @@ -1,180 +0,0 @@ -// Package registry contains client primitives to interact with a remote Docker registry. -package registry // import "github.com/docker/docker/registry" - -import ( - "crypto/tls" - "net" - "net/http" - "os" - "path/filepath" - "strings" - "time" - - "github.com/docker/distribution/registry/client/transport" - "github.com/docker/go-connections/tlsconfig" - "github.com/sirupsen/logrus" -) - -// HostCertsDir returns the config directory for a specific host. -func HostCertsDir(hostname string) string { - return filepath.Join(CertsDir(), cleanPath(hostname)) -} - -// newTLSConfig constructs a client TLS configuration based on server defaults -func newTLSConfig(hostname string, isSecure bool) (*tls.Config, error) { - // PreferredServerCipherSuites should have no effect - tlsConfig := tlsconfig.ServerDefault() - - tlsConfig.InsecureSkipVerify = !isSecure - - if isSecure && CertsDir() != "" { - hostDir := HostCertsDir(hostname) - logrus.Debugf("hostDir: %s", hostDir) - if err := ReadCertsDirectory(tlsConfig, hostDir); err != nil { - return nil, err - } - } - - return tlsConfig, nil -} - -func hasFile(files []os.DirEntry, name string) bool { - for _, f := range files { - if f.Name() == name { - return true - } - } - return false -} - -// ReadCertsDirectory reads the directory for TLS certificates -// including roots and certificate pairs and updates the -// provided TLS configuration. -func ReadCertsDirectory(tlsConfig *tls.Config, directory string) error { - fs, err := os.ReadDir(directory) - if err != nil && !os.IsNotExist(err) { - return invalidParam(err) - } - - for _, f := range fs { - if strings.HasSuffix(f.Name(), ".crt") { - if tlsConfig.RootCAs == nil { - systemPool, err := tlsconfig.SystemCertPool() - if err != nil { - return invalidParamWrapf(err, "unable to get system cert pool") - } - tlsConfig.RootCAs = systemPool - } - logrus.Debugf("crt: %s", filepath.Join(directory, f.Name())) - data, err := os.ReadFile(filepath.Join(directory, f.Name())) - if err != nil { - return err - } - tlsConfig.RootCAs.AppendCertsFromPEM(data) - } - if strings.HasSuffix(f.Name(), ".cert") { - certName := f.Name() - keyName := certName[:len(certName)-5] + ".key" - logrus.Debugf("cert: %s", filepath.Join(directory, f.Name())) - if !hasFile(fs, keyName) { - return invalidParamf("missing key %s for client certificate %s. CA certificates must use the extension .crt", keyName, certName) - } - cert, err := tls.LoadX509KeyPair(filepath.Join(directory, certName), filepath.Join(directory, keyName)) - if err != nil { - return err - } - tlsConfig.Certificates = append(tlsConfig.Certificates, cert) - } - if strings.HasSuffix(f.Name(), ".key") { - keyName := f.Name() - certName := keyName[:len(keyName)-4] + ".cert" - logrus.Debugf("key: %s", filepath.Join(directory, f.Name())) - if !hasFile(fs, certName) { - return invalidParamf("missing client certificate %s for key %s", certName, keyName) - } - } - } - - return nil -} - -// Headers returns request modifiers with a User-Agent and metaHeaders -func Headers(userAgent string, metaHeaders http.Header) []transport.RequestModifier { - modifiers := []transport.RequestModifier{} - if userAgent != "" { - modifiers = append(modifiers, transport.NewHeaderRequestModifier(http.Header{ - "User-Agent": []string{userAgent}, - })) - } - if metaHeaders != nil { - modifiers = append(modifiers, transport.NewHeaderRequestModifier(metaHeaders)) - } - return modifiers -} - -// httpClient returns an HTTP client structure which uses the given transport -// and contains the necessary headers for redirected requests -func httpClient(transport http.RoundTripper) *http.Client { - return &http.Client{ - Transport: transport, - CheckRedirect: addRequiredHeadersToRedirectedRequests, - } -} - -func trustedLocation(req *http.Request) bool { - var ( - trusteds = []string{"docker.com", "docker.io"} - hostname = strings.SplitN(req.Host, ":", 2)[0] - ) - if req.URL.Scheme != "https" { - return false - } - - for _, trusted := range trusteds { - if hostname == trusted || strings.HasSuffix(hostname, "."+trusted) { - return true - } - } - return false -} - -// addRequiredHeadersToRedirectedRequests adds the necessary redirection headers -// for redirected requests -func addRequiredHeadersToRedirectedRequests(req *http.Request, via []*http.Request) error { - if len(via) != 0 && via[0] != nil { - if trustedLocation(req) && trustedLocation(via[0]) { - req.Header = via[0].Header - return nil - } - for k, v := range via[0].Header { - if k != "Authorization" { - for _, vv := range v { - req.Header.Add(k, vv) - } - } - } - } - return nil -} - -// newTransport returns a new HTTP transport. If tlsConfig is nil, it uses the -// default TLS configuration. -func newTransport(tlsConfig *tls.Config) *http.Transport { - if tlsConfig == nil { - tlsConfig = tlsconfig.ServerDefault() - } - - direct := &net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - } - - return &http.Transport{ - Proxy: http.ProxyFromEnvironment, - DialContext: direct.DialContext, - TLSHandshakeTimeout: 10 * time.Second, - TLSClientConfig: tlsConfig, - // TODO(dmcgowan): Call close idle connections when complete and use keep alive - DisableKeepAlives: true, - } -} diff --git a/vendor/github.com/docker/docker/registry/search.go b/vendor/github.com/docker/docker/registry/search.go deleted file mode 100644 index 60b86ea22..000000000 --- a/vendor/github.com/docker/docker/registry/search.go +++ /dev/null @@ -1,139 +0,0 @@ -package registry // import "github.com/docker/docker/registry" - -import ( - "context" - "net/http" - "strconv" - "strings" - - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/registry" - "github.com/docker/docker/errdefs" - - "github.com/docker/distribution/registry/client/auth" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" -) - -var acceptedSearchFilterTags = map[string]bool{ - "is-automated": true, - "is-official": true, - "stars": true, -} - -// Search queries the public registry for repositories matching the specified -// search term and filters. -func (s *Service) Search(ctx context.Context, searchFilters filters.Args, term string, limit int, authConfig *registry.AuthConfig, headers map[string][]string) ([]registry.SearchResult, error) { - if err := searchFilters.Validate(acceptedSearchFilterTags); err != nil { - return nil, err - } - - isAutomated, err := searchFilters.GetBoolOrDefault("is-automated", false) - if err != nil { - return nil, err - } - isOfficial, err := searchFilters.GetBoolOrDefault("is-official", false) - if err != nil { - return nil, err - } - - hasStarFilter := 0 - if searchFilters.Contains("stars") { - hasStars := searchFilters.Get("stars") - for _, hasStar := range hasStars { - iHasStar, err := strconv.Atoi(hasStar) - if err != nil { - return nil, errdefs.InvalidParameter(errors.Wrapf(err, "invalid filter 'stars=%s'", hasStar)) - } - if iHasStar > hasStarFilter { - hasStarFilter = iHasStar - } - } - } - - unfilteredResult, err := s.searchUnfiltered(ctx, term, limit, authConfig, headers) - if err != nil { - return nil, err - } - - filteredResults := []registry.SearchResult{} - for _, result := range unfilteredResult.Results { - if searchFilters.Contains("is-automated") { - if isAutomated != result.IsAutomated { - continue - } - } - if searchFilters.Contains("is-official") { - if isOfficial != result.IsOfficial { - continue - } - } - if searchFilters.Contains("stars") { - if result.StarCount < hasStarFilter { - continue - } - } - filteredResults = append(filteredResults, result) - } - - return filteredResults, nil -} - -func (s *Service) searchUnfiltered(ctx context.Context, term string, limit int, authConfig *registry.AuthConfig, headers http.Header) (*registry.SearchResults, error) { - // TODO Use ctx when searching for repositories - if hasScheme(term) { - return nil, invalidParamf("invalid repository name: repository name (%s) should not have a scheme", term) - } - - indexName, remoteName := splitReposSearchTerm(term) - - // Search is a long-running operation, just lock s.config to avoid block others. - s.mu.RLock() - index, err := newIndexInfo(s.config, indexName) - s.mu.RUnlock() - - if err != nil { - return nil, err - } - if index.Official { - // If pull "library/foo", it's stored locally under "foo" - remoteName = strings.TrimPrefix(remoteName, "library/") - } - - endpoint, err := newV1Endpoint(index, headers) - if err != nil { - return nil, err - } - - var client *http.Client - if authConfig != nil && authConfig.IdentityToken != "" && authConfig.Username != "" { - creds := NewStaticCredentialStore(authConfig) - scopes := []auth.Scope{ - auth.RegistryScope{ - Name: "catalog", - Actions: []string{"search"}, - }, - } - - // TODO(thaJeztah); is there a reason not to include other headers here? (originally added in 19d48f0b8ba59eea9f2cac4ad1c7977712a6b7ac) - modifiers := Headers(headers.Get("User-Agent"), nil) - v2Client, err := v2AuthHTTPClient(endpoint.URL, endpoint.client.Transport, modifiers, creds, scopes) - if err != nil { - return nil, err - } - // Copy non transport http client features - v2Client.Timeout = endpoint.client.Timeout - v2Client.CheckRedirect = endpoint.client.CheckRedirect - v2Client.Jar = endpoint.client.Jar - - logrus.Debugf("using v2 client for search to %s", endpoint.URL) - client = v2Client - } else { - client = endpoint.client - if err := authorizeClient(client, authConfig, endpoint); err != nil { - return nil, err - } - } - - return newSession(client, endpoint).searchRepositories(remoteName, limit) -} diff --git a/vendor/github.com/docker/docker/registry/service.go b/vendor/github.com/docker/docker/registry/service.go deleted file mode 100644 index b848065b3..000000000 --- a/vendor/github.com/docker/docker/registry/service.go +++ /dev/null @@ -1,167 +0,0 @@ -package registry // import "github.com/docker/docker/registry" - -import ( - "context" - "crypto/tls" - "net/url" - "strings" - "sync" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types/registry" - "github.com/docker/docker/errdefs" - "github.com/sirupsen/logrus" -) - -// Service is a registry service. It tracks configuration data such as a list -// of mirrors. -type Service struct { - config *serviceConfig - mu sync.RWMutex -} - -// NewService returns a new instance of defaultService ready to be -// installed into an engine. -func NewService(options ServiceOptions) (*Service, error) { - config, err := newServiceConfig(options) - - return &Service{config: config}, err -} - -// ServiceConfig returns a copy of the public registry service's configuration. -func (s *Service) ServiceConfig() *registry.ServiceConfig { - s.mu.RLock() - defer s.mu.RUnlock() - return s.config.copy() -} - -// LoadAllowNondistributableArtifacts loads allow-nondistributable-artifacts registries for Service. -func (s *Service) LoadAllowNondistributableArtifacts(registries []string) error { - s.mu.Lock() - defer s.mu.Unlock() - - return s.config.loadAllowNondistributableArtifacts(registries) -} - -// LoadMirrors loads registry mirrors for Service -func (s *Service) LoadMirrors(mirrors []string) error { - s.mu.Lock() - defer s.mu.Unlock() - - return s.config.loadMirrors(mirrors) -} - -// LoadInsecureRegistries loads insecure registries for Service -func (s *Service) LoadInsecureRegistries(registries []string) error { - s.mu.Lock() - defer s.mu.Unlock() - - return s.config.loadInsecureRegistries(registries) -} - -// Auth contacts the public registry with the provided credentials, -// and returns OK if authentication was successful. -// It can be used to verify the validity of a client's credentials. -func (s *Service) Auth(ctx context.Context, authConfig *registry.AuthConfig, userAgent string) (status, token string, err error) { - // TODO Use ctx when searching for repositories - var registryHostName = IndexHostname - - if authConfig.ServerAddress != "" { - serverAddress := authConfig.ServerAddress - if !strings.HasPrefix(serverAddress, "https://") && !strings.HasPrefix(serverAddress, "http://") { - serverAddress = "https://" + serverAddress - } - u, err := url.Parse(serverAddress) - if err != nil { - return "", "", invalidParamWrapf(err, "unable to parse server address") - } - registryHostName = u.Host - } - - // Lookup endpoints for authentication using "LookupPushEndpoints", which - // excludes mirrors to prevent sending credentials of the upstream registry - // to a mirror. - endpoints, err := s.LookupPushEndpoints(registryHostName) - if err != nil { - return "", "", invalidParam(err) - } - - for _, endpoint := range endpoints { - status, token, err = loginV2(authConfig, endpoint, userAgent) - if err == nil { - return - } - if errdefs.IsUnauthorized(err) { - // Failed to authenticate; don't continue with (non-TLS) endpoints. - return status, token, err - } - logrus.WithError(err).Infof("Error logging in to endpoint, trying next endpoint") - } - - return "", "", err -} - -// splitReposSearchTerm breaks a search term into an index name and remote name -func splitReposSearchTerm(reposName string) (string, string) { - nameParts := strings.SplitN(reposName, "/", 2) - if len(nameParts) == 1 || (!strings.Contains(nameParts[0], ".") && - !strings.Contains(nameParts[0], ":") && nameParts[0] != "localhost") { - // This is a Docker Hub repository (ex: samalba/hipache or ubuntu), - // use the default Docker Hub registry (docker.io) - return IndexName, reposName - } - return nameParts[0], nameParts[1] -} - -// ResolveRepository splits a repository name into its components -// and configuration of the associated registry. -func (s *Service) ResolveRepository(name reference.Named) (*RepositoryInfo, error) { - s.mu.RLock() - defer s.mu.RUnlock() - return newRepositoryInfo(s.config, name) -} - -// APIEndpoint represents a remote API endpoint -type APIEndpoint struct { - Mirror bool - URL *url.URL - Version APIVersion - AllowNondistributableArtifacts bool - Official bool - TrimHostname bool - TLSConfig *tls.Config -} - -// LookupPullEndpoints creates a list of v2 endpoints to try to pull from, in order of preference. -// It gives preference to mirrors over the actual registry, and HTTPS over plain HTTP. -func (s *Service) LookupPullEndpoints(hostname string) (endpoints []APIEndpoint, err error) { - s.mu.RLock() - defer s.mu.RUnlock() - - return s.lookupV2Endpoints(hostname) -} - -// LookupPushEndpoints creates a list of v2 endpoints to try to push to, in order of preference. -// It gives preference to HTTPS over plain HTTP. Mirrors are not included. -func (s *Service) LookupPushEndpoints(hostname string) (endpoints []APIEndpoint, err error) { - s.mu.RLock() - defer s.mu.RUnlock() - - allEndpoints, err := s.lookupV2Endpoints(hostname) - if err == nil { - for _, endpoint := range allEndpoints { - if !endpoint.Mirror { - endpoints = append(endpoints, endpoint) - } - } - } - return endpoints, err -} - -// IsInsecureRegistry returns true if the registry at given host is configured as -// insecure registry. -func (s *Service) IsInsecureRegistry(host string) bool { - s.mu.RLock() - defer s.mu.RUnlock() - return !s.config.isSecureIndex(host) -} diff --git a/vendor/github.com/docker/docker/registry/service_v2.go b/vendor/github.com/docker/docker/registry/service_v2.go deleted file mode 100644 index c8c545d21..000000000 --- a/vendor/github.com/docker/docker/registry/service_v2.go +++ /dev/null @@ -1,80 +0,0 @@ -package registry // import "github.com/docker/docker/registry" - -import ( - "net/url" - "strings" - - "github.com/docker/go-connections/tlsconfig" -) - -func (s *Service) lookupV2Endpoints(hostname string) (endpoints []APIEndpoint, err error) { - ana := s.config.allowNondistributableArtifacts(hostname) - - if hostname == DefaultNamespace || hostname == IndexHostname { - for _, mirror := range s.config.Mirrors { - if !strings.HasPrefix(mirror, "http://") && !strings.HasPrefix(mirror, "https://") { - mirror = "https://" + mirror - } - mirrorURL, err := url.Parse(mirror) - if err != nil { - return nil, invalidParam(err) - } - mirrorTLSConfig, err := newTLSConfig(mirrorURL.Host, s.config.isSecureIndex(mirrorURL.Host)) - if err != nil { - return nil, err - } - endpoints = append(endpoints, APIEndpoint{ - URL: mirrorURL, - Version: APIVersion2, - Mirror: true, - TrimHostname: true, - TLSConfig: mirrorTLSConfig, - }) - } - endpoints = append(endpoints, APIEndpoint{ - URL: DefaultV2Registry, - Version: APIVersion2, - Official: true, - TrimHostname: true, - TLSConfig: tlsconfig.ServerDefault(), - - AllowNondistributableArtifacts: ana, - }) - - return endpoints, nil - } - - tlsConfig, err := newTLSConfig(hostname, s.config.isSecureIndex(hostname)) - if err != nil { - return nil, err - } - - endpoints = []APIEndpoint{ - { - URL: &url.URL{ - Scheme: "https", - Host: hostname, - }, - Version: APIVersion2, - AllowNondistributableArtifacts: ana, - TrimHostname: true, - TLSConfig: tlsConfig, - }, - } - - if tlsConfig.InsecureSkipVerify { - endpoints = append(endpoints, APIEndpoint{ - URL: &url.URL{ - Scheme: "http", - Host: hostname, - }, - Version: APIVersion2, - AllowNondistributableArtifacts: ana, - TrimHostname: true, - // used to check if supposed to be secure via InsecureSkipVerify - TLSConfig: tlsConfig, - }) - } - - return endpoints, nil -} diff --git a/vendor/github.com/docker/docker/registry/session.go b/vendor/github.com/docker/docker/registry/session.go deleted file mode 100644 index 86a5cd9ed..000000000 --- a/vendor/github.com/docker/docker/registry/session.go +++ /dev/null @@ -1,216 +0,0 @@ -package registry // import "github.com/docker/docker/registry" - -import ( - // this is required for some certificates - _ "crypto/sha512" - "encoding/json" - "fmt" - "net/http" - "net/http/cookiejar" - "net/url" - "strings" - "sync" - - "github.com/docker/docker/api/types/registry" - "github.com/docker/docker/errdefs" - "github.com/docker/docker/pkg/ioutils" - "github.com/docker/docker/pkg/jsonmessage" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" -) - -// A session is used to communicate with a V1 registry -type session struct { - indexEndpoint *v1Endpoint - client *http.Client -} - -type authTransport struct { - http.RoundTripper - *registry.AuthConfig - - alwaysSetBasicAuth bool - token []string - - mu sync.Mutex // guards modReq - modReq map[*http.Request]*http.Request // original -> modified -} - -// newAuthTransport handles the auth layer when communicating with a v1 registry (private or official) -// -// For private v1 registries, set alwaysSetBasicAuth to true. -// -// For the official v1 registry, if there isn't already an Authorization header in the request, -// but there is an X-Docker-Token header set to true, then Basic Auth will be used to set the Authorization header. -// After sending the request with the provided base http.RoundTripper, if an X-Docker-Token header, representing -// a token, is present in the response, then it gets cached and sent in the Authorization header of all subsequent -// requests. -// -// If the server sends a token without the client having requested it, it is ignored. -// -// This RoundTripper also has a CancelRequest method important for correct timeout handling. -func newAuthTransport(base http.RoundTripper, authConfig *registry.AuthConfig, alwaysSetBasicAuth bool) *authTransport { - if base == nil { - base = http.DefaultTransport - } - return &authTransport{ - RoundTripper: base, - AuthConfig: authConfig, - alwaysSetBasicAuth: alwaysSetBasicAuth, - modReq: make(map[*http.Request]*http.Request), - } -} - -// 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 { - // shallow copy of the struct - r2 := new(http.Request) - *r2 = *r - // deep copy of the Header - r2.Header = make(http.Header, len(r.Header)) - for k, s := range r.Header { - r2.Header[k] = append([]string(nil), s...) - } - - return r2 -} - -// RoundTrip changes an HTTP request's headers to add the necessary -// authentication-related headers -func (tr *authTransport) RoundTrip(orig *http.Request) (*http.Response, error) { - // Authorization should not be set on 302 redirect for untrusted locations. - // This logic mirrors the behavior in addRequiredHeadersToRedirectedRequests. - // As the authorization logic is currently implemented in RoundTrip, - // a 302 redirect is detected by looking at the Referrer header as go http package adds said header. - // This is safe as Docker doesn't set Referrer in other scenarios. - if orig.Header.Get("Referer") != "" && !trustedLocation(orig) { - return tr.RoundTripper.RoundTrip(orig) - } - - req := cloneRequest(orig) - tr.mu.Lock() - tr.modReq[orig] = req - tr.mu.Unlock() - - if tr.alwaysSetBasicAuth { - if tr.AuthConfig == nil { - return nil, errors.New("unexpected error: empty auth config") - } - req.SetBasicAuth(tr.Username, tr.Password) - return tr.RoundTripper.RoundTrip(req) - } - - // Don't override - if req.Header.Get("Authorization") == "" { - if req.Header.Get("X-Docker-Token") == "true" && tr.AuthConfig != nil && len(tr.Username) > 0 { - req.SetBasicAuth(tr.Username, tr.Password) - } else if len(tr.token) > 0 { - req.Header.Set("Authorization", "Token "+strings.Join(tr.token, ",")) - } - } - resp, err := tr.RoundTripper.RoundTrip(req) - if err != nil { - tr.mu.Lock() - delete(tr.modReq, orig) - tr.mu.Unlock() - return nil, err - } - if len(resp.Header["X-Docker-Token"]) > 0 { - tr.token = resp.Header["X-Docker-Token"] - } - resp.Body = &ioutils.OnEOFReader{ - Rc: resp.Body, - Fn: func() { - tr.mu.Lock() - delete(tr.modReq, orig) - tr.mu.Unlock() - }, - } - return resp, nil -} - -// CancelRequest cancels an in-flight request by closing its connection. -func (tr *authTransport) CancelRequest(req *http.Request) { - type canceler interface { - CancelRequest(*http.Request) - } - if cr, ok := tr.RoundTripper.(canceler); ok { - tr.mu.Lock() - modReq := tr.modReq[req] - delete(tr.modReq, req) - tr.mu.Unlock() - cr.CancelRequest(modReq) - } -} - -func authorizeClient(client *http.Client, authConfig *registry.AuthConfig, endpoint *v1Endpoint) error { - var alwaysSetBasicAuth bool - - // If we're working with a standalone private registry over HTTPS, send Basic Auth headers - // alongside all our requests. - if endpoint.String() != IndexServer && endpoint.URL.Scheme == "https" { - info, err := endpoint.ping() - if err != nil { - return err - } - if info.Standalone && authConfig != nil { - logrus.Debugf("Endpoint %s is eligible for private registry. Enabling decorator.", endpoint.String()) - alwaysSetBasicAuth = true - } - } - - // Annotate the transport unconditionally so that v2 can - // properly fallback on v1 when an image is not found. - client.Transport = newAuthTransport(client.Transport, authConfig, alwaysSetBasicAuth) - - jar, err := cookiejar.New(nil) - if err != nil { - return errdefs.System(errors.New("cookiejar.New is not supposed to return an error")) - } - client.Jar = jar - - return nil -} - -func newSession(client *http.Client, endpoint *v1Endpoint) *session { - return &session{ - client: client, - indexEndpoint: endpoint, - } -} - -// defaultSearchLimit is the default value for maximum number of returned search results. -const defaultSearchLimit = 25 - -// searchRepositories performs a search against the remote repository -func (r *session) searchRepositories(term string, limit int) (*registry.SearchResults, error) { - if limit == 0 { - limit = defaultSearchLimit - } - if limit < 1 || limit > 100 { - return nil, invalidParamf("limit %d is outside the range of [1, 100]", limit) - } - logrus.Debugf("Index server: %s", r.indexEndpoint) - u := r.indexEndpoint.String() + "search?q=" + url.QueryEscape(term) + "&n=" + url.QueryEscape(fmt.Sprintf("%d", limit)) - - req, err := http.NewRequest(http.MethodGet, u, nil) - if err != nil { - return nil, invalidParamWrapf(err, "error building request") - } - // Have the AuthTransport send authentication, when logged in. - req.Header.Set("X-Docker-Token", "true") - res, err := r.client.Do(req) - if err != nil { - return nil, errdefs.System(err) - } - defer res.Body.Close() - if res.StatusCode != http.StatusOK { - return nil, errdefs.Unknown(&jsonmessage.JSONError{ - Message: fmt.Sprintf("Unexpected status code %d", res.StatusCode), - Code: res.StatusCode, - }) - } - result := new(registry.SearchResults) - return result, errors.Wrap(json.NewDecoder(res.Body).Decode(result), "error decoding registry search results") -} diff --git a/vendor/github.com/docker/docker/registry/types.go b/vendor/github.com/docker/docker/registry/types.go deleted file mode 100644 index 37094737f..000000000 --- a/vendor/github.com/docker/docker/registry/types.go +++ /dev/null @@ -1,39 +0,0 @@ -package registry // import "github.com/docker/docker/registry" - -import ( - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types/registry" -) - -// APIVersion is an integral representation of an API version (presently -// either 1 or 2) -type APIVersion int - -func (av APIVersion) String() string { - return apiVersions[av] -} - -// API Version identifiers. -const ( - APIVersion1 APIVersion = 1 - APIVersion2 APIVersion = 2 -) - -var apiVersions = map[APIVersion]string{ - APIVersion1: "v1", - APIVersion2: "v2", -} - -// RepositoryInfo describes a repository -type RepositoryInfo struct { - Name reference.Named - // Index points to registry information - Index *registry.IndexInfo - // Official indicates whether the repository is considered official. - // If the registry is official, and the normalized name does not - // contain a '/' (e.g. "foo"), then it is considered an official repo. - Official bool - // Class represents the class of the repository, such as "plugin" - // or "image". - Class string -} diff --git a/vendor/github.com/docker/go-connections/LICENSE b/vendor/github.com/docker/go-connections/LICENSE deleted file mode 100644 index b55b37bc3..000000000 --- a/vendor/github.com/docker/go-connections/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2015 Docker, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - https://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/docker/go-connections/nat/nat.go b/vendor/github.com/docker/go-connections/nat/nat.go deleted file mode 100644 index 4049d780c..000000000 --- a/vendor/github.com/docker/go-connections/nat/nat.go +++ /dev/null @@ -1,240 +0,0 @@ -// Package nat is a convenience package for manipulation of strings describing network ports. -package nat - -import ( - "fmt" - "net" - "strconv" - "strings" -) - -// PortBinding represents a binding between a Host IP address and a Host Port -type PortBinding struct { - // HostIP is the host IP Address - HostIP string `json:"HostIp"` - // HostPort is the host port number - HostPort string -} - -// PortMap is a collection of PortBinding indexed by Port -type PortMap map[Port][]PortBinding - -// PortSet is a collection of structs indexed by Port -type PortSet map[Port]struct{} - -// Port is a string containing port number and protocol in the format "80/tcp" -type Port string - -// NewPort creates a new instance of a Port given a protocol and port number or port range -func NewPort(proto, port string) (Port, error) { - // Check for parsing issues on "port" now so we can avoid having - // to check it later on. - - portStartInt, portEndInt, err := ParsePortRangeToInt(port) - if err != nil { - return "", err - } - - if portStartInt == portEndInt { - return Port(fmt.Sprintf("%d/%s", portStartInt, proto)), nil - } - return Port(fmt.Sprintf("%d-%d/%s", portStartInt, portEndInt, proto)), nil -} - -// ParsePort parses the port number string and returns an int -func ParsePort(rawPort string) (int, error) { - if len(rawPort) == 0 { - return 0, nil - } - port, err := strconv.ParseUint(rawPort, 10, 16) - if err != nil { - return 0, err - } - return int(port), nil -} - -// ParsePortRangeToInt parses the port range string and returns start/end ints -func ParsePortRangeToInt(rawPort string) (int, int, error) { - if len(rawPort) == 0 { - return 0, 0, nil - } - start, end, err := ParsePortRange(rawPort) - if err != nil { - return 0, 0, err - } - return int(start), int(end), nil -} - -// Proto returns the protocol of a Port -func (p Port) Proto() string { - proto, _ := SplitProtoPort(string(p)) - return proto -} - -// Port returns the port number of a Port -func (p Port) Port() string { - _, port := SplitProtoPort(string(p)) - return port -} - -// Int returns the port number of a Port as an int -func (p Port) Int() int { - portStr := p.Port() - // We don't need to check for an error because we're going to - // assume that any error would have been found, and reported, in NewPort() - port, _ := ParsePort(portStr) - return port -} - -// Range returns the start/end port numbers of a Port range as ints -func (p Port) Range() (int, int, error) { - return ParsePortRangeToInt(p.Port()) -} - -// SplitProtoPort splits a port in the format of proto/port -func SplitProtoPort(rawPort string) (string, string) { - parts := strings.Split(rawPort, "/") - l := len(parts) - if len(rawPort) == 0 || l == 0 || len(parts[0]) == 0 { - return "", "" - } - if l == 1 { - return "tcp", rawPort - } - if len(parts[1]) == 0 { - return "tcp", parts[0] - } - return parts[1], parts[0] -} - -func validateProto(proto string) bool { - for _, availableProto := range []string{"tcp", "udp", "sctp"} { - if availableProto == proto { - return true - } - } - return false -} - -// ParsePortSpecs receives port specs in the format of ip:public:private/proto and parses -// these in to the internal types -func ParsePortSpecs(ports []string) (map[Port]struct{}, map[Port][]PortBinding, error) { - var ( - exposedPorts = make(map[Port]struct{}, len(ports)) - bindings = make(map[Port][]PortBinding) - ) - for _, rawPort := range ports { - portMappings, err := ParsePortSpec(rawPort) - if err != nil { - return nil, nil, err - } - - for _, portMapping := range portMappings { - port := portMapping.Port - if _, exists := exposedPorts[port]; !exists { - exposedPorts[port] = struct{}{} - } - bslice, exists := bindings[port] - if !exists { - bslice = []PortBinding{} - } - bindings[port] = append(bslice, portMapping.Binding) - } - } - return exposedPorts, bindings, nil -} - -// PortMapping is a data object mapping a Port to a PortBinding -type PortMapping struct { - Port Port - Binding PortBinding -} - -func splitParts(rawport string) (string, string, string) { - parts := strings.Split(rawport, ":") - n := len(parts) - containerPort := parts[n-1] - - switch n { - case 1: - return "", "", containerPort - case 2: - return "", parts[0], containerPort - case 3: - return parts[0], parts[1], containerPort - default: - return strings.Join(parts[:n-2], ":"), parts[n-2], containerPort - } -} - -// ParsePortSpec parses a port specification string into a slice of PortMappings -func ParsePortSpec(rawPort string) ([]PortMapping, error) { - var proto string - ip, hostPort, containerPort := splitParts(rawPort) - proto, containerPort = SplitProtoPort(containerPort) - - if ip != "" && ip[0] == '[' { - // Strip [] from IPV6 addresses - rawIP, _, err := net.SplitHostPort(ip + ":") - if err != nil { - return nil, fmt.Errorf("invalid IP address %v: %w", ip, err) - } - ip = rawIP - } - if ip != "" && net.ParseIP(ip) == nil { - return nil, fmt.Errorf("invalid IP address: %s", ip) - } - if containerPort == "" { - return nil, fmt.Errorf("no port specified: %s", rawPort) - } - - startPort, endPort, err := ParsePortRange(containerPort) - if err != nil { - return nil, fmt.Errorf("invalid containerPort: %s", containerPort) - } - - var startHostPort, endHostPort uint64 = 0, 0 - if len(hostPort) > 0 { - startHostPort, endHostPort, err = ParsePortRange(hostPort) - if err != nil { - return nil, fmt.Errorf("invalid hostPort: %s", hostPort) - } - } - - if hostPort != "" && (endPort-startPort) != (endHostPort-startHostPort) { - // Allow host port range iff containerPort is not a range. - // In this case, use the host port range as the dynamic - // host port range to allocate into. - if endPort != startPort { - return nil, fmt.Errorf("invalid ranges specified for container and host Ports: %s and %s", containerPort, hostPort) - } - } - - if !validateProto(strings.ToLower(proto)) { - return nil, fmt.Errorf("invalid proto: %s", proto) - } - - ports := []PortMapping{} - for i := uint64(0); i <= (endPort - startPort); i++ { - containerPort = strconv.FormatUint(startPort+i, 10) - if len(hostPort) > 0 { - hostPort = strconv.FormatUint(startHostPort+i, 10) - } - // Set hostPort to a range only if there is a single container port - // and a dynamic host port. - if startPort == endPort && startHostPort != endHostPort { - hostPort = fmt.Sprintf("%s-%s", hostPort, strconv.FormatUint(endHostPort, 10)) - } - port, err := NewPort(strings.ToLower(proto), containerPort) - if err != nil { - return nil, err - } - - binding := PortBinding{ - HostIP: ip, - HostPort: hostPort, - } - ports = append(ports, PortMapping{Port: port, Binding: binding}) - } - return ports, nil -} diff --git a/vendor/github.com/docker/go-connections/nat/parse.go b/vendor/github.com/docker/go-connections/nat/parse.go deleted file mode 100644 index e4b53e8a3..000000000 --- a/vendor/github.com/docker/go-connections/nat/parse.go +++ /dev/null @@ -1,33 +0,0 @@ -package nat - -import ( - "fmt" - "strconv" - "strings" -) - -// ParsePortRange parses and validates the specified string as a port-range (8000-9000) -func ParsePortRange(ports string) (uint64, uint64, error) { - if ports == "" { - return 0, 0, fmt.Errorf("empty string specified for ports") - } - if !strings.Contains(ports, "-") { - start, err := strconv.ParseUint(ports, 10, 16) - end := start - return start, end, err - } - - parts := strings.Split(ports, "-") - start, err := strconv.ParseUint(parts[0], 10, 16) - if err != nil { - return 0, 0, err - } - end, err := strconv.ParseUint(parts[1], 10, 16) - if err != nil { - return 0, 0, err - } - if end < start { - return 0, 0, fmt.Errorf("invalid range specified for port: %s", ports) - } - return start, end, nil -} diff --git a/vendor/github.com/docker/go-connections/nat/sort.go b/vendor/github.com/docker/go-connections/nat/sort.go deleted file mode 100644 index b6eed145e..000000000 --- a/vendor/github.com/docker/go-connections/nat/sort.go +++ /dev/null @@ -1,96 +0,0 @@ -package nat - -import ( - "sort" - "strings" -) - -type portSorter struct { - ports []Port - by func(i, j Port) bool -} - -func (s *portSorter) Len() int { - return len(s.ports) -} - -func (s *portSorter) Swap(i, j int) { - s.ports[i], s.ports[j] = s.ports[j], s.ports[i] -} - -func (s *portSorter) Less(i, j int) bool { - ip := s.ports[i] - jp := s.ports[j] - - return s.by(ip, jp) -} - -// Sort sorts a list of ports using the provided predicate -// This function should compare `i` and `j`, returning true if `i` is -// considered to be less than `j` -func Sort(ports []Port, predicate func(i, j Port) bool) { - s := &portSorter{ports, predicate} - sort.Sort(s) -} - -type portMapEntry struct { - port Port - binding PortBinding -} - -type portMapSorter []portMapEntry - -func (s portMapSorter) Len() int { return len(s) } -func (s portMapSorter) Swap(i, j int) { s[i], s[j] = s[j], s[i] } - -// Less sorts the port so that the order is: -// 1. port with larger specified bindings -// 2. larger port -// 3. port with tcp protocol -func (s portMapSorter) Less(i, j int) bool { - pi, pj := s[i].port, s[j].port - hpi, hpj := toInt(s[i].binding.HostPort), toInt(s[j].binding.HostPort) - return hpi > hpj || pi.Int() > pj.Int() || (pi.Int() == pj.Int() && strings.ToLower(pi.Proto()) == "tcp") -} - -// SortPortMap sorts the list of ports and their respected mapping. The ports -// will explicit HostPort will be placed first. -func SortPortMap(ports []Port, bindings PortMap) { - s := portMapSorter{} - for _, p := range ports { - if binding, ok := bindings[p]; ok && len(binding) > 0 { - for _, b := range binding { - s = append(s, portMapEntry{port: p, binding: b}) - } - bindings[p] = []PortBinding{} - } else { - s = append(s, portMapEntry{port: p}) - } - } - - sort.Sort(s) - var ( - i int - pm = make(map[Port]struct{}) - ) - // reorder ports - for _, entry := range s { - if _, ok := pm[entry.port]; !ok { - ports[i] = entry.port - pm[entry.port] = struct{}{} - i++ - } - // reorder bindings for this port - if _, ok := bindings[entry.port]; ok { - bindings[entry.port] = append(bindings[entry.port], entry.binding) - } - } -} - -func toInt(s string) uint64 { - i, _, err := ParsePortRange(s) - if err != nil { - i = 0 - } - return i -} diff --git a/vendor/github.com/docker/go-connections/sockets/README.md b/vendor/github.com/docker/go-connections/sockets/README.md deleted file mode 100644 index e69de29bb..000000000 diff --git a/vendor/github.com/docker/go-connections/sockets/inmem_socket.go b/vendor/github.com/docker/go-connections/sockets/inmem_socket.go deleted file mode 100644 index 99846ffdd..000000000 --- a/vendor/github.com/docker/go-connections/sockets/inmem_socket.go +++ /dev/null @@ -1,81 +0,0 @@ -package sockets - -import ( - "errors" - "net" - "sync" -) - -var errClosed = errors.New("use of closed network connection") - -// InmemSocket implements net.Listener using in-memory only connections. -type InmemSocket struct { - chConn chan net.Conn - chClose chan struct{} - addr string - mu sync.Mutex -} - -// dummyAddr is used to satisfy net.Addr for the in-mem socket -// it is just stored as a string and returns the string for all calls -type dummyAddr string - -// NewInmemSocket creates an in-memory only net.Listener -// The addr argument can be any string, but is used to satisfy the `Addr()` part -// of the net.Listener interface -func NewInmemSocket(addr string, bufSize int) *InmemSocket { - return &InmemSocket{ - chConn: make(chan net.Conn, bufSize), - chClose: make(chan struct{}), - addr: addr, - } -} - -// Addr returns the socket's addr string to satisfy net.Listener -func (s *InmemSocket) Addr() net.Addr { - return dummyAddr(s.addr) -} - -// Accept implements the Accept method in the Listener interface; it waits for the next call and returns a generic Conn. -func (s *InmemSocket) Accept() (net.Conn, error) { - select { - case conn := <-s.chConn: - return conn, nil - case <-s.chClose: - return nil, errClosed - } -} - -// Close closes the listener. It will be unavailable for use once closed. -func (s *InmemSocket) Close() error { - s.mu.Lock() - defer s.mu.Unlock() - select { - case <-s.chClose: - default: - close(s.chClose) - } - return nil -} - -// Dial is used to establish a connection with the in-mem server -func (s *InmemSocket) Dial(network, addr string) (net.Conn, error) { - srvConn, clientConn := net.Pipe() - select { - case s.chConn <- srvConn: - case <-s.chClose: - return nil, errClosed - } - - return clientConn, nil -} - -// Network returns the addr string, satisfies net.Addr -func (a dummyAddr) Network() string { - return string(a) -} - -// String returns the string form -func (a dummyAddr) String() string { - return string(a) -} diff --git a/vendor/github.com/docker/go-connections/sockets/proxy.go b/vendor/github.com/docker/go-connections/sockets/proxy.go deleted file mode 100644 index c897cb02a..000000000 --- a/vendor/github.com/docker/go-connections/sockets/proxy.go +++ /dev/null @@ -1,28 +0,0 @@ -package sockets - -import ( - "net" - "os" - "strings" -) - -// GetProxyEnv allows access to the uppercase and the lowercase forms of -// proxy-related variables. See the Go specification for details on these -// variables. https://golang.org/pkg/net/http/ -func GetProxyEnv(key string) string { - proxyValue := os.Getenv(strings.ToUpper(key)) - if proxyValue == "" { - return os.Getenv(strings.ToLower(key)) - } - return proxyValue -} - -// DialerFromEnvironment was previously used to configure a net.Dialer to route -// connections through a SOCKS proxy. -// DEPRECATED: SOCKS proxies are now supported by configuring only -// http.Transport.Proxy, and no longer require changing http.Transport.Dial. -// Therefore, only sockets.ConfigureTransport() needs to be called, and any -// sockets.DialerFromEnvironment() calls can be dropped. -func DialerFromEnvironment(direct *net.Dialer) (*net.Dialer, error) { - return direct, nil -} diff --git a/vendor/github.com/docker/go-connections/sockets/sockets.go b/vendor/github.com/docker/go-connections/sockets/sockets.go deleted file mode 100644 index b0eae239d..000000000 --- a/vendor/github.com/docker/go-connections/sockets/sockets.go +++ /dev/null @@ -1,37 +0,0 @@ -// Package sockets provides helper functions to create and configure Unix or TCP sockets. -package sockets - -import ( - "errors" - "net" - "net/http" - "time" -) - -const defaultTimeout = 10 * time.Second - -// ErrProtocolNotAvailable is returned when a given transport protocol is not provided by the operating system. -var ErrProtocolNotAvailable = errors.New("protocol not available") - -// ConfigureTransport configures the specified [http.Transport] according to the specified proto -// and addr. -// -// If the proto is unix (using a unix socket to communicate) or npipe the compression is disabled. -// For other protos, compression is enabled. If you want to manually enable/disable compression, -// make sure you do it _after_ any subsequent calls to ConfigureTransport is made against the same -// [http.Transport]. -func ConfigureTransport(tr *http.Transport, proto, addr string) error { - switch proto { - case "unix": - return configureUnixTransport(tr, proto, addr) - case "npipe": - return configureNpipeTransport(tr, proto, addr) - default: - tr.Proxy = http.ProxyFromEnvironment - tr.DisableCompression = false - tr.DialContext = (&net.Dialer{ - Timeout: defaultTimeout, - }).DialContext - } - return nil -} diff --git a/vendor/github.com/docker/go-connections/sockets/sockets_unix.go b/vendor/github.com/docker/go-connections/sockets/sockets_unix.go deleted file mode 100644 index 78a34a980..000000000 --- a/vendor/github.com/docker/go-connections/sockets/sockets_unix.go +++ /dev/null @@ -1,39 +0,0 @@ -//go:build !windows - -package sockets - -import ( - "context" - "fmt" - "net" - "net/http" - "syscall" - "time" -) - -const maxUnixSocketPathSize = len(syscall.RawSockaddrUnix{}.Path) - -func configureUnixTransport(tr *http.Transport, proto, addr string) error { - if len(addr) > maxUnixSocketPathSize { - return fmt.Errorf("unix socket path %q is too long", addr) - } - // No need for compression in local communications. - tr.DisableCompression = true - dialer := &net.Dialer{ - Timeout: defaultTimeout, - } - tr.DialContext = func(ctx context.Context, _, _ string) (net.Conn, error) { - return dialer.DialContext(ctx, proto, addr) - } - return nil -} - -func configureNpipeTransport(tr *http.Transport, proto, addr string) error { - return ErrProtocolNotAvailable -} - -// DialPipe connects to a Windows named pipe. -// This is not supported on other OSes. -func DialPipe(_ string, _ time.Duration) (net.Conn, error) { - return nil, syscall.EAFNOSUPPORT -} diff --git a/vendor/github.com/docker/go-connections/sockets/sockets_windows.go b/vendor/github.com/docker/go-connections/sockets/sockets_windows.go deleted file mode 100644 index 7acafc5a2..000000000 --- a/vendor/github.com/docker/go-connections/sockets/sockets_windows.go +++ /dev/null @@ -1,28 +0,0 @@ -package sockets - -import ( - "context" - "net" - "net/http" - "time" - - "github.com/Microsoft/go-winio" -) - -func configureUnixTransport(tr *http.Transport, proto, addr string) error { - return ErrProtocolNotAvailable -} - -func configureNpipeTransport(tr *http.Transport, proto, addr string) error { - // No need for compression in local communications. - tr.DisableCompression = true - tr.DialContext = func(ctx context.Context, _, _ string) (net.Conn, error) { - return winio.DialPipeContext(ctx, addr) - } - return nil -} - -// DialPipe connects to a Windows named pipe. -func DialPipe(addr string, timeout time.Duration) (net.Conn, error) { - return winio.DialPipe(addr, &timeout) -} diff --git a/vendor/github.com/docker/go-connections/sockets/tcp_socket.go b/vendor/github.com/docker/go-connections/sockets/tcp_socket.go deleted file mode 100644 index 53cbb6c79..000000000 --- a/vendor/github.com/docker/go-connections/sockets/tcp_socket.go +++ /dev/null @@ -1,22 +0,0 @@ -// Package sockets provides helper functions to create and configure Unix or TCP sockets. -package sockets - -import ( - "crypto/tls" - "net" -) - -// NewTCPSocket creates a TCP socket listener with the specified address and -// the specified tls configuration. If TLSConfig is set, will encapsulate the -// TCP listener inside a TLS one. -func NewTCPSocket(addr string, tlsConfig *tls.Config) (net.Listener, error) { - l, err := net.Listen("tcp", addr) - if err != nil { - return nil, err - } - if tlsConfig != nil { - tlsConfig.NextProtos = []string{"http/1.1"} - l = tls.NewListener(l, tlsConfig) - } - return l, nil -} diff --git a/vendor/github.com/docker/go-connections/sockets/unix_socket.go b/vendor/github.com/docker/go-connections/sockets/unix_socket.go deleted file mode 100644 index b9233521e..000000000 --- a/vendor/github.com/docker/go-connections/sockets/unix_socket.go +++ /dev/null @@ -1,126 +0,0 @@ -//go:build !windows - -/* -Package sockets is a simple unix domain socket wrapper. - -# Usage - -For example: - - import( - "fmt" - "net" - "os" - "github.com/docker/go-connections/sockets" - ) - - func main() { - l, err := sockets.NewUnixSocketWithOpts("/path/to/sockets", - sockets.WithChown(0,0),sockets.WithChmod(0660)) - if err != nil { - panic(err) - } - echoStr := "hello" - - go func() { - for { - conn, err := l.Accept() - if err != nil { - return - } - conn.Write([]byte(echoStr)) - conn.Close() - } - }() - - conn, err := net.Dial("unix", path) - if err != nil { - t.Fatal(err) - } - - buf := make([]byte, 5) - if _, err := conn.Read(buf); err != nil { - panic(err) - } else if string(buf) != echoStr { - panic(fmt.Errorf("msg may lost")) - } - } -*/ -package sockets - -import ( - "net" - "os" - "syscall" -) - -// SockOption sets up socket file's creating option -type SockOption func(string) error - -// WithChown modifies the socket file's uid and gid -func WithChown(uid, gid int) SockOption { - return func(path string) error { - if err := os.Chown(path, uid, gid); err != nil { - return err - } - return nil - } -} - -// WithChmod modifies socket file's access mode. -func WithChmod(mask os.FileMode) SockOption { - return func(path string) error { - if err := os.Chmod(path, mask); err != nil { - return err - } - return nil - } -} - -// NewUnixSocketWithOpts creates a unix socket with the specified options. -// By default, socket permissions are 0000 (i.e.: no access for anyone); pass -// WithChmod() and WithChown() to set the desired ownership and permissions. -// -// This function temporarily changes the system's "umask" to 0777 to work around -// a race condition between creating the socket and setting its permissions. While -// this should only be for a short duration, it may affect other processes that -// create files/directories during that period. -func NewUnixSocketWithOpts(path string, opts ...SockOption) (net.Listener, error) { - if err := syscall.Unlink(path); err != nil && !os.IsNotExist(err) { - return nil, err - } - - // net.Listen does not allow for permissions to be set. As a result, when - // specifying custom permissions ("WithChmod()"), there is a short time - // between creating the socket and applying the permissions, during which - // the socket permissions are Less restrictive than desired. - // - // To work around this limitation of net.Listen(), we temporarily set the - // umask to 0777, which forces the socket to be created with 000 permissions - // (i.e.: no access for anyone). After that, WithChmod() must be used to set - // the desired permissions. - // - // We don't use "defer" here, to reset the umask to its original value as soon - // as possible. Ideally we'd be able to detect if WithChmod() was passed as - // an option, and skip changing umask if default permissions are used. - origUmask := syscall.Umask(0o777) - l, err := net.Listen("unix", path) - syscall.Umask(origUmask) - if err != nil { - return nil, err - } - - for _, op := range opts { - if err := op(path); err != nil { - _ = l.Close() - return nil, err - } - } - - return l, nil -} - -// NewUnixSocket creates a unix socket with the specified path and group. -func NewUnixSocket(path string, gid int) (net.Listener, error) { - return NewUnixSocketWithOpts(path, WithChown(0, gid), WithChmod(0o660)) -} diff --git a/vendor/github.com/docker/go-connections/tlsconfig/certpool.go b/vendor/github.com/docker/go-connections/tlsconfig/certpool.go deleted file mode 100644 index f84c624ba..000000000 --- a/vendor/github.com/docker/go-connections/tlsconfig/certpool.go +++ /dev/null @@ -1,16 +0,0 @@ -package tlsconfig - -import ( - "crypto/x509" - "runtime" -) - -// SystemCertPool returns a copy of the system cert pool, -// returns an error if failed to load or empty pool on windows. -func SystemCertPool() (*x509.CertPool, error) { - certpool, err := x509.SystemCertPool() - if err != nil && runtime.GOOS == "windows" { - return x509.NewCertPool(), nil - } - return certpool, err -} diff --git a/vendor/github.com/docker/go-connections/tlsconfig/config.go b/vendor/github.com/docker/go-connections/tlsconfig/config.go deleted file mode 100644 index 606c98a38..000000000 --- a/vendor/github.com/docker/go-connections/tlsconfig/config.go +++ /dev/null @@ -1,261 +0,0 @@ -// Package tlsconfig provides primitives to retrieve secure-enough TLS configurations for both clients and servers. -// -// As a reminder from https://golang.org/pkg/crypto/tls/#Config: -// -// A Config structure is used to configure a TLS client or server. After one has been passed to a TLS function it must not be modified. -// A Config may be reused; the tls package will also not modify it. -package tlsconfig - -import ( - "crypto/tls" - "crypto/x509" - "encoding/pem" - "errors" - "fmt" - "os" -) - -// Options represents the information needed to create client and server TLS configurations. -type Options struct { - CAFile string - - // If either CertFile or KeyFile is empty, Client() will not load them - // preventing the client from authenticating to the server. - // However, Server() requires them and will error out if they are empty. - CertFile string - KeyFile string - - // client-only option - InsecureSkipVerify bool - // server-only option - ClientAuth tls.ClientAuthType - // If ExclusiveRootPools is set, then if a CA file is provided, the root pool used for TLS - // creds will include exclusively the roots in that CA file. If no CA file is provided, - // the system pool will be used. - ExclusiveRootPools bool - MinVersion uint16 - // If Passphrase is set, it will be used to decrypt a TLS private key - // if the key is encrypted. - // - // Deprecated: Use of encrypted TLS private keys has been deprecated, and - // will be removed in a future release. Golang has deprecated support for - // legacy PEM encryption (as specified in RFC 1423), as it is insecure by - // design (see https://go-review.googlesource.com/c/go/+/264159). - Passphrase string -} - -// Extra (server-side) accepted CBC cipher suites - will phase out in the future -var acceptedCBCCiphers = []uint16{ - tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, - tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, - tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, - tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, -} - -// DefaultServerAcceptedCiphers should be uses by code which already has a crypto/tls -// options struct but wants to use a commonly accepted set of TLS cipher suites, with -// known weak algorithms removed. -var DefaultServerAcceptedCiphers = append(clientCipherSuites, acceptedCBCCiphers...) - -// ServerDefault returns a secure-enough TLS configuration for the server TLS configuration. -func ServerDefault(ops ...func(*tls.Config)) *tls.Config { - tlsConfig := &tls.Config{ - // Avoid fallback by default to SSL protocols < TLS1.2 - MinVersion: tls.VersionTLS12, - PreferServerCipherSuites: true, - CipherSuites: DefaultServerAcceptedCiphers, - } - - for _, op := range ops { - op(tlsConfig) - } - - return tlsConfig -} - -// ClientDefault returns a secure-enough TLS configuration for the client TLS configuration. -func ClientDefault(ops ...func(*tls.Config)) *tls.Config { - tlsConfig := &tls.Config{ - // Prefer TLS1.2 as the client minimum - MinVersion: tls.VersionTLS12, - CipherSuites: clientCipherSuites, - } - - for _, op := range ops { - op(tlsConfig) - } - - return tlsConfig -} - -// certPool returns an X.509 certificate pool from `caFile`, the certificate file. -func certPool(caFile string, exclusivePool bool) (*x509.CertPool, error) { - // If we should verify the server, we need to load a trusted ca - var ( - certPool *x509.CertPool - err error - ) - if exclusivePool { - certPool = x509.NewCertPool() - } else { - certPool, err = SystemCertPool() - if err != nil { - return nil, fmt.Errorf("failed to read system certificates: %v", err) - } - } - pemData, err := os.ReadFile(caFile) - if err != nil { - return nil, fmt.Errorf("could not read CA certificate %q: %v", caFile, err) - } - if !certPool.AppendCertsFromPEM(pemData) { - return nil, fmt.Errorf("failed to append certificates from PEM file: %q", caFile) - } - return certPool, nil -} - -// allTLSVersions lists all the TLS versions and is used by the code that validates -// a uint16 value as a TLS version. -var allTLSVersions = map[uint16]struct{}{ - tls.VersionTLS10: {}, - tls.VersionTLS11: {}, - tls.VersionTLS12: {}, - tls.VersionTLS13: {}, -} - -// isValidMinVersion checks that the input value is a valid tls minimum version -func isValidMinVersion(version uint16) bool { - _, ok := allTLSVersions[version] - return ok -} - -// adjustMinVersion sets the MinVersion on `config`, the input configuration. -// It assumes the current MinVersion on the `config` is the lowest allowed. -func adjustMinVersion(options Options, config *tls.Config) error { - if options.MinVersion > 0 { - if !isValidMinVersion(options.MinVersion) { - return fmt.Errorf("invalid minimum TLS version: %x", options.MinVersion) - } - if options.MinVersion < config.MinVersion { - return fmt.Errorf("requested minimum TLS version is too low. Should be at-least: %x", config.MinVersion) - } - config.MinVersion = options.MinVersion - } - - return nil -} - -// IsErrEncryptedKey returns true if the 'err' is an error of incorrect -// password when trying to decrypt a TLS private key. -// -// Deprecated: Use of encrypted TLS private keys has been deprecated, and -// will be removed in a future release. Golang has deprecated support for -// legacy PEM encryption (as specified in RFC 1423), as it is insecure by -// design (see https://go-review.googlesource.com/c/go/+/264159). -func IsErrEncryptedKey(err error) bool { - return errors.Is(err, x509.IncorrectPasswordError) -} - -// getPrivateKey returns the private key in 'keyBytes', in PEM-encoded format. -// If the private key is encrypted, 'passphrase' is used to decrypted the -// private key. -func getPrivateKey(keyBytes []byte, passphrase string) ([]byte, error) { - // this section makes some small changes to code from notary/tuf/utils/x509.go - pemBlock, _ := pem.Decode(keyBytes) - if pemBlock == nil { - return nil, fmt.Errorf("no valid private key found") - } - - var err error - if x509.IsEncryptedPEMBlock(pemBlock) { //nolint:staticcheck // Ignore SA1019 (IsEncryptedPEMBlock is deprecated) - keyBytes, err = x509.DecryptPEMBlock(pemBlock, []byte(passphrase)) //nolint:staticcheck // Ignore SA1019 (DecryptPEMBlock is deprecated) - if err != nil { - return nil, fmt.Errorf("private key is encrypted, but could not decrypt it: %w", err) - } - keyBytes = pem.EncodeToMemory(&pem.Block{Type: pemBlock.Type, Bytes: keyBytes}) - } - - return keyBytes, nil -} - -// getCert returns a Certificate from the CertFile and KeyFile in 'options', -// if the key is encrypted, the Passphrase in 'options' will be used to -// decrypt it. -func getCert(options Options) ([]tls.Certificate, error) { - if options.CertFile == "" && options.KeyFile == "" { - return nil, nil - } - - cert, err := os.ReadFile(options.CertFile) - if err != nil { - return nil, err - } - - prKeyBytes, err := os.ReadFile(options.KeyFile) - if err != nil { - return nil, err - } - - prKeyBytes, err = getPrivateKey(prKeyBytes, options.Passphrase) - if err != nil { - return nil, err - } - - tlsCert, err := tls.X509KeyPair(cert, prKeyBytes) - if err != nil { - return nil, err - } - - return []tls.Certificate{tlsCert}, nil -} - -// Client returns a TLS configuration meant to be used by a client. -func Client(options Options) (*tls.Config, error) { - tlsConfig := ClientDefault() - tlsConfig.InsecureSkipVerify = options.InsecureSkipVerify - if !options.InsecureSkipVerify && options.CAFile != "" { - CAs, err := certPool(options.CAFile, options.ExclusiveRootPools) - if err != nil { - return nil, err - } - tlsConfig.RootCAs = CAs - } - - tlsCerts, err := getCert(options) - if err != nil { - return nil, fmt.Errorf("could not load X509 key pair: %w", err) - } - tlsConfig.Certificates = tlsCerts - - if err := adjustMinVersion(options, tlsConfig); err != nil { - return nil, err - } - - return tlsConfig, nil -} - -// Server returns a TLS configuration meant to be used by a server. -func Server(options Options) (*tls.Config, error) { - tlsConfig := ServerDefault() - tlsConfig.ClientAuth = options.ClientAuth - tlsCert, err := tls.LoadX509KeyPair(options.CertFile, options.KeyFile) - if err != nil { - if os.IsNotExist(err) { - return nil, fmt.Errorf("could not load X509 key pair (cert: %q, key: %q): %v", options.CertFile, options.KeyFile, err) - } - return nil, fmt.Errorf("error reading X509 key pair - make sure the key is not encrypted (cert: %q, key: %q): %v", options.CertFile, options.KeyFile, err) - } - tlsConfig.Certificates = []tls.Certificate{tlsCert} - if options.ClientAuth >= tls.VerifyClientCertIfGiven && options.CAFile != "" { - CAs, err := certPool(options.CAFile, options.ExclusiveRootPools) - if err != nil { - return nil, err - } - tlsConfig.ClientCAs = CAs - } - - if err := adjustMinVersion(options, tlsConfig); err != nil { - return nil, err - } - - return tlsConfig, nil -} diff --git a/vendor/github.com/docker/go-connections/tlsconfig/config_client_ciphers.go b/vendor/github.com/docker/go-connections/tlsconfig/config_client_ciphers.go deleted file mode 100644 index a82f9fa52..000000000 --- a/vendor/github.com/docker/go-connections/tlsconfig/config_client_ciphers.go +++ /dev/null @@ -1,14 +0,0 @@ -// Package tlsconfig provides primitives to retrieve secure-enough TLS configurations for both clients and servers. -package tlsconfig - -import ( - "crypto/tls" -) - -// Client TLS cipher suites (dropping CBC ciphers for client preferred suite set) -var clientCipherSuites = []uint16{ - tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, - tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, - tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, - tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, -} diff --git a/vendor/github.com/docker/go-metrics/CONTRIBUTING.md b/vendor/github.com/docker/go-metrics/CONTRIBUTING.md deleted file mode 100644 index b8a512c36..000000000 --- a/vendor/github.com/docker/go-metrics/CONTRIBUTING.md +++ /dev/null @@ -1,55 +0,0 @@ -# Contributing - -## Sign your work - -The sign-off is a simple line at the end of the explanation for the patch. Your -signature certifies that you wrote the patch or otherwise have the right to pass -it on as an open-source patch. The rules are pretty simple: if you can certify -the below (from [developercertificate.org](http://developercertificate.org/)): - -``` -Developer Certificate of Origin -Version 1.1 - -Copyright (C) 2004, 2006 The Linux Foundation and its contributors. -660 York Street, Suite 102, -San Francisco, CA 94110 USA - -Everyone is permitted to copy and distribute verbatim copies of this -license document, but changing it is not allowed. - -Developer's Certificate of Origin 1.1 - -By making a contribution to this project, I certify that: - -(a) The contribution was created in whole or in part by me and I - have the right to submit it under the open source license - indicated in the file; or - -(b) The contribution is based upon previous work that, to the best - of my knowledge, is covered under an appropriate open source - license and I have the right under that license to submit that - work with modifications, whether created in whole or in part - by me, under the same open source license (unless I am - permitted to submit under a different license), as indicated - in the file; or - -(c) The contribution was provided directly to me by some other - person who certified (a), (b) or (c) and I have not modified - it. - -(d) I understand and agree that this project and the contribution - are public and that a record of the contribution (including all - personal information I submit with it, including my sign-off) is - maintained indefinitely and may be redistributed consistent with - this project or the open source license(s) involved. -``` - -Then you just add a line to every git commit message: - - Signed-off-by: Joe Smith - -Use your real name (sorry, no pseudonyms or anonymous contributions.) - -If you set your `user.name` and `user.email` git configs, you can sign your -commit automatically with `git commit -s`. diff --git a/vendor/github.com/docker/go-metrics/LICENSE b/vendor/github.com/docker/go-metrics/LICENSE deleted file mode 100644 index 8f3fee627..000000000 --- a/vendor/github.com/docker/go-metrics/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2013-2016 Docker, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - https://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/docker/go-metrics/LICENSE.docs b/vendor/github.com/docker/go-metrics/LICENSE.docs deleted file mode 100644 index e26cd4fc8..000000000 --- a/vendor/github.com/docker/go-metrics/LICENSE.docs +++ /dev/null @@ -1,425 +0,0 @@ -Attribution-ShareAlike 4.0 International - -======================================================================= - -Creative Commons Corporation ("Creative Commons") is not a law firm and -does not provide legal services or legal advice. Distribution of -Creative Commons public licenses does not create a lawyer-client or -other relationship. Creative Commons makes its licenses and related -information available on an "as-is" basis. Creative Commons gives no -warranties regarding its licenses, any material licensed under their -terms and conditions, or any related information. Creative Commons -disclaims all liability for damages resulting from their use to the -fullest extent possible. - -Using Creative Commons Public Licenses - -Creative Commons public licenses provide a standard set of terms and -conditions that creators and other rights holders may use to share -original works of authorship and other material subject to copyright -and certain other rights specified in the public license below. The -following considerations are for informational purposes only, are not -exhaustive, and do not form part of our licenses. - - Considerations for licensors: Our public licenses are - intended for use by those authorized to give the public - permission to use material in ways otherwise restricted by - copyright and certain other rights. Our licenses are - irrevocable. Licensors should read and understand the terms - and conditions of the license they choose before applying it. - Licensors should also secure all rights necessary before - applying our licenses so that the public can reuse the - material as expected. Licensors should clearly mark any - material not subject to the license. This includes other CC- - licensed material, or material used under an exception or - limitation to copyright. More considerations for licensors: - wiki.creativecommons.org/Considerations_for_licensors - - Considerations for the public: By using one of our public - licenses, a licensor grants the public permission to use the - licensed material under specified terms and conditions. If - the licensor's permission is not necessary for any reason--for - example, because of any applicable exception or limitation to - copyright--then that use is not regulated by the license. Our - licenses grant only permissions under copyright and certain - other rights that a licensor has authority to grant. Use of - the licensed material may still be restricted for other - reasons, including because others have copyright or other - rights in the material. A licensor may make special requests, - such as asking that all changes be marked or described. - Although not required by our licenses, you are encouraged to - respect those requests where reasonable. More_considerations - for the public: - wiki.creativecommons.org/Considerations_for_licensees - -======================================================================= - -Creative Commons Attribution-ShareAlike 4.0 International Public -License - -By exercising the Licensed Rights (defined below), You accept and agree -to be bound by the terms and conditions of this Creative Commons -Attribution-ShareAlike 4.0 International Public License ("Public -License"). To the extent this Public License may be interpreted as a -contract, You are granted the Licensed Rights in consideration of Your -acceptance of these terms and conditions, and the Licensor grants You -such rights in consideration of benefits the Licensor receives from -making the Licensed Material available under these terms and -conditions. - - -Section 1 -- Definitions. - - a. Adapted Material means material subject to Copyright and Similar - Rights that is derived from or based upon the Licensed Material - and in which the Licensed Material is translated, altered, - arranged, transformed, or otherwise modified in a manner requiring - permission under the Copyright and Similar Rights held by the - Licensor. For purposes of this Public License, where the Licensed - Material is a musical work, performance, or sound recording, - Adapted Material is always produced where the Licensed Material is - synched in timed relation with a moving image. - - b. Adapter's License means the license You apply to Your Copyright - and Similar Rights in Your contributions to Adapted Material in - accordance with the terms and conditions of this Public License. - - c. BY-SA Compatible License means a license listed at - creativecommons.org/compatiblelicenses, approved by Creative - Commons as essentially the equivalent of this Public License. - - d. Copyright and Similar Rights means copyright and/or similar rights - closely related to copyright including, without limitation, - performance, broadcast, sound recording, and Sui Generis Database - Rights, without regard to how the rights are labeled or - categorized. For purposes of this Public License, the rights - specified in Section 2(b)(1)-(2) are not Copyright and Similar - Rights. - - e. Effective Technological Measures means those measures that, in the - absence of proper authority, may not be circumvented under laws - fulfilling obligations under Article 11 of the WIPO Copyright - Treaty adopted on December 20, 1996, and/or similar international - agreements. - - f. Exceptions and Limitations means fair use, fair dealing, and/or - any other exception or limitation to Copyright and Similar Rights - that applies to Your use of the Licensed Material. - - g. License Elements means the license attributes listed in the name - of a Creative Commons Public License. The License Elements of this - Public License are Attribution and ShareAlike. - - h. Licensed Material means the artistic or literary work, database, - or other material to which the Licensor applied this Public - License. - - i. Licensed Rights means the rights granted to You subject to the - terms and conditions of this Public License, which are limited to - all Copyright and Similar Rights that apply to Your use of the - Licensed Material and that the Licensor has authority to license. - - j. Licensor means the individual(s) or entity(ies) granting rights - under this Public License. - - k. Share means to provide material to the public by any means or - process that requires permission under the Licensed Rights, such - as reproduction, public display, public performance, distribution, - dissemination, communication, or importation, and to make material - available to the public including in ways that members of the - public may access the material from a place and at a time - individually chosen by them. - - l. Sui Generis Database Rights means rights other than copyright - resulting from Directive 96/9/EC of the European Parliament and of - the Council of 11 March 1996 on the legal protection of databases, - as amended and/or succeeded, as well as other essentially - equivalent rights anywhere in the world. - - m. You means the individual or entity exercising the Licensed Rights - under this Public License. Your has a corresponding meaning. - - -Section 2 -- Scope. - - a. License grant. - - 1. Subject to the terms and conditions of this Public License, - the Licensor hereby grants You a worldwide, royalty-free, - non-sublicensable, non-exclusive, irrevocable license to - exercise the Licensed Rights in the Licensed Material to: - - a. reproduce and Share the Licensed Material, in whole or - in part; and - - b. produce, reproduce, and Share Adapted Material. - - 2. Exceptions and Limitations. For the avoidance of doubt, where - Exceptions and Limitations apply to Your use, this Public - License does not apply, and You do not need to comply with - its terms and conditions. - - 3. Term. The term of this Public License is specified in Section - 6(a). - - 4. Media and formats; technical modifications allowed. The - Licensor authorizes You to exercise the Licensed Rights in - all media and formats whether now known or hereafter created, - and to make technical modifications necessary to do so. The - Licensor waives and/or agrees not to assert any right or - authority to forbid You from making technical modifications - necessary to exercise the Licensed Rights, including - technical modifications necessary to circumvent Effective - Technological Measures. For purposes of this Public License, - simply making modifications authorized by this Section 2(a) - (4) never produces Adapted Material. - - 5. Downstream recipients. - - a. Offer from the Licensor -- Licensed Material. Every - recipient of the Licensed Material automatically - receives an offer from the Licensor to exercise the - Licensed Rights under the terms and conditions of this - Public License. - - b. Additional offer from the Licensor -- Adapted Material. - Every recipient of Adapted Material from You - automatically receives an offer from the Licensor to - exercise the Licensed Rights in the Adapted Material - under the conditions of the Adapter's License You apply. - - c. No downstream restrictions. You may not offer or impose - any additional or different terms or conditions on, or - apply any Effective Technological Measures to, the - Licensed Material if doing so restricts exercise of the - Licensed Rights by any recipient of the Licensed - Material. - - 6. No endorsement. Nothing in this Public License constitutes or - may be construed as permission to assert or imply that You - are, or that Your use of the Licensed Material is, connected - with, or sponsored, endorsed, or granted official status by, - the Licensor or others designated to receive attribution as - provided in Section 3(a)(1)(A)(i). - - b. Other rights. - - 1. Moral rights, such as the right of integrity, are not - licensed under this Public License, nor are publicity, - privacy, and/or other similar personality rights; however, to - the extent possible, the Licensor waives and/or agrees not to - assert any such rights held by the Licensor to the limited - extent necessary to allow You to exercise the Licensed - Rights, but not otherwise. - - 2. Patent and trademark rights are not licensed under this - Public License. - - 3. To the extent possible, the Licensor waives any right to - collect royalties from You for the exercise of the Licensed - Rights, whether directly or through a collecting society - under any voluntary or waivable statutory or compulsory - licensing scheme. In all other cases the Licensor expressly - reserves any right to collect such royalties. - - -Section 3 -- License Conditions. - -Your exercise of the Licensed Rights is expressly made subject to the -following conditions. - - a. Attribution. - - 1. If You Share the Licensed Material (including in modified - form), You must: - - a. retain the following if it is supplied by the Licensor - with the Licensed Material: - - i. identification of the creator(s) of the Licensed - Material and any others designated to receive - attribution, in any reasonable manner requested by - the Licensor (including by pseudonym if - designated); - - ii. a copyright notice; - - iii. a notice that refers to this Public License; - - iv. a notice that refers to the disclaimer of - warranties; - - v. a URI or hyperlink to the Licensed Material to the - extent reasonably practicable; - - b. indicate if You modified the Licensed Material and - retain an indication of any previous modifications; and - - c. indicate the Licensed Material is licensed under this - Public License, and include the text of, or the URI or - hyperlink to, this Public License. - - 2. You may satisfy the conditions in Section 3(a)(1) in any - reasonable manner based on the medium, means, and context in - which You Share the Licensed Material. For example, it may be - reasonable to satisfy the conditions by providing a URI or - hyperlink to a resource that includes the required - information. - - 3. If requested by the Licensor, You must remove any of the - information required by Section 3(a)(1)(A) to the extent - reasonably practicable. - - b. ShareAlike. - - In addition to the conditions in Section 3(a), if You Share - Adapted Material You produce, the following conditions also apply. - - 1. The Adapter's License You apply must be a Creative Commons - license with the same License Elements, this version or - later, or a BY-SA Compatible License. - - 2. You must include the text of, or the URI or hyperlink to, the - Adapter's License You apply. You may satisfy this condition - in any reasonable manner based on the medium, means, and - context in which You Share Adapted Material. - - 3. You may not offer or impose any additional or different terms - or conditions on, or apply any Effective Technological - Measures to, Adapted Material that restrict exercise of the - rights granted under the Adapter's License You apply. - - -Section 4 -- Sui Generis Database Rights. - -Where the Licensed Rights include Sui Generis Database Rights that -apply to Your use of the Licensed Material: - - a. for the avoidance of doubt, Section 2(a)(1) grants You the right - to extract, reuse, reproduce, and Share all or a substantial - portion of the contents of the database; - - b. if You include all or a substantial portion of the database - contents in a database in which You have Sui Generis Database - Rights, then the database in which You have Sui Generis Database - Rights (but not its individual contents) is Adapted Material, - - including for purposes of Section 3(b); and - c. You must comply with the conditions in Section 3(a) if You Share - all or a substantial portion of the contents of the database. - -For the avoidance of doubt, this Section 4 supplements and does not -replace Your obligations under this Public License where the Licensed -Rights include other Copyright and Similar Rights. - - -Section 5 -- Disclaimer of Warranties and Limitation of Liability. - - a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE - EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS - AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF - ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, - IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, - WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR - PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, - ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT - KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT - ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. - - b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE - TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, - NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, - INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, - COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR - USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN - ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR - DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR - IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. - - c. The disclaimer of warranties and limitation of liability provided - above shall be interpreted in a manner that, to the extent - possible, most closely approximates an absolute disclaimer and - waiver of all liability. - - -Section 6 -- Term and Termination. - - a. This Public License applies for the term of the Copyright and - Similar Rights licensed here. However, if You fail to comply with - this Public License, then Your rights under this Public License - terminate automatically. - - b. Where Your right to use the Licensed Material has terminated under - Section 6(a), it reinstates: - - 1. automatically as of the date the violation is cured, provided - it is cured within 30 days of Your discovery of the - violation; or - - 2. upon express reinstatement by the Licensor. - - For the avoidance of doubt, this Section 6(b) does not affect any - right the Licensor may have to seek remedies for Your violations - of this Public License. - - c. For the avoidance of doubt, the Licensor may also offer the - Licensed Material under separate terms or conditions or stop - distributing the Licensed Material at any time; however, doing so - will not terminate this Public License. - - d. Sections 1, 5, 6, 7, and 8 survive termination of this Public - License. - - -Section 7 -- Other Terms and Conditions. - - a. The Licensor shall not be bound by any additional or different - terms or conditions communicated by You unless expressly agreed. - - b. Any arrangements, understandings, or agreements regarding the - Licensed Material not stated herein are separate from and - independent of the terms and conditions of this Public License. - - -Section 8 -- Interpretation. - - a. For the avoidance of doubt, this Public License does not, and - shall not be interpreted to, reduce, limit, restrict, or impose - conditions on any use of the Licensed Material that could lawfully - be made without permission under this Public License. - - b. To the extent possible, if any provision of this Public License is - deemed unenforceable, it shall be automatically reformed to the - minimum extent necessary to make it enforceable. If the provision - cannot be reformed, it shall be severed from this Public License - without affecting the enforceability of the remaining terms and - conditions. - - c. No term or condition of this Public License will be waived and no - failure to comply consented to unless expressly agreed to by the - Licensor. - - d. Nothing in this Public License constitutes or may be interpreted - as a limitation upon, or waiver of, any privileges and immunities - that apply to the Licensor or You, including from the legal - processes of any jurisdiction or authority. - - -======================================================================= - -Creative Commons is not a party to its public licenses. -Notwithstanding, Creative Commons may elect to apply one of its public -licenses to material it publishes and in those instances will be -considered the "Licensor." Except for the limited purpose of indicating -that material is shared under a Creative Commons public license or as -otherwise permitted by the Creative Commons policies published at -creativecommons.org/policies, Creative Commons does not authorize the -use of the trademark "Creative Commons" or any other trademark or logo -of Creative Commons without its prior written consent including, -without limitation, in connection with any unauthorized modifications -to any of its public licenses or any other arrangements, -understandings, or agreements concerning use of licensed material. For -the avoidance of doubt, this paragraph does not form part of the public -licenses. - -Creative Commons may be contacted at creativecommons.org. diff --git a/vendor/github.com/docker/go-metrics/NOTICE b/vendor/github.com/docker/go-metrics/NOTICE deleted file mode 100644 index 8915f0277..000000000 --- a/vendor/github.com/docker/go-metrics/NOTICE +++ /dev/null @@ -1,16 +0,0 @@ -Docker -Copyright 2012-2015 Docker, Inc. - -This product includes software developed at Docker, Inc. (https://www.docker.com). - -The following is courtesy of our legal counsel: - - -Use and transfer of Docker may be subject to certain restrictions by the -United States and other governments. -It is your responsibility to ensure that your use and/or transfer does not -violate applicable laws. - -For more information, please see https://www.bis.doc.gov - -See also https://www.apache.org/dev/crypto.html and/or seek legal counsel. diff --git a/vendor/github.com/docker/go-metrics/README.md b/vendor/github.com/docker/go-metrics/README.md deleted file mode 100644 index a9e947cb5..000000000 --- a/vendor/github.com/docker/go-metrics/README.md +++ /dev/null @@ -1,91 +0,0 @@ -# go-metrics [![GoDoc](https://godoc.org/github.com/docker/go-metrics?status.svg)](https://godoc.org/github.com/docker/go-metrics) ![Badge Badge](http://doyouevenbadge.com/github.com/docker/go-metrics) - -This package is small wrapper around the prometheus go client to help enforce convention and best practices for metrics collection in Docker projects. - -## Best Practices - -This packages is meant to be used for collecting metrics in Docker projects. -It is not meant to be used as a replacement for the prometheus client but to help enforce consistent naming across metrics collected. -If you have not already read the prometheus best practices around naming and labels you can read the page [here](https://prometheus.io/docs/practices/naming/). - -The following are a few Docker specific rules that will help you name and work with metrics in your project. - -1. Namespace and Subsystem - -This package provides you with a namespace type that allows you to specify the same namespace and subsystem for your metrics. - -```go -ns := metrics.NewNamespace("engine", "daemon", metrics.Labels{ - "version": dockerversion.Version, - "commit": dockerversion.GitCommit, -}) -``` - -In the example above we are creating metrics for the Docker engine's daemon package. -`engine` would be the namespace in this example where `daemon` is the subsystem or package where we are collecting the metrics. - -A namespace also allows you to attach constant labels to the metrics such as the git commit and version that it is collecting. - -2. Declaring your Metrics - -Try to keep all your metric declarations in one file. -This makes it easy for others to see what constant labels are defined on the namespace and what labels are defined on the metrics when they are created. - -3. Use labels instead of multiple metrics - -Labels allow you to define one metric such as the time it takes to perform a certain action on an object. -If we wanted to collect timings on various container actions such as create, start, and delete then we can define one metric called `container_actions` and use labels to specify the type of action. - - -```go -containerActions = ns.NewLabeledTimer("container_actions", "The number of milliseconds it takes to process each container action", "action") -``` - -The last parameter is the label name or key. -When adding a data point to the metric you will use the `WithValues` function to specify the `action` that you are collecting for. - -```go -containerActions.WithValues("create").UpdateSince(start) -``` - -4. Always use a unit - -The metric name should describe what you are measuring but you also need to provide the unit that it is being measured with. -For a timer, the standard unit is seconds and a counter's standard unit is a total. -For gauges you must provide the unit. -This package provides a standard set of units for use within the Docker projects. - -```go -Nanoseconds Unit = "nanoseconds" -Seconds Unit = "seconds" -Bytes Unit = "bytes" -Total Unit = "total" -``` - -If you need to use a unit but it is not defined in the package please open a PR to add it but first try to see if one of the already created units will work for your metric, i.e. seconds or nanoseconds vs adding milliseconds. - -## Docs - -Package documentation can be found [here](https://godoc.org/github.com/docker/go-metrics). - -## HTTP Metrics - -To instrument a http handler, you can wrap the code like this: - -```go -namespace := metrics.NewNamespace("docker_distribution", "http", metrics.Labels{"handler": "your_http_handler_name"}) -httpMetrics := namespace.NewDefaultHttpMetrics() -metrics.Register(namespace) -instrumentedHandler = metrics.InstrumentHandler(httpMetrics, unInstrumentedHandler) -``` -Note: The `handler` label must be provided when a new namespace is created. - -## Additional Metrics - -Additional metrics are also defined here that are not available in the prometheus client. -If you need a custom metrics and it is generic enough to be used by multiple projects, define it here. - - -## Copyright and license - -Copyright © 2016 Docker, Inc. All rights reserved, except as follows. Code is released under the Apache 2.0 license. The README.md file, and files in the "docs" folder are licensed under the Creative Commons Attribution 4.0 International License under the terms and conditions set forth in the file "LICENSE.docs". You may obtain a duplicate copy of the same license, titled CC-BY-SA-4.0, at http://creativecommons.org/licenses/by/4.0/. diff --git a/vendor/github.com/docker/go-metrics/counter.go b/vendor/github.com/docker/go-metrics/counter.go deleted file mode 100644 index fe36316a4..000000000 --- a/vendor/github.com/docker/go-metrics/counter.go +++ /dev/null @@ -1,52 +0,0 @@ -package metrics - -import "github.com/prometheus/client_golang/prometheus" - -// Counter is a metrics that can only increment its current count -type Counter interface { - // Inc adds Sum(vs) to the counter. Sum(vs) must be positive. - // - // If len(vs) == 0, increments the counter by 1. - Inc(vs ...float64) -} - -// LabeledCounter is counter that must have labels populated before use. -type LabeledCounter interface { - WithValues(vs ...string) Counter -} - -type labeledCounter struct { - pc *prometheus.CounterVec -} - -func (lc *labeledCounter) WithValues(vs ...string) Counter { - return &counter{pc: lc.pc.WithLabelValues(vs...)} -} - -func (lc *labeledCounter) Describe(ch chan<- *prometheus.Desc) { - lc.pc.Describe(ch) -} - -func (lc *labeledCounter) Collect(ch chan<- prometheus.Metric) { - lc.pc.Collect(ch) -} - -type counter struct { - pc prometheus.Counter -} - -func (c *counter) Inc(vs ...float64) { - if len(vs) == 0 { - c.pc.Inc() - } - - c.pc.Add(sumFloat64(vs...)) -} - -func (c *counter) Describe(ch chan<- *prometheus.Desc) { - c.pc.Describe(ch) -} - -func (c *counter) Collect(ch chan<- prometheus.Metric) { - c.pc.Collect(ch) -} diff --git a/vendor/github.com/docker/go-metrics/docs.go b/vendor/github.com/docker/go-metrics/docs.go deleted file mode 100644 index 8fbdfc697..000000000 --- a/vendor/github.com/docker/go-metrics/docs.go +++ /dev/null @@ -1,3 +0,0 @@ -// This package is small wrapper around the prometheus go client to help enforce convention and best practices for metrics collection in Docker projects. - -package metrics diff --git a/vendor/github.com/docker/go-metrics/gauge.go b/vendor/github.com/docker/go-metrics/gauge.go deleted file mode 100644 index 74296e877..000000000 --- a/vendor/github.com/docker/go-metrics/gauge.go +++ /dev/null @@ -1,72 +0,0 @@ -package metrics - -import "github.com/prometheus/client_golang/prometheus" - -// Gauge is a metric that allows incrementing and decrementing a value -type Gauge interface { - Inc(...float64) - Dec(...float64) - - // Add adds the provided value to the gauge's current value - Add(float64) - - // Set replaces the gauge's current value with the provided value - Set(float64) -} - -// LabeledGauge describes a gauge the must have values populated before use. -type LabeledGauge interface { - WithValues(labels ...string) Gauge -} - -type labeledGauge struct { - pg *prometheus.GaugeVec -} - -func (lg *labeledGauge) WithValues(labels ...string) Gauge { - return &gauge{pg: lg.pg.WithLabelValues(labels...)} -} - -func (lg *labeledGauge) Describe(c chan<- *prometheus.Desc) { - lg.pg.Describe(c) -} - -func (lg *labeledGauge) Collect(c chan<- prometheus.Metric) { - lg.pg.Collect(c) -} - -type gauge struct { - pg prometheus.Gauge -} - -func (g *gauge) Inc(vs ...float64) { - if len(vs) == 0 { - g.pg.Inc() - } - - g.Add(sumFloat64(vs...)) -} - -func (g *gauge) Dec(vs ...float64) { - if len(vs) == 0 { - g.pg.Dec() - } - - g.Add(-sumFloat64(vs...)) -} - -func (g *gauge) Add(v float64) { - g.pg.Add(v) -} - -func (g *gauge) Set(v float64) { - g.pg.Set(v) -} - -func (g *gauge) Describe(c chan<- *prometheus.Desc) { - g.pg.Describe(c) -} - -func (g *gauge) Collect(c chan<- prometheus.Metric) { - g.pg.Collect(c) -} diff --git a/vendor/github.com/docker/go-metrics/handler.go b/vendor/github.com/docker/go-metrics/handler.go deleted file mode 100644 index 05601e9ec..000000000 --- a/vendor/github.com/docker/go-metrics/handler.go +++ /dev/null @@ -1,74 +0,0 @@ -package metrics - -import ( - "net/http" - - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/promhttp" -) - -// HTTPHandlerOpts describes a set of configurable options of http metrics -type HTTPHandlerOpts struct { - DurationBuckets []float64 - RequestSizeBuckets []float64 - ResponseSizeBuckets []float64 -} - -const ( - InstrumentHandlerResponseSize = iota - InstrumentHandlerRequestSize - InstrumentHandlerDuration - InstrumentHandlerCounter - InstrumentHandlerInFlight -) - -type HTTPMetric struct { - prometheus.Collector - handlerType int -} - -var ( - defaultDurationBuckets = []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10, 25, 60} - defaultRequestSizeBuckets = prometheus.ExponentialBuckets(1024, 2, 22) //1K to 4G - defaultResponseSizeBuckets = defaultRequestSizeBuckets -) - -// Handler returns the global http.Handler that provides the prometheus -// metrics format on GET requests. This handler is no longer instrumented. -func Handler() http.Handler { - return promhttp.Handler() -} - -func InstrumentHandler(metrics []*HTTPMetric, handler http.Handler) http.HandlerFunc { - return InstrumentHandlerFunc(metrics, handler.ServeHTTP) -} - -func InstrumentHandlerFunc(metrics []*HTTPMetric, handlerFunc http.HandlerFunc) http.HandlerFunc { - var handler http.Handler - handler = http.HandlerFunc(handlerFunc) - for _, metric := range metrics { - switch metric.handlerType { - case InstrumentHandlerResponseSize: - if collector, ok := metric.Collector.(prometheus.ObserverVec); ok { - handler = promhttp.InstrumentHandlerResponseSize(collector, handler) - } - case InstrumentHandlerRequestSize: - if collector, ok := metric.Collector.(prometheus.ObserverVec); ok { - handler = promhttp.InstrumentHandlerRequestSize(collector, handler) - } - case InstrumentHandlerDuration: - if collector, ok := metric.Collector.(prometheus.ObserverVec); ok { - handler = promhttp.InstrumentHandlerDuration(collector, handler) - } - case InstrumentHandlerCounter: - if collector, ok := metric.Collector.(*prometheus.CounterVec); ok { - handler = promhttp.InstrumentHandlerCounter(collector, handler) - } - case InstrumentHandlerInFlight: - if collector, ok := metric.Collector.(prometheus.Gauge); ok { - handler = promhttp.InstrumentHandlerInFlight(collector, handler) - } - } - } - return handler.ServeHTTP -} diff --git a/vendor/github.com/docker/go-metrics/helpers.go b/vendor/github.com/docker/go-metrics/helpers.go deleted file mode 100644 index 68b7f51b3..000000000 --- a/vendor/github.com/docker/go-metrics/helpers.go +++ /dev/null @@ -1,10 +0,0 @@ -package metrics - -func sumFloat64(vs ...float64) float64 { - var sum float64 - for _, v := range vs { - sum += v - } - - return sum -} diff --git a/vendor/github.com/docker/go-metrics/namespace.go b/vendor/github.com/docker/go-metrics/namespace.go deleted file mode 100644 index 798315451..000000000 --- a/vendor/github.com/docker/go-metrics/namespace.go +++ /dev/null @@ -1,315 +0,0 @@ -package metrics - -import ( - "fmt" - "sync" - - "github.com/prometheus/client_golang/prometheus" -) - -type Labels map[string]string - -// NewNamespace returns a namespaces that is responsible for managing a collection of -// metrics for a particual namespace and subsystem -// -// labels allows const labels to be added to all metrics created in this namespace -// and are commonly used for data like application version and git commit -func NewNamespace(name, subsystem string, labels Labels) *Namespace { - if labels == nil { - labels = make(map[string]string) - } - return &Namespace{ - name: name, - subsystem: subsystem, - labels: labels, - } -} - -// Namespace describes a set of metrics that share a namespace and subsystem. -type Namespace struct { - name string - subsystem string - labels Labels - mu sync.Mutex - metrics []prometheus.Collector -} - -// WithConstLabels returns a namespace with the provided set of labels merged -// with the existing constant labels on the namespace. -// -// Only metrics created with the returned namespace will get the new constant -// labels. The returned namespace must be registered separately. -func (n *Namespace) WithConstLabels(labels Labels) *Namespace { - n.mu.Lock() - ns := &Namespace{ - name: n.name, - subsystem: n.subsystem, - labels: mergeLabels(n.labels, labels), - } - n.mu.Unlock() - return ns -} - -func (n *Namespace) NewCounter(name, help string) Counter { - c := &counter{pc: prometheus.NewCounter(n.newCounterOpts(name, help))} - n.Add(c) - return c -} - -func (n *Namespace) NewLabeledCounter(name, help string, labels ...string) LabeledCounter { - c := &labeledCounter{pc: prometheus.NewCounterVec(n.newCounterOpts(name, help), labels)} - n.Add(c) - return c -} - -func (n *Namespace) newCounterOpts(name, help string) prometheus.CounterOpts { - return prometheus.CounterOpts{ - Namespace: n.name, - Subsystem: n.subsystem, - Name: makeName(name, Total), - Help: help, - ConstLabels: prometheus.Labels(n.labels), - } -} - -func (n *Namespace) NewTimer(name, help string) Timer { - t := &timer{ - m: prometheus.NewHistogram(n.newTimerOpts(name, help)), - } - n.Add(t) - return t -} - -func (n *Namespace) NewLabeledTimer(name, help string, labels ...string) LabeledTimer { - t := &labeledTimer{ - m: prometheus.NewHistogramVec(n.newTimerOpts(name, help), labels), - } - n.Add(t) - return t -} - -func (n *Namespace) newTimerOpts(name, help string) prometheus.HistogramOpts { - return prometheus.HistogramOpts{ - Namespace: n.name, - Subsystem: n.subsystem, - Name: makeName(name, Seconds), - Help: help, - ConstLabels: prometheus.Labels(n.labels), - } -} - -func (n *Namespace) NewGauge(name, help string, unit Unit) Gauge { - g := &gauge{ - pg: prometheus.NewGauge(n.newGaugeOpts(name, help, unit)), - } - n.Add(g) - return g -} - -func (n *Namespace) NewLabeledGauge(name, help string, unit Unit, labels ...string) LabeledGauge { - g := &labeledGauge{ - pg: prometheus.NewGaugeVec(n.newGaugeOpts(name, help, unit), labels), - } - n.Add(g) - return g -} - -func (n *Namespace) newGaugeOpts(name, help string, unit Unit) prometheus.GaugeOpts { - return prometheus.GaugeOpts{ - Namespace: n.name, - Subsystem: n.subsystem, - Name: makeName(name, unit), - Help: help, - ConstLabels: prometheus.Labels(n.labels), - } -} - -func (n *Namespace) Describe(ch chan<- *prometheus.Desc) { - n.mu.Lock() - defer n.mu.Unlock() - - for _, metric := range n.metrics { - metric.Describe(ch) - } -} - -func (n *Namespace) Collect(ch chan<- prometheus.Metric) { - n.mu.Lock() - defer n.mu.Unlock() - - for _, metric := range n.metrics { - metric.Collect(ch) - } -} - -func (n *Namespace) Add(collector prometheus.Collector) { - n.mu.Lock() - n.metrics = append(n.metrics, collector) - n.mu.Unlock() -} - -func (n *Namespace) NewDesc(name, help string, unit Unit, labels ...string) *prometheus.Desc { - name = makeName(name, unit) - namespace := n.name - if n.subsystem != "" { - namespace = fmt.Sprintf("%s_%s", namespace, n.subsystem) - } - name = fmt.Sprintf("%s_%s", namespace, name) - return prometheus.NewDesc(name, help, labels, prometheus.Labels(n.labels)) -} - -// mergeLabels merges two or more labels objects into a single map, favoring -// the later labels. -func mergeLabels(lbs ...Labels) Labels { - merged := make(Labels) - - for _, target := range lbs { - for k, v := range target { - merged[k] = v - } - } - - return merged -} - -func makeName(name string, unit Unit) string { - if unit == "" { - return name - } - - return fmt.Sprintf("%s_%s", name, unit) -} - -func (n *Namespace) NewDefaultHttpMetrics(handlerName string) []*HTTPMetric { - return n.NewHttpMetricsWithOpts(handlerName, HTTPHandlerOpts{ - DurationBuckets: defaultDurationBuckets, - RequestSizeBuckets: defaultResponseSizeBuckets, - ResponseSizeBuckets: defaultResponseSizeBuckets, - }) -} - -func (n *Namespace) NewHttpMetrics(handlerName string, durationBuckets, requestSizeBuckets, responseSizeBuckets []float64) []*HTTPMetric { - return n.NewHttpMetricsWithOpts(handlerName, HTTPHandlerOpts{ - DurationBuckets: durationBuckets, - RequestSizeBuckets: requestSizeBuckets, - ResponseSizeBuckets: responseSizeBuckets, - }) -} - -func (n *Namespace) NewHttpMetricsWithOpts(handlerName string, opts HTTPHandlerOpts) []*HTTPMetric { - var httpMetrics []*HTTPMetric - inFlightMetric := n.NewInFlightGaugeMetric(handlerName) - requestTotalMetric := n.NewRequestTotalMetric(handlerName) - requestDurationMetric := n.NewRequestDurationMetric(handlerName, opts.DurationBuckets) - requestSizeMetric := n.NewRequestSizeMetric(handlerName, opts.RequestSizeBuckets) - responseSizeMetric := n.NewResponseSizeMetric(handlerName, opts.ResponseSizeBuckets) - httpMetrics = append(httpMetrics, inFlightMetric, requestDurationMetric, requestTotalMetric, requestSizeMetric, responseSizeMetric) - return httpMetrics -} - -func (n *Namespace) NewInFlightGaugeMetric(handlerName string) *HTTPMetric { - labels := prometheus.Labels(n.labels) - labels["handler"] = handlerName - metric := prometheus.NewGauge(prometheus.GaugeOpts{ - Namespace: n.name, - Subsystem: n.subsystem, - Name: "in_flight_requests", - Help: "The in-flight HTTP requests", - ConstLabels: prometheus.Labels(labels), - }) - httpMetric := &HTTPMetric{ - Collector: metric, - handlerType: InstrumentHandlerInFlight, - } - n.Add(httpMetric) - return httpMetric -} - -func (n *Namespace) NewRequestTotalMetric(handlerName string) *HTTPMetric { - labels := prometheus.Labels(n.labels) - labels["handler"] = handlerName - metric := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Namespace: n.name, - Subsystem: n.subsystem, - Name: "requests_total", - Help: "Total number of HTTP requests made.", - ConstLabels: prometheus.Labels(labels), - }, - []string{"code", "method"}, - ) - httpMetric := &HTTPMetric{ - Collector: metric, - handlerType: InstrumentHandlerCounter, - } - n.Add(httpMetric) - return httpMetric -} -func (n *Namespace) NewRequestDurationMetric(handlerName string, buckets []float64) *HTTPMetric { - if len(buckets) == 0 { - panic("DurationBuckets must be provided") - } - labels := prometheus.Labels(n.labels) - labels["handler"] = handlerName - opts := prometheus.HistogramOpts{ - Namespace: n.name, - Subsystem: n.subsystem, - Name: "request_duration_seconds", - Help: "The HTTP request latencies in seconds.", - Buckets: buckets, - ConstLabels: prometheus.Labels(labels), - } - metric := prometheus.NewHistogramVec(opts, []string{"method"}) - httpMetric := &HTTPMetric{ - Collector: metric, - handlerType: InstrumentHandlerDuration, - } - n.Add(httpMetric) - return httpMetric -} - -func (n *Namespace) NewRequestSizeMetric(handlerName string, buckets []float64) *HTTPMetric { - if len(buckets) == 0 { - panic("RequestSizeBuckets must be provided") - } - labels := prometheus.Labels(n.labels) - labels["handler"] = handlerName - opts := prometheus.HistogramOpts{ - Namespace: n.name, - Subsystem: n.subsystem, - Name: "request_size_bytes", - Help: "The HTTP request sizes in bytes.", - Buckets: buckets, - ConstLabels: prometheus.Labels(labels), - } - metric := prometheus.NewHistogramVec(opts, []string{}) - httpMetric := &HTTPMetric{ - Collector: metric, - handlerType: InstrumentHandlerRequestSize, - } - n.Add(httpMetric) - return httpMetric -} - -func (n *Namespace) NewResponseSizeMetric(handlerName string, buckets []float64) *HTTPMetric { - if len(buckets) == 0 { - panic("ResponseSizeBuckets must be provided") - } - labels := prometheus.Labels(n.labels) - labels["handler"] = handlerName - opts := prometheus.HistogramOpts{ - Namespace: n.name, - Subsystem: n.subsystem, - Name: "response_size_bytes", - Help: "The HTTP response sizes in bytes.", - Buckets: buckets, - ConstLabels: prometheus.Labels(labels), - } - metrics := prometheus.NewHistogramVec(opts, []string{}) - httpMetric := &HTTPMetric{ - Collector: metrics, - handlerType: InstrumentHandlerResponseSize, - } - n.Add(httpMetric) - return httpMetric -} diff --git a/vendor/github.com/docker/go-metrics/register.go b/vendor/github.com/docker/go-metrics/register.go deleted file mode 100644 index 708358df0..000000000 --- a/vendor/github.com/docker/go-metrics/register.go +++ /dev/null @@ -1,15 +0,0 @@ -package metrics - -import "github.com/prometheus/client_golang/prometheus" - -// Register adds all the metrics in the provided namespace to the global -// metrics registry -func Register(n *Namespace) { - prometheus.MustRegister(n) -} - -// Deregister removes all the metrics in the provided namespace from the -// global metrics registry -func Deregister(n *Namespace) { - prometheus.Unregister(n) -} diff --git a/vendor/github.com/docker/go-metrics/timer.go b/vendor/github.com/docker/go-metrics/timer.go deleted file mode 100644 index 824c98739..000000000 --- a/vendor/github.com/docker/go-metrics/timer.go +++ /dev/null @@ -1,85 +0,0 @@ -package metrics - -import ( - "time" - - "github.com/prometheus/client_golang/prometheus" -) - -// StartTimer begins a timer observation at the callsite. When the target -// operation is completed, the caller should call the return done func(). -func StartTimer(timer Timer) (done func()) { - start := time.Now() - return func() { - timer.Update(time.Since(start)) - } -} - -// Timer is a metric that allows collecting the duration of an action in seconds -type Timer interface { - // Update records an observation, duration, and converts to the target - // units. - Update(duration time.Duration) - - // UpdateSince will add the duration from the provided starting time to the - // timer's summary with the precisions that was used in creation of the timer - UpdateSince(time.Time) -} - -// LabeledTimer is a timer that must have label values populated before use. -type LabeledTimer interface { - WithValues(labels ...string) *labeledTimerObserver -} - -type labeledTimer struct { - m *prometheus.HistogramVec -} - -type labeledTimerObserver struct { - m prometheus.Observer -} - -func (lbo *labeledTimerObserver) Update(duration time.Duration) { - lbo.m.Observe(duration.Seconds()) -} - -func (lbo *labeledTimerObserver) UpdateSince(since time.Time) { - lbo.m.Observe(time.Since(since).Seconds()) -} - -func (lt *labeledTimer) WithValues(labels ...string) *labeledTimerObserver { - return &labeledTimerObserver{m: lt.m.WithLabelValues(labels...)} -} - -func (lt *labeledTimer) Describe(c chan<- *prometheus.Desc) { - lt.m.Describe(c) -} - -func (lt *labeledTimer) Collect(c chan<- prometheus.Metric) { - lt.m.Collect(c) -} - -type timer struct { - m prometheus.Observer -} - -func (t *timer) Update(duration time.Duration) { - t.m.Observe(duration.Seconds()) -} - -func (t *timer) UpdateSince(since time.Time) { - t.m.Observe(time.Since(since).Seconds()) -} - -func (t *timer) Describe(c chan<- *prometheus.Desc) { - c <- t.m.(prometheus.Metric).Desc() -} - -func (t *timer) Collect(c chan<- prometheus.Metric) { - // Are there any observers that don't implement Collector? It is really - // unclear what the point of the upstream change was, but we'll let this - // panic if we get an observer that doesn't implement collector. In this - // case, we should almost always see metricVec objects, so this should - // never panic. - t.m.(prometheus.Collector).Collect(c) -} diff --git a/vendor/github.com/docker/go-metrics/unit.go b/vendor/github.com/docker/go-metrics/unit.go deleted file mode 100644 index c96622f90..000000000 --- a/vendor/github.com/docker/go-metrics/unit.go +++ /dev/null @@ -1,12 +0,0 @@ -package metrics - -// Unit represents the type or precision of a metric that is appended to -// the metrics fully qualified name -type Unit string - -const ( - Nanoseconds Unit = "nanoseconds" - Seconds Unit = "seconds" - Bytes Unit = "bytes" - Total Unit = "total" -) diff --git a/vendor/github.com/docker/go-units/CONTRIBUTING.md b/vendor/github.com/docker/go-units/CONTRIBUTING.md deleted file mode 100644 index 9ea86d784..000000000 --- a/vendor/github.com/docker/go-units/CONTRIBUTING.md +++ /dev/null @@ -1,67 +0,0 @@ -# Contributing to go-units - -Want to hack on go-units? Awesome! Here are instructions to get you started. - -go-units is a part of the [Docker](https://www.docker.com) project, and follows -the same rules and principles. If you're already familiar with the way -Docker does things, you'll feel right at home. - -Otherwise, go read Docker's -[contributions guidelines](https://github.com/docker/docker/blob/master/CONTRIBUTING.md), -[issue triaging](https://github.com/docker/docker/blob/master/project/ISSUE-TRIAGE.md), -[review process](https://github.com/docker/docker/blob/master/project/REVIEWING.md) and -[branches and tags](https://github.com/docker/docker/blob/master/project/BRANCHES-AND-TAGS.md). - -### Sign your work - -The sign-off is a simple line at the end of the explanation for the patch. Your -signature certifies that you wrote the patch or otherwise have the right to pass -it on as an open-source patch. The rules are pretty simple: if you can certify -the below (from [developercertificate.org](http://developercertificate.org/)): - -``` -Developer Certificate of Origin -Version 1.1 - -Copyright (C) 2004, 2006 The Linux Foundation and its contributors. -660 York Street, Suite 102, -San Francisco, CA 94110 USA - -Everyone is permitted to copy and distribute verbatim copies of this -license document, but changing it is not allowed. - -Developer's Certificate of Origin 1.1 - -By making a contribution to this project, I certify that: - -(a) The contribution was created in whole or in part by me and I - have the right to submit it under the open source license - indicated in the file; or - -(b) The contribution is based upon previous work that, to the best - of my knowledge, is covered under an appropriate open source - license and I have the right under that license to submit that - work with modifications, whether created in whole or in part - by me, under the same open source license (unless I am - permitted to submit under a different license), as indicated - in the file; or - -(c) The contribution was provided directly to me by some other - person who certified (a), (b) or (c) and I have not modified - it. - -(d) I understand and agree that this project and the contribution - are public and that a record of the contribution (including all - personal information I submit with it, including my sign-off) is - maintained indefinitely and may be redistributed consistent with - this project or the open source license(s) involved. -``` - -Then you just add a line to every git commit message: - - Signed-off-by: Joe Smith - -Use your real name (sorry, no pseudonyms or anonymous contributions.) - -If you set your `user.name` and `user.email` git configs, you can sign your -commit automatically with `git commit -s`. diff --git a/vendor/github.com/docker/go-units/LICENSE b/vendor/github.com/docker/go-units/LICENSE deleted file mode 100644 index b55b37bc3..000000000 --- a/vendor/github.com/docker/go-units/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2015 Docker, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - https://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/docker/go-units/MAINTAINERS b/vendor/github.com/docker/go-units/MAINTAINERS deleted file mode 100644 index 4aac7c741..000000000 --- a/vendor/github.com/docker/go-units/MAINTAINERS +++ /dev/null @@ -1,46 +0,0 @@ -# go-units maintainers file -# -# This file describes who runs the docker/go-units project and how. -# This is a living document - if you see something out of date or missing, speak up! -# -# It is structured to be consumable by both humans and programs. -# To extract its contents programmatically, use any TOML-compliant parser. -# -# This file is compiled into the MAINTAINERS file in docker/opensource. -# -[Org] - [Org."Core maintainers"] - people = [ - "akihirosuda", - "dnephin", - "thajeztah", - "vdemeester", - ] - -[people] - -# A reference list of all people associated with the project. -# All other sections should refer to people by their canonical key -# in the people section. - - # ADD YOURSELF HERE IN ALPHABETICAL ORDER - - [people.akihirosuda] - Name = "Akihiro Suda" - Email = "akihiro.suda.cz@hco.ntt.co.jp" - GitHub = "AkihiroSuda" - - [people.dnephin] - Name = "Daniel Nephin" - Email = "dnephin@gmail.com" - GitHub = "dnephin" - - [people.thajeztah] - Name = "Sebastiaan van Stijn" - Email = "github@gone.nl" - GitHub = "thaJeztah" - - [people.vdemeester] - Name = "Vincent Demeester" - Email = "vincent@sbr.pm" - GitHub = "vdemeester" \ No newline at end of file diff --git a/vendor/github.com/docker/go-units/README.md b/vendor/github.com/docker/go-units/README.md deleted file mode 100644 index 4f70a4e13..000000000 --- a/vendor/github.com/docker/go-units/README.md +++ /dev/null @@ -1,16 +0,0 @@ -[![GoDoc](https://godoc.org/github.com/docker/go-units?status.svg)](https://godoc.org/github.com/docker/go-units) - -# Introduction - -go-units is a library to transform human friendly measurements into machine friendly values. - -## Usage - -See the [docs in godoc](https://godoc.org/github.com/docker/go-units) for examples and documentation. - -## Copyright and license - -Copyright © 2015 Docker, Inc. - -go-units is licensed under the Apache License, Version 2.0. -See [LICENSE](LICENSE) for the full text of the license. diff --git a/vendor/github.com/docker/go-units/circle.yml b/vendor/github.com/docker/go-units/circle.yml deleted file mode 100644 index af9d60552..000000000 --- a/vendor/github.com/docker/go-units/circle.yml +++ /dev/null @@ -1,11 +0,0 @@ -dependencies: - post: - # install golint - - go get golang.org/x/lint/golint - -test: - pre: - # run analysis before tests - - go vet ./... - - test -z "$(golint ./... | tee /dev/stderr)" - - test -z "$(gofmt -s -l . | tee /dev/stderr)" diff --git a/vendor/github.com/docker/go-units/duration.go b/vendor/github.com/docker/go-units/duration.go deleted file mode 100644 index 48dd8744d..000000000 --- a/vendor/github.com/docker/go-units/duration.go +++ /dev/null @@ -1,35 +0,0 @@ -// Package units provides helper function to parse and print size and time units -// in human-readable format. -package units - -import ( - "fmt" - "time" -) - -// HumanDuration returns a human-readable approximation of a duration -// (eg. "About a minute", "4 hours ago", etc.). -func HumanDuration(d time.Duration) string { - if seconds := int(d.Seconds()); seconds < 1 { - return "Less than a second" - } else if seconds == 1 { - return "1 second" - } else if seconds < 60 { - return fmt.Sprintf("%d seconds", seconds) - } else if minutes := int(d.Minutes()); minutes == 1 { - return "About a minute" - } else if minutes < 60 { - return fmt.Sprintf("%d minutes", minutes) - } else if hours := int(d.Hours() + 0.5); hours == 1 { - return "About an hour" - } else if hours < 48 { - return fmt.Sprintf("%d hours", hours) - } else if hours < 24*7*2 { - return fmt.Sprintf("%d days", hours/24) - } else if hours < 24*30*2 { - return fmt.Sprintf("%d weeks", hours/24/7) - } else if hours < 24*365*2 { - return fmt.Sprintf("%d months", hours/24/30) - } - return fmt.Sprintf("%d years", int(d.Hours())/24/365) -} diff --git a/vendor/github.com/docker/go-units/size.go b/vendor/github.com/docker/go-units/size.go deleted file mode 100644 index c245a8951..000000000 --- a/vendor/github.com/docker/go-units/size.go +++ /dev/null @@ -1,154 +0,0 @@ -package units - -import ( - "fmt" - "strconv" - "strings" -) - -// See: http://en.wikipedia.org/wiki/Binary_prefix -const ( - // Decimal - - KB = 1000 - MB = 1000 * KB - GB = 1000 * MB - TB = 1000 * GB - PB = 1000 * TB - - // Binary - - KiB = 1024 - MiB = 1024 * KiB - GiB = 1024 * MiB - TiB = 1024 * GiB - PiB = 1024 * TiB -) - -type unitMap map[byte]int64 - -var ( - decimalMap = unitMap{'k': KB, 'm': MB, 'g': GB, 't': TB, 'p': PB} - binaryMap = unitMap{'k': KiB, 'm': MiB, 'g': GiB, 't': TiB, 'p': PiB} -) - -var ( - decimapAbbrs = []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"} - binaryAbbrs = []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"} -) - -func getSizeAndUnit(size float64, base float64, _map []string) (float64, string) { - i := 0 - unitsLimit := len(_map) - 1 - for size >= base && i < unitsLimit { - size = size / base - i++ - } - return size, _map[i] -} - -// CustomSize returns a human-readable approximation of a size -// using custom format. -func CustomSize(format string, size float64, base float64, _map []string) string { - size, unit := getSizeAndUnit(size, base, _map) - return fmt.Sprintf(format, size, unit) -} - -// HumanSizeWithPrecision allows the size to be in any precision, -// instead of 4 digit precision used in units.HumanSize. -func HumanSizeWithPrecision(size float64, precision int) string { - size, unit := getSizeAndUnit(size, 1000.0, decimapAbbrs) - return fmt.Sprintf("%.*g%s", precision, size, unit) -} - -// HumanSize returns a human-readable approximation of a size -// capped at 4 valid numbers (eg. "2.746 MB", "796 KB"). -func HumanSize(size float64) string { - return HumanSizeWithPrecision(size, 4) -} - -// BytesSize returns a human-readable size in bytes, kibibytes, -// mebibytes, gibibytes, or tebibytes (eg. "44kiB", "17MiB"). -func BytesSize(size float64) string { - return CustomSize("%.4g%s", size, 1024.0, binaryAbbrs) -} - -// FromHumanSize returns an integer from a human-readable specification of a -// size using SI standard (eg. "44kB", "17MB"). -func FromHumanSize(size string) (int64, error) { - return parseSize(size, decimalMap) -} - -// RAMInBytes parses a human-readable string representing an amount of RAM -// in bytes, kibibytes, mebibytes, gibibytes, or tebibytes and -// returns the number of bytes, or -1 if the string is unparseable. -// Units are case-insensitive, and the 'b' suffix is optional. -func RAMInBytes(size string) (int64, error) { - return parseSize(size, binaryMap) -} - -// Parses the human-readable size string into the amount it represents. -func parseSize(sizeStr string, uMap unitMap) (int64, error) { - // TODO: rewrite to use strings.Cut if there's a space - // once Go < 1.18 is deprecated. - sep := strings.LastIndexAny(sizeStr, "01234567890. ") - if sep == -1 { - // There should be at least a digit. - return -1, fmt.Errorf("invalid size: '%s'", sizeStr) - } - var num, sfx string - if sizeStr[sep] != ' ' { - num = sizeStr[:sep+1] - sfx = sizeStr[sep+1:] - } else { - // Omit the space separator. - num = sizeStr[:sep] - sfx = sizeStr[sep+1:] - } - - size, err := strconv.ParseFloat(num, 64) - if err != nil { - return -1, err - } - // Backward compatibility: reject negative sizes. - if size < 0 { - return -1, fmt.Errorf("invalid size: '%s'", sizeStr) - } - - if len(sfx) == 0 { - return int64(size), nil - } - - // Process the suffix. - - if len(sfx) > 3 { // Too long. - goto badSuffix - } - sfx = strings.ToLower(sfx) - // Trivial case: b suffix. - if sfx[0] == 'b' { - if len(sfx) > 1 { // no extra characters allowed after b. - goto badSuffix - } - return int64(size), nil - } - // A suffix from the map. - if mul, ok := uMap[sfx[0]]; ok { - size *= float64(mul) - } else { - goto badSuffix - } - - // The suffix may have extra "b" or "ib" (e.g. KiB or MB). - switch { - case len(sfx) == 2 && sfx[1] != 'b': - goto badSuffix - case len(sfx) == 3 && sfx[1:] != "ib": - goto badSuffix - } - - return int64(size), nil - -badSuffix: - return -1, fmt.Errorf("invalid suffix: '%s'", sfx) -} diff --git a/vendor/github.com/docker/go-units/ulimit.go b/vendor/github.com/docker/go-units/ulimit.go deleted file mode 100644 index fca0400cc..000000000 --- a/vendor/github.com/docker/go-units/ulimit.go +++ /dev/null @@ -1,123 +0,0 @@ -package units - -import ( - "fmt" - "strconv" - "strings" -) - -// Ulimit is a human friendly version of Rlimit. -type Ulimit struct { - Name string - Hard int64 - Soft int64 -} - -// Rlimit specifies the resource limits, such as max open files. -type Rlimit struct { - Type int `json:"type,omitempty"` - Hard uint64 `json:"hard,omitempty"` - Soft uint64 `json:"soft,omitempty"` -} - -const ( - // magic numbers for making the syscall - // some of these are defined in the syscall package, but not all. - // Also since Windows client doesn't get access to the syscall package, need to - // define these here - rlimitAs = 9 - rlimitCore = 4 - rlimitCPU = 0 - rlimitData = 2 - rlimitFsize = 1 - rlimitLocks = 10 - rlimitMemlock = 8 - rlimitMsgqueue = 12 - rlimitNice = 13 - rlimitNofile = 7 - rlimitNproc = 6 - rlimitRss = 5 - rlimitRtprio = 14 - rlimitRttime = 15 - rlimitSigpending = 11 - rlimitStack = 3 -) - -var ulimitNameMapping = map[string]int{ - //"as": rlimitAs, // Disabled since this doesn't seem usable with the way Docker inits a container. - "core": rlimitCore, - "cpu": rlimitCPU, - "data": rlimitData, - "fsize": rlimitFsize, - "locks": rlimitLocks, - "memlock": rlimitMemlock, - "msgqueue": rlimitMsgqueue, - "nice": rlimitNice, - "nofile": rlimitNofile, - "nproc": rlimitNproc, - "rss": rlimitRss, - "rtprio": rlimitRtprio, - "rttime": rlimitRttime, - "sigpending": rlimitSigpending, - "stack": rlimitStack, -} - -// ParseUlimit parses and returns a Ulimit from the specified string. -func ParseUlimit(val string) (*Ulimit, error) { - parts := strings.SplitN(val, "=", 2) - if len(parts) != 2 { - return nil, fmt.Errorf("invalid ulimit argument: %s", val) - } - - if _, exists := ulimitNameMapping[parts[0]]; !exists { - return nil, fmt.Errorf("invalid ulimit type: %s", parts[0]) - } - - var ( - soft int64 - hard = &soft // default to soft in case no hard was set - temp int64 - err error - ) - switch limitVals := strings.Split(parts[1], ":"); len(limitVals) { - case 2: - temp, err = strconv.ParseInt(limitVals[1], 10, 64) - if err != nil { - return nil, err - } - hard = &temp - fallthrough - case 1: - soft, err = strconv.ParseInt(limitVals[0], 10, 64) - if err != nil { - return nil, err - } - default: - return nil, fmt.Errorf("too many limit value arguments - %s, can only have up to two, `soft[:hard]`", parts[1]) - } - - if *hard != -1 { - if soft == -1 { - return nil, fmt.Errorf("ulimit soft limit must be less than or equal to hard limit: soft: -1 (unlimited), hard: %d", *hard) - } - if soft > *hard { - return nil, fmt.Errorf("ulimit soft limit must be less than or equal to hard limit: %d > %d", soft, *hard) - } - } - - return &Ulimit{Name: parts[0], Soft: soft, Hard: *hard}, nil -} - -// GetRlimit returns the RLimit corresponding to Ulimit. -func (u *Ulimit) GetRlimit() (*Rlimit, error) { - t, exists := ulimitNameMapping[u.Name] - if !exists { - return nil, fmt.Errorf("invalid ulimit name %s", u.Name) - } - - return &Rlimit{Type: t, Soft: uint64(u.Soft), Hard: uint64(u.Hard)}, nil -} - -func (u *Ulimit) String() string { - return fmt.Sprintf("%s=%d:%d", u.Name, u.Soft, u.Hard) -} diff --git a/vendor/github.com/docker/go/LICENSE b/vendor/github.com/docker/go/LICENSE deleted file mode 100644 index 744875676..000000000 --- a/vendor/github.com/docker/go/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2012 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/github.com/docker/go/canonical/json/decode.go b/vendor/github.com/docker/go/canonical/json/decode.go deleted file mode 100644 index 72b981c53..000000000 --- a/vendor/github.com/docker/go/canonical/json/decode.go +++ /dev/null @@ -1,1168 +0,0 @@ -// 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. - -// Represents JSON data structure using native Go types: booleans, floats, -// strings, arrays, and maps. - -package json - -import ( - "bytes" - "encoding" - "encoding/base64" - "errors" - "fmt" - "reflect" - "runtime" - "strconv" - "unicode" - "unicode/utf16" - "unicode/utf8" -) - -// Unmarshal parses the JSON-encoded data and stores the result -// in the value pointed to by v. -// -// Unmarshal uses the inverse of the encodings that -// Marshal uses, allocating maps, slices, and pointers as necessary, -// with the following additional rules: -// -// To unmarshal JSON into a pointer, Unmarshal first handles the case of -// the JSON being the JSON literal null. In that case, Unmarshal sets -// the pointer to nil. Otherwise, Unmarshal unmarshals the JSON into -// the value pointed at by the pointer. If the pointer is nil, Unmarshal -// allocates a new value for it to point to. -// -// To unmarshal JSON into a struct, Unmarshal matches incoming object -// keys to the keys used by Marshal (either the struct field name or its tag), -// preferring an exact match but also accepting a case-insensitive match. -// Unmarshal will only set exported fields of the struct. -// -// To unmarshal JSON into an interface value, -// Unmarshal stores one of these in the interface value: -// -// bool, for JSON booleans -// float64, for JSON numbers -// string, for JSON strings -// []interface{}, for JSON arrays -// map[string]interface{}, for JSON objects -// nil for JSON null -// -// To unmarshal a JSON array into a slice, Unmarshal resets the slice length -// to zero and then appends each element to the slice. -// As a special case, to unmarshal an empty JSON array into a slice, -// Unmarshal replaces the slice with a new empty slice. -// -// To unmarshal a JSON array into a Go array, Unmarshal decodes -// JSON array elements into corresponding Go array elements. -// If the Go array is smaller than the JSON array, -// the additional JSON array elements are discarded. -// If the JSON array is smaller than the Go array, -// the additional Go array elements are set to zero values. -// -// To unmarshal a JSON object into a string-keyed map, Unmarshal first -// establishes a map to use, If the map is nil, Unmarshal allocates a new map. -// Otherwise Unmarshal reuses the existing map, keeping existing entries. -// Unmarshal then stores key-value pairs from the JSON object into the map. -// -// If a JSON value is not appropriate for a given target type, -// or if a JSON number overflows the target type, Unmarshal -// skips that field and completes the unmarshaling as best it can. -// If no more serious errors are encountered, Unmarshal returns -// an UnmarshalTypeError describing the earliest such error. -// -// The JSON null value unmarshals into an interface, map, pointer, or slice -// by setting that Go value to nil. Because null is often used in JSON to mean -// ``not present,'' unmarshaling a JSON null into any other Go type has no effect -// on the value and produces no error. -// -// When unmarshaling quoted strings, invalid UTF-8 or -// invalid UTF-16 surrogate pairs are not treated as an error. -// Instead, they are replaced by the Unicode replacement -// character U+FFFD. -// -func Unmarshal(data []byte, v interface{}) error { - // Check for well-formedness. - // Avoids filling out half a data structure - // before discovering a JSON syntax error. - var d decodeState - err := checkValid(data, &d.scan) - if err != nil { - return err - } - - d.init(data) - return d.unmarshal(v) -} - -// Unmarshaler is the interface implemented by objects -// that can unmarshal a JSON description of themselves. -// The input can be assumed to be a valid encoding of -// a JSON value. UnmarshalJSON must copy the JSON data -// if it wishes to retain the data after returning. -type Unmarshaler interface { - UnmarshalJSON([]byte) error -} - -// An UnmarshalTypeError describes a JSON value that was -// not appropriate for a value of a specific Go type. -type UnmarshalTypeError struct { - Value string // description of JSON value - "bool", "array", "number -5" - Type reflect.Type // type of Go value it could not be assigned to - Offset int64 // error occurred after reading Offset bytes -} - -func (e *UnmarshalTypeError) Error() string { - return "json: cannot unmarshal " + e.Value + " into Go value of type " + e.Type.String() -} - -// An UnmarshalFieldError describes a JSON object key that -// led to an unexported (and therefore unwritable) struct field. -// (No longer used; kept for compatibility.) -type UnmarshalFieldError struct { - Key string - Type reflect.Type - Field reflect.StructField -} - -func (e *UnmarshalFieldError) Error() string { - return "json: cannot unmarshal object key " + strconv.Quote(e.Key) + " into unexported field " + e.Field.Name + " of type " + e.Type.String() -} - -// An InvalidUnmarshalError describes an invalid argument passed to Unmarshal. -// (The argument to Unmarshal must be a non-nil pointer.) -type InvalidUnmarshalError struct { - Type reflect.Type -} - -func (e *InvalidUnmarshalError) Error() string { - if e.Type == nil { - return "json: Unmarshal(nil)" - } - - if e.Type.Kind() != reflect.Ptr { - return "json: Unmarshal(non-pointer " + e.Type.String() + ")" - } - return "json: Unmarshal(nil " + e.Type.String() + ")" -} - -func (d *decodeState) unmarshal(v interface{}) (err error) { - defer func() { - if r := recover(); r != nil { - if _, ok := r.(runtime.Error); ok { - panic(r) - } - err = r.(error) - } - }() - - rv := reflect.ValueOf(v) - if rv.Kind() != reflect.Ptr || rv.IsNil() { - return &InvalidUnmarshalError{reflect.TypeOf(v)} - } - - d.scan.reset() - // We decode rv not rv.Elem because the Unmarshaler interface - // test must be applied at the top level of the value. - d.value(rv) - return d.savedError -} - -// A Number represents a JSON number literal. -type Number string - -// String returns the literal text of the number. -func (n Number) String() string { return string(n) } - -// Float64 returns the number as a float64. -func (n Number) Float64() (float64, error) { - return strconv.ParseFloat(string(n), 64) -} - -// Int64 returns the number as an int64. -func (n Number) Int64() (int64, error) { - return strconv.ParseInt(string(n), 10, 64) -} - -// isValidNumber reports whether s is a valid JSON number literal. -func isValidNumber(s string) bool { - // This function implements the JSON numbers grammar. - // See https://tools.ietf.org/html/rfc7159#section-6 - // and http://json.org/number.gif - - if s == "" { - return false - } - - // Optional - - if s[0] == '-' { - s = s[1:] - if s == "" { - return false - } - } - - // Digits - switch { - default: - return false - - case s[0] == '0': - s = s[1:] - - case '1' <= s[0] && s[0] <= '9': - s = s[1:] - for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { - s = s[1:] - } - } - - // . followed by 1 or more digits. - if len(s) >= 2 && s[0] == '.' && '0' <= s[1] && s[1] <= '9' { - s = s[2:] - for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { - s = s[1:] - } - } - - // e or E followed by an optional - or + and - // 1 or more digits. - if len(s) >= 2 && (s[0] == 'e' || s[0] == 'E') { - s = s[1:] - if s[0] == '+' || s[0] == '-' { - s = s[1:] - if s == "" { - return false - } - } - for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { - s = s[1:] - } - } - - // Make sure we are at the end. - return s == "" -} - -// decodeState represents the state while decoding a JSON value. -type decodeState struct { - data []byte - off int // read offset in data - scan scanner - nextscan scanner // for calls to nextValue - savedError error - useNumber bool - canonical bool -} - -// errPhase is used for errors that should not happen unless -// there is a bug in the JSON decoder or something is editing -// the data slice while the decoder executes. -var errPhase = errors.New("JSON decoder out of sync - data changing underfoot?") - -func (d *decodeState) init(data []byte) *decodeState { - d.data = data - d.off = 0 - d.savedError = nil - return d -} - -// error aborts the decoding by panicking with err. -func (d *decodeState) error(err error) { - panic(err) -} - -// saveError saves the first err it is called with, -// for reporting at the end of the unmarshal. -func (d *decodeState) saveError(err error) { - if d.savedError == nil { - d.savedError = err - } -} - -// next cuts off and returns the next full JSON value in d.data[d.off:]. -// The next value is known to be an object or array, not a literal. -func (d *decodeState) next() []byte { - c := d.data[d.off] - item, rest, err := nextValue(d.data[d.off:], &d.nextscan) - if err != nil { - d.error(err) - } - d.off = len(d.data) - len(rest) - - // Our scanner has seen the opening brace/bracket - // and thinks we're still in the middle of the object. - // invent a closing brace/bracket to get it out. - if c == '{' { - d.scan.step(&d.scan, '}') - } else { - d.scan.step(&d.scan, ']') - } - - return item -} - -// scanWhile processes bytes in d.data[d.off:] until it -// receives a scan code not equal to op. -// It updates d.off and returns the new scan code. -func (d *decodeState) scanWhile(op int) int { - var newOp int - for { - if d.off >= len(d.data) { - newOp = d.scan.eof() - d.off = len(d.data) + 1 // mark processed EOF with len+1 - } else { - c := d.data[d.off] - d.off++ - newOp = d.scan.step(&d.scan, c) - } - if newOp != op { - break - } - } - return newOp -} - -// value decodes a JSON value from d.data[d.off:] into the value. -// it updates d.off to point past the decoded value. -func (d *decodeState) value(v reflect.Value) { - if !v.IsValid() { - _, rest, err := nextValue(d.data[d.off:], &d.nextscan) - if err != nil { - d.error(err) - } - d.off = len(d.data) - len(rest) - - // d.scan thinks we're still at the beginning of the item. - // Feed in an empty string - the shortest, simplest value - - // so that it knows we got to the end of the value. - if d.scan.redo { - // rewind. - d.scan.redo = false - d.scan.step = stateBeginValue - } - d.scan.step(&d.scan, '"') - d.scan.step(&d.scan, '"') - - n := len(d.scan.parseState) - if n > 0 && d.scan.parseState[n-1] == parseObjectKey { - // d.scan thinks we just read an object key; finish the object - d.scan.step(&d.scan, ':') - d.scan.step(&d.scan, '"') - d.scan.step(&d.scan, '"') - d.scan.step(&d.scan, '}') - } - - return - } - - switch op := d.scanWhile(scanSkipSpace); op { - default: - d.error(errPhase) - - case scanBeginArray: - d.array(v) - - case scanBeginObject: - d.object(v) - - case scanBeginLiteral: - d.literal(v) - } -} - -type unquotedValue struct{} - -// valueQuoted is like value but decodes a -// quoted string literal or literal null into an interface value. -// If it finds anything other than a quoted string literal or null, -// valueQuoted returns unquotedValue{}. -func (d *decodeState) valueQuoted() interface{} { - switch op := d.scanWhile(scanSkipSpace); op { - default: - d.error(errPhase) - - case scanBeginArray: - d.array(reflect.Value{}) - - case scanBeginObject: - d.object(reflect.Value{}) - - case scanBeginLiteral: - switch v := d.literalInterface().(type) { - case nil, string: - return v - } - } - return unquotedValue{} -} - -// indirect walks down v allocating pointers as needed, -// until it gets to a non-pointer. -// if it encounters an Unmarshaler, indirect stops and returns that. -// if decodingNull is true, indirect stops at the last pointer so it can be set to nil. -func (d *decodeState) indirect(v reflect.Value, decodingNull bool) (Unmarshaler, encoding.TextUnmarshaler, reflect.Value) { - // If v is a named type and is addressable, - // start with its address, so that if the type has pointer methods, - // we find them. - if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() { - v = v.Addr() - } - for { - // Load value from interface, but only if the result will be - // usefully addressable. - if v.Kind() == reflect.Interface && !v.IsNil() { - e := v.Elem() - if e.Kind() == reflect.Ptr && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Ptr) { - v = e - continue - } - } - - if v.Kind() != reflect.Ptr { - break - } - - if v.Elem().Kind() != reflect.Ptr && decodingNull && v.CanSet() { - break - } - if v.IsNil() { - v.Set(reflect.New(v.Type().Elem())) - } - if v.Type().NumMethod() > 0 { - if u, ok := v.Interface().(Unmarshaler); ok { - return u, nil, reflect.Value{} - } - if u, ok := v.Interface().(encoding.TextUnmarshaler); ok { - return nil, u, reflect.Value{} - } - } - v = v.Elem() - } - return nil, nil, v -} - -// array consumes an array from d.data[d.off-1:], decoding into the value v. -// the first byte of the array ('[') has been read already. -func (d *decodeState) array(v reflect.Value) { - // Check for unmarshaler. - u, ut, pv := d.indirect(v, false) - if u != nil { - d.off-- - err := u.UnmarshalJSON(d.next()) - if err != nil { - d.error(err) - } - return - } - if ut != nil { - d.saveError(&UnmarshalTypeError{"array", v.Type(), int64(d.off)}) - d.off-- - d.next() - return - } - - v = pv - - // Check type of target. - switch v.Kind() { - case reflect.Interface: - if v.NumMethod() == 0 { - // Decoding into nil interface? Switch to non-reflect code. - v.Set(reflect.ValueOf(d.arrayInterface())) - return - } - // Otherwise it's invalid. - fallthrough - default: - d.saveError(&UnmarshalTypeError{"array", v.Type(), int64(d.off)}) - d.off-- - d.next() - return - case reflect.Array: - case reflect.Slice: - break - } - - i := 0 - for { - // Look ahead for ] - can only happen on first iteration. - op := d.scanWhile(scanSkipSpace) - if op == scanEndArray { - break - } - - // Back up so d.value can have the byte we just read. - d.off-- - d.scan.undo(op) - - // Get element of array, growing if necessary. - if v.Kind() == reflect.Slice { - // Grow slice if necessary - if i >= v.Cap() { - newcap := v.Cap() + v.Cap()/2 - if newcap < 4 { - newcap = 4 - } - newv := reflect.MakeSlice(v.Type(), v.Len(), newcap) - reflect.Copy(newv, v) - v.Set(newv) - } - if i >= v.Len() { - v.SetLen(i + 1) - } - } - - if i < v.Len() { - // Decode into element. - d.value(v.Index(i)) - } else { - // Ran out of fixed array: skip. - d.value(reflect.Value{}) - } - i++ - - // Next token must be , or ]. - op = d.scanWhile(scanSkipSpace) - if op == scanEndArray { - break - } - if op != scanArrayValue { - d.error(errPhase) - } - } - - if i < v.Len() { - if v.Kind() == reflect.Array { - // Array. Zero the rest. - z := reflect.Zero(v.Type().Elem()) - for ; i < v.Len(); i++ { - v.Index(i).Set(z) - } - } else { - v.SetLen(i) - } - } - if i == 0 && v.Kind() == reflect.Slice { - v.Set(reflect.MakeSlice(v.Type(), 0, 0)) - } -} - -var nullLiteral = []byte("null") - -// object consumes an object from d.data[d.off-1:], decoding into the value v. -// the first byte ('{') of the object has been read already. -func (d *decodeState) object(v reflect.Value) { - // Check for unmarshaler. - u, ut, pv := d.indirect(v, false) - if u != nil { - d.off-- - err := u.UnmarshalJSON(d.next()) - if err != nil { - d.error(err) - } - return - } - if ut != nil { - d.saveError(&UnmarshalTypeError{"object", v.Type(), int64(d.off)}) - d.off-- - d.next() // skip over { } in input - return - } - v = pv - - // Decoding into nil interface? Switch to non-reflect code. - if v.Kind() == reflect.Interface && v.NumMethod() == 0 { - v.Set(reflect.ValueOf(d.objectInterface())) - return - } - - // Check type of target: struct or map[string]T - switch v.Kind() { - case reflect.Map: - // map must have string kind - t := v.Type() - if t.Key().Kind() != reflect.String { - d.saveError(&UnmarshalTypeError{"object", v.Type(), int64(d.off)}) - d.off-- - d.next() // skip over { } in input - return - } - if v.IsNil() { - v.Set(reflect.MakeMap(t)) - } - case reflect.Struct: - - default: - d.saveError(&UnmarshalTypeError{"object", v.Type(), int64(d.off)}) - d.off-- - d.next() // skip over { } in input - return - } - - var mapElem reflect.Value - - for { - // Read opening " of string key or closing }. - op := d.scanWhile(scanSkipSpace) - if op == scanEndObject { - // closing } - can only happen on first iteration. - break - } - if op != scanBeginLiteral { - d.error(errPhase) - } - - // Read key. - start := d.off - 1 - op = d.scanWhile(scanContinue) - item := d.data[start : d.off-1] - key, ok := unquoteBytes(item) - if !ok { - d.error(errPhase) - } - - // Figure out field corresponding to key. - var subv reflect.Value - destring := false // whether the value is wrapped in a string to be decoded first - - if v.Kind() == reflect.Map { - elemType := v.Type().Elem() - if !mapElem.IsValid() { - mapElem = reflect.New(elemType).Elem() - } else { - mapElem.Set(reflect.Zero(elemType)) - } - subv = mapElem - } else { - var f *field - fields := cachedTypeFields(v.Type(), false) - for i := range fields { - ff := &fields[i] - if bytes.Equal(ff.nameBytes, key) { - f = ff - break - } - if f == nil && ff.equalFold(ff.nameBytes, key) { - f = ff - } - } - if f != nil { - subv = v - destring = f.quoted - for _, i := range f.index { - if subv.Kind() == reflect.Ptr { - if subv.IsNil() { - subv.Set(reflect.New(subv.Type().Elem())) - } - subv = subv.Elem() - } - subv = subv.Field(i) - } - } - } - - // Read : before value. - if op == scanSkipSpace { - op = d.scanWhile(scanSkipSpace) - } - if op != scanObjectKey { - d.error(errPhase) - } - - // Read value. - if destring { - switch qv := d.valueQuoted().(type) { - case nil: - d.literalStore(nullLiteral, subv, false) - case string: - d.literalStore([]byte(qv), subv, true) - default: - d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal unquoted value into %v", subv.Type())) - } - } else { - d.value(subv) - } - - // Write value back to map; - // if using struct, subv points into struct already. - if v.Kind() == reflect.Map { - kv := reflect.ValueOf(key).Convert(v.Type().Key()) - v.SetMapIndex(kv, subv) - } - - // Next token must be , or }. - op = d.scanWhile(scanSkipSpace) - if op == scanEndObject { - break - } - if op != scanObjectValue { - d.error(errPhase) - } - } -} - -// literal consumes a literal from d.data[d.off-1:], decoding into the value v. -// The first byte of the literal has been read already -// (that's how the caller knows it's a literal). -func (d *decodeState) literal(v reflect.Value) { - // All bytes inside literal return scanContinue op code. - start := d.off - 1 - op := d.scanWhile(scanContinue) - - // Scan read one byte too far; back up. - d.off-- - d.scan.undo(op) - - d.literalStore(d.data[start:d.off], v, false) -} - -// convertNumber converts the number literal s to a float64 or a Number -// depending on the setting of d.useNumber. -func (d *decodeState) convertNumber(s string) (interface{}, error) { - if d.useNumber { - return Number(s), nil - } - f, err := strconv.ParseFloat(s, 64) - if err != nil { - return nil, &UnmarshalTypeError{"number " + s, reflect.TypeOf(0.0), int64(d.off)} - } - return f, nil -} - -var numberType = reflect.TypeOf(Number("")) - -// literalStore decodes a literal stored in item into v. -// -// fromQuoted indicates whether this literal came from unwrapping a -// string from the ",string" struct tag option. this is used only to -// produce more helpful error messages. -func (d *decodeState) literalStore(item []byte, v reflect.Value, fromQuoted bool) { - // Check for unmarshaler. - if len(item) == 0 { - //Empty string given - d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - return - } - wantptr := item[0] == 'n' // null - u, ut, pv := d.indirect(v, wantptr) - if u != nil { - err := u.UnmarshalJSON(item) - if err != nil { - d.error(err) - } - return - } - if ut != nil { - if item[0] != '"' { - if fromQuoted { - d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - } else { - d.saveError(&UnmarshalTypeError{"string", v.Type(), int64(d.off)}) - } - return - } - s, ok := unquoteBytes(item) - if !ok { - if fromQuoted { - d.error(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - } else { - d.error(errPhase) - } - } - err := ut.UnmarshalText(s) - if err != nil { - d.error(err) - } - return - } - - v = pv - - switch c := item[0]; c { - case 'n': // null - switch v.Kind() { - case reflect.Interface, reflect.Ptr, reflect.Map, reflect.Slice: - v.Set(reflect.Zero(v.Type())) - // otherwise, ignore null for primitives/string - } - case 't', 'f': // true, false - value := c == 't' - switch v.Kind() { - default: - if fromQuoted { - d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - } else { - d.saveError(&UnmarshalTypeError{"bool", v.Type(), int64(d.off)}) - } - case reflect.Bool: - v.SetBool(value) - case reflect.Interface: - if v.NumMethod() == 0 { - v.Set(reflect.ValueOf(value)) - } else { - d.saveError(&UnmarshalTypeError{"bool", v.Type(), int64(d.off)}) - } - } - - case '"': // string - s, ok := unquoteBytes(item) - if !ok { - if fromQuoted { - d.error(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - } else { - d.error(errPhase) - } - } - switch v.Kind() { - default: - d.saveError(&UnmarshalTypeError{"string", v.Type(), int64(d.off)}) - case reflect.Slice: - if v.Type().Elem().Kind() != reflect.Uint8 { - d.saveError(&UnmarshalTypeError{"string", v.Type(), int64(d.off)}) - break - } - b := make([]byte, base64.StdEncoding.DecodedLen(len(s))) - n, err := base64.StdEncoding.Decode(b, s) - if err != nil { - d.saveError(err) - break - } - v.SetBytes(b[:n]) - case reflect.String: - v.SetString(string(s)) - case reflect.Interface: - if v.NumMethod() == 0 { - v.Set(reflect.ValueOf(string(s))) - } else { - d.saveError(&UnmarshalTypeError{"string", v.Type(), int64(d.off)}) - } - } - - default: // number - if c != '-' && (c < '0' || c > '9') { - if fromQuoted { - d.error(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - } else { - d.error(errPhase) - } - } - s := string(item) - switch v.Kind() { - default: - if v.Kind() == reflect.String && v.Type() == numberType { - v.SetString(s) - if !isValidNumber(s) { - d.error(fmt.Errorf("json: invalid number literal, trying to unmarshal %q into Number", item)) - } - break - } - if fromQuoted { - d.error(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - } else { - d.error(&UnmarshalTypeError{"number", v.Type(), int64(d.off)}) - } - case reflect.Interface: - n, err := d.convertNumber(s) - if err != nil { - d.saveError(err) - break - } - if v.NumMethod() != 0 { - d.saveError(&UnmarshalTypeError{"number", v.Type(), int64(d.off)}) - break - } - v.Set(reflect.ValueOf(n)) - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - n, err := strconv.ParseInt(s, 10, 64) - if err != nil || v.OverflowInt(n) { - d.saveError(&UnmarshalTypeError{"number " + s, v.Type(), int64(d.off)}) - break - } - v.SetInt(n) - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - n, err := strconv.ParseUint(s, 10, 64) - if err != nil || v.OverflowUint(n) { - d.saveError(&UnmarshalTypeError{"number " + s, v.Type(), int64(d.off)}) - break - } - v.SetUint(n) - - case reflect.Float32, reflect.Float64: - n, err := strconv.ParseFloat(s, v.Type().Bits()) - if err != nil || v.OverflowFloat(n) { - d.saveError(&UnmarshalTypeError{"number " + s, v.Type(), int64(d.off)}) - break - } - v.SetFloat(n) - } - } -} - -// The xxxInterface routines build up a value to be stored -// in an empty interface. They are not strictly necessary, -// but they avoid the weight of reflection in this common case. - -// valueInterface is like value but returns interface{} -func (d *decodeState) valueInterface() interface{} { - switch d.scanWhile(scanSkipSpace) { - default: - d.error(errPhase) - panic("unreachable") - case scanBeginArray: - return d.arrayInterface() - case scanBeginObject: - return d.objectInterface() - case scanBeginLiteral: - return d.literalInterface() - } -} - -// arrayInterface is like array but returns []interface{}. -func (d *decodeState) arrayInterface() []interface{} { - var v = make([]interface{}, 0) - for { - // Look ahead for ] - can only happen on first iteration. - op := d.scanWhile(scanSkipSpace) - if op == scanEndArray { - break - } - - // Back up so d.value can have the byte we just read. - d.off-- - d.scan.undo(op) - - v = append(v, d.valueInterface()) - - // Next token must be , or ]. - op = d.scanWhile(scanSkipSpace) - if op == scanEndArray { - break - } - if op != scanArrayValue { - d.error(errPhase) - } - } - return v -} - -// objectInterface is like object but returns map[string]interface{}. -func (d *decodeState) objectInterface() map[string]interface{} { - m := make(map[string]interface{}) - for { - // Read opening " of string key or closing }. - op := d.scanWhile(scanSkipSpace) - if op == scanEndObject { - // closing } - can only happen on first iteration. - break - } - if op != scanBeginLiteral { - d.error(errPhase) - } - - // Read string key. - start := d.off - 1 - op = d.scanWhile(scanContinue) - item := d.data[start : d.off-1] - key, ok := unquote(item) - if !ok { - d.error(errPhase) - } - - // Read : before value. - if op == scanSkipSpace { - op = d.scanWhile(scanSkipSpace) - } - if op != scanObjectKey { - d.error(errPhase) - } - - // Read value. - m[key] = d.valueInterface() - - // Next token must be , or }. - op = d.scanWhile(scanSkipSpace) - if op == scanEndObject { - break - } - if op != scanObjectValue { - d.error(errPhase) - } - } - return m -} - -// literalInterface is like literal but returns an interface value. -func (d *decodeState) literalInterface() interface{} { - // All bytes inside literal return scanContinue op code. - start := d.off - 1 - op := d.scanWhile(scanContinue) - - // Scan read one byte too far; back up. - d.off-- - d.scan.undo(op) - item := d.data[start:d.off] - - switch c := item[0]; c { - case 'n': // null - return nil - - case 't', 'f': // true, false - return c == 't' - - case '"': // string - s, ok := unquote(item) - if !ok { - d.error(errPhase) - } - return s - - default: // number - if c != '-' && (c < '0' || c > '9') { - d.error(errPhase) - } - n, err := d.convertNumber(string(item)) - if err != nil { - d.saveError(err) - } - return n - } -} - -// getu4 decodes \uXXXX from the beginning of s, returning the hex value, -// or it returns -1. -func getu4(s []byte) rune { - if len(s) < 6 || s[0] != '\\' || s[1] != 'u' { - return -1 - } - r, err := strconv.ParseUint(string(s[2:6]), 16, 64) - if err != nil { - return -1 - } - return rune(r) -} - -// unquote converts a quoted JSON string literal s into an actual string t. -// The rules are different than for Go, so cannot use strconv.Unquote. -func unquote(s []byte) (t string, ok bool) { - s, ok = unquoteBytes(s) - t = string(s) - return -} - -func unquoteBytes(s []byte) (t []byte, ok bool) { - if len(s) < 2 || s[0] != '"' || s[len(s)-1] != '"' { - return - } - s = s[1 : len(s)-1] - - // Check for unusual characters. If there are none, - // then no unquoting is needed, so return a slice of the - // original bytes. - r := 0 - for r < len(s) { - c := s[r] - if c == '\\' || c == '"' || c < ' ' { - break - } - if c < utf8.RuneSelf { - r++ - continue - } - rr, size := utf8.DecodeRune(s[r:]) - if rr == utf8.RuneError && size == 1 { - break - } - r += size - } - if r == len(s) { - return s, true - } - - b := make([]byte, len(s)+2*utf8.UTFMax) - w := copy(b, s[0:r]) - for r < len(s) { - // Out of room? Can only happen if s is full of - // malformed UTF-8 and we're replacing each - // byte with RuneError. - if w >= len(b)-2*utf8.UTFMax { - nb := make([]byte, (len(b)+utf8.UTFMax)*2) - copy(nb, b[0:w]) - b = nb - } - switch c := s[r]; { - case c == '\\': - r++ - if r >= len(s) { - return - } - switch s[r] { - default: - return - case '"', '\\', '/', '\'': - b[w] = s[r] - r++ - w++ - case 'b': - b[w] = '\b' - r++ - w++ - case 'f': - b[w] = '\f' - r++ - w++ - case 'n': - b[w] = '\n' - r++ - w++ - case 'r': - b[w] = '\r' - r++ - w++ - case 't': - b[w] = '\t' - r++ - w++ - case 'u': - r-- - rr := getu4(s[r:]) - if rr < 0 { - return - } - r += 6 - if utf16.IsSurrogate(rr) { - rr1 := getu4(s[r:]) - if dec := utf16.DecodeRune(rr, rr1); dec != unicode.ReplacementChar { - // A valid pair; consume. - r += 6 - w += utf8.EncodeRune(b[w:], dec) - break - } - // Invalid surrogate; fall back to replacement rune. - rr = unicode.ReplacementChar - } - w += utf8.EncodeRune(b[w:], rr) - } - - // Quote, control characters are invalid. - case c == '"', c < ' ': - return - - // ASCII - case c < utf8.RuneSelf: - b[w] = c - r++ - w++ - - // Coerce to well-formed UTF-8. - default: - rr, size := utf8.DecodeRune(s[r:]) - r += size - w += utf8.EncodeRune(b[w:], rr) - } - } - return b[0:w], true -} diff --git a/vendor/github.com/docker/go/canonical/json/encode.go b/vendor/github.com/docker/go/canonical/json/encode.go deleted file mode 100644 index f3491b160..000000000 --- a/vendor/github.com/docker/go/canonical/json/encode.go +++ /dev/null @@ -1,1250 +0,0 @@ -// 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 json implements encoding and decoding of JSON objects as defined in -// RFC 4627. The mapping between JSON objects and Go values is described -// in the documentation for the Marshal and Unmarshal functions. -// -// See "JSON and Go" for an introduction to this package: -// https://golang.org/doc/articles/json_and_go.html -package json - -import ( - "bytes" - "encoding" - "encoding/base64" - "fmt" - "math" - "reflect" - "runtime" - "sort" - "strconv" - "strings" - "sync" - "unicode" - "unicode/utf8" -) - -// Marshal returns the JSON encoding of v. -// -// Marshal traverses the value v recursively. -// If an encountered value implements the Marshaler interface -// and is not a nil pointer, Marshal calls its MarshalJSON method -// to produce JSON. If no MarshalJSON method is present but the -// value implements encoding.TextMarshaler instead, Marshal calls -// its MarshalText method. -// The nil pointer exception is not strictly necessary -// but mimics a similar, necessary exception in the behavior of -// UnmarshalJSON. -// -// Otherwise, Marshal uses the following type-dependent default encodings: -// -// Boolean values encode as JSON booleans. -// -// Floating point, integer, and Number values encode as JSON numbers. -// -// String values encode as JSON strings coerced to valid UTF-8, -// replacing invalid bytes with the Unicode replacement rune. -// The angle brackets "<" and ">" are escaped to "\u003c" and "\u003e" -// to keep some browsers from misinterpreting JSON output as HTML. -// Ampersand "&" is also escaped to "\u0026" for the same reason. -// -// Array and slice values encode as JSON arrays, except that -// []byte encodes as a base64-encoded string, and a nil slice -// encodes as the null JSON object. -// -// Struct values encode as JSON objects. Each exported struct field -// becomes a member of the object unless -// - the field's tag is "-", or -// - the field is empty and its tag specifies the "omitempty" option. -// The empty values are false, 0, any -// nil pointer or interface value, and any array, slice, map, or string of -// length zero. The object's default key string is the struct field name -// but can be specified in the struct field's tag value. The "json" key in -// the struct field's tag value is the key name, followed by an optional comma -// and options. Examples: -// -// // Field is ignored by this package. -// Field int `json:"-"` -// -// // Field appears in JSON as key "myName". -// Field int `json:"myName"` -// -// // Field appears in JSON as key "myName" and -// // the field is omitted from the object if its value is empty, -// // as defined above. -// Field int `json:"myName,omitempty"` -// -// // Field appears in JSON as key "Field" (the default), but -// // the field is skipped if empty. -// // Note the leading comma. -// Field int `json:",omitempty"` -// -// The "string" option signals that a field is stored as JSON inside a -// JSON-encoded string. It applies only to fields of string, floating point, -// integer, or boolean types. This extra level of encoding is sometimes used -// when communicating with JavaScript programs: -// -// Int64String int64 `json:",string"` -// -// The key name will be used if it's a non-empty string consisting of -// only Unicode letters, digits, dollar signs, percent signs, hyphens, -// underscores and slashes. -// -// Anonymous struct fields are usually marshaled as if their inner exported fields -// were fields in the outer struct, subject to the usual Go visibility rules amended -// as described in the next paragraph. -// An anonymous struct field with a name given in its JSON tag is treated as -// having that name, rather than being anonymous. -// An anonymous struct field of interface type is treated the same as having -// that type as its name, rather than being anonymous. -// -// The Go visibility rules for struct fields are amended for JSON when -// deciding which field to marshal or unmarshal. If there are -// multiple fields at the same level, and that level is the least -// nested (and would therefore be the nesting level selected by the -// usual Go rules), the following extra rules apply: -// -// 1) Of those fields, if any are JSON-tagged, only tagged fields are considered, -// even if there are multiple untagged fields that would otherwise conflict. -// 2) If there is exactly one field (tagged or not according to the first rule), that is selected. -// 3) Otherwise there are multiple fields, and all are ignored; no error occurs. -// -// Handling of anonymous struct fields is new in Go 1.1. -// Prior to Go 1.1, anonymous struct fields were ignored. To force ignoring of -// an anonymous struct field in both current and earlier versions, give the field -// a JSON tag of "-". -// -// Map values encode as JSON objects. -// The map's key type must be string; the map keys are used as JSON object -// keys, subject to the UTF-8 coercion described for string values above. -// -// Pointer values encode as the value pointed to. -// A nil pointer encodes as the null JSON object. -// -// Interface values encode as the value contained in the interface. -// A nil interface value encodes as the null JSON object. -// -// Channel, complex, and function values cannot be encoded in JSON. -// Attempting to encode such a value causes Marshal to return -// an UnsupportedTypeError. -// -// JSON cannot represent cyclic data structures and Marshal does not -// handle them. Passing cyclic structures to Marshal will result in -// an infinite recursion. -// -func Marshal(v interface{}) ([]byte, error) { - return marshal(v, false) -} - -// MarshalIndent is like Marshal but applies Indent to format the output. -func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { - b, err := Marshal(v) - if err != nil { - return nil, err - } - var buf bytes.Buffer - err = Indent(&buf, b, prefix, indent) - if err != nil { - return nil, err - } - return buf.Bytes(), nil -} - -// MarshalCanonical is like Marshal but encodes into Canonical JSON. -// Read more at: http://wiki.laptop.org/go/Canonical_JSON -func MarshalCanonical(v interface{}) ([]byte, error) { - return marshal(v, true) -} - -func marshal(v interface{}, canonical bool) ([]byte, error) { - e := &encodeState{canonical: canonical} - err := e.marshal(v) - if err != nil { - return nil, err - } - return e.Bytes(), nil -} - -// HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029 -// characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029 -// so that the JSON will be safe to embed inside HTML